answer
stringlengths
17
10.2M
package com.hp.oo.internal.sdk.execution.events; import com.hp.oo.enginefacade.execution.ExecutionEnums; import com.hp.oo.enginefacade.execution.ExecutionEnums.ExecutionStatus; import com.hp.oo.enginefacade.execution.ExecutionEnums.LogLevel; import com.hp.oo.enginefacade.execution.ExecutionEnums.LogLevelCategory; import com.hp.oo.internal.sdk.execution.ExecutionConstants; import com.hp.oo.internal.sdk.execution.OOContext; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class ExecutionEventFactory { private static ObjectMapper mapper = new ObjectMapper(); public static final int SEQUENCE_SIZE = 5; public static ExecutionEvent createStartEvent(String executionId, String flowUuid, final String triggerType, final String executionName, final String executionLogLevel, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.START, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setData4(json( "flow_UUID", flowUuid, "trigger_type", triggerType, "execution_name", executionName, ExecutionConstants.EXECUTION_EVENTS_LOG_LEVEL, executionLogLevel )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createCompletedFinishEvent(String executionId, String flowUUID, String context, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.FINISH, executionEventSequenceOrder, flowPath) .setData1(ExecutionStatus.COMPLETED.name()) .setData2(flowUUID) .setData4(json( "execution_status", ExecutionStatus.COMPLETED.name(), "context", context )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createFailureFinishEvent(String executionId, String flowUUID, String exceptionStr, String context, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.FINISH, executionEventSequenceOrder, flowPath) .setData1(ExecutionStatus.SYSTEM_FAILURE.name()) .setData2(flowUUID) .setData4(json( "execution_status", ExecutionStatus.SYSTEM_FAILURE.name(), "error_message", exceptionStr, "context", context )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } @SuppressWarnings("UnusedDeclaration") public static ExecutionEvent createCancelledFinishEvent(String executionId, String flowUUID, String context, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.FINISH, executionEventSequenceOrder, flowPath) .setData1(ExecutionStatus.CANCELED.name()) .setData2(flowUUID) .setData4(json( "execution_status", ExecutionStatus.CANCELED.name(), "context", context )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createPausedEvent(String executionId, String flowUuid, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.PAUSE, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createResumeEvent(String executionId, String flowUuid, String branchId, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.RESUME, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setData4(json( "branch_id", branchId )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createNoWorkersEvent(String executionId, Long pausedExecutionId, String flowUuid, String branchId, String group, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.NO_WORKERS_IN_GROUP, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setData2(json( "group", group )) .setData3(pausedExecutionId) .setData4(json( "branch_id", branchId)) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } // todo (Shehab): it is probably redundant, and need to use the FINISH event (with execution_status CANCEL). public static ExecutionEvent createCancelEvent(String executionId, String flowUuid, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.CANCEL, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createDisplayEvent(String executionId, Long pausedExecutionId, String flowUuid, String stepUuid, String stepName, String branchId, String displayTitle, String messageKey, HashMap<String, String> displayTextMapLocale, String displayWindowHeight, String displayWindowWidth, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.DISPLAY, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setData2(json( "display_text_key", messageKey )) .setData3(pausedExecutionId) .setData4(json( "step_id", stepUuid, "step_name", stepName, "branch_id", branchId, "display_title", displayTitle, "display_height", displayWindowHeight, "display_width", displayWindowWidth, "display_text_map_locale", json(displayTextMapLocale) )).setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createGatedTransitionEvent(String executionId, Long pausedExecutionId, String flowUuid, String stepUuid, String stepName, String branchId, String roleName, String userName, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.GATED_TRANSITION, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setData3(pausedExecutionId) .setData4(json( "step_id", stepUuid, "step_name", stepName, "branch_id", branchId, "role_name", roleName, "user_name", userName )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createHandOffEvent(String executionId, Long pausedExecutionId, String flowUuid, String stepUuid, String stepName, String branchId, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.HAND_OFF, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setData3(pausedExecutionId) .setData4(json( "step_id", stepUuid, "step_name", stepName, "branch_id", branchId )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createResultEvent(String executionId, String resultType, String resultName, ExecutionEventSequenceOrder eventOrder, Map systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.RESULT, executionEventSequenceOrder, flowPath) .setData1(resultType) .setData2(resultName) .setData4(json( "result_type", resultType, "result_name", resultName )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createFlowInputEvent(String executionId, String paramName, String paramValue, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.FLOW_INPUT, executionEventSequenceOrder, flowPath) .setData1(paramName) .setData2(paramValue) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createOperationalEvent(String executionId, String stepId, String stepName,String stepType, String flowName, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.OPERATIONAL, executionEventSequenceOrder, flowPath) .setData4(json( "step_id", stepId, "step_name", stepName, "step_type", stepType, "flow_name",flowName, ExecutionConstants.EFFECTIVE_RUNNING_USER, (String)systemContext.get(ExecutionConstants.EFFECTIVE_RUNNING_USER), ExecutionConstants.FLOW_UUID, (String)systemContext.get(ExecutionConstants.FLOW_UUID), ExecutionConstants.PARENT_STEP_UUID, (String)systemContext.get("PARENT_MSS_STEP_UUID") )) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent, systemContext); return executionEvent; } public static ExecutionEvent createStepLogEvent(String executionId,ExecutionEventSequenceOrder eventOrder,ExecutionEnums.StepLogCategory stepLogCategory, Map<String, Serializable> systemContext) { //TODO do we need sequence order String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); List<ExecutionEvent> events = ((Map<String,List>)systemContext.get(ExecutionConstants.EXECUTION_EVENTS_STEP_MAPPED)).get(flowPath); if(stepLogCategory.equals(ExecutionEnums.StepLogCategory.STEP_END)){ ((Map<String,List>)systemContext.get(ExecutionConstants.EXECUTION_EVENTS_STEP_MAPPED)).remove(flowPath); } return new ExecutionEvent(executionId, ExecutionEnums.Event.STEP_LOG, stepLogCategory, executionEventSequenceOrder, flowPath) .setData5(new ArrayList<>(events)); } public static ExecutionEvent createPauseFlowForInputsEvent(String executionId, Long pausedExecutionId, String flowUuid, String stepId, String branchId, String stepName, List<Object> promptInputs, Map<String, Map<String, String>> l10nMapAfterReferences, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.INPUT_REQUIRED, executionEventSequenceOrder, flowPath) .setData1(flowUuid) .setData3(pausedExecutionId) .setData4(json( "step_id", stepId, "step_name", stepName, "branch_id", branchId, "required_inputs", json(promptInputs), "key_to_locale_to_value_map", json(l10nMapAfterReferences) )).setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createAggregationFinishedEvent(String executionId, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemCtx) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.AGGREGATION_FINISHED, executionEventSequenceOrder, flowPath); addEventToSysContext(executionEvent,systemCtx); return executionEvent; } public static ExecutionEvent createInputsEvent(String executionId, String flowId, String stepId, ExecutionEnums.Event type, ExecutionEventSequenceOrder eventOrder, String branchId, String stepName, List<Object> inputs, Map<String, Serializable> systemContext) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); String eventData; if (type.equals(ExecutionEnums.Event.STEP_INPUTS)) { eventData = json( "step_id", stepId, "step_name", stepName, "branch_id", branchId, "inputs", json(inputs)); } else { eventData = json("inputs", json(inputs)); } ExecutionEvent executionEvent = new ExecutionEvent(executionId, type, executionEventSequenceOrder, flowPath) .setData1(flowId) .setData2(branchId) .setData4(eventData) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createLogEvent(String executionId, String stepId, String logMessage, LogLevel logLevel, LogLevelCategory logLevelCategory, OOContext context, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> systemContext) { HashMap<String, String> contextMap; if (context != null) { contextMap = (HashMap<String, String>) context.retrieveSecureMap(); } else { contextMap = new HashMap<>(); } String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); contextMap.put("logLevelCategory", logLevelCategory.name()); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.LOG, executionEventSequenceOrder, flowPath) .setData1(stepId) .setData2(logMessage) .setData3((long) logLevel.ordinal()) .setData4(json(contextMap)) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createBreakpointEvent(String executionId, String branchId, String stepUuid, ExecutionEventSequenceOrder eventOrder, LogLevelCategory logLevelCategory, Map<String, Serializable> context, String interruptUuid, String interruptType) { context.put("logLevelCategory", logLevelCategory.name()); context.put("branch_id", branchId); context.put("debugInterruptUuid", interruptUuid); context.put("debugInterruptType", interruptType); String eventDataAsString; try { eventDataAsString = mapper.writeValueAsString(context); } catch (IOException e) { throw new RuntimeException("Failed to create json", e); } String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.DEBUGGER, executionEventSequenceOrder, flowPath) .setData1(stepUuid) .setData2(logLevelCategory.name()) .setData3((long) LogLevel.DEBUG.ordinal()) .setData4(eventDataAsString) .setDebuggerMode(isDebuggerMode(context)); addEventToSysContext(executionEvent,context); return executionEvent; } private static boolean isDebuggerMode(Map<String, Serializable> systemContext) { Boolean isDebuggerMode = (Boolean) systemContext.get(ExecutionConstants.DEBUGGER_MODE); if (isDebuggerMode == null) { return false; } return isDebuggerMode; } public static ExecutionEvent createManualPausedEvent(String executionId, String branchId, String stepUuid, ExecutionEventSequenceOrder eventOrder, Map<String, Serializable> eventData, Map<String, Serializable> systemContext) { systemContext.put("branch_id", branchId); String eventDataAsString; try { eventDataAsString = mapper.writeValueAsString(systemContext); } catch (IOException e) { throw new RuntimeException("Failed to create json", e); } String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); // return new ExecutionEvent(executionId, ExecutionEnums.Event.PAUSE,executionEventSequenceOrder, flowPath) ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.DEBUGGER, executionEventSequenceOrder, flowPath) .setData1(stepUuid) .setData2(LogLevelCategory.MANUAL_PAUSE.name()) .setData3((long) LogLevel.DEBUG.ordinal()) .setData4(eventDataAsString) .setDebuggerMode(isDebuggerMode(systemContext)); addEventToSysContext(executionEvent,systemContext); return executionEvent; } public static ExecutionEvent createRoiEvent(String executionId, String stepUuid, ExecutionEventSequenceOrder eventOrder, String roi, Map<String, Serializable> systemCtx) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); ExecutionEvent executionEvent = new ExecutionEvent(executionId, ExecutionEnums.Event.ROI, executionEventSequenceOrder, flowPath) .setData1(stepUuid) .setData2(roi) .setDebuggerMode(isDebuggerMode(systemCtx)); addEventToSysContext(executionEvent,systemCtx); return executionEvent; } @SuppressWarnings("UnusedDeclaration") public static ExecutionEvent createDebuggerEvent(String executionId, String stepUuid, ExecutionEventSequenceOrder eventOrder, LogLevelCategory logLevelCategory, Map<String, Serializable> context) { String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = eventOrder.getFlowPath().toString(); return createDebuggerEvent(executionId, stepUuid, eventOrder, flowPath, logLevelCategory, context); } public static ExecutionEvent createDebuggerEvent(String executionId, String stepUuid, ExecutionEventSequenceOrder eventOrder, String path, LogLevelCategory logLevelCategory, Map<String, Serializable> context) { context.put("logLevelCategory", logLevelCategory.name()); String eventDataAsString; try { eventDataAsString = mapper.writeValueAsString(context); } catch (IOException e) { throw new RuntimeException("Failed to create json", e); } String executionEventSequenceOrder = formatExecutionEventSequenceOrder(eventOrder.getEventPath().toString()); String flowPath = path != null ? path : eventOrder.getFlowPath().toString(); return new ExecutionEvent(executionId, ExecutionEnums.Event.DEBUGGER, executionEventSequenceOrder, flowPath) .setData1(stepUuid) .setData2(logLevelCategory.name()) .setData3((long) LogLevel.DEBUG.ordinal()) .setData4(eventDataAsString) .setDebuggerMode(isDebuggerMode(context)); } private static String json(Map map) { if (map == null || map.isEmpty()) { return null; } try { return mapper.writeValueAsString(map); } catch (IOException ex) { throw new RuntimeException("Failed to create json", ex); } } private static String json(Collection collection) { if (collection == null || collection.isEmpty()) { return null; } try { return mapper.writeValueAsString(collection); } catch (IOException ex) { throw new RuntimeException("Failed to create json", ex); } } private static String json(String... values) { if (ArrayUtils.isEmpty(values)) return null; if (values.length % 2 != 0) throw new IllegalArgumentException("values should have an even length"); Map<String, String> map = new HashMap<>(); for (int i = 0; i < values.length; i += 2) { if (values[i] != null && values[i + 1] != null) { map.put(values[i], values[i + 1]); } } return json((HashMap<String, String>) map); } private static String formatExecutionEventSequenceOrder(String executionEventSequenceOrder) { StringBuilder formatSequence = new StringBuilder(); String[] splitStrings = executionEventSequenceOrder.split("\\."); for (String subString : splitStrings) { if (StringUtils.isNotBlank(subString)) { formatSequence.append(String.format("%0" + SEQUENCE_SIZE + "d", Integer.valueOf(subString))); // "%04d", } } return formatSequence.toString(); } private static void addEventToSysContext(ExecutionEvent executionEvent, Map<String, Serializable> systemContext) { Map<String,List<ExecutionEvent>> stepExecutionEvents = (Map<String,List<ExecutionEvent>>)systemContext.get(ExecutionConstants.EXECUTION_EVENTS_STEP_MAPPED); List<ExecutionEvent> exEvents = stepExecutionEvents.get(executionEvent.getPath()); if(exEvents == null){ exEvents = new ArrayList<>(); stepExecutionEvents.put(executionEvent.getPath(),exEvents); } exEvents.add(executionEvent); } }
package de.uni_freiburg.informatik.dbis.sempala.translator; import java.util.HashMap; /** * * @author ALKA2008 */ public final class Tags { // Global Constants public static final String IMPALA_PROPERTYTABLE_TABLENAME = "bigtable_parquet"; public static final String IMPALA_SINGLETABLE_TABLENAME = "singletable"; public static final String IMPALA_TABLENAME_TRIPLESTORE = "triplestore_parquet"; // tables produced by the complex property table loading process public static final String COMPLEX_TRIPLETABLE_TABLENAME = "tripletable"; public static final String COMPLEX_PROPERTYTABLE_TABLENAME = "complex_property_table"; public static final String COMPLEX_PROPERTIES_TABLENAME = "properties"; public static final String SEMPALA_RESULTS_DB_NAME = "sempala_results"; public static final String BGP = "BGP"; public static final String FILTER = "FILTER"; public static final String JOIN = "JOIN"; public static final String SEQUENCE = "SEQUENCE_JOIN"; public static final String LEFT_JOIN = "OPTIONAL"; public static final String CONDITIONAL = "OPTIONAL"; public static final String UNION = "UNION"; public static final String PROJECT = "PROJECTION "; public static final String DISTINCT = "SM_Distinct"; public static final String ORDER = "SM_Order"; public static final String SLICE = "SM_Slice"; public static final String REDUCED = "SM_Reduced"; public static final String GREATER_THAN = " > "; public static final String GREATER_THAN_OR_EQUAL = " >= "; public static final String LESS_THAN = " < "; public static final String LESS_THAN_OR_EQUAL = " <= "; public static final String EQUALS = " = "; public static final String NOT_EQUALS = " != "; public static final String LOGICAL_AND = " AND "; public static final String LOGICAL_OR = " OR "; public static final String LOGICAL_NOT = "NOT "; public static final String BOUND = " IS NOT NULL"; public static final String NOT_BOUND = " IS NULL"; public static final String NO_VAR = "#noVar"; public static final String NO_SUPPORT = "#noSupport"; public static final String OFFSETCHAR = "\t"; public static final String SUBJECT_COLUMN_NAME = "s"; public static final String PREDICATE_COLUMN_NAME = "p"; public static final String OBJECT_COLUMN_NAME = "o"; public static final int LIMIT_LARGE_NUMBER = 100000000; public static final String ADD = "+"; public static final String SUBTRACT = "-"; public static final String LIKE = " LIKE "; public static final String LANG_MATCHES = " LIKE "; // names which cannot be used for columns and their replacements public static HashMap<String, String> restrictedNames = new HashMap<String, String>(); static { restrictedNames.put("comment", "comme"); restrictedNames.put("date", "dat"); restrictedNames.put("?comment", "comme"); restrictedNames.put("?date", "dat"); } // Suppress default constructor for noninstantiability private Tags() { } }
package com.codingchili.router.controller.transport; import com.codingchili.common.Strings; import com.codingchili.router.Service; import com.codingchili.router.configuration.ListenerSettings; import com.codingchili.router.configuration.RouterSettings; import com.codingchili.router.model.Endpoint; import com.codingchili.router.model.WireType; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.Timeout; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.*; import org.junit.runner.RunWith; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.codingchili.core.protocol.ResponseStatus; import com.codingchili.core.security.RemoteIdentity; import static com.codingchili.common.Strings.*; /** * @author Robin Duda * <p> * Contains test cases for transport implementations. */ @Ignore("Extend this class to run the tests.") @RunWith(VertxUnitRunner.class) public abstract class TransportTestCases { static final String PATCHING_ROOT = "/patching"; static final String HOST = getLoopbackAddress(); private static final AtomicInteger PORT = new AtomicInteger(9421); private static final int MAX_REQUEST_BYTES = 256; private static final String ONE_CHAR = "x"; private static final String DATA = "data"; private ContextMock context; private WireType wireType; int port = PORT.getAndIncrement(); String nodeId = "node-" + port; Vertx vertx; TransportTestCases(WireType wireType) { this.wireType = wireType; } @Rule public Timeout timeout = new Timeout(30, TimeUnit.SECONDS); @Before public void setUp(TestContext test) { Async async = test.async(); vertx = Vertx.vertx(); context = new ContextMock(vertx); ListenerSettings listener = new ListenerSettings() .setMaxRequestBytes(MAX_REQUEST_BYTES) .setPort(port) .setType(wireType) .setTimeout(60000) .setHttpOptions(new HttpServerOptions().setCompressionSupported(false)) .addMapping(PATCHING_ROOT, new Endpoint(NODE_PATCHING)); RouterSettings settings = new RouterSettings(new RemoteIdentity("node", "host")) .setHidden(NODE_LOGGING) .addTransport(listener); settings.setHidden(Strings.NODE_LOGGING); settings.addTransport(listener); context.setSettings(settings); vertx.deployVerticle(new Service(context), deploy -> { test.assertTrue(deploy.succeeded(), deploy.cause().getMessage()); async.complete(); }); } @After public void tearDown(TestContext context) { vertx.close(context.asyncAssertSuccess()); } @Test public void testLargePacketRejected(TestContext test) { Async async = test.async(); mockNode(nodeId); sendRequest(nodeId, (result, status) -> { test.assertEquals(ResponseStatus.BAD, status); async.complete(); }, new JsonObject() .put(DATA, new String(new byte[MAX_REQUEST_BYTES]).replace("\0", ONE_CHAR))); } @Test public void testAccepted(TestContext test) { Async async = test.async(); sendRequest(DIR_ROOT, (result, status) -> { test.assertEquals(ResponseStatus.ACCEPTED, status); async.complete(); }, new JsonObject() .put(PROTOCOL_TARGET, NODE_ROUTING) .put(PROTOCOL_ROUTE, ID_PING)); } void mockNode(String node) { context.bus().consumer(node, message -> { message.reply(new JsonObject() .put(PROTOCOL_STATUS, ResponseStatus.ACCEPTED) .put(PROTOCOL_TARGET, node)); }); } /** * Implementing class must provide transport specific implementation. * * @param route the request route * @param listener invoked with the request response * @param data the request data. */ abstract void sendRequest(String route, ResponseListener listener, JsonObject data); void handleBody(ResponseListener listener, Buffer body) { ResponseStatus status = ResponseStatus.valueOf(body.toJsonObject().getString(PROTOCOL_STATUS)); listener.handle(body.toJsonObject(), status); } @FunctionalInterface interface ResponseListener { void handle(JsonObject result, ResponseStatus status); } }
package es.tid.smartsteps.dispersion.data; import java.math.BigDecimal; import java.math.MathContext; import java.util.ArrayList; import java.util.HashMap; import net.sf.json.JSONObject; import es.tid.smartsteps.dispersion.parsing.TrafficCountsEntryParser; /** * TrafficCountsEntry * * holds all counts per sociodemographic variable in a traffic log line, plus a * cell ID and location information. * * @author logc */ public class TrafficCountsEntry implements Entry { public static final String[] EXPECTED_POIS = { "HOME", "NONE", "WORK", "OTHER", "BILL" }; private static final int HOURLY_SLOTS = 25; public String cellId; public String date; public double latitude; public double longitude; public HashMap<String, ArrayList<BigDecimal>> counts; public HashMap<String, ArrayList<BigDecimal>> pois; public String microgridId; public String polygonId; public TrafficCountsEntry(String[] countFields) { this.pois = new HashMap<String, ArrayList<BigDecimal>>(); for (String expectedPoi : EXPECTED_POIS) { this.pois.put(expectedPoi, new ArrayList<BigDecimal>(HOURLY_SLOTS)); } this.counts = new HashMap<String, ArrayList<BigDecimal>>(); for (String countField : countFields) { this.counts.put(countField, new ArrayList<BigDecimal>()); } } public TrafficCountsEntry(TrafficCountsEntry entry) { this.cellId = entry.cellId; this.date = entry.date; this.latitude = entry.latitude; this.longitude = entry.longitude; this.counts = new HashMap<String, ArrayList<BigDecimal>>(); for (String key : entry.counts.keySet()) { this.counts.put(key, new ArrayList<BigDecimal>(entry.counts.get(key))); } this.pois = new HashMap<String, ArrayList<BigDecimal>>(entry.pois); for (String key : entry.pois.keySet()) { this.pois.put(key, new ArrayList<BigDecimal>(entry.pois.get(key))); } this.microgridId = entry.microgridId; this.polygonId = entry.polygonId; } @Override public String getKey() { if (this.polygonId != null && !this.polygonId.isEmpty()) { return this.polygonId; } else if (this.microgridId != null && !this.microgridId.isEmpty()) { return this.microgridId; } else { return this.cellId; } } public TrafficCountsEntry scale(BigDecimal factor) { TrafficCountsEntry scaled = new TrafficCountsEntry(this); for (String countField : scaled.counts.keySet()) { final ArrayList<BigDecimal> countsForField = scaled.counts.get(countField); for (int i = 0; i < countsForField.size(); i++) { countsForField.set(i, countsForField.get(i).multiply(factor)); } } for (String poi : scaled.pois.keySet()) { ArrayList<BigDecimal> countsForPoi = scaled.pois.get(poi); for (int i = 0; i < countsForPoi.size(); i++) { countsForPoi.set(i, countsForPoi.get(i).multiply(factor)); } } return scaled; } public HashMap<String, ArrayList<BigDecimal>> roundCounts() { HashMap<String, ArrayList<BigDecimal>> roundedCounts = new HashMap<String, ArrayList<BigDecimal>>(); for (String countField : this.counts.keySet()) { final ArrayList<BigDecimal> countsForField = this.counts.get(countField); ArrayList<BigDecimal> roundedCountsForField = new ArrayList<BigDecimal>(); for (int i = 0; i < roundedCounts.size(); i++) { roundedCountsForField.add(i, countsForField.get(i).round( MathContext.UNLIMITED)); } roundedCounts.put(countField, roundedCountsForField); } return roundedCounts; } public JSONObject toJSON(){ final JSONObject obj = new JSONObject(); obj.put(TrafficCountsEntryParser.CELLID_FIELD_NAME, this.cellId); obj.put(TrafficCountsEntryParser.DATE_FIELD_NAME, this.date); obj.put(TrafficCountsEntryParser.LATITUDE_FIELD_NAME, this.latitude); obj.put(TrafficCountsEntryParser.LONGITUDE_FIELD_NAME, this.longitude); for (String field : this.counts.keySet()) { obj.put(field, this.counts.get(field)); } obj.put(TrafficCountsEntryParser.POIS_FIELD_NAME, this.pois); obj.put(TrafficCountsEntryParser.MICROGRIDID_FIELD_NAME, this.microgridId); obj.put(TrafficCountsEntryParser.POLYGONID_FIELD_NAME, this.polygonId); return obj; } }
// This file is part of Elveos.org. // Elveos.org is free software: you can redistribute it and/or modify it // option) any later version. // Elveos.org is distributed in the hope that it will be useful, but WITHOUT // more details. package com.bloatit.data; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Cacheable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.ManyToOne; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.NamedQueries; import org.hibernate.annotations.NamedQuery; import com.bloatit.data.queries.QueryCollection; import com.bloatit.framework.exceptions.lowlevel.NonOptionalParameterException; import com.bloatit.framework.utils.PageIterable; @Entity @Cacheable @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) //@formatter:off @NamedQueries(value = { @NamedQuery( name = "memberid.event.byDate.withMail", query = "SELECT mff.id, e " + "FROM DaoEvent e " + "JOIN e.feature f " + "LEFT JOIN f.followers mf " + "LEFT JOIN mf.follower mff " + "WHERE e.creationDate > :beginDate " + "AND e.creationDate <= :endDate " + "AND (mff.emailStrategy = :strategy OR mff is null) " + "AND (mf.mail = true OR mf is null) " + "ORDER BY mff.id, e.creationDate " ), @NamedQuery( name = "memberid.event.byDate.withMail.size", query = "SELECT count(*) " + "FROM DaoEvent e " + "JOIN e.feature f " + "LEFT JOIN f.followers mf " + "LEFT JOIN mf.follower mff " + "WHERE e.creationDate > :beginDate " + "AND e.creationDate <= :endDate " + "AND (mff.emailStrategy = :strategy OR mff is null) " + "AND (mf.mail = true OR mf is null) " ), @NamedQuery( name = "event.byMember", query = "SELECT e " + "FROM DaoEvent e " + "JOIN e.feature f " + "LEFT JOIN f.followers mf " + "LEFT JOIN mf.follower mff " + "WHERE NOT (mf.featureComment=false AND e.isFeatureComment=true) " + "AND NOT (mf.bugComment=false AND e.isBugComment=true) " + "AND mff.id = :member "+ "ORDER BY e.creationDate DESC " ), @NamedQuery( name = "event.byMember.size", query = "SELECT count(*) " + "FROM DaoEvent e " + "JOIN e.feature f " + "LEFT JOIN f.followers mf " + "LEFT JOIN mf.follower mff " + "WHERE NOT (mf.featureComment=false AND e.isFeatureComment=true) " + "AND NOT (mf.bugComment=false AND e.isBugComment=true) " + "AND mff.id = :member " ), @NamedQuery( name = "event.getall", query = "SELECT e " + "FROM DaoEvent e " + "JOIN e.feature f " + "ORDER BY e.creationDate DESC " ), @NamedQuery( name = "event.getall.size", query = "SELECT count(*) " + "FROM DaoEvent e " + "JOIN e.feature f " ), }) //@formatter:on public class DaoEvent extends DaoIdentifiable { public enum EventType { // Feature CREATE_FEATURE, IN_DEVELOPING_STATE, DISCARDED, // TODO: remove every event from this feature. FINICHED, // Contributions ADD_CONTRIBUTION, REMOVE_CONTRIBUTION, // Offer ADD_OFFER, REMOVE_OFFER, ADD_SELECTED_OFFER, CHANGE_SELECTED_OFFER, REMOVE_SELECTED_OFFER, // Release ADD_RELEASE, // Bugs ADD_BUG, BUG_CHANGE_LEVEL, BUG_SET_RESOLVED, BUG_SET_DEVELOPING, // Comment FEATURE_ADD_COMMENT, BUG_ADD_COMMENT, } @Basic(optional = false) @Enumerated(EnumType.STRING) private EventType type; @Basic(optional = false) private boolean isBugComment; @Basic(optional = false) private boolean isFeatureComment; @Basic(optional = false) private Date creationDate; @ManyToOne(optional = false) private DaoFeature feature; @ManyToOne(optional = false) private DaoActor actor; @ManyToOne private DaoSoftware software; @ManyToOne private DaoContribution contribution; @ManyToOne(cascade = { CascadeType.ALL }) private DaoOffer offer; @ManyToOne private DaoComment comment; @ManyToOne private DaoBug bug; @ManyToOne private DaoRelease release; @ManyToOne private DaoMilestone milestone; public static PageIterable<DaoEvent> getEvent(final DaoMember member, final Date fromDate) { return new QueryCollection<DaoEvent>("event.byMemberDate"); } public static PageIterable<DaoEvent> getMailEvent(final DaoMember member, final Date fromDate) { return new QueryCollection<DaoEvent>("event.byMemberDate.withMail"); } private static DaoEvent createAndPersist(final EventType type, final DaoFeature feature, final DaoContribution contribution, final DaoOffer offer, final DaoComment comment, final DaoBug bug, final DaoRelease release, final DaoMilestone milestone) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoEvent event = new DaoEvent(type, feature, contribution, offer, comment, bug, release, milestone); try { session.save(event); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } return event; } public static DaoEvent createFeatureEvent(final DaoFeature feature, final EventType type) { return (createAndPersist(type, feature, null, null, null, null, null, null)); } public static DaoEvent createContributionEvent(final DaoFeature feature, final EventType type, final DaoContribution contribution) { return (createAndPersist(type, feature, contribution, null, null, null, null, null)); } public static DaoEvent createOfferEvent(final DaoFeature feature, final EventType type, final DaoOffer offer) { return (createAndPersist(type, feature, null, offer, null, null, null, null)); } public static DaoEvent createCommentEvent(final DaoFeature feature, final EventType type, final DaoComment comment) { return (createAndPersist(type, feature, null, null, comment, null, null, null)); } public static DaoEvent createCommentEvent(final DaoFeature feature, final EventType type, final DaoBug bug, final DaoComment comment, final DaoOffer offer, final DaoMilestone milestone) { return (createAndPersist(type, feature, null, offer, comment, bug, null, milestone)); } public static DaoEvent createBugEvent(final DaoFeature feature, final EventType type, final DaoBug bug, final DaoOffer offer, final DaoMilestone milestone) { return (createAndPersist(type, feature, null, offer, null, bug, null, milestone)); } public static DaoEvent createReleaseEvent(final DaoFeature feature, final EventType type, final DaoRelease release, final DaoOffer offer, final DaoMilestone milestone) { return (createAndPersist(type, feature, null, offer, null, null, release, milestone)); } public static DaoEvent createReleaseCommentEvent(final DaoFeature feature, final EventType type, final DaoComment comment, final DaoRelease release, final DaoOffer offer, final DaoMilestone milestone) { return (createAndPersist(type, feature, null, offer, comment, null, release, milestone)); } private DaoEvent(final EventType type, final DaoFeature feature, final DaoContribution contribution, final DaoOffer offer, final DaoComment comment, final DaoBug bug, final DaoRelease release, final DaoMilestone milestone) { super(); if (type == null || feature == null) { throw new NonOptionalParameterException(); } this.feature = feature; this.actor = feature.getAuthor(); this.software = feature.getSoftware(); this.creationDate = new Date(); this.isFeatureComment = release == null && bug == null && comment != null; this.isBugComment = bug != null && comment != null; this.type = type; this.contribution = contribution; this.offer = offer; this.comment = comment; this.bug = bug; this.release = release; this.milestone = milestone; } public EventType getType() { return type; } public boolean isBugComment() { return isBugComment; } public boolean isFeatureComment() { return isFeatureComment; } public Date getCreationDate() { return creationDate; } public DaoFeature getFeature() { return feature; } public DaoContribution getContribution() { return contribution; } public DaoOffer getOffer() { return offer; } public DaoComment getComment() { return comment; } public DaoBug getBug() { return bug; } public DaoRelease getRelease() { return release; } public DaoMilestone getMilestone() { return milestone; } public DaoActor getActor() { return actor; } public DaoSoftware getSoftware() { return software; } // Visitor. /* * (non-Javadoc) * @see * com.bloatit.data.DaoIdentifiable#accept(com.bloatit.data.DataClassVisitor * ) */ @Override public <ReturnType> ReturnType accept(final DataClassVisitor<ReturnType> visitor) { return visitor.visit(this); } // Hibernate mapping /** * Instantiates a new dao bug. */ protected DaoEvent() { super(); } // equals hashcode. @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bug == null) ? 0 : bug.hashCode()); result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((contribution == null) ? 0 : contribution.hashCode()); result = prime * result + ((feature == null) ? 0 : feature.hashCode()); result = prime * result + (isBugComment ? 1231 : 1237); result = prime * result + (isFeatureComment ? 1231 : 1237); result = prime * result + ((milestone == null) ? 0 : milestone.hashCode()); result = prime * result + ((offer == null) ? 0 : offer.hashCode()); result = prime * result + ((release == null) ? 0 : release.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final DaoEvent other = (DaoEvent) obj; if (bug == null) { if (other.bug != null) { return false; } } else if (!bug.equals(other.bug)) { return false; } if (comment == null) { if (other.comment != null) { return false; } } else if (!comment.equals(other.comment)) { return false; } if (contribution == null) { if (other.contribution != null) { return false; } } else if (!contribution.equals(other.contribution)) { return false; } if (feature == null) { if (other.feature != null) { return false; } } else if (!feature.equals(other.feature)) { return false; } if (isBugComment != other.isBugComment) { return false; } if (isFeatureComment != other.isFeatureComment) { return false; } if (milestone == null) { if (other.milestone != null) { return false; } } else if (!milestone.equals(other.milestone)) { return false; } if (offer == null) { if (other.offer != null) { return false; } } else if (!offer.equals(other.offer)) { return false; } if (release == null) { if (other.release != null) { return false; } } else if (!release.equals(other.release)) { return false; } if (type != other.type) { return false; } return true; } }
package ui; import com.alee.extended.label.WebLinkLabel; import com.alee.laf.WebLookAndFeel; import com.alee.laf.button.WebButton; import com.alee.laf.checkbox.WebCheckBox; import com.alee.laf.combobox.WebComboBox; import com.alee.laf.label.WebLabel; import com.alee.laf.menu.WebMenu; import com.alee.laf.menu.WebMenuBar; import com.alee.laf.menu.WebMenuItem; import com.alee.laf.menu.WebPopupMenu; import com.alee.laf.optionpane.WebOptionPane; import com.alee.laf.panel.WebPanel; import com.alee.laf.rootpane.WebDialog; import com.alee.laf.rootpane.WebFrame; import com.alee.laf.scroll.WebScrollPane; import com.alee.laf.separator.WebSeparator; import com.alee.laf.text.WebPasswordField; import com.alee.laf.text.WebTextField; import com.alee.laf.text.WebTextPane; import com.alee.managers.tooltip.TooltipManager; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import javax.swing.JFrame; import javax.swing.SwingConstants; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.StyledDocument; import main.FocusTraversalOnArray; import main.Main; import main.Status; import utilities.Config; //TODO split up user interface for Outlook, DAV and general configuration information public class Userinterface { private final static String RES_PATH = "res"; private Main control; private WebFrame frame; private final WebPasswordField passwordField; private final WebTextField usernameField; private final WebTextField urlField; private final WebCheckBox insecureSSLBox; private final WebLabel lblContactNumbers; private final WebCheckBox savePasswordBox; private final WebCheckBox initModeBox; static private WebTextPane textPane; static private StyledDocument docTextPane; static private WebComboBox contactFolderBox; /** * Create the application. */ public Userinterface(final Main main) { control = main; WebLookAndFeel.install(); frame = new WebFrame(); frame.setBounds(100, 100, 630, 430); frame.setResizable(false); frame.setTitle("CardDAVSyncOutlook"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Userinterface.this.shutdown(); } }); // menu WebMenuBar menubar = new WebMenuBar(); WebMenu fileMenu = new WebMenu("File"); WebMenuItem exitMenuItem = new WebMenuItem("Exit"); exitMenuItem.setToolTipText("Exit application"); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); } }); fileMenu.add(exitMenuItem); menubar.add(fileMenu); WebMenu extrasMenu = new WebMenu("Extras"); WebMenuItem exportICALMenuItem = new WebMenuItem("Export calendar"); exportICALMenuItem.setToolTipText("Export Outlook calendar to iCAL file (to date - one month)"); exportICALMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.exportICAL(); } }); extrasMenu.add(exportICALMenuItem); WebMenuItem prefMenuItem = new WebMenuItem("Preferences"); prefMenuItem.setToolTipText("Global Preferences"); prefMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PreferencesDialog pref = new PreferencesDialog(); pref.setVisible(true); } }); extrasMenu.add(prefMenuItem); menubar.add(extrasMenu); WebMenu helpMenu = new WebMenu("Help"); WebMenuItem aboutMenuItem = new WebMenuItem("About"); aboutMenuItem.setToolTipText("About..."); aboutMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { WebPanel aboutPanel = new WebPanel(); aboutPanel.add(new WebLabel("CardDAVSyncOutlook v0.04 (Beta)")); WebLinkLabel linkLabel = new WebLinkLabel(); linkLabel.setLink("https://github.com/somedevelopment/CardDAVSyncOutlook/"); linkLabel.setText("Visit the developer site"); aboutPanel.add(linkLabel, BorderLayout.SOUTH); WebOptionPane.showMessageDialog(frame, aboutPanel, "About", WebOptionPane.INFORMATION_MESSAGE); } }); helpMenu.add(aboutMenuItem); menubar.add(helpMenu); frame.setJMenuBar(menubar); // ui components and layout:... WebPanel northPanel = new WebPanel(); northPanel.setBorderColor(Color.LIGHT_GRAY); northPanel.setMargin(new Insets(0, 5, 0, 5)); northPanel.setLayout(new GridLayout(0, 1, 0, 0)); // ...URL... WebLabel lblHost = new WebLabel("CardDAV addressbook URL: "); lblHost.setVerticalAlignment(SwingConstants.BOTTOM); lblHost.setMargin(new Insets(0, 3, 0, 0)); lblHost.setFont(new Font("Calibri", Font.BOLD, 12)); northPanel.add(lblHost); urlField = new WebTextField(); // urlField.addMouseListener(new MouseAdapter() { //@Override //public void mouseExited(MouseEvent arg0) { // insecureSSLBox.setSelected(true); // urlField.setText("http" + urlField.getText().substring(5)); // Status.print("Activated insecure SSL"); urlField.setFont(new Font("Calibri", Font.PLAIN, 12)); //textHostURL.setColumns(10) urlField.setInputPrompt("http://<server-name>/owncloud/remote.php/carddav/addressbooks/<user_name>/<addr_book_name>"); urlField.setHideInputPromptOnFocus(false); northPanel.add(urlField); // ...account: credentials and login options... WebPanel accountPanel = new WebPanel(); accountPanel.setLayout(new FlowLayout(FlowLayout.LEADING)); WebLabel lblUsername = new WebLabel("Username:"); lblUsername.setFont(new Font("Calibri", Font.BOLD, 12)); accountPanel.add(lblUsername); usernameField = new WebTextField(); usernameField.setFont(new Font("Calibri", Font.PLAIN, 12)); usernameField.setColumns(10); accountPanel.add(usernameField); accountPanel.add(new WebSeparator()); WebLabel lblPassword = new WebLabel("Password:"); lblPassword.setFont(new Font("Calibri", Font.BOLD, 12)); accountPanel.add(lblPassword); passwordField = new WebPasswordField(); passwordField.setColumns(10); passwordField.setFont(new Font("Calibri", Font.PLAIN, 11)); passwordField.setEchoChar('*'); accountPanel.add(passwordField); accountPanel.add(new WebSeparator()); savePasswordBox = new WebCheckBox("Save Password"); savePasswordBox.setFont(new Font("Calibri", Font.BOLD, 12)); String tooltipText = "Save the password in configuration file as plaintext(!)"; TooltipManager.addTooltip(savePasswordBox, tooltipText); accountPanel.add(savePasswordBox); accountPanel.add(new WebSeparator()); insecureSSLBox = new WebCheckBox("Allow insecure SSL"); insecureSSLBox.setFont(new Font("Calibri", Font.BOLD, 12)); tooltipText = "Do not check the SSL certificate. Needed when the server uses a self-signed certificate"; TooltipManager.addTooltip(insecureSSLBox, tooltipText); accountPanel.add(insecureSSLBox); northPanel.add(accountPanel); // ...outlook contact folder... WebPanel contactFolderPanel = new WebPanel(); contactFolderPanel.setLayout(new FlowLayout(FlowLayout.LEADING)); WebLabel contactFolderLabel = new WebLabel("Outlook Folder: "); contactFolderLabel.setFont(new Font("Calibri", Font.BOLD, 12)); contactFolderPanel.add(contactFolderLabel); contactFolderBox = new WebComboBox(); tooltipText = "The Outlook Contact Folder to sync with"; TooltipManager.addTooltip(contactFolderBox, tooltipText); contactFolderBox.addItem("Default"); contactFolderPanel.add(contactFolderBox); contactFolderPanel.add(new WebSeparator()); WebButton listContactFolderButton = new WebButton("Get list"); listContactFolderButton.setFont(new Font("Calibri", Font.BOLD, 12)); tooltipText = "Get a list of all Outlook Contact Folders"; TooltipManager.addTooltip(listContactFolderButton, tooltipText); listContactFolderButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO } }); contactFolderPanel.add(listContactFolderButton); northPanel.add(contactFolderPanel); // ...sync button and sync options... WebPanel runPanel = new WebPanel(); WebButton btnSync = new WebButton("Start Synchronization"); btnSync.setFont(new Font("Calibri", Font.BOLD, 12)); btnSync.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Userinterface.this.callSync(); } }); runPanel.add(btnSync, BorderLayout.CENTER); initModeBox = new WebCheckBox("Initialization Mode"); initModeBox.setFont(new Font("Calibri", Font.BOLD, 12)); tooltipText = "Compare contacts by all fields. Useful on the first run"; TooltipManager.addTooltip(initModeBox, tooltipText); runPanel.add(initModeBox, BorderLayout.EAST); northPanel.add(runPanel); frame.getContentPane().add(northPanel, BorderLayout.NORTH); // ... status text pane... textPane = new WebTextPane(); textPane.setFont(new Font("Calibri", Font.PLAIN, 12)); textPane.setEditable(false); docTextPane = textPane.getStyledDocument(); WebScrollPane scrollPane = new WebScrollPane(textPane); scrollPane.setDarkBorder(Color.LIGHT_GRAY); scrollPane.setBorderColor(Color.LIGHT_GRAY); frame.getContentPane().add(scrollPane, BorderLayout.CENTER); //textPane.getCaret(). DefaultCaret caret = (DefaultCaret) textPane.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); // ...number of contacts. WebPanel southPanel = new WebPanel(); frame.getContentPane().add(southPanel, BorderLayout.SOUTH); southPanel.setLayout(new FlowLayout(FlowLayout.LEADING)); WebLabel lblNumbersOfContacts = new WebLabel("# of loaded Contacts:"); southPanel.add(lblNumbersOfContacts); lblNumbersOfContacts.setFont(new Font("Calibri", Font.BOLD, 12)); southPanel.add(new WebSeparator()); lblContactNumbers = new WebLabel(""); southPanel.add(lblContactNumbers); lblContactNumbers.setFont(new Font("Calibri", Font.PLAIN, 12)); frame.getContentPane().setFocusTraversalPolicy( new FocusTraversalOnArray( new Component[]{ usernameField, passwordField, urlField, btnSync, textPane, scrollPane, lblHost, lblPassword, lblUsername } ) ); frame.setFocusTraversalPolicy( new FocusTraversalOnArray( new Component[]{ usernameField, passwordField, urlField, btnSync, textPane, lblHost, lblPassword, frame.getContentPane(), scrollPane, lblUsername } ) ); //Load config Status.print("Load Config"); Config config = Config.getInstance(); usernameField.setText(config.getString(Config.ACC_USER, "")); passwordField.setText(config.getString(Config.ACC_PASS, "")); urlField.setText(config.getString(Config.ACC_URL, "")); insecureSSLBox.setSelected(config.getBoolean(Config.ACC_SSL, false)); savePasswordBox.setSelected(config.getBoolean(Config.ACC_SAVE_PASS, false)); this.setTray(); } public void setVisible() { frame.setVisible(true); } public void setContactNumbers(String text) { lblContactNumbers.setText(text); } public void runAndShutDown() { this.callSync(); this.shutdown(); } private void callSync() { // options from gui components String url = urlField.getText().trim(); String username = usernameField.getText().trim(); String password = String.valueOf(passwordField.getPassword()).trim(); boolean insecureSSL = insecureSSLBox.isSelected(); boolean initMode = initModeBox.isSelected(); // options from config Config config = Config.getInstance(); boolean closeOutlook = config.getBoolean(Config.GLOB_CLOSE, false); boolean clearNumbers = config.getBoolean(Config.GLOB_CORRECT_NUMBERS, false); String region = config.getString(Config.GLOB_REGION_CODE, ""); control.syncContacts(url, clearNumbers, region, username, password, insecureSSL, closeOutlook, initMode); // TODO, for testing a appointments sync //control.syncAppointments(); } private void saveConfig() { Config config = Config.getInstance(); config.setProperty(Config.ACC_USER, usernameField.getText()); if (savePasswordBox.isSelected()) config.setProperty(Config.ACC_PASS, new String(passwordField.getPassword())); config.setProperty(Config.ACC_URL, urlField.getText()); config.setProperty(Config.ACC_SSL, insecureSSLBox.isSelected()); config.setProperty(Config.ACC_SAVE_PASS, savePasswordBox.isSelected()); config.saveToFile(); Status.print("Config Saved"); } private void toggleState() { if (frame.getState() == Frame.NORMAL) { frame.setState(Frame.ICONIFIED); frame.setVisible(false); } else { frame.setState(Frame.NORMAL); frame.setVisible(true); frame.toFront(); } } void shutdown() { this.saveConfig(); frame.setVisible(false); frame.dispose(); control.shutdown(); } private void setTray() { if (!SystemTray.isSupported()) { System.out.println("tray icon not supported"); return; } // load image Image image = getImage("dav_sync_outlook.png"); final WebPopupMenu popup = new WebPopupMenu(); WebMenuItem syncItem = new WebMenuItem("Sync"); syncItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Userinterface.this.callSync(); } }); popup.add(syncItem); WebMenuItem quitItem = new WebMenuItem("Quit"); quitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Userinterface.this.shutdown(); } }); popup.add(quitItem); // workaround: hidden dialog, so that the popup menu disappears when // focus is lost /* Initialize the hidden dialog as a headless, titleless dialog window */ final WebDialog hiddenDialog = new WebDialog (); hiddenDialog.setUndecorated(true); // create an action listener to listen for default action executed on the tray icon MouseListener listener = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { check(e); } @Override public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) Userinterface.this.toggleState(); else check(e); } private void check(MouseEvent e) { if (!e.isPopupTrigger()) return; hiddenDialog.setVisible(true); // TODO ugly // Weblaf 1.28 doesn't support popups outside of a frame, this // is a workaround popup.setLocation(e.getX() - 20, e.getY() - 40); // this is wrong, but a TrayIcon is not a component popup.setInvoker(hiddenDialog); popup.setCornerWidth(0); popup.setVisible(true); } }; TrayIcon trayIcon = new TrayIcon(image, "CardDAVSyncOutlook" /*, popup*/); trayIcon.setImageAutoSize(true); trayIcon.addMouseListener(listener); SystemTray tray = SystemTray.getSystemTray(); try { tray.add(trayIcon); } catch (AWTException e) { e.printStackTrace(); } } public static void resetTextPane() { textPane.setText(""); } public static void setTextInTextPane(String strText) { try { if (docTextPane.getLength() > 0) { docTextPane.insertString(docTextPane.getLength(), strText + "\n", null); } else { docTextPane.insertString(0, strText + "\n", null); } } catch (BadLocationException e) { e.printStackTrace(); } } static Image getImage(String fileName) { Path filePath = Paths.get(RES_PATH, fileName); URL imageUrl = ClassLoader.getSystemResource(filePath.toString()); if (imageUrl == null) { System.out.println("can't find image resource"); return new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); } return Toolkit.getDefaultToolkit().createImage(imageUrl); } }
package com.phoenixie.minigame; import java.io.InputStream; import java.io.OutputStream; import java.util.Random; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.input.GestureDetector; import com.badlogic.gdx.input.GestureDetector.GestureListener; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.ButtonGroup; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.badlogic.gdx.utils.Timer; import com.badlogic.gdx.utils.Timer.Task; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.phoenixie.minigame.utils.Queue; public class MiniGame extends Game implements GestureListener { static final int CHIFFRE_MAX = 16; static final int CADRE_WIDTH = 6; static final int LINE_WIDTH = 3; static final int TABLE_WIDTH = 760; static final int FONT_SIZE = 48; static final int SCREEN_WIDTH = 800; static final int SCREEN_HEIGHT = 1280; static final float ASPECT_RATIO = (float) SCREEN_WIDTH / (float) SCREEN_HEIGHT; static final int BUTTON_UNDO = 0; static final int BUTTON_RESET = 1; static final int BUTTON_RESUME = 2; static final int BUTTON_SETTINGS = 3; static final int IMG_WIDTH = 128; static final int BUTTON_WIDTH = 240; static final int BUTTON_HEIGHT = 80; static final int BOTTOM_SPACE = 150; static final Color COLEUR_BACKGROUND = new Color(0.96875f, 0.9453125f, 0.8515625f, 1); static final Color COLEUR_CADRE = new Color(0.77734375f, 0.68359375f, 0.73828125f, 1); private OrthographicCamera camera; private SpriteBatch batch; private Skin skin; private BitmapFont font; private Texture chiffreImage; private TextureRegion[] chiffres; private Texture photoImage; private TextureRegion[] photos; private TextureRegion[] currImages; private ShapeRenderer renderer; private Rectangle viewport; private Texture buttonImage; private ImageButton buttonReset; private ImageButton buttonUndo; private ImageButton buttonResume; private ImageButton buttonSettings; private Stage stage; private CheckBox checkChiffres; private CheckBox checkPhotos; private CheckBox checkTable44; private CheckBox checkTable55; private CheckBox checkTable66; private Dialog dialogSettings; private int boiteHorzCount = 5; private int boiteVertCount = 5; private int tableWidth = 0; private int tableHeight = 0; private int boiteWidth = IMG_WIDTH; enum Direction { UP, DOWN, LEFT, RIGHT } enum BoiteType { CHIFFRES, PHOTOS } private static class Pos { public int x; public int y; } private static class GameState { public int boiteHorzCount; public int boiteVertCount; public int gameCount; public long gameScore; public long gameTime; public int[][][] gameEtapes; public int[][] chiffreTable; } private static class Settings { public BoiteType boiteType = BoiteType.PHOTOS; public int boiteHorzCount = 5; public int boiteVertCount = 5; }; private Pos tableVertex; private Pos tableLeftBottom; private Pos tableRightTop; private Pos[][] boitesPos; private int[][] chiffreTable; private Queue etapeQueue; private int gameCount; private long gameScore; private long gameTime; private long gameStartTime; private int[][][] gameEtapeBuffer; private GameState gameState = new GameState(); private boolean gameLoaded = false; private Settings settings = new Settings(); private Kryo kryo; private Pos[] videBoites; private int videBoitesCount = 0; private static Random random = new Random(System.currentTimeMillis()); @Override public void create() { // Gdx.graphics.setContinuousRendering(false); Gdx.graphics.requestRendering(); Texture.setEnforcePotImages(false); stage = new Stage(); etapeQueue = new Queue(); gameEtapeBuffer = new int[etapeQueue.capacity()][][]; kryo = new Kryo(); camera = new OrthographicCamera(SCREEN_WIDTH, SCREEN_HEIGHT); camera.position.set(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0); stage.setCamera(camera); batch = new SpriteBatch(); skin = new Skin(Gdx.files.internal("data/uiskin.json")); font = new BitmapFont(Gdx.files.internal("data/fonts/fonts.fnt"), Gdx.files.internal("data/fonts/fonts.png"), false); renderer = new ShapeRenderer(); chiffreImage = new Texture(Gdx.files.internal("data/chiffres.png")); chiffres = new TextureRegion[CHIFFRE_MAX]; for (int i = 0; i < CHIFFRE_MAX; ++i) { chiffres[i] = new TextureRegion(chiffreImage, i * IMG_WIDTH, 0, IMG_WIDTH, IMG_WIDTH); } photoImage = new Texture(Gdx.files.internal("data/photos.png")); photos = new TextureRegion[CHIFFRE_MAX]; for (int i = 0; i < CHIFFRE_MAX; ++i) { photos[i] = new TextureRegion(photoImage, i * IMG_WIDTH, 0, IMG_WIDTH, IMG_WIDTH); } tableVertex = new Pos(); tableVertex.x = (SCREEN_WIDTH - TABLE_WIDTH) / 2; tableVertex.y = BOTTOM_SPACE; tableRightTop = new Pos(); Gdx.input.setInputProcessor(new InputMultiplexer(stage, new GestureDetector(0.0f, 0.0f, 0.0f, 5f, this) { private boolean wrongStart = false; @Override public boolean touchDown(int x, int y, int pointer, int button) { Vector3 touchPos = new Vector3(x, y, 0); camera.unproject(touchPos); if (touchPos.x < tableLeftBottom.x || touchPos.x > tableRightTop.x) { wrongStart = true; return false; } if (touchPos.y < tableLeftBottom.y || touchPos.y > tableRightTop.y) { wrongStart = true; return false; } wrongStart = false; return super.touchDown((float) x, (float) y, pointer, button); } @Override public boolean touchDragged(int x, int y, int pointer) { if (wrongStart) { return false; } return super .touchDragged((float) x, (float) y, pointer); } @Override public boolean touchUp(int x, int y, int pointer, int button) { if (wrongStart) { return false; } return super.touchUp((float) x, (float) y, pointer, button); } })); loadSettings(); if (settings.boiteType == BoiteType.CHIFFRES) { currImages = chiffres; } else if (settings.boiteType == BoiteType.PHOTOS) { currImages = photos; } changeTableSize(settings.boiteHorzCount); loadGame(); drawButtons(); createDialogSettings(); if (!gameLoaded) { buttonResume.setVisible(false); } resetGame(); Timer.schedule(new Task() { @Override public void run() { Gdx.graphics.requestRendering(); } }, 0f, 0.5f); } private void changeTableSize(int size) { boiteHorzCount = boiteVertCount = size; boitesPos = new Pos[boiteHorzCount][boiteVertCount]; chiffreTable = new int[boiteHorzCount][boiteVertCount]; videBoites = new Pos[boiteHorzCount * boiteVertCount]; for (int i = 0; i < boiteHorzCount * boiteVertCount; ++i) { videBoites[i] = new Pos(); } videBoitesCount = 0; tableWidth = TABLE_WIDTH; boiteWidth = (tableWidth - 2 * CADRE_WIDTH - (boiteHorzCount - 1) * LINE_WIDTH) / boiteHorzCount; tableHeight = boiteVertCount * boiteWidth + (boiteVertCount - 1) * LINE_WIDTH + 2 * CADRE_WIDTH; int yPos = tableVertex.y + CADRE_WIDTH; for (int j = 0; j < boiteVertCount; ++j) { int xPos = tableVertex.x + CADRE_WIDTH; for (int i = 0; i < boiteHorzCount; ++i) { boitesPos[i][boiteVertCount - 1 - j] = new Pos(); boitesPos[i][boiteVertCount - 1 - j].x = xPos; boitesPos[i][boiteVertCount - 1 - j].y = yPos; xPos += boiteWidth + LINE_WIDTH; } yPos += boiteWidth + LINE_WIDTH; } tableLeftBottom = tableVertex; tableRightTop.x = tableVertex.x + tableWidth; tableRightTop.y = tableVertex.y + tableHeight; } private void saveSettings() { if (!Gdx.files.isLocalStorageAvailable()) { return; } FileHandle file = Gdx.files.local("settings"); OutputStream ostream = file.write(false); Output output = new Output(ostream); kryo.writeObject(output, settings); output.close(); } private void loadSettings() { if (!Gdx.files.isLocalStorageAvailable()) { return; } try { FileHandle file = Gdx.files.local("settings"); InputStream istream = file.read(); Input input = new Input(istream); settings = kryo.readObject(input, Settings.class); input.close(); } catch (Exception e) { e.printStackTrace(); return; } } private void saveGame() { if (!Gdx.files.isLocalStorageAvailable()) { return; } int etapeCount = etapeQueue.dump(gameEtapeBuffer); FileHandle file = Gdx.files.local("gamedata"); OutputStream ostream = file.write(false); Output output = new Output(ostream); gameState.boiteHorzCount = boiteHorzCount; gameState.boiteVertCount = boiteVertCount; gameState.gameCount = gameCount; gameState.gameScore = gameScore; gameState.gameTime = gameTime; gameState.chiffreTable = chiffreTable; gameState.gameEtapes = gameEtapeBuffer; kryo.writeObject(output, gameState); output.close(); } private boolean loadGame() { gameLoaded = false; if (!Gdx.files.isLocalStorageAvailable()) { return false; } try { FileHandle file = Gdx.files.local("gamedata"); InputStream istream = file.read(); Input input = new Input(istream); gameState = kryo.readObject(input, GameState.class); input.close(); if (gameState.gameCount == 0) { return false; } gameLoaded = true; } catch (Exception e) { e.printStackTrace(); return false; } return true; } private void resumeGame() { if (boiteHorzCount != gameState.boiteHorzCount) { changeTableSize(gameState.boiteHorzCount); } resetGame(); gameCount = gameState.gameCount; gameScore = gameState.gameScore; gameTime = gameState.gameTime; chiffreTable = gameState.chiffreTable; for (int i = 0; i < gameState.gameEtapes.length; ++i) { if (gameState.gameEtapes[i] == null) { break; } etapeQueue.enqueue(gameState.gameEtapes[i]); } if (!etapeQueue.isEmpty()) { buttonUndo.setVisible(true); buttonReset.setVisible(true); } Gdx.graphics.requestRendering(); } private void resetGame() { for (int j = 0; j < boiteVertCount; ++j) { for (int i = 0; i < boiteHorzCount; ++i) { chiffreTable[i][j] = -1; } } gameCount = 0; gameScore = 0; gameTime = 0; gameStartTime = System.currentTimeMillis(); etapeQueue.clear(); buttonUndo.setVisible(false); buttonReset.setVisible(false); generateChiffre(); generateChiffre(); shufflePhotos(); Gdx.graphics.requestRendering(); } private void drawStat() { long currTime = System.currentTimeMillis(); long delta = currTime - gameStartTime; gameTime += delta; gameStartTime = currTime; currTime = gameTime / 1000; int seconds = (int) (currTime % 60); currTime /= 60; int minutes = (int) (currTime % 60); int hours = (int) (currTime / 60); font.setColor(0f, 0f, 0f, 1f); font.draw(batch, "Points: " + gameScore, 20, SCREEN_HEIGHT - FONT_SIZE - 30); font.draw(batch, "Temps: " + hours + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds), 20, SCREEN_HEIGHT - FONT_SIZE - 100); font.draw(batch, "Tours: " + gameCount, SCREEN_WIDTH / 2, SCREEN_HEIGHT - FONT_SIZE - 100); } private void drawCadre() { renderer.begin(ShapeType.FilledRectangle); renderer.setColor(COLEUR_CADRE); renderer.filledRect(tableVertex.x, tableVertex.y, tableWidth, CADRE_WIDTH); renderer.filledRect(tableVertex.x, tableVertex.y, CADRE_WIDTH, tableHeight); renderer.filledRect(tableVertex.x + tableWidth - CADRE_WIDTH, tableVertex.y, CADRE_WIDTH, tableHeight); renderer.filledRect(tableVertex.x, tableVertex.y + tableHeight - CADRE_WIDTH, tableWidth, CADRE_WIDTH); int linepos = CADRE_WIDTH + boiteWidth; for (int i = 0; i < boiteHorzCount - 1; ++i) { renderer.filledRect(tableVertex.x + linepos, tableVertex.y, LINE_WIDTH, tableHeight); linepos += LINE_WIDTH + boiteWidth; } linepos = CADRE_WIDTH + boiteWidth; for (int i = 0; i < boiteVertCount - 1; ++i) { renderer.filledRect(tableVertex.x, tableVertex.y + linepos, tableWidth, LINE_WIDTH); linepos += LINE_WIDTH + boiteWidth; } renderer.end(); } private void drawButtons() { buttonImage = new Texture(Gdx.files.internal("data/buttons.png")); TextureRegion buttonUp = new TextureRegion(buttonImage, BUTTON_UNDO * BUTTON_WIDTH, 0, BUTTON_WIDTH, BUTTON_HEIGHT); TextureRegion buttonDown = new TextureRegion(buttonImage, BUTTON_UNDO * BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); ImageButtonStyle style = new ImageButtonStyle(); style.imageUp = new TextureRegionDrawable(buttonUp); style.imageDown = new TextureRegionDrawable(buttonDown); buttonUndo = new ImageButton(style); buttonUp = new TextureRegion(buttonImage, BUTTON_RESET * BUTTON_WIDTH, 0, BUTTON_WIDTH, BUTTON_HEIGHT); buttonDown = new TextureRegion(buttonImage, BUTTON_RESET * BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); style = new ImageButtonStyle(); style.imageUp = new TextureRegionDrawable(buttonUp); style.imageDown = new TextureRegionDrawable(buttonDown); buttonReset = new ImageButton(style); buttonUp = new TextureRegion(buttonImage, BUTTON_RESUME * BUTTON_WIDTH, 0, BUTTON_WIDTH, BUTTON_HEIGHT); buttonDown = new TextureRegion(buttonImage, BUTTON_RESUME * BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); style = new ImageButtonStyle(); style.imageUp = new TextureRegionDrawable(buttonUp); style.imageDown = new TextureRegionDrawable(buttonDown); buttonResume = new ImageButton(style); buttonUp = new TextureRegion(buttonImage, BUTTON_SETTINGS * BUTTON_WIDTH, 0, BUTTON_WIDTH, BUTTON_HEIGHT); buttonDown = new TextureRegion(buttonImage, BUTTON_SETTINGS * BUTTON_WIDTH, BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT); style = new ImageButtonStyle(); style.imageUp = new TextureRegionDrawable(buttonUp); style.imageDown = new TextureRegionDrawable(buttonDown); buttonSettings = new ImageButton(style); buttonUndo.setX(SCREEN_WIDTH - 20 - BUTTON_WIDTH); buttonUndo.setY(BOTTOM_SPACE + tableHeight + 40); buttonReset.setX(20); buttonReset.setY(BOTTOM_SPACE + tableHeight + 40); buttonResume.setX(20 + BUTTON_WIDTH + 20); buttonResume.setY(BOTTOM_SPACE + tableHeight + 40); buttonSettings.setX(SCREEN_WIDTH - 20 - BUTTON_WIDTH); buttonSettings.setY(SCREEN_HEIGHT - 30 - BUTTON_HEIGHT); stage.addActor(buttonUndo); stage.addActor(buttonReset); stage.addActor(buttonResume); stage.addActor(buttonSettings); buttonReset.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (boiteHorzCount != settings.boiteHorzCount) { changeTableSize(settings.boiteHorzCount); } resetGame(); } }); buttonUndo.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { int[][] load = (int[][]) etapeQueue.pop(); if (load != null) { chiffreTable = load; Gdx.graphics.requestRendering(); if (etapeQueue.isEmpty()) { buttonUndo.setVisible(false); } } } }); buttonResume.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { resumeGame(); buttonResume.setVisible(false); } }); buttonSettings.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { showSettings(); } }); } private void createDialogSettings() { checkChiffres = new CheckBox("Chiffres", skin); checkPhotos = new CheckBox("Photos", skin); ButtonGroup buttonTable = new ButtonGroup(checkChiffres, checkPhotos); buttonTable.setMaxCheckCount(1); buttonTable.setMinCheckCount(1); buttonTable.setUncheckLast(true); checkTable44 = new CheckBox("4 X 4", skin); checkTable55 = new CheckBox("5 X 5", skin); checkTable66 = new CheckBox("6 X 6", skin); ButtonGroup tableSize = new ButtonGroup(checkTable44, checkTable55, checkTable66); tableSize.setMaxCheckCount(1); tableSize.setMinCheckCount(1); tableSize.setUncheckLast(true); dialogSettings = new Dialog("Paramtre", skin, "dialog") { protected void result(Object object) { if (!(Boolean) object) { return; } if (checkChiffres.isChecked()) { if (settings.boiteType != BoiteType.CHIFFRES) { settings.boiteType = BoiteType.CHIFFRES; currImages = chiffres; Gdx.graphics.requestRendering(); } } else if (checkPhotos.isChecked()) { if (settings.boiteType != BoiteType.PHOTOS) { settings.boiteType = BoiteType.PHOTOS; currImages = photos; Gdx.graphics.requestRendering(); } } int tableSize = settings.boiteHorzCount; if (checkTable44.isChecked()) { tableSize = 4; } else if (checkTable55.isChecked()) { tableSize = 5; } else if (checkTable66.isChecked()) { tableSize = 6; } if (tableSize != settings.boiteHorzCount) { settings.boiteHorzCount = settings.boiteVertCount = tableSize; } saveSettings(); } }; dialogSettings.padTop(50).padBottom(50); dialogSettings.getContentTable().add(checkChiffres).width(225).colspan(3); dialogSettings.getContentTable().add(checkPhotos).width(225).colspan(3); dialogSettings.getContentTable().row(); dialogSettings.getContentTable().add(checkTable44).width(150).colspan(2).padTop(20); dialogSettings.getContentTable().add(checkTable55).width(150).colspan(2).padTop(20); dialogSettings.getContentTable().add(checkTable66).width(150).colspan(2).padTop(20); dialogSettings.getContentTable().row(); dialogSettings.getButtonTable().padTop(30); TextButton dbutton = new TextButton("OK", skin); dialogSettings.button(dbutton, true); dbutton = new TextButton("Annuler", skin); dialogSettings.button(dbutton, false); dialogSettings.invalidateHierarchy(); dialogSettings.invalidate(); dialogSettings.layout(); } private void showSettings() { if (settings.boiteType == BoiteType.CHIFFRES) { checkChiffres.setChecked(true); } else { checkPhotos.setChecked(true); } switch (settings.boiteHorzCount) { case 4: checkTable44.setChecked(true); break; case 5: checkTable55.setChecked(true); break; case 6: checkTable66.setChecked(true); break; } dialogSettings.show(stage); } @Override public void dispose() { chiffreImage.dispose(); batch.dispose(); renderer.dispose(); } @Override public void render() { super.render(); camera.update(); camera.apply(Gdx.gl10); Gdx.gl.glViewport((int) viewport.x, (int) viewport.y, (int) viewport.width, (int) viewport.height); Gdx.gl.glClearColor(COLEUR_BACKGROUND.r, COLEUR_BACKGROUND.g, COLEUR_BACKGROUND.b, COLEUR_BACKGROUND.a); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); batch.setProjectionMatrix(camera.combined); batch.begin(); font.setColor(1f, 1f, 1f, 0.8f); for (int i = 0; i < boiteHorzCount; ++i) { for (int j = 0; j < boiteVertCount; ++j) { int cur = chiffreTable[i][j]; if (cur == -1) { continue; } batch.draw(currImages[cur], boitesPos[i][j].x, boitesPos[i][j].y, boiteWidth, boiteWidth); if (currImages == photos) { font.draw(batch, "" + (cur + 1), boitesPos[i][j].x + 10, boitesPos[i][j].y + FONT_SIZE); } } } drawStat(); batch.end(); renderer.setProjectionMatrix(camera.combined); drawCadre(); stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1f / 30f)); stage.draw(); if (Gdx.input.isKeyPressed(Keys.LEFT)) move(Direction.LEFT); else if (Gdx.input.isKeyPressed(Keys.RIGHT)) move(Direction.RIGHT); else if (Gdx.input.isKeyPressed(Keys.UP)) move(Direction.UP); else if (Gdx.input.isKeyPressed(Keys.DOWN)) move(Direction.DOWN); } @Override public void resize(int width, int height) { float aspectRatio = (float) width / (float) height; float scale = 1f; Vector2 crop = new Vector2(0f, 0f); if (aspectRatio > ASPECT_RATIO) { scale = (float) height / (float) SCREEN_HEIGHT; crop.x = (width - SCREEN_WIDTH * scale) / 2f; } else if (aspectRatio < ASPECT_RATIO) { scale = (float) width / (float) SCREEN_WIDTH; crop.y = (height - SCREEN_HEIGHT * scale) / 2f; } else { scale = (float) width / (float) SCREEN_WIDTH; } float w = (float) SCREEN_WIDTH * scale; float h = (float) SCREEN_HEIGHT * scale; viewport = new Rectangle(crop.x, crop.y, w, h); } @Override public void pause() { } @Override public void resume() { gameStartTime = System.currentTimeMillis(); } private void shufflePhotos() { for (int i = 0; i < photos.length; i++) { int randomPosition = random.nextInt(photos.length); TextureRegion temp = photos[i]; photos[i] = photos[randomPosition]; photos[randomPosition] = temp; } } private void calVideBoites() { videBoitesCount = 0; for (int i = 0; i < boiteHorzCount; ++i) { for (int j = 0; j < boiteVertCount; ++j) { if (chiffreTable[i][j] == -1) { videBoites[videBoitesCount].x = i; videBoites[videBoitesCount].y = j; ++videBoitesCount; } } } } private void generateChiffre() { calVideBoites(); if (videBoitesCount == 0) { return; } int pos = random.nextInt(videBoitesCount); Pos boite = videBoites[pos]; chiffreTable[boite.x][boite.y] = random.nextInt(20) == 0 ? 1 : 0; } private void move(Direction direction) { int[][] bak = chiffreTable.clone(); for (int i = 0; i < chiffreTable.length; ++i) { bak[i] = bak[i].clone(); } int score = 0; if (direction == Direction.UP) { score = moveUp(); } else if (direction == Direction.DOWN) { score = moveDown(); } else if (direction == Direction.LEFT) { score = moveLeft(); } else if (direction == Direction.RIGHT) { score = moveRight(); } if (score >= 0) { ++gameCount; gameScore += score; generateChiffre(); etapeQueue.enqueue(bak); buttonUndo.setVisible(true); buttonReset.setVisible(true); buttonResume.setVisible(false); saveGame(); } } private int moveRight() { boolean moved = false; int score = 0; for (int j = 0; j < boiteVertCount; ++j) { int gap = 0; boolean merged = false; if (chiffreTable[boiteHorzCount - 1][j] == -1) { gap = 1; } for (int i = boiteHorzCount - 1 - 1; i >= 0; --i) { if (chiffreTable[i][j] == -1) { ++gap; continue; } int cur = chiffreTable[i][j]; if (gap > 0) { chiffreTable[i + gap][j] = cur; chiffreTable[i][j] = -1; moved = true; } if (merged) { merged = false; continue; } int newi = i + gap; if (newi == boiteHorzCount - 1) { continue; } if (chiffreTable[newi + 1][j] == cur) { ++chiffreTable[newi + 1][j]; chiffreTable[newi][j] = -1; ++gap; moved = true; merged = true; score += (1 << (chiffreTable[newi + 1][j] + 1)); } } } if (!moved) { return -1; } return score; } private int moveLeft() { boolean moved = false; int score = 0; for (int j = 0; j < boiteVertCount; ++j) { int gap = 0; boolean merged = false; if (chiffreTable[0][j] == -1) { gap = 1; } for (int i = 1; i < boiteHorzCount; ++i) { if (chiffreTable[i][j] == -1) { ++gap; continue; } int cur = chiffreTable[i][j]; if (gap > 0) { chiffreTable[i - gap][j] = cur; chiffreTable[i][j] = -1; moved = true; } if (merged) { merged = false; continue; } int newi = i - gap; if (newi == 0) { continue; } if (chiffreTable[newi - 1][j] == cur) { ++chiffreTable[newi - 1][j]; chiffreTable[newi][j] = -1; ++gap; moved = true; merged = true; score += (1 << (chiffreTable[newi - 1][j] + 1)); } } } if (!moved) { return -1; } return score; } private int moveDown() { boolean moved = false; int score = 0; for (int i = 0; i < boiteHorzCount; ++i) { int gap = 0; boolean merged = false; if (chiffreTable[i][boiteVertCount - 1] == -1) { gap = 1; } for (int j = boiteVertCount - 1 - 1; j >= 0; --j) { if (chiffreTable[i][j] == -1) { ++gap; continue; } int cur = chiffreTable[i][j]; if (gap > 0) { chiffreTable[i][j + gap] = cur; chiffreTable[i][j] = -1; moved = true; } if (merged) { merged = false; continue; } int newj = j + gap; if (newj == boiteVertCount - 1) { continue; } if (chiffreTable[i][newj + 1] == cur) { ++chiffreTable[i][newj + 1]; chiffreTable[i][newj] = -1; ++gap; moved = true; merged = true; score += (1 << (chiffreTable[i][newj + 1] + 1)); } } } if (!moved) { return -1; } return score; } private int moveUp() { boolean moved = false; int score = 0; for (int i = 0; i < boiteHorzCount; ++i) { int gap = 0; boolean merged = false; if (chiffreTable[i][0] == -1) { gap = 1; } for (int j = 1; j < boiteVertCount; ++j) { if (chiffreTable[i][j] == -1) { ++gap; continue; } int cur = chiffreTable[i][j]; if (gap > 0) { chiffreTable[i][j - gap] = cur; chiffreTable[i][j] = -1; moved = true; } if (merged) { merged = false; continue; } int newj = j - gap; if (newj == 0) { continue; } if (chiffreTable[i][newj - 1] == cur) { ++chiffreTable[i][newj - 1]; chiffreTable[i][newj] = -1; ++gap; moved = true; merged = true; score += (1 << (chiffreTable[i][newj - 1] + 1)); } } } if (!moved) { return -1; } return score; } @Override public boolean touchDown(float x, float y, int pointer, int button) { // TODO Auto-generated method stub return false; } @Override public boolean tap(float x, float y, int count, int button) { // TODO Auto-generated method stub return false; } @Override public boolean longPress(float x, float y) { // TODO Auto-generated method stub return false; } @Override public boolean fling(float velocityX, float velocityY, int button) { float x = Math.abs(velocityX); float y = Math.abs(velocityY); int comp = Float.compare(x, y); if (comp > 0) { if (velocityX > 0.0) { move(Direction.RIGHT); } else if (velocityX < 0.0) { move(Direction.LEFT); } else { return false; } } else { if (velocityY > 0.0) { move(Direction.DOWN); } else if (velocityY < 0.0) { move(Direction.UP); } else { return false; } } return true; } @Override public boolean pan(float x, float y, float deltaX, float deltaY) { return false; } @Override public boolean zoom(float initialDistance, float distance) { // TODO Auto-generated method stub return false; } @Override public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) { // TODO Auto-generated method stub return false; } }
//FILE: MMStudioMainFrame.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. //CVS: $Id$ package org.micromanager; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.Line; import ij.gui.Roi; import ij.process.ImageProcessor; import ij.process.ShortProcessor; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SpringLayout; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.event.AncestorEvent; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.MMCoreJ; import mmcorej.MMEventCallback; import mmcorej.StrVector; import org.json.JSONObject; import org.micromanager.acquisition.AcquisitionManager; import org.micromanager.api.Autofocus; import org.micromanager.api.DataProcessor; import org.micromanager.api.MMPlugin; import org.micromanager.api.MMTags; import org.micromanager.api.PositionList; import org.micromanager.api.ScriptInterface; import org.micromanager.api.MMListenerInterface; import org.micromanager.api.SequenceSettings; import org.micromanager.conf2.ConfiguratorDlg2; import org.micromanager.conf2.MMConfigFileException; import org.micromanager.conf2.MicroscopeModel; import org.micromanager.graph.GraphData; import org.micromanager.graph.GraphFrame; import org.micromanager.navigation.CenterAndDragListener; import org.micromanager.navigation.XYZKeyListener; import org.micromanager.navigation.ZWheelListener; import org.micromanager.utils.AutofocusManager; import org.micromanager.utils.ContrastSettings; import org.micromanager.utils.GUIColors; import org.micromanager.utils.GUIUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.TextUtils; import org.micromanager.utils.TooltipTextMaker; import org.micromanager.utils.WaitDialog; import bsh.EvalError; import bsh.Interpreter; import com.swtdesigner.SwingResourceManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.gui.Toolbar; import java.awt.*; import java.awt.dnd.DropTarget; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collections; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.*; import javax.swing.event.AncestorListener; import mmcorej.TaggedImage; import org.json.JSONException; import org.micromanager.acquisition.*; import org.micromanager.api.ImageCache; import org.micromanager.api.IAcquisitionEngine2010; import org.micromanager.graph.HistogramSettings; import org.micromanager.internalinterfaces.LiveModeListener; import org.micromanager.utils.DragDropUtil; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.FileDialogs.FileType; import org.micromanager.utils.HotKeysDialog; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMKeyDispatcher; import org.micromanager.utils.ReportingUtils; import org.micromanager.utils.UIMonitor; /* * Main panel and application class for the MMStudio. */ public class MMStudioMainFrame extends JFrame implements ScriptInterface { private static final String MICRO_MANAGER_TITLE = "Micro-Manager"; private static final long serialVersionUID = 3556500289598574541L; private static final String MAIN_FRAME_X = "x"; private static final String MAIN_FRAME_Y = "y"; private static final String MAIN_FRAME_WIDTH = "width"; private static final String MAIN_FRAME_HEIGHT = "height"; private static final String MAIN_FRAME_DIVIDER_POS = "divider_pos"; private static final String MAIN_EXPOSURE = "exposure"; private static final String MAIN_SAVE_METHOD = "saveMethod"; private static final String SYSTEM_CONFIG_FILE = "sysconfig_file"; private static final String OPEN_ACQ_DIR = "openDataDir"; private static final String SCRIPT_CORE_OBJECT = "mmc"; private static final String SCRIPT_ACQENG_OBJECT = "acq"; private static final String SCRIPT_GUI_OBJECT = "gui"; private static final String AUTOFOCUS_DEVICE = "autofocus_device"; private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage"; private static final String EXPOSURE_SETTINGS_NODE = "MainExposureSettings"; private static final String CONTRAST_SETTINGS_NODE = "MainContrastSettings"; private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000; private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000; // cfg file saving private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4} // GUI components private JComboBox comboBinning_; private JComboBox shutterComboBox_; private JTextField textFieldExp_; private JLabel labelImageDimensions_; private JToggleButton liveButton_; private JButton toAlbumButton_; private JCheckBox autoShutterCheckBox_; private MMOptions options_; private boolean runsAsPlugin_; private JCheckBoxMenuItem centerAndDragMenuItem_; private JButton snapButton_; private JButton autofocusNowButton_; private JButton autofocusConfigureButton_; private JToggleButton toggleShutterButton_; private GUIColors guiColors_; private GraphFrame profileWin_; private PropertyEditor propertyBrowser_; private CalibrationListDlg calibrationListDlg_; private AcqControlDlg acqControlWin_; private ReportProblemDialog reportProblemDialog_; private JMenu pluginMenu_; private ArrayList<PluginItem> plugins_; private List<MMListenerInterface> MMListeners_ = Collections.synchronizedList(new ArrayList<MMListenerInterface>()); private List<LiveModeListener> liveModeListeners_ = Collections.synchronizedList(new ArrayList<LiveModeListener>()); private List<Component> MMFrames_ = Collections.synchronizedList(new ArrayList<Component>()); private AutofocusManager afMgr_; private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg"; private ArrayList<String> MRUConfigFiles_; private static final int maxMRUCfgs_ = 5; private String sysConfigFile_; private String startupScriptFile_; private String sysStateFile_ = "MMSystemState.cfg"; private ConfigGroupPad configPad_; private LiveModeTimer liveModeTimer_; private GraphData lineProfileData_; // labels for standard devices private String cameraLabel_; private String zStageLabel_; private String shutterLabel_; private String xyStageLabel_; // applications settings private Preferences mainPrefs_; private Preferences systemPrefs_; private Preferences colorPrefs_; private Preferences exposurePrefs_; private Preferences contrastPrefs_; // MMcore private CMMCore core_; private AcquisitionWrapperEngine engine_; private PositionList posList_; private PositionListDlg posListDlg_; private String openAcqDirectory_ = ""; private boolean running_; private boolean configChanged_ = false; private StrVector shutters_ = null; private JButton saveConfigButton_; private ScriptPanel scriptPanel_; private org.micromanager.utils.HotKeys hotKeys_; private CenterAndDragListener centerAndDragListener_; private ZWheelListener zWheelListener_; private XYZKeyListener xyzKeyListener_; private AcquisitionManager acqMgr_; private static VirtualAcquisitionDisplay simpleDisplay_; private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN}; private int snapCount_ = -1; private boolean liveModeSuspended_; public Font defaultScriptFont_ = null; public static final String SIMPLE_ACQ = "Snap/Live Window"; public static FileType MM_CONFIG_FILE = new FileType("MM_CONFIG_FILE", "Micro-Manager Config File", "./MyScope.cfg", true, "cfg"); // Our instance private static MMStudioMainFrame gui_; // Callback private CoreEventCallback cb_; // Lock invoked while shutting down private final Object shutdownLock_ = new Object(); private JMenuBar menuBar_; private ConfigPadButtonPanel configPadButtonPanel_; private final JMenu switchConfigurationMenu_; private final MetadataPanel metadataPanel_; public static FileType MM_DATA_SET = new FileType("MM_DATA_SET", "Micro-Manager Image Location", System.getProperty("user.home") + "/Untitled", false, (String[]) null); private Thread acquisitionEngine2010LoadingThread = null; private Class<?> acquisitionEngine2010Class = null; private IAcquisitionEngine2010 acquisitionEngine2010 = null; private final JSplitPane splitPane_; private volatile boolean ignorePropertyChanges_; private AbstractButton setRoiButton_; private AbstractButton clearRoiButton_; private DropTarget dt_; // private ProcessorStackManager processorStackManager_; public ImageWindow getImageWin() { return getSnapLiveWin(); } @Override public ImageWindow getSnapLiveWin() { if (simpleDisplay_ == null) { return null; } return simpleDisplay_.getHyperImage().getWindow(); } public static VirtualAcquisitionDisplay getSimpleDisplay() { return simpleDisplay_; } public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException { simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name); } public void checkSimpleAcquisition() { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } int width = (int) core_.getImageWidth(); int height = (int) core_.getImageHeight(); int depth = (int) core_.getBytesPerPixel(); int bitDepth = (int) core_.getImageBitDepth(); int numCamChannels = (int) core_.getNumberOfCameraChannels(); try { if (acquisitionExists(SIMPLE_ACQ)) { if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width) || (getAcquisitionImageHeight(SIMPLE_ACQ) != height) || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth) || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth) || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window closeAcquisitionWindow(SIMPLE_ACQ); } } if (!acquisitionExists(SIMPLE_ACQ)) { openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true); if (numCamChannels > 1) { for (long i = 0; i < numCamChannels; i++) { String chName = core_.getCameraChannelName(i); int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB(); setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor)); setChannelName(SIMPLE_ACQ, (int) i, chName); } } initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels); getAcquisition(SIMPLE_ACQ).promptToSave(false); getAcquisition(SIMPLE_ACQ).toFront(); this.updateCenterAndDragListener(); } } catch (Exception ex) { ReportingUtils.showError(ex); } } public void checkSimpleAcquisition(TaggedImage image) { try { JSONObject tags = image.tags; int width = MDUtils.getWidth(tags); int height = MDUtils.getHeight(tags); int depth = MDUtils.getDepth(tags); int bitDepth = MDUtils.getBitDepth(tags); int numCamChannels = (int) core_.getNumberOfCameraChannels(); if (acquisitionExists(SIMPLE_ACQ)) { if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width) || (getAcquisitionImageHeight(SIMPLE_ACQ) != height) || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth) || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth) || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window closeAcquisitionWindow(SIMPLE_ACQ); // Seems that closeAcquisitionWindow also closes the acquisition... //closeAcquisition(SIMPLE_ACQ); } } if (!acquisitionExists(SIMPLE_ACQ)) { openAcquisition(SIMPLE_ACQ, "", 1, numCamChannels, 1, true); if (numCamChannels > 1) { for (long i = 0; i < numCamChannels; i++) { String chName = core_.getCameraChannelName(i); int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB(); setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor)); setChannelName(SIMPLE_ACQ, (int) i, chName); } } initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels); getAcquisition(SIMPLE_ACQ).promptToSave(false); getAcquisition(SIMPLE_ACQ).toFront(); this.updateCenterAndDragListener(); } } catch (Exception ex) { ReportingUtils.showError(ex); } } public void saveChannelColor(String chName, int rgb) { if (colorPrefs_ != null) { colorPrefs_.putInt("Color_" + chName, rgb); } } public Color getChannelColor(String chName, int defaultColor) { if (colorPrefs_ != null) { defaultColor = colorPrefs_.getInt("Color_" + chName, defaultColor); } return new Color(defaultColor); } @Override public void enableRoiButtons(final boolean enabled) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { setRoiButton_.setEnabled(enabled); clearRoiButton_.setEnabled(enabled); } }); } public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException { ImageCache ic = display.getImageCache(); int channels = ic.getSummaryMetadata().getInt("Channels"); if (channels == 1) { //RGB or monchrome addToAlbum(ic.getImage(0, 0, 0, 0), ic.getDisplayAndComments()); } else { //multicamera for (int i = 0; i < channels; i++) { addToAlbum(ic.getImage(i, 0, 0, 0), ic.getDisplayAndComments()); } } } private void createActiveShutterChooser(JPanel topPanel) { createLabel("Shutter", false, topPanel, 111, 73, 158, 86); shutterComboBox_ = new JComboBox(); shutterComboBox_.setName("Shutter"); shutterComboBox_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) { core_.setShutterDevice((String) shutterComboBox_.getSelectedItem()); } } catch (Exception e) { ReportingUtils.showError(e); } } }); GUIUtils.addWithEdges(topPanel, shutterComboBox_, 170, 70, 275, 92); } private void createBinningChooser(JPanel topPanel) { createLabel("Binning", false, topPanel, 111, 43, 199, 64); comboBinning_ = new JComboBox(); comboBinning_.setName("Binning"); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { changeBinning(); } }); GUIUtils.addWithEdges(topPanel, comboBinning_, 200, 43, 275, 66); } private void createExposureField(JPanel topPanel) { createLabel("Exposure [ms]", false, topPanel, 111, 23, 198, 39); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent fe) { synchronized(shutdownLock_) { if (core_ != null) setExposure(); } } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setExposure(); } }); GUIUtils.addWithEdges(topPanel, textFieldExp_, 203, 21, 276, 40); } private void toggleAutoShutter() { shutterLabel_ = core_.getShutterDevice(); if (shutterLabel_.length() == 0) { toggleShutterButton_.setEnabled(false); } else { if (autoShutterCheckBox_.isSelected()) { try { core_.setAutoShutter(true); core_.setShutterOpen(false); toggleShutterButton_.setSelected(false); toggleShutterButton_.setText("Open"); toggleShutterButton_.setEnabled(false); } catch (Exception e2) { ReportingUtils.logError(e2); } } else { try { core_.setAutoShutter(false); core_.setShutterOpen(false); toggleShutterButton_.setEnabled(true); toggleShutterButton_.setText("Open"); } catch (Exception exc) { ReportingUtils.logError(exc); } } } } private void createShutterControls(JPanel topPanel) { autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggleAutoShutter(); } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); GUIUtils.addWithEdges(topPanel, autoShutterCheckBox_, 107, 96, 199, 119); toggleShutterButton_ = (JToggleButton) GUIUtils.createButton(true, "toggleShutterButton", "Open", "Open/close the shutter", new Runnable() { public void run() { toggleShutter(); } }, null, topPanel, 203, 96, 275, 117); // Shutter button } private void createCameraSettingsWidgets(JPanel topPanel) { createLabel("Camera settings", true, topPanel, 109, 2, 211, 22); createExposureField(topPanel); createBinningChooser(topPanel); createActiveShutterChooser(topPanel); createShutterControls(topPanel); } private void createConfigurationControls(JPanel topPanel) { createLabel("Configuration settings", true, topPanel, 280, 2, 430, 22); saveConfigButton_ = (JButton) GUIUtils.createButton(false, "saveConfigureButton", "Save", "Save current presets to the configuration file", new Runnable() { public void run() { saveConfigPresets(); } }, null, topPanel, -80, 2, -5, 20); configPad_ = new ConfigGroupPad(); configPadButtonPanel_ = new ConfigPadButtonPanel(); configPadButtonPanel_.setConfigPad(configPad_); configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance()); configPad_.setFont(new Font("", Font.PLAIN, 10)); GUIUtils.addWithEdges(topPanel, configPad_, 280, 21, -4, -44); GUIUtils.addWithEdges(topPanel, configPadButtonPanel_, 280, -40, -4, -20); } private void createMainButtons(JPanel topPanel) { snapButton_ = (JButton) GUIUtils.createButton(false, "Snap", "Snap", "Snap single image", new Runnable() { public void run() { doSnap(); } }, "camera.png", topPanel, 7, 4, 95, 25); liveButton_ = (JToggleButton) GUIUtils.createButton(true, "Live", "Live", "Continuous live view", new Runnable() { public void run() { enableLiveMode(!isLiveModeOn()); } }, "camera_go.png", topPanel, 7, 26, 95, 47); toAlbumButton_ = (JButton) GUIUtils.createButton(false, "Album", "Album", "Acquire single frame and add to an album", new Runnable() { public void run() { snapAndAddToImage5D(); } }, "camera_plus_arrow.png", topPanel, 7, 48, 95, 69); /* MDA Button = */ GUIUtils.createButton(false, "Multi-D Acq.", "Multi-D Acq.", "Open multi-dimensional acquisition window", new Runnable() { public void run() { openAcqControlDialog(); } }, "film.png", topPanel, 7, 70, 95, 91); /* Refresh = */ GUIUtils.createButton(false, "Refresh", "Refresh", "Refresh all GUI controls directly from the hardware", new Runnable() { public void run() { core_.updateSystemStateCache(); updateGUI(true); } }, "arrow_refresh.png", topPanel, 7, 92, 95, 113); } private static MetadataPanel createMetadataPanel(JPanel bottomPanel) { MetadataPanel metadataPanel = new MetadataPanel(); GUIUtils.addWithEdges(bottomPanel, metadataPanel, 0, 0, 0, 0); metadataPanel.setBorder(BorderFactory.createEmptyBorder()); return metadataPanel; } private void createPleaLabel(JPanel topPanel) { JLabel citePleaLabel = new JLabel("<html>Please <a href=\"http://micro-manager.org\">cite Micro-Manager</a> so funding will continue!</html>"); citePleaLabel.setFont(new Font("Arial", Font.PLAIN, 11)); GUIUtils.addWithEdges(topPanel, citePleaLabel, 7, 119, 270, 139); class Pleader extends Thread{ Pleader(){ super("pleader"); } @Override public void run(){ try { ij.plugin.BrowserLauncher.openURL("https://micro-manager.org/wiki/Citing_Micro-Manager"); } catch (IOException e1) { ReportingUtils.showError(e1); } } } citePleaLabel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Pleader p = new Pleader(); p.start(); } }); // add a listener to the main ImageJ window to catch it quitting out on us if (ij.IJ.getInstance() != null) { ij.IJ.getInstance().addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeSequence(true); }; }); } } private JSplitPane createSplitPane(int dividerPos) { JPanel topPanel = new JPanel(); JPanel bottomPanel = new JPanel(); topPanel.setLayout(new SpringLayout()); topPanel.setMinimumSize(new Dimension(580, 195)); bottomPanel.setLayout(new SpringLayout()); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, topPanel, bottomPanel); splitPane.setBorder(BorderFactory.createEmptyBorder()); splitPane.setDividerLocation(dividerPos); splitPane.setResizeWeight(0.0); return splitPane; } private void createTopPanelWidgets(JPanel topPanel) { createMainButtons(topPanel); createCameraSettingsWidgets(topPanel); createPleaLabel(topPanel); createUtilityButtons(topPanel); createConfigurationControls(topPanel); labelImageDimensions_ = createLabel("", false, topPanel, 5, -20, 0, 0); } private void createUtilityButtons(JPanel topPanel) { // ROI createLabel("ROI", true, topPanel, 8, 140, 71, 154); setRoiButton_ = GUIUtils.createButton(false, "setRoiButton", null, "Set Region Of Interest to selected rectangle", new Runnable() { public void run() { setROI(); } }, "shape_handles.png", topPanel, 7, 154, 37, 174); clearRoiButton_ = GUIUtils.createButton(false, "clearRoiButton", null, "Reset Region of Interest to full frame", new Runnable() { public void run() { clearROI(); } }, "arrow_out.png", topPanel, 40, 154, 70, 174); // Zoom createLabel("Zoom", true, topPanel, 81, 140, 139, 154); GUIUtils.createButton(false, "zoomInButton", null, "Zoom in", new Runnable() { public void run() { zoomIn(); } }, "zoom_in.png", topPanel, 80, 154, 110, 174); GUIUtils.createButton(false, "zoomOutButton", null, "Zoom out", new Runnable() { public void run() { zoomOut(); } }, "zoom_out.png", topPanel, 113, 154, 143, 174); // Profile createLabel("Profile", true, topPanel, 154, 140, 217, 154); GUIUtils.createButton(false, "lineProfileButton", null, "Open line profile window (requires line selection)", new Runnable() { public void run() { openLineProfileWindow(); } }, "chart_curve.png", topPanel, 153, 154, 183, 174); // Autofocus createLabel("Autofocus", true, topPanel, 194, 140, 276, 154); autofocusNowButton_ = (JButton) GUIUtils.createButton(false, "autofocusNowButton", null, "Autofocus now", new Runnable() { public void run() { autofocusNow(); } }, "find.png", topPanel, 193, 154, 223, 174); autofocusConfigureButton_ = (JButton) GUIUtils.createButton(false, "autofocusConfigureButton", null, "Set autofocus options", new Runnable() { public void run() { showAutofocusDialog(); } }, "wrench_orange.png", topPanel, 226, 154, 256, 174); } private void initializeFileMenu() { JMenu fileMenu = GUIUtils.createMenuInMenuBar(menuBar_, "File"); GUIUtils.addMenuItem(fileMenu, "Open (Virtual)...", null, new Runnable() { public void run() { new Thread() { @Override public void run() { openAcquisitionData(false); } }.start(); } }); GUIUtils.addMenuItem(fileMenu, "Open (RAM)...", null, new Runnable() { public void run() { new Thread() { @Override public void run() { openAcquisitionData(true); } }.start(); } }); fileMenu.addSeparator(); GUIUtils.addMenuItem(fileMenu, "Exit", null, new Runnable() { public void run() { closeSequence(false); } }); } private void initializeHelpMenu() { final JMenu helpMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Help"); GUIUtils.addMenuItem(helpMenu, "User's Guide", null, new Runnable() { public void run() { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_User%27s_Guide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); GUIUtils.addMenuItem(helpMenu, "Configuration Guide", null, new Runnable() { public void run() { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/wiki/Micro-Manager_Configuration_Guide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) { GUIUtils.addMenuItem(helpMenu, "Register your copy of Micro-Manager...", null, new Runnable() { public void run() { try { RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_); regDlg.setVisible(true); } catch (Exception e1) { ReportingUtils.showError(e1); } } }); } GUIUtils.addMenuItem(helpMenu, "Report Problem...", null, new Runnable() { public void run() { if (null == reportProblemDialog_) { reportProblemDialog_ = new ReportProblemDialog(core_, MMStudioMainFrame.this, options_); MMStudioMainFrame.this.addMMBackgroundListener(reportProblemDialog_); reportProblemDialog_.setBackground(guiColors_.background.get(options_.displayBackground_)); } reportProblemDialog_.setVisible(true); } }); GUIUtils.addMenuItem(helpMenu, "About Micromanager", null, new Runnable() { public void run() { MMAboutDlg dlg = new MMAboutDlg(); String versionInfo = "MM Studio version: " + MMVersion.VERSION_STRING; versionInfo += "\n" + core_.getVersionInfo(); versionInfo += "\n" + core_.getAPIVersionInfo(); versionInfo += "\nUser: " + core_.getUserId(); versionInfo += "\nHost: " + core_.getHostName(); dlg.setVersionInfo(versionInfo); dlg.setVisible(true); } }); menuBar_.validate(); } private void initializeToolsMenu() { // Tools menu final JMenu toolsMenu = GUIUtils.createMenuInMenuBar(menuBar_, "Tools"); GUIUtils.addMenuItem(toolsMenu, "Refresh GUI", "Refresh all GUI controls directly from the hardware", new Runnable() { public void run() { core_.updateSystemStateCache(); updateGUI(true); } }, "arrow_refresh.png"); GUIUtils.addMenuItem(toolsMenu, "Rebuild GUI", "Regenerate Micro-Manager user interface", new Runnable() { public void run() { initializeGUI(); core_.updateSystemStateCache(); } }); toolsMenu.addSeparator(); GUIUtils.addMenuItem(toolsMenu, "Script Panel...", "Open Micro-Manager script editor window", new Runnable() { public void run() { scriptPanel_.setVisible(true); } }); GUIUtils.addMenuItem(toolsMenu, "Shortcuts...", "Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts", new Runnable() { public void run() { HotKeysDialog hk = new HotKeysDialog(guiColors_.background.get((options_.displayBackground_))); //hk.setBackground(guiColors_.background.get((options_.displayBackground_))); } }); GUIUtils.addMenuItem(toolsMenu, "Device/Property Browser...", "Open new window to view and edit property values in current configuration", new Runnable() { public void run() { createPropertyEditor(); } }); toolsMenu.addSeparator(); GUIUtils.addMenuItem(toolsMenu, "XY List...", "Open position list manager window", new Runnable() { public void run() { showXYPositionList(); } }, "application_view_list.png"); GUIUtils.addMenuItem(toolsMenu, "Multi-Dimensional Acquisition...", "Open multi-dimensional acquisition setup window", new Runnable() { public void run() { openAcqControlDialog(); } }, "film.png"); centerAndDragMenuItem_ = GUIUtils.addCheckBoxMenuItem(toolsMenu, "Mouse Moves Stage (use Hand Tool)", "When enabled, double clicking or dragging in the snap/live\n" + "window moves the XY-stage. Requires the hand tool.", new Runnable() { public void run() { updateCenterAndDragListener(); IJ.setTool(Toolbar.HAND); mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected()); } }, mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false)); GUIUtils.addMenuItem(toolsMenu, "Pixel Size Calibration...", "Define size calibrations specific to each objective lens. " + "When the objective in use has a calibration defined, " + "micromanager will automatically use it when " + "calculating metadata", new Runnable() { public void run() { createCalibrationListDlg(); } }); /* GUIUtils.addMenuItem(toolsMenu, "Image Processor Manager", "Control the order in which Image Processor plugins" + "are applied to incoming images.", new Runnable() { public void run() { processorStackManager_.show(); } }); */ toolsMenu.addSeparator(); GUIUtils.addMenuItem(toolsMenu, "Hardware Configuration Wizard...", "Open wizard to create new hardware configuration", new Runnable() { public void run() { runHardwareWizard(); } }); GUIUtils.addMenuItem(toolsMenu, "Load Hardware Configuration...", "Un-initialize current configuration and initialize new one", new Runnable() { public void run() { loadConfiguration(); initializeGUI(); } }); GUIUtils.addMenuItem(toolsMenu, "Reload Hardware Configuration", "Shutdown current configuration and initialize most recently loaded configuration", new Runnable() { public void run() { loadSystemConfiguration(); initializeGUI(); } }); for (int i=0; i<5; i++) { JMenuItem configItem = new JMenuItem(); configItem.setText(Integer.toString(i)); switchConfigurationMenu_.add(configItem); } switchConfigurationMenu_.setText("Switch Hardware Configuration"); toolsMenu.add(switchConfigurationMenu_); switchConfigurationMenu_.setToolTipText("Switch between recently used configurations"); GUIUtils.addMenuItem(toolsMenu, "Save Configuration Settings as...", "Save current configuration settings as new configuration file", new Runnable() { public void run() { saveConfigPresets(); updateChannelCombos(); } }); toolsMenu.addSeparator(); final MMStudioMainFrame thisInstance = this; GUIUtils.addMenuItem(toolsMenu, "Options...", "Set a variety of Micro-Manager configuration options", new Runnable() { public void run() { final int oldBufsize = options_.circularBufferSizeMB_; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB_) { try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_); } catch (Exception exc) { ReportingUtils.showError(exc); } } } }); } private void showRegistrationDialogMaybe() { // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!userReg) { boolean systemReg = systemPrefs_.getBoolean( RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(systemPrefs_); dlg.setVisible(true); } } } private void updateSwitchConfigurationMenu() { switchConfigurationMenu_.removeAll(); for (final String configFile : MRUConfigFiles_) { if (!configFile.equals(sysConfigFile_)) { GUIUtils.addMenuItem(switchConfigurationMenu_, configFile, null, new Runnable() { public void run() { sysConfigFile_ = configFile; loadSystemConfiguration(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); } }); } } } /** * Allows MMListeners to register themselves */ @Override public void addMMListener(MMListenerInterface newL) { if (MMListeners_.contains(newL)) return; MMListeners_.add(newL); } /** * Allows MMListeners to remove themselves */ @Override public void removeMMListener(MMListenerInterface oldL) { if (!MMListeners_.contains(oldL)) return; MMListeners_.remove(oldL); } public final void addLiveModeListener (LiveModeListener listener) { if (liveModeListeners_.contains(listener)) { return; } liveModeListeners_.add(listener); } public void removeLiveModeListener(LiveModeListener listener) { liveModeListeners_.remove(listener); } public void callLiveModeListeners(boolean enable) { for (LiveModeListener listener : liveModeListeners_) { listener.liveModeEnabled(enable); } } /** * Lets JComponents register themselves so that their background can be * manipulated */ @Override public void addMMBackgroundListener(Component comp) { if (MMFrames_.contains(comp)) return; MMFrames_.add(comp); } /** * Lets JComponents remove themselves from the list whose background gets * changes */ @Override public void removeMMBackgroundListener(Component comp) { if (!MMFrames_.contains(comp)) return; MMFrames_.remove(comp); } /** * Part of ScriptInterface * Manipulate acquisition so that it looks like a burst */ public void runBurstAcquisition() throws MMScriptException { double interval = engine_.getFrameIntervalMs(); int nr = engine_.getNumFrames(); boolean doZStack = engine_.isZSliceSettingEnabled(); boolean doChannels = engine_.isChannelsSettingEnabled(); engine_.enableZSliceSetting(false); engine_.setFrames(nr, 0); engine_.enableChannelsSetting(false); try { engine_.acquire(); } catch (MMException e) { throw new MMScriptException(e); } engine_.setFrames(nr, interval); engine_.enableZSliceSetting(doZStack); engine_.enableChannelsSetting(doChannels); } public void runBurstAcquisition(int nr) throws MMScriptException { int originalNr = engine_.getNumFrames(); double interval = engine_.getFrameIntervalMs(); engine_.setFrames(nr, 0); this.runBurstAcquisition(); engine_.setFrames(originalNr, interval); } public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException { String originalRoot = engine_.getRootName(); engine_.setDirName(name); engine_.setRootName(root); this.runBurstAcquisition(nr); engine_.setRootName(originalRoot); } /** * Inserts version info for various components in the Corelog */ @Override public void logStartupProperties() { core_.enableDebugLog(options_.debugLogEnabled_); core_.logMessage("MM Studio version: " + getVersion()); core_.logMessage(core_.getVersionInfo()); core_.logMessage(core_.getAPIVersionInfo()); core_.logMessage("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") " + System.getProperty("os.version")); core_.logMessage("JVM: " + System.getProperty("java.vm.name") + ", version " + System.getProperty("java.version") + ", " + System.getProperty("sun.arch.data.model") + "-bit"); } /** * @Deprecated * @throws MMScriptException */ public void startBurstAcquisition() throws MMScriptException { runAcquisition(); } public boolean isBurstAcquisitionRunning() throws MMScriptException { if (engine_ == null) return false; return engine_.isAcquisitionRunning(); } private void startLoadingPipelineClass() { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); acquisitionEngine2010LoadingThread = new Thread("Pipeline Class loading thread") { @Override public void run() { try { acquisitionEngine2010Class = Class.forName("org.micromanager.AcquisitionEngine2010"); } catch (Exception ex) { ReportingUtils.logError(ex); acquisitionEngine2010Class = null; } } }; acquisitionEngine2010LoadingThread.start(); } @Override public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException { return getAcquisition(acquisitionName).getImageCache(); } /** * Shows images as they appear in the default display window. Uses * the default processor stack to process images as they arrive on * the rawImageQueue. */ public void runDisplayThread(BlockingQueue<TaggedImage> rawImageQueue, final DisplayImageRoutine displayImageRoutine) { final BlockingQueue<TaggedImage> processedImageQueue = ProcessorStack.run(rawImageQueue, getAcquisitionEngine().getImageProcessors()); new Thread("Display thread") { @Override public void run() { try { TaggedImage image; do { image = processedImageQueue.take(); if (image != TaggedImageQueue.POISON) { displayImageRoutine.show(image); } } while (image != TaggedImageQueue.POISON); } catch (InterruptedException ex) { ReportingUtils.logError(ex); } } }.start(); } private static JLabel createLabel(String text, boolean big, JPanel parentPanel, int west, int north, int east, int south) { final JLabel label = new JLabel(); label.setFont(new Font("Arial", big ? Font.BOLD : Font.PLAIN, big ? 11 : 10)); label.setText(text); GUIUtils.addWithEdges(parentPanel, label, west, north, east, south); return label; } public interface DisplayImageRoutine { public void show(TaggedImage image); } /** * Callback to update GUI when a change happens in the MMCore. */ public class CoreEventCallback extends MMEventCallback { public CoreEventCallback() { super(); } @Override public void onPropertiesChanged() { // TODO: remove test once acquisition engine is fully multithreaded if (engine_ != null && engine_.isAcquisitionRunning()) { core_.logMessage("Notification from MMCore ignored because acquistion is running!", true); } else { if (ignorePropertyChanges_) { core_.logMessage("Notification from MMCore ignored since the system is still loading", true); } else { core_.updateSystemStateCache(); updateGUI(true); // update all registered listeners for (MMListenerInterface mmIntf : MMListeners_) { mmIntf.propertiesChangedAlert(); } core_.logMessage("Notification from MMCore!", true); } } } @Override public void onPropertyChanged(String deviceName, String propName, String propValue) { core_.logMessage("Notification for Device: " + deviceName + " Property: " + propName + " changed to value: " + propValue, true); // update all registered listeners for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.propertyChangedAlert(deviceName, propName, propValue); } } @Override public void onConfigGroupChanged(String groupName, String newConfig) { try { configPad_.refreshGroup(groupName, newConfig); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.configGroupChangedAlert(groupName, newConfig); } } catch (Exception e) { } } @Override public void onSystemConfigurationLoaded() { for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.systemConfigurationLoaded(); } } @Override public void onPixelSizeChanged(double newPixelSizeUm) { updatePixSizeUm (newPixelSizeUm); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.pixelSizeChangedAlert(newPixelSizeUm); } } @Override public void onStagePositionChanged(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) { updateZPos(pos); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.stagePositionChangedAlert(deviceName, pos); } } } @Override public void onStagePositionChangedRelative(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) updateZPosRelative(pos); } @Override public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) { updateXYPos(xPos, yPos); for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.xyStagePositionChanged(deviceName, xPos, yPos); } } } @Override public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) updateXYPosRelative(xPos, yPos); } @Override public void onExposureChanged(String deviceName, double exposure) { if (deviceName.equals(cameraLabel_)){ // update exposure in gui textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); } for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.exposureChanged(deviceName, exposure); } } } private class PluginItem { public Class<?> pluginClass = null; public String menuItem = "undefined"; public MMPlugin plugin = null; public String className = ""; public void instantiate() { try { if (plugin == null) { plugin = (MMPlugin) pluginClass.newInstance(); } } catch (InstantiationException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } plugin.setApp(MMStudioMainFrame.this); } } /* * Simple class used to cache static info */ private class StaticInfo { public long width_; public long height_; public long bytesPerPixel_; public long imageBitDepth_; public double pixSizeUm_; public double zPos_; public double x_; public double y_; } private StaticInfo staticInfo_ = new StaticInfo(); private void setupWindowHandlers() { // add window listeners addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeSequence(false); } @Override public void windowOpened(WindowEvent e) { // initialize hardware try { core_ = new CMMCore(); } catch(UnsatisfiedLinkError ex) { ReportingUtils.showError(ex, "Failed to load the MMCoreJ_wrap native library"); return; } ReportingUtils.setCore(core_); logStartupProperties(); cameraLabel_ = ""; shutterLabel_ = ""; zStageLabel_ = ""; xyStageLabel_ = ""; engine_ = new AcquisitionWrapperEngine(acqMgr_); // processorStackManager_ = new ProcessorStackManager(engine_); // register callback for MMCore notifications, this is a global // to avoid garbage collection cb_ = new CoreEventCallback(); core_.registerCallback(cb_); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_); } catch (Exception e2) { ReportingUtils.showError(e2); } MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) { engine_.setParentGUI(parent); } loadMRUConfigFiles(); afMgr_ = new AutofocusManager(gui_); Thread pluginLoader = initializePlugins(); toFront(); if (!options_.doNotAskForConfigFile_) { MMIntroDlg introDlg = new MMIntroDlg(MMVersion.VERSION_STRING, MRUConfigFiles_); introDlg.setConfigFile(sysConfigFile_); introDlg.setBackground(guiColors_.background.get((options_.displayBackground_))); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } saveMRUConfigFiles(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); paint(MMStudioMainFrame.this.getGraphics()); engine_.setCore(core_, afMgr_); posList_ = new PositionList(); engine_.setPositionList(posList_); // load (but do no show) the scriptPanel createScriptPanel(); // Create an instance of HotKeys so that they can be read in from prefs hotKeys_ = new org.micromanager.utils.HotKeys(); hotKeys_.loadSettings(); // before loading the system configuration, we need to wait // until the plugins are loaded try { pluginLoader.join(2000); } catch (InterruptedException ex) { ReportingUtils.logError(ex, "Plugin loader thread was interupted"); } // if an error occurred during config loading, // do not display more errors than needed if (!loadSystemConfiguration()) ReportingUtils.showErrorOn(false); executeStartupScript(); // Create Multi-D window here but do not show it. // This window needs to be created in order to properly set the "ChannelGroup" // based on the Multi-D parameters acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this, options_); addMMBackgroundListener(acqControlWin_); configPad_.setCore(core_); if (parent != null) { configPad_.setParentGUI(parent); } configPadButtonPanel_.setCore(core_); // initialize controls // initializeGUI(); Not needed since it is already called in loadSystemConfiguration initializeHelpMenu(); String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, ""); if (afMgr_.hasDevice(afDevice)) { try { afMgr_.selectDevice(afDevice); } catch (MMException e1) { // this error should never happen ReportingUtils.showError(e1); } } centerAndDragListener_ = new CenterAndDragListener(gui_); zWheelListener_ = new ZWheelListener(core_, gui_); gui_.addLiveModeListener(zWheelListener_); xyzKeyListener_ = new XYZKeyListener(core_, gui_); gui_.addLiveModeListener(xyzKeyListener_); // switch error reporting back on ReportingUtils.showErrorOn(true); } private Thread initializePlugins() { pluginMenu_ = GUIUtils.createMenuInMenuBar(menuBar_, "Plugins"); Thread myThread = new ThreadPluginLoading("Plugin loading"); myThread.start(); return myThread; } class ThreadPluginLoading extends Thread { public ThreadPluginLoading(String string) { super(string); } @Override public void run() { // Needed for loading clojure-based jars: Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); loadPlugins(); } } }); } /** * Main procedure for stand alone operation. */ public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); MMStudioMainFrame frame = new MMStudioMainFrame(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } catch (Throwable e) { ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit."); System.exit(1); } } @SuppressWarnings("LeakingThisInConstructor") public MMStudioMainFrame(boolean pluginStatus) { org.micromanager.diagnostics.ThreadExceptionLogger.setUp(); startLoadingPipelineClass(); options_ = new MMOptions(); try { options_.loadSettings(); } catch (NullPointerException ex) { ReportingUtils.logError(ex); } UIMonitor.enable(options_.debugLogEnabled_); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem>(); gui_ = this; runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; acqMgr_ = new AcquisitionManager(); sysConfigFile_ = System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME; if (options_.startupScript_.length() > 0) { startupScriptFile_ = System.getProperty("user.dir") + "/" + options_.startupScript_; } else { startupScriptFile_ = ""; } ReportingUtils.SetContainingFrame(gui_); // set the location for app preferences try { mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); } catch (Exception e) { ReportingUtils.logError(e); } systemPrefs_ = mainPrefs_; colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + AcqControlDlg.COLOR_SETTINGS_NODE); exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + EXPOSURE_SETTINGS_NODE); contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + "/" + CONTRAST_SETTINGS_NODE); // check system preferences try { Preferences p = Preferences.systemNodeForPackage(this.getClass()); if (null != p) { // if we can not write to the systemPrefs, use AppPrefs instead if (JavaUtils.backingStoreAvailable(p)) { systemPrefs_ = p; } } } catch (Exception e) { ReportingUtils.logError(e); } showRegistrationDialogMaybe(); // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems // with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 644); int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 570); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); try { ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD, ImageUtils.getImageStorageClass().getName()) ) ); } catch (ClassNotFoundException ex) { ReportingUtils.logError(ex, "Class not found error. Should never happen"); } ToolTipManager ttManager = ToolTipManager.sharedInstance(); ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS); ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS); setBounds(x, y, width, height); setExitStrategy(options_.closeOnExit_); setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING); setBackground(guiColors_.background.get((options_.displayBackground_))); setMinimumSize(new Dimension(605,480)); menuBar_ = new JMenuBar(); switchConfigurationMenu_ = new JMenu(); setJMenuBar(menuBar_); initializeFileMenu(); initializeToolsMenu(); splitPane_ = createSplitPane(mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 200)); getContentPane().add(splitPane_); createTopPanelWidgets((JPanel) splitPane_.getComponent(0)); metadataPanel_ = createMetadataPanel((JPanel) splitPane_.getComponent(1)); setupWindowHandlers(); // Add our own keyboard manager that handles Micro-Manager shortcuts MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_); KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD); dt_ = new DropTarget(this, new DragDropUtil()); } private void handleException(Exception e, String msg) { String errText = "Exception occurred: "; if (msg.length() > 0) { errText += msg + " } if (options_.debugLogEnabled_) { errText += e.getMessage(); } else { errText += e.toString() + "\n"; ReportingUtils.showError(e); } handleError(errText); } private void handleException(Exception e) { handleException(e, ""); } private void handleError(String message) { if (isLiveModeOn()) { // Should we always stop live mode on any error? enableLiveMode(false); } JOptionPane.showMessageDialog(this, message); core_.logMessage(message); } @Override public void makeActive() { toFront(); } /** * used to store contrast settings to be later used for initialization of contrast of new windows. * Shouldn't be called by loaded data sets, only * ones that have been acquired */ public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda, HistogramSettings settings) { String type = mda ? "MDA_" : "SnapLive_"; if (options_.syncExposureMainAndMDA_) { type = ""; //only one group of contrast settings } contrastPrefs_.putInt("ContrastMin_" + channelGroup + "_" + type + channel, settings.min_); contrastPrefs_.putInt("ContrastMax_" + channelGroup + "_" + type + channel, settings.max_); contrastPrefs_.putDouble("ContrastGamma_" + channelGroup + "_" + type + channel, settings.gamma_); contrastPrefs_.putInt("ContrastHistMax_" + channelGroup + "_" + type + channel, settings.histMax_); contrastPrefs_.putInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, settings.displayMode_); } public HistogramSettings loadStoredChannelHisotgramSettings(String channelGroup, String channel, boolean mda) { String type = mda ? "MDA_" : "SnapLive_"; if (options_.syncExposureMainAndMDA_) { type = ""; //only one group of contrast settings } return new HistogramSettings( contrastPrefs_.getInt("ContrastMin_" + channelGroup + "_" + type + channel,0), contrastPrefs_.getInt("ContrastMax_" + channelGroup + "_" + type + channel, 65536), contrastPrefs_.getDouble("ContrastGamma_" + channelGroup + "_" + type + channel, 1.0), contrastPrefs_.getInt("ContrastHistMax_" + channelGroup + "_" + type + channel, -1), contrastPrefs_.getInt("ContrastHistDisplayMode_" + channelGroup + "_" + type + channel, 1) ); } private void setExposure() { try { if (!isLiveModeOn()) { core_.setExposure(NumberUtils.displayStringToDouble( textFieldExp_.getText())); } else { liveModeTimer_.stop(); core_.setExposure(NumberUtils.displayStringToDouble( textFieldExp_.getText())); try { liveModeTimer_.begin(); } catch (Exception e) { ReportingUtils.showError("Couldn't restart live mode"); liveModeTimer_.stop(); } } // Display the new exposure time double exposure = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); // update current channel in MDA window with this exposure String channelGroup = core_.getChannelGroup(); String channel = core_.getCurrentConfigFromCache(channelGroup); if (!channel.equals("") ) { exposurePrefs_.putDouble("Exposure_" + channelGroup + "_" + channel, exposure); if (options_.syncExposureMainAndMDA_) { getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure); } } } catch (Exception exp) { // Do nothing. } } /** * Returns exposure time for the desired preset in the given channelgroup * Acquires its info from the preferences * Same thing is used in MDA window, but this class keeps its own copy * * @param channelGroup * @param channel - * @param defaultExp - default value * @return exposure time */ @Override public double getChannelExposureTime(String channelGroup, String channel, double defaultExp) { return exposurePrefs_.getDouble("Exposure_" + channelGroup + "_" + channel, defaultExp); } /** * Updates the exposure time in the given preset * Will also update current exposure if it the given channel and channelgroup * are the current one * * @param channelGroup - * * @param channel - preset for which to change exposure time * @param exposure - desired exposure time */ @Override public void setChannelExposureTime(String channelGroup, String channel, double exposure) { try { exposurePrefs_.putDouble("Exposure_" + channelGroup + "_" + channel, exposure); if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) { if (channel != null && !channel.equals("") && channel.equals(core_.getCurrentConfigFromCache(channelGroup))) { textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); setExposure(); } } } catch (Exception ex) { ReportingUtils.logError("Failed to set Exposure prefs using Channelgroup: " + channelGroup + ", channel: " + channel + ", exposure: " + exposure); } } @Override public boolean getAutoreloadOption() { return options_.autoreloadDevices_; } public double getPreferredWindowMag() { return options_.windowMag_; } public boolean getMetadataFileWithMultipageTiff() { return options_.mpTiffMetadataFile_; } public boolean getSeparateFilesForPositionsMPTiff() { return options_.mpTiffSeparateFilesForPositions_; } @Override public boolean getHideMDADisplayOption() { return options_.hideMDADisplay_; } private void updateTitle() { this.setTitle(MICRO_MANAGER_TITLE + " " + MMVersion.VERSION_STRING + " - " + sysConfigFile_); } public void updateLineProfile() { if (WindowManager.getCurrentWindow() == null || profileWin_ == null || !profileWin_.isShowing()) { return; } calculateLineProfileData(WindowManager.getCurrentImage()); profileWin_.setData(lineProfileData_); } private void openLineProfileWindow() { if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) { return; } calculateLineProfileData(WindowManager.getCurrentImage()); if (lineProfileData_ == null) { return; } profileWin_ = new GraphFrame(); profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); profileWin_.setData(lineProfileData_); profileWin_.setAutoScale(); profileWin_.setTitle("Live line profile"); profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_))); addMMBackgroundListener(profileWin_); profileWin_.setVisible(true); } @Override public Rectangle getROI() throws MMScriptException { // ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++): int[][] a = new int[4][1]; try { core_.getROI(a[0], a[1], a[2], a[3]); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } // Return as a single array with x,y,w,h: return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]); } private void calculateLineProfileData(ImagePlus imp) { // generate line profile Roi roi = imp.getRoi(); if (roi == null || !roi.isLine()) { // if there is no line ROI, create one Rectangle r = imp.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iXROI += iWidth / 2; iYROI += iHeight / 2; } roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI + iWidth / 4, iYROI + iHeight / 4); imp.setRoi(roi); roi = imp.getRoi(); } ImageProcessor ip = imp.getProcessor(); ip.setInterpolate(true); Line line = (Line) roi; if (lineProfileData_ == null) { lineProfileData_ = new GraphData(); } lineProfileData_.setData(line.getPixels()); } @Override public void setROI(Rectangle r) throws MMScriptException { boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } try { core_.setROI(r.x, r.y, r.width, r.height); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } private void setROI() { ImagePlus curImage = WindowManager.getCurrentImage(); if (curImage == null) { return; } Roi roi = curImage.getRoi(); try { if (roi == null) { // if there is no ROI, create one Rectangle r = curImage.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iWidth /= 2; iHeight /= 2; iXROI += iWidth / 2; iYROI += iHeight / 2; } curImage.setRoi(iXROI, iYROI, iWidth, iHeight); roi = curImage.getRoi(); } if (roi.getType() != Roi.RECTANGLE) { handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI."); return; } Rectangle r = roi.getBounds(); // if we already had an ROI defined, correct for the offsets Rectangle cameraR = getROI(); r.x += cameraR.x; r.y += cameraR.y; // Stop (and restart) live mode if it is running setROI(r); } catch (Exception e) { ReportingUtils.showError(e); } } private void clearROI() { try { boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } core_.clearROI(); updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } /** * Returns instance of the core uManager object; */ @Override public CMMCore getMMCore() { return core_; } /** * Returns singleton instance of MMStudioMainFrame */ public static MMStudioMainFrame getInstance() { return gui_; } public MetadataPanel getMetadataPanel() { return metadataPanel_; } public final void setExitStrategy(boolean closeOnExit) { if (closeOnExit) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } @Override public void saveConfigPresets() { MicroscopeModel model = new MicroscopeModel(); try { model.loadFromFile(sysConfigFile_); model.createSetupConfigsFromHardware(core_); model.createResolutionsFromHardware(core_); File f = FileDialogs.save(this, "Save the configuration file", MM_CONFIG_FILE); if (f != null) { model.saveToFile(f.getAbsolutePath()); sysConfigFile_ = f.getAbsolutePath(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); updateTitle(); } } catch (MMConfigFileException e) { ReportingUtils.showError(e); } } protected void setConfigSaveButtonStatus(boolean changed) { saveConfigButton_.setEnabled(changed); } public String getAcqDirectory() { return openAcqDirectory_; } /** * Get currently used configuration file * @return - Path to currently used configuration file */ public String getSysConfigFile() { return sysConfigFile_; } public void setAcqDirectory(String dir) { openAcqDirectory_ = dir; } /** * Open an existing acquisition directory and build viewer window. * */ public void openAcquisitionData(boolean inRAM) { // choose the directory File f = FileDialogs.openDir(this, "Please select an image data set", MM_DATA_SET); if (f != null) { if (f.isDirectory()) { openAcqDirectory_ = f.getAbsolutePath(); } else { openAcqDirectory_ = f.getParent(); } String acq = null; try { acq = openAcquisitionData(openAcqDirectory_, inRAM); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } finally { try { acqMgr_.closeAcquisition(acq); } catch (MMScriptException ex) { ReportingUtils.logError(ex); } } } } @Override public String openAcquisitionData(String dir, boolean inRAM, boolean show) throws MMScriptException { String rootDir = new File(dir).getAbsolutePath(); String name = new File(dir).getName(); rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1)); acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true); try { getAcquisition(name).initialize(); } catch (MMScriptException mex) { acqMgr_.closeAcquisition(name); throw (mex); } return name; } /** * Opens an existing data set. Shows the acquisition in a window. * @return The acquisition object. */ @Override public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException { return openAcquisitionData(dir, inRam, true); } protected void zoomOut() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomOut(r.width / 2, r.height / 2); VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus()); if (vad != null) { vad.storeWindowSizeAfterZoom(curWin); vad.updateWindowTitleAndStatus(); } } } protected void zoomIn() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomIn(r.width / 2, r.height / 2); VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus()); if (vad != null) { vad.storeWindowSizeAfterZoom(curWin); vad.updateWindowTitleAndStatus(); } } } protected void changeBinning() { try { boolean liveRunning = false; if (isLiveModeOn() ) { liveRunning = true; enableLiveMode(false); } if (isCameraAvailable()) { Object item = comboBinning_.getSelectedItem(); if (item != null) { core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString()); } } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } private void createPropertyEditor() { if (propertyBrowser_ != null) { propertyBrowser_.dispose(); } propertyBrowser_ = new PropertyEditor(); propertyBrowser_.setGui(this); propertyBrowser_.setVisible(true); propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); propertyBrowser_.setCore(core_); } private void createCalibrationListDlg() { if (calibrationListDlg_ != null) { calibrationListDlg_.dispose(); } calibrationListDlg_ = new CalibrationListDlg(core_); calibrationListDlg_.setVisible(true); calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); calibrationListDlg_.setParentGUI(this); } public CalibrationListDlg getCalibrationListDlg() { if (calibrationListDlg_ == null) { createCalibrationListDlg(); } return calibrationListDlg_; } private void createScriptPanel() { if (scriptPanel_ == null) { scriptPanel_ = new ScriptPanel(core_, options_, this); scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_); scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_); scriptPanel_.setParentGUI(this); scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_))); addMMBackgroundListener(scriptPanel_); } } /** * Updates Status line in main window from cached values */ private void updateStaticInfoFromCache() { String dimText = "Image info (from camera): " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X " + staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits"; dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix"; if (zStageLabel_.length() > 0) { dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um"; } if (xyStageLabel_.length() > 0) { dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um"; } labelImageDimensions_.setText(dimText); } public void updateXYPos(double x, double y) { staticInfo_.x_ = x; staticInfo_.y_ = y; updateStaticInfoFromCache(); } public void updateZPos(double z) { staticInfo_.zPos_ = z; updateStaticInfoFromCache(); } public void updateXYPosRelative(double x, double y) { staticInfo_.x_ += x; staticInfo_.y_ += y; updateStaticInfoFromCache(); } public void updateZPosRelative(double z) { staticInfo_.zPos_ += z; updateStaticInfoFromCache(); } public void updateXYStagePosition(){ double x[] = new double[1]; double y[] = new double[1]; try { if (xyStageLabel_.length() > 0) core_.getXYPosition(xyStageLabel_, x, y); } catch (Exception e) { ReportingUtils.showError(e); } staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } private void updatePixSizeUm (double pixSizeUm) { staticInfo_.pixSizeUm_ = pixSizeUm; updateStaticInfoFromCache(); } private void updateStaticInfo() { double zPos = 0.0; double x[] = new double[1]; double y[] = new double[1]; try { if (zStageLabel_.length() > 0) { zPos = core_.getPosition(zStageLabel_); } if (xyStageLabel_.length() > 0) { core_.getXYPosition(xyStageLabel_, x, y); } } catch (Exception e) { handleException(e); } staticInfo_.width_ = core_.getImageWidth(); staticInfo_.height_ = core_.getImageHeight(); staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel(); staticInfo_.imageBitDepth_ = core_.getImageBitDepth(); staticInfo_.pixSizeUm_ = core_.getPixelSizeUm(); staticInfo_.zPos_ = zPos; staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } public void toggleShutter() { try { if (!toggleShutterButton_.isEnabled()) return; toggleShutterButton_.requestFocusInWindow(); if (toggleShutterButton_.getText().equals("Open")) { setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { ReportingUtils.showError(e1); } } private void updateCenterAndDragListener() { if (centerAndDragMenuItem_.isSelected()) { centerAndDragListener_.start(); } else { centerAndDragListener_.stop(); } } private void setShutterButton(boolean state) { if (state) { toggleShutterButton_.setText("Close"); } else { toggleShutterButton_.setText("Open"); } } // public interface available for scripting access @Override public void snapSingleImage() { doSnap(); } public Object getPixels() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) { return ip.getProcessor().getPixels(); } return null; } public void setPixels(Object obj) { ImagePlus ip = WindowManager.getCurrentImage(); if (ip == null) { return; } ip.getProcessor().setPixels(obj); } public int getImageHeight() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getHeight(); return 0; } public int getImageWidth() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getWidth(); return 0; } public int getImageDepth() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null) return ip.getBitDepth(); return 0; } public ImageProcessor getImageProcessor() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip == null) return null; return ip.getProcessor(); } private boolean isCameraAvailable() { return cameraLabel_.length() > 0; } /** * Part of ScriptInterface API * Opens the XYPositionList when it is not opened * Adds the current position to the list (same as pressing the "Mark" button) */ @Override public void markCurrentPosition() { if (posListDlg_ == null) { showXYPositionList(); } if (posListDlg_ != null) { posListDlg_.markPosition(); } } /** * Implements ScriptInterface */ @Override public AcqControlDlg getAcqDlg() { return acqControlWin_; } /** * Implements ScriptInterface */ @Override public PositionListDlg getXYPosListDlg() { if (posListDlg_ == null) posListDlg_ = new PositionListDlg(core_, this, posList_, options_); return posListDlg_; } /** * Implements ScriptInterface */ @Override public boolean isAcquisitionRunning() { if (engine_ == null) return false; return engine_.isAcquisitionRunning(); } /** * Implements ScriptInterface */ @Override public boolean versionLessThan(String version) throws MMScriptException { try { String[] v = MMVersion.VERSION_STRING.split(" ", 2); String[] m = v[0].split("\\.", 3); String[] v2 = version.split(" ", 2); String[] m2 = v2[0].split("\\.", 3); for (int i=0; i < 3; i++) { if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return true; } if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) { return false; } } if (v2.length < 2 || v2[1].equals("") ) return false; if (v.length < 2 ) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return true; } if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) { ReportingUtils.showError("This code needs Micro-Manager version " + version + " or greater"); return false; } return true; } catch (Exception ex) { throw new MMScriptException ("Format of version String should be \"a.b.c\""); } } @Override public boolean isLiveModeOn() { return liveModeTimer_ != null && liveModeTimer_.isRunning(); } public LiveModeTimer getLiveModeTimer() { if (liveModeTimer_ == null) { liveModeTimer_ = new LiveModeTimer(); } return liveModeTimer_; } @Override public void enableLiveMode(boolean enable) { if (core_ == null) { return; } if (enable == isLiveModeOn()) { return; } if (enable) { try { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); updateButtonsForLiveMode(false); return; } if (liveModeTimer_ == null) { liveModeTimer_ = new LiveModeTimer(); } liveModeTimer_.begin(); callLiveModeListeners(enable); } catch (Exception e) { ReportingUtils.showError(e); liveModeTimer_.stop(); callLiveModeListeners(false); updateButtonsForLiveMode(false); return; } } else { liveModeTimer_.stop(); callLiveModeListeners(enable); } updateButtonsForLiveMode(enable); } public void updateButtonsForLiveMode(boolean enable) { autoShutterCheckBox_.setEnabled(!enable); if (core_.getAutoShutter()) { toggleShutterButton_.setText(enable ? "Close" : "Open" ); } snapButton_.setEnabled(!enable); //toAlbumButton_.setEnabled(!enable); liveButton_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/cancel.png") : SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); liveButton_.setSelected(false); liveButton_.setText(enable ? "Stop Live" : "Live"); } public boolean getLiveMode() { return isLiveModeOn(); } public boolean updateImage() { try { if (isLiveModeOn()) { enableLiveMode(false); return true; // nothing to do, just show the last image } if (WindowManager.getCurrentWindow() == null) { return false; } ImagePlus ip = WindowManager.getCurrentImage(); core_.snapImage(); Object img = core_.getImage(); ip.getProcessor().setPixels(img); ip.updateAndRepaintWindow(); if (!isCurrentImageFormatSupported()) { return false; } updateLineProfile(); } catch (Exception e) { ReportingUtils.showError(e); return false; } return true; } public boolean displayImage(final Object pixels) { if (pixels instanceof TaggedImage) { return displayTaggedImage((TaggedImage) pixels, true); } else { return displayImage(pixels, true); } } public boolean displayImage(final Object pixels, boolean wait) { checkSimpleAcquisition(); try { int width = getAcquisition(SIMPLE_ACQ).getWidth(); int height = getAcquisition(SIMPLE_ACQ).getHeight(); int byteDepth = getAcquisition(SIMPLE_ACQ).getByteDepth(); TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, byteDepth); simpleDisplay_.getImageCache().putImage(ti); simpleDisplay_.showImage(ti, wait); return true; } catch (Exception ex) { ReportingUtils.showError(ex); return false; } } public boolean displayImageWithStatusLine(Object pixels, String statusLine) { boolean ret = displayImage(pixels); simpleDisplay_.displayStatusLine(statusLine); return ret; } public void displayStatusLine(String statusLine) { ImagePlus ip = WindowManager.getCurrentImage(); if (!(ip.getWindow() instanceof VirtualAcquisitionDisplay.DisplayWindow)) { return; } VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine); } private boolean isCurrentImageFormatSupported() { boolean ret = false; long channels = core_.getNumberOfComponents(); long bpp = core_.getBytesPerPixel(); if (channels > 1 && channels != 4 && bpp != 1) { handleError("Unsupported image format."); } else { ret = true; } return ret; } public void doSnap() { doSnap(false); } public void doSnap(final boolean album) { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } BlockingQueue<TaggedImage> snapImageQueue = new LinkedBlockingQueue<TaggedImage>(); try { core_.snapImage(); long c = core_.getNumberOfCameraChannels(); runDisplayThread(snapImageQueue, new DisplayImageRoutine() { @Override public void show(final TaggedImage image) { if (album) { try { addToAlbum(image); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } } else { displayImage(image); } } }); for (int i = 0; i < c; ++i) { TaggedImage img = core_.getTaggedImage(i); img.tags.put("Channels", c); snapImageQueue.put(img); } snapImageQueue.put(TaggedImageQueue.POISON); if (simpleDisplay_ != null) { ImagePlus imgp = simpleDisplay_.getImagePlus(); if (imgp != null) { ImageWindow win = imgp.getWindow(); if (win != null) { win.toFront(); } } } } catch (Exception ex) { ReportingUtils.showError(ex); } } /** * Is this function still needed? It does some magic with tags. I found * it to do harmful thing with tags when a Multi-Camera device is * present (that issue is now fixed). */ public void normalizeTags(TaggedImage ti) { if (ti != TaggedImageQueue.POISON) { int channel = 0; try { if (ti.tags.has("ChannelIndex")) { channel = MDUtils.getChannelIndex(ti.tags); } MDUtils.setChannelIndex(ti.tags, channel); MDUtils.setPositionIndex(ti.tags, 0); MDUtils.setSliceIndex(ti.tags, 0); MDUtils.setFrameIndex(ti.tags, 0); } catch (JSONException ex) { ReportingUtils.logError(ex); } } } @Override public boolean displayImage(TaggedImage ti) { normalizeTags(ti); return displayTaggedImage(ti, true); } private boolean displayTaggedImage(TaggedImage ti, boolean update) { try { checkSimpleAcquisition(ti); setCursor(new Cursor(Cursor.WAIT_CURSOR)); ti.tags.put("Summary", getAcquisition(SIMPLE_ACQ).getSummaryMetadata()); addStagePositionToTags(ti); addImage(SIMPLE_ACQ, ti, update, true); } catch (Exception ex) { ReportingUtils.logError(ex); return false; } if (update) { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); updateLineProfile(); } return true; } public void addStagePositionToTags(TaggedImage ti) throws JSONException { if (gui_.xyStageLabel_.length() > 0) { ti.tags.put("XPositionUm", gui_.staticInfo_.x_); ti.tags.put("YPositionUm", gui_.staticInfo_.y_); } if (gui_.zStageLabel_.length() > 0) { ti.tags.put("ZPositionUm", gui_.staticInfo_.zPos_); } } private void configureBinningCombo() throws Exception { if (cameraLabel_.length() > 0) { ActionListener[] listeners; // binning combo if (comboBinning_.getItemCount() > 0) { comboBinning_.removeAllItems(); } StrVector binSizes = core_.getAllowedPropertyValues( cameraLabel_, MMCoreJ.getG_Keyword_Binning()); listeners = comboBinning_.getActionListeners(); for (int i = 0; i < listeners.length; i++) { comboBinning_.removeActionListener(listeners[i]); } for (int i = 0; i < binSizes.size(); i++) { comboBinning_.addItem(binSizes.get(i)); } comboBinning_.setMaximumRowCount((int) binSizes.size()); if (binSizes.isEmpty()) { comboBinning_.setEditable(true); } else { comboBinning_.setEditable(false); } for (int i = 0; i < listeners.length; i++) { comboBinning_.addActionListener(listeners[i]); } } } public void initializeGUI() { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); engine_.setZStageDevice(zStageLabel_); configureBinningCombo(); // active shutter combo try { shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice); } catch (Exception e) { ReportingUtils.logError(e); } if (shutters_ != null) { String items[] = new String[(int) shutters_.size()]; for (int i = 0; i < shutters_.size(); i++) { items[i] = shutters_.get(i); } GUIUtils.replaceComboContents(shutterComboBox_, items); String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // Autofocus autofocusConfigureButton_.setEnabled(afMgr_.getDevice() != null); autofocusNowButton_.setEnabled(afMgr_.getDevice() != null); // Rebuild stage list in XY PositinList if (posListDlg_ != null) { posListDlg_.rebuildAxisList(); } updateGUI(true); } catch (Exception e) { ReportingUtils.showError(e); } } @Override public String getVersion() { return MMVersion.VERSION_STRING; } private void addPluginToMenu(final PluginItem plugin, Class<?> cl) { // add plugin menu items String toolTipDescription = ""; try { // Get this static field from the class implementing MMPlugin. toolTipDescription = (String) cl.getDeclaredField("tooltipDescription").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); toolTipDescription = "Description not available"; } catch (NoSuchFieldException e) { toolTipDescription = "Description not available"; ReportingUtils.logMessage(cl.getName() + " fails to implement static String tooltipDescription."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } GUIUtils.addMenuItem(pluginMenu_, plugin.menuItem, toolTipDescription, new Runnable() { public void run() { ReportingUtils.logMessage("Plugin command: " + plugin.menuItem); plugin.instantiate(); plugin.plugin.show(); } }); pluginMenu_.validate(); menuBar_.validate(); } public void updateGUI(boolean updateConfigPadStructure) { updateGUI(updateConfigPadStructure, false); } public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); afMgr_.refresh(); // camera settings if (isCameraAvailable()) { double exp = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp)); configureBinningCombo(); String binSize; if (fromCache) { binSize = core_.getPropertyFromCache(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); } else { binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); } GUIUtils.setComboSelection(comboBinning_, binSize); } if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) { autoShutterCheckBox_.setSelected(core_.getAutoShutter()); boolean shutterOpen = core_.getShutterOpen(); setShutterButton(shutterOpen); if (autoShutterCheckBox_.isSelected()) { toggleShutterButton_.setEnabled(false); } else { toggleShutterButton_.setEnabled(true); } } // active shutter combo if (shutters_ != null) { String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // state devices if (updateConfigPadStructure && (configPad_ != null)) { configPad_.refreshStructure(fromCache); // Needed to update read-only properties. May slow things down... if (!fromCache) core_.updateSystemStateCache(); } // update Channel menus in Multi-dimensional acquisition dialog updateChannelCombos(); // update list of pixel sizes in pixel size configuration window if (calibrationListDlg_ != null) { calibrationListDlg_.refreshCalibrations(); } if (propertyBrowser_ != null) { propertyBrowser_.refresh(); } } catch (Exception e) { ReportingUtils.logError(e); } updateStaticInfo(); updateTitle(); } //TODO: Deprecated @Override public boolean okToAcquire() { return !isLiveModeOn(); } //TODO: Deprecated @Override public void stopAllActivity() { if (this.acquisitionEngine2010 != null) { this.acquisitionEngine2010.stop(); } enableLiveMode(false); } /** * Cleans up resources while shutting down * * @param calledByImageJ * @return flag indicating success. Shut down should abort when flag is false */ private boolean cleanupOnClose(boolean calledByImageJ) { // Save config presets if they were changed. if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); // if the configChanged_ flag did not become false, the user // must have cancelled the configuration saving and we should cancel // quitting as well if (configChanged_) { return false; } } } if (liveModeTimer_ != null) liveModeTimer_.stop(); // check needed to avoid deadlock if (!calledByImageJ) { if (!WindowManager.closeAllWindows()) { core_.logMessage("Failed to close some windows"); } } if (profileWin_ != null) { removeMMBackgroundListener(profileWin_); profileWin_.dispose(); } if (scriptPanel_ != null) { removeMMBackgroundListener(scriptPanel_); scriptPanel_.closePanel(); } if (propertyBrowser_ != null) { removeMMBackgroundListener(propertyBrowser_); propertyBrowser_.dispose(); } if (acqControlWin_ != null) { removeMMBackgroundListener(acqControlWin_); acqControlWin_.close(); } if (engine_ != null) { engine_.shutdown(); } if (afMgr_ != null) { afMgr_.closeOptionsDialog(); } // dispose plugins for (int i = 0; i < plugins_.size(); i++) { MMPlugin plugin = plugins_.get(i).plugin; if (plugin != null) { plugin.dispose(); } } synchronized (shutdownLock_) { try { if (core_ != null) { ReportingUtils.setCore(null); core_.delete(); core_ = null; } } catch (Exception err) { ReportingUtils.showError(err); } } return true; } private void saveSettings() { Rectangle r = this.getBounds(); mainPrefs_.putInt(MAIN_FRAME_X, r.x); mainPrefs_.putInt(MAIN_FRAME_Y, r.y); mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width); mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height); mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation()); mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_); mainPrefs_.put(MAIN_SAVE_METHOD, ImageUtils.getImageStorageClass().getName()); // save field values from the main window // NOTE: automatically restoring these values on startup may cause // problems mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText()); // NOTE: do not save auto shutter state if (afMgr_ != null && afMgr_.getDevice() != null) { mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName()); } } private void loadConfiguration() { File f = FileDialogs.openFile(this, "Load a config file",MM_CONFIG_FILE); if (f != null) { sysConfigFile_ = f.getAbsolutePath(); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); } } public synchronized boolean closeSequence(boolean calledByImageJ) { if (!this.isRunning()) { if (core_ != null) { core_.logMessage("MMStudioMainFrame::closeSequence called while running_ is false"); } return true; } if (engine_ != null && engine_.isAcquisitionRunning()) { int result = JOptionPane.showConfirmDialog( this, "Acquisition in progress. Are you sure you want to exit and discard all data?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.NO_OPTION) { return false; } } stopAllActivity(); try { // Close all image windows associated with MM. Canceling saving of // any of these should abort shutdown if (!acqMgr_.closeAllImageWindows()) { return false; } } catch (MMScriptException ex) { // Not sure what to do here... } if (!cleanupOnClose(calledByImageJ)) { return false; } running_ = false; saveSettings(); try { configPad_.saveSettings(); options_.saveSettings(); hotKeys_.saveSettings(); } catch (NullPointerException e) { if (core_ != null) this.logError(e); } // disposing sometimes hangs ImageJ! // this.dispose(); if (options_.closeOnExit_) { if (!runsAsPlugin_) { System.exit(0); } else { ImageJ ij = IJ.getInstance(); if (ij != null) { ij.quit(); } } } else { this.dispose(); } return true; } public void applyContrastSettings(ContrastSettings contrast8, ContrastSettings contrast16) { ImagePlus img = WindowManager.getCurrentImage(); if (img == null|| VirtualAcquisitionDisplay.getDisplay(img) == null ) return; if (img.getBytesPerPixel() == 1) VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, contrast8.min, contrast8.max, contrast8.gamma); else VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, contrast16.min, contrast16.max, contrast16.gamma); } //TODO: Deprecated @Override public ContrastSettings getContrastSettings() { ImagePlus img = WindowManager.getCurrentImage(); if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null ) return null; return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0); } public boolean is16bit() { ImagePlus ip = WindowManager.getCurrentImage(); if (ip != null && ip.getProcessor() instanceof ShortProcessor) { return true; } return false; } public boolean isRunning() { return running_; } /** * Executes the beanShell script. This script instance only supports * commands directed to the core object. */ private void executeStartupScript() { // execute startup script File f = new File(startupScriptFile_); if (startupScriptFile_.length() > 0 && f.exists()) { WaitDialog waitDlg = new WaitDialog( "Executing startup script, please wait..."); waitDlg.showDialog(); Interpreter interp = new Interpreter(); try { // insert core object only interp.set(SCRIPT_CORE_OBJECT, core_); interp.set(SCRIPT_ACQENG_OBJECT, engine_); interp.set(SCRIPT_GUI_OBJECT, this); // read text file and evaluate interp.eval(TextUtils.readTextFile(startupScriptFile_)); } catch (IOException exc) { ReportingUtils.logError(exc, "Unable to read the startup script (" + startupScriptFile_ + ")."); } catch (EvalError exc) { ReportingUtils.logError(exc); } finally { waitDlg.closeDialog(); } } else { if (startupScriptFile_.length() > 0) ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present."); } } /** * Loads system configuration from the cfg file. */ private boolean loadSystemConfiguration() { boolean result = true; saveMRUConfigFiles(); final WaitDialog waitDlg = new WaitDialog( "Loading system configuration, please wait..."); waitDlg.setAlwaysOnTop(true); waitDlg.showDialog(); this.setEnabled(false); try { if (sysConfigFile_.length() > 0) { GUIUtils.preventDisplayAdapterChangeExceptions(); core_.waitForSystem(); ignorePropertyChanges_ = true; core_.loadSystemConfiguration(sysConfigFile_); ignorePropertyChanges_ = false; GUIUtils.preventDisplayAdapterChangeExceptions(); } } catch (final Exception err) { GUIUtils.preventDisplayAdapterChangeExceptions(); ReportingUtils.showError(err); result = false; } finally { waitDlg.closeDialog(); } setEnabled(true); initializeGUI(); updateSwitchConfigurationMenu(); FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_)); return result; } private void saveMRUConfigFiles() { if (0 < sysConfigFile_.length()) { if (MRUConfigFiles_.contains(sysConfigFile_)) { MRUConfigFiles_.remove(sysConfigFile_); } if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); // save the MRU list to the preferences for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) { String value = ""; if (null != MRUConfigFiles_.get(icfg)) { value = MRUConfigFiles_.get(icfg).toString(); } mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value); } } } private void loadMRUConfigFiles() { sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_); // startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE, // startupScriptFile_); MRUConfigFiles_ = new ArrayList<String>(); for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) { String value = ""; value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value); if (0 < value.length()) { File ruFile = new File(value); if (ruFile.exists()) { if (!MRUConfigFiles_.contains(value)) { MRUConfigFiles_.add(value); } } } } // initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE if (0 < sysConfigFile_.length()) { if (!MRUConfigFiles_.contains(sysConfigFile_)) { // in case persistant data is inconsistent if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); } } } /** * Opens Acquisition dialog. */ private void openAcqControlDialog() { try { if (acqControlWin_ == null) { acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this, options_); } if (acqControlWin_.isActive()) { acqControlWin_.setTopPosition(); } acqControlWin_.setVisible(true); acqControlWin_.repaint(); // TODO: this call causes a strange exception the first time the // dialog is created // something to do with the order in which combo box creation is // performed // acqControlWin_.updateGroupsCombo(); } catch (Exception exc) { ReportingUtils.showError(exc, "\nAcquistion window failed to open due to invalid or corrupted settings.\n" + "Try resetting registry settings to factory defaults (Menu Tools|Options)."); } } /** * Opens a dialog to record stage positions */ @Override public void showXYPositionList() { if (posListDlg_ == null) { posListDlg_ = new PositionListDlg(core_, this, posList_, options_); } posListDlg_.setVisible(true); } private void updateChannelCombos() { if (this.acqControlWin_ != null) { this.acqControlWin_.updateChannelAndGroupCombo(); } } @Override public void setConfigChanged(boolean status) { configChanged_ = status; setConfigSaveButtonStatus(configChanged_); } /** * Returns the current background color * @return current background color */ @Override public Color getBackgroundColor() { return guiColors_.background.get((options_.displayBackground_)); } /* * Changes background color of this window and all other MM windows */ @Override public void setBackgroundStyle(String backgroundType) { setBackground(guiColors_.background.get((backgroundType))); paint(MMStudioMainFrame.this.getGraphics()); // sets background of all registered Components for (Component comp:MMFrames_) { if (comp != null) comp.setBackground(guiColors_.background.get(backgroundType)); } } @Override public String getBackgroundStyle() { return options_.displayBackground_; } // Scripting interface private class ExecuteAcq implements Runnable { public ExecuteAcq() { } @Override public void run() { if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); } } } private void testForAbortRequests() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } } } /** * @Deprecated - used to be in api/AcquisitionEngine */ public void startAcquisition() throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new ExecuteAcq()); } @Override public String runAcquisition() throws MMScriptException { if (SwingUtilities.isEventDispatchThread()) { throw new MMScriptException("Acquisition can not be run from this (EDT) thread"); } testForAbortRequests(); if (acqControlWin_ != null) { String name = acqControlWin_.runAcquisition(); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(50); } } catch (InterruptedException e) { ReportingUtils.showError(e); } return name; } else { throw new MMScriptException( "Acquisition setup window must be open for this command to work."); } } @Override public String runAcquisition(String name, String root) throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { String acqName = acqControlWin_.runAcquisition(name, root); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(100); } // ensure that the acquisition has finished. // This does not seem to work, needs something better MMAcquisition acq = acqMgr_.getAcquisition(acqName); boolean finished = false; while (!finished) { ImageCache imCache = acq.getImageCache(); if (imCache != null) { if (imCache.isFinished()) { finished = true; } else { Thread.sleep(100); } } } } catch (InterruptedException e) { ReportingUtils.showError(e); } return acqName; } else { throw new MMScriptException( "Acquisition setup window must be open for this command to work."); } } /** * @Deprecated used to be part of api */ public String runAcqusition(String name, String root) throws MMScriptException { return runAcquisition(name, root); } /** * Loads acquisition settings from file * @param path file containing previously saved acquisition settings * @throws MMScriptException */ @Override public void loadAcquisition(String path) throws MMScriptException { testForAbortRequests(); try { engine_.shutdown(); // load protocol if (acqControlWin_ != null) { acqControlWin_.loadAcqSettingsFromFile(path); } } catch (Exception ex) { throw new MMScriptException(ex.getMessage()); } } @Override public void setPositionList(PositionList pl) throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object posList_ = pl; // PositionList.newInstance(pl); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (posListDlg_ != null) posListDlg_.setPositionList(posList_); if (engine_ != null) engine_.setPositionList(posList_); if (acqControlWin_ != null) acqControlWin_.updateGUIContents(); } }); } @Override public PositionList getPositionList() throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object return posList_; //PositionList.newInstance(posList_); } @Override public void sleep(long ms) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.sleep(ms); } } @Override public String getUniqueAcquisitionName(String stub) { return acqMgr_.getUniqueAcquisitionName(stub); } //@Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, true, false); } //@Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices) throws MMScriptException { openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0); } //@Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false); } //@Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false); } @Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show, boolean save) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir, show, save); MMAcquisition acq = acqMgr_.getAcquisition(name); acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions); } //@Override public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show, boolean virtual) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual); } //@Override public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) { return createAcquisition(summaryMetadata, diskCached, false); } @Override public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) { return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff); } //@Override public void initializeSimpleAcquisition(String name, int width, int height, int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh); acq.initializeSimpleAcq(); } @Override public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); //number of multi-cam cameras is set to 1 here for backwards compatibility //might want to change this later acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, 1); acq.initialize(); } @Override public int getAcquisitionImageWidth(String acqName) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getWidth(); } @Override public int getAcquisitionImageHeight(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getHeight(); } @Override public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getBitDepth(); } @Override public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getByteDepth(); } @Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{ MMAcquisition acq = acqMgr_.getAcquisition(acqName); return acq.getMultiCameraNumChannels(); } @Override public Boolean acquisitionExists(String name) { return acqMgr_.acquisitionExists(name); } @Override public void closeAcquisition(String name) throws MMScriptException { acqMgr_.closeAcquisition(name); } /** * @Deprecated use closeAcquisitionWindow instead * @Deprecated - used to be in api/AcquisitionEngine */ public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException { acqMgr_.closeImageWindow(acquisitionName); } @Override public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException { acqMgr_.closeImageWindow(acquisitionName); } /** * @Deprecated - used to be in api/AcquisitionEngine * Since Burst and normal acquisition are now carried out by the same engine, * loadBurstAcquistion simply calls loadAcquisition * t * @param path - path to file specifying acquisition settings */ public void loadBurstAcquisition(String path) throws MMScriptException { this.loadAcquisition(path); } @Override public void refreshGUI() { updateGUI(true); } @Override public void refreshGUIFromCache() { updateGUI(true, true); } @Override public void setAcquisitionProperty(String acqName, String propertyName, String value) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); acq.setProperty(propertyName, value); } public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException { // acqMgr_.getAcquisition(acqName).setSystemState(md); setAcquisitionSummary(acqName, md); } //@Override public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException { acqMgr_.getAcquisition(acqName).setSummaryProperties(md); } @Override public void setImageProperty(String acqName, int frame, int channel, int slice, String propName, String value) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(acqName); acq.setProperty(frame, channel, slice, propName, value); } @Override public String getCurrentAlbum() { return acqMgr_.getCurrentAlbum(); } public String createNewAlbum() { return acqMgr_.createNewAlbum(); } public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); int f = 1 + acq.getLastAcquiredFrame(); try { MDUtils.setFrameIndex(taggedImg.tags, f); } catch (JSONException e) { throw new MMScriptException("Unable to set the frame index."); } acq.insertTaggedImage(taggedImg, f, 0, 0); } @Override public void addToAlbum(TaggedImage taggedImg) throws MMScriptException { addToAlbum(taggedImg, null); } public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException { normalizeTags(taggedImg); acqMgr_.addToAlbum(taggedImg,displaySettings); } public void addImage(String name, Object img, int frame, int channel, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); acq.insertImage(img, frame, channel, slice); } //@Override public void addImage(String name, TaggedImage taggedImg) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(name); if (!acq.isInitialized()) { JSONObject tags = taggedImg.tags; // initialize physical dimensions of the image try { int width = tags.getInt(MMTags.Image.WIDTH); int height = tags.getInt(MMTags.Image.HEIGHT); int byteDepth = MDUtils.getDepth(tags); int bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH); initializeAcquisition(name, width, height, byteDepth, bitDepth); } catch (JSONException e) { throw new MMScriptException(e); } } acq.insertImage(taggedImg); } @Override /** * The basic method for adding images to an existing data set. * If the acquisition was not previously initialized, it will attempt to initialize it from the available image data */ public void addImageToAcquisition(String name, int frame, int channel, int slice, int position, TaggedImage taggedImg) throws MMScriptException { // TODO: complete the tag set and initialize the acquisition MMAcquisition acq = acqMgr_.getAcquisition(name); // check position, for multi-position data set the number of declared positions should be at least 2 if (acq.getPositions() <= 1 && position > 0) { throw new MMScriptException("The acquisition was open as a single position data set.\n" + "Open acqusition with two or more positions in order to crate a multi-position data set."); } // check position, for multi-position data set the number of declared positions should be at least 2 if (acq.getChannels() <= channel) { throw new MMScriptException("This acquisition was opened with " + acq.getChannels() + " channels.\n" + "The channel number must not exceed declared number of positions."); } JSONObject tags = taggedImg.tags; // if the acquisition was not previously initialized, set physical dimensions of the image if (!acq.isInitialized()) { // automatically initialize physical dimensions of the image try { int width = tags.getInt(MMTags.Image.WIDTH); int height = tags.getInt(MMTags.Image.HEIGHT); int byteDepth = MDUtils.getDepth(tags); int bitDepth = byteDepth * 8; if (tags.has(MMTags.Image.BIT_DEPTH)) bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH); initializeAcquisition(name, width, height, byteDepth, bitDepth); } catch (JSONException e) { throw new MMScriptException(e); } } // create required coordinate tags try { tags.put(MMTags.Image.FRAME_INDEX, frame); tags.put(MMTags.Image.FRAME, frame); tags.put(MMTags.Image.CHANNEL_INDEX, channel); tags.put(MMTags.Image.SLICE_INDEX, slice); tags.put(MMTags.Image.POS_INDEX, position); if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) { // add default setting tags.put(MMTags.Summary.SLICES_FIRST, true); tags.put(MMTags.Summary.TIME_FIRST, false); } if (acq.getPositions() > 1) { // if no position name is defined we need to insert a default one if (tags.has(MMTags.Image.POS_NAME)) tags.put(MMTags.Image.POS_NAME, "Pos" + position); } // update frames if necessary if (acq.getFrames() <= frame) { acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame+1)); } } catch (JSONException e) { throw new MMScriptException(e); } // System.out.println("Inserting frame: " + frame + ", channel: " + channel + ", slice: " + slice + ", pos: " + position); acq.insertImage(taggedImg); } @Override /** * A quick way to implicitly snap an image and add it to the data set. * Works in the same way as above. */ public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException { TaggedImage ti; try { if (core_.isSequenceRunning()) { ti = core_.getLastTaggedImage(); } else { core_.snapImage(); ti = core_.getTaggedImage(); } MDUtils.setChannelIndex(ti.tags, channel); MDUtils.setFrameIndex(ti.tags, frame); MDUtils.setSliceIndex(ti.tags, slice); MDUtils.setPositionIndex(ti.tags, position); MMAcquisition acq = acqMgr_.getAcquisition(name); if (!acq.isInitialized()) { long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); long bitDepth = core_.getImageBitDepth(); int multiCamNumCh = (int) core_.getNumberOfCameraChannels(); acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh); acq.initialize(); } if (acq.getPositions() > 1) { MDUtils.setPositionName(ti.tags, "Pos" + position); } addImageToAcquisition(name, frame, channel, slice, position, ti); } catch (Exception e) { throw new MMScriptException(e); } } //@Override public void addImage(String name, TaggedImage img, boolean updateDisplay) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(img, updateDisplay); } //@Override public void addImage(String name, TaggedImage taggedImg, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay); } //@Override public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position); } catch (JSONException ex) { ReportingUtils.showError(ex); } } //@Override public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position, boolean updateDisplay) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay); } catch (JSONException ex) { ReportingUtils.showError(ex); } } //@Override public void addImage(String name, TaggedImage taggedImg, int frame, int channel, int slice, int position, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException { try { acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay, waitForDisplay); } catch (JSONException ex) { ReportingUtils.showError(ex); } } /** * Closes all acquisitions */ @Override public void closeAllAcquisitions() { acqMgr_.closeAll(); } @Override public String[] getAcquisitionNames() { return acqMgr_.getAcqusitionNames(); } @Override public MMAcquisition getAcquisition(String name) throws MMScriptException { return acqMgr_.getAcquisition(name); } private class ScriptConsoleMessage implements Runnable { String msg_; public ScriptConsoleMessage(String text) { msg_ = text; } @Override public void run() { if (scriptPanel_ != null) scriptPanel_.message(msg_); } } @Override public void message(String text) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } SwingUtilities.invokeLater(new ScriptConsoleMessage(text)); } } @Override public void clearMessageWindow() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.clearOutput(); } } public void clearOutput() throws MMScriptException { clearMessageWindow(); } public void clear() throws MMScriptException { clearMessageWindow(); } @Override public void setChannelContrast(String title, int channel, int min, int max) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelContrast(channel, min, max); } @Override public void setChannelName(String title, int channel, String name) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelName(channel, name); } @Override public void setChannelColor(String title, int channel, Color color) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setChannelColor(channel, color.getRGB()); } @Override public void setContrastBasedOnFrame(String title, int frame, int slice) throws MMScriptException { MMAcquisition acq = acqMgr_.getAcquisition(title); acq.setContrastBasedOnFrame(frame, slice); } @Override public void setStagePosition(double z) throws MMScriptException { try { core_.setPosition(core_.getFocusDevice(),z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public void setRelativeStagePosition(double z) throws MMScriptException { try { core_.setRelativePosition(core_.getFocusDevice(), z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public void setXYStagePosition(double x, double y) throws MMScriptException { try { core_.setXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public void setRelativeXYStagePosition(double x, double y) throws MMScriptException { try { core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public Point2D.Double getXYStagePosition() throws MMScriptException { String stage = core_.getXYStageDevice(); if (stage.length() == 0) { throw new MMScriptException("XY Stage device is not available"); } double x[] = new double[1]; double y[] = new double[1]; try { core_.getXYPosition(stage, x, y); Point2D.Double pt = new Point2D.Double(x[0], y[0]); return pt; } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } @Override public String getXYStageName() { return core_.getXYStageDevice(); } @Override public void setXYOrigin(double x, double y) throws MMScriptException { String xyStage = core_.getXYStageDevice(); try { core_.setAdapterOriginXY(xyStage, x, y); } catch (Exception e) { throw new MMScriptException(e); } } public AcquisitionWrapperEngine getAcquisitionEngine() { return engine_; } public String installPlugin(Class<?> cl) { String className = cl.getSimpleName(); String msg = className + " module loaded."; try { for (PluginItem plugin : plugins_) { if (plugin.className.contentEquals(className)) { return className + " already loaded."; } } PluginItem pi = new PluginItem(); pi.className = className; try { // Get this static field from the class implementing MMPlugin. pi.menuItem = (String) cl.getDeclaredField("menuName").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); pi.menuItem = className; } catch (NoSuchFieldException e) { pi.menuItem = className; ReportingUtils.logMessage(className + " fails to implement static String menuName."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } if (pi.menuItem == null) { pi.menuItem = className; } pi.menuItem = pi.menuItem.replace("_", " "); pi.pluginClass = cl; plugins_.add(pi); final PluginItem pi2 = pi; final Class<?> cl2 = cl; SwingUtilities.invokeLater( new Runnable() { @Override public void run() { addPluginToMenu(pi2, cl2); } }); } catch (NoClassDefFoundError e) { msg = className + " class definition not found."; ReportingUtils.logError(e, msg); } return msg; } public String installPlugin(String className, String menuName) { String msg = "installPlugin(String className, String menuName) is Deprecated. Use installPlugin(String className) instead."; core_.logMessage(msg); installPlugin(className); return msg; } @Override public String installPlugin(String className) { try { Class clazz = Class.forName(className); return installPlugin(clazz); } catch (ClassNotFoundException e) { String msg = className + " plugin not found."; ReportingUtils.logError(e, msg); return msg; } } @Override public String installAutofocusPlugin(String className) { try { return installAutofocusPlugin(Class.forName(className)); } catch (ClassNotFoundException e) { String msg = "Internal error: AF manager not instantiated."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(Class<?> autofocus) { String msg = autofocus.getSimpleName() + " module loaded."; if (afMgr_ != null) { try { afMgr_.refresh(); } catch (MMException e) { msg = e.getMessage(); ReportingUtils.logError(e); } afMgr_.setAFPluginClassName(autofocus.getSimpleName()); } else { msg = "Internal error: AF manager not instantiated."; } return msg; } public CMMCore getCore() { return core_; } @Override public IAcquisitionEngine2010 getAcquisitionEngine2010() { try { acquisitionEngine2010LoadingThread.join(); if (acquisitionEngine2010 == null) { acquisitionEngine2010 = (IAcquisitionEngine2010) acquisitionEngine2010Class.getConstructor(ScriptInterface.class).newInstance(this); } return acquisitionEngine2010; } catch (Exception e) { ReportingUtils.logError(e); return null; } } @Override public void addImageProcessor(DataProcessor<TaggedImage> processor) { System.out.println("Processor: "+processor.getClass().getSimpleName()); getAcquisitionEngine().addImageProcessor(processor); } @Override public void removeImageProcessor(DataProcessor<TaggedImage> processor) { getAcquisitionEngine().removeImageProcessor(processor); } @Override public void setPause(boolean state) { getAcquisitionEngine().setPause(state); } @Override public boolean isPaused() { return getAcquisitionEngine().isPaused(); } @Override public void attachRunnable(int frame, int position, int channel, int slice, Runnable runnable) { getAcquisitionEngine().attachRunnable(frame, position, channel, slice, runnable); } @Override public void clearRunnables() { getAcquisitionEngine().clearRunnables(); } @Override public SequenceSettings getAcqusitionSettings() { if (engine_ == null) return new SequenceSettings(); return engine_.getSequenceSettings(); } @Override public String getAcquisitionPath() { if (engine_ == null) return null; return engine_.getImageCache().getDiskLocation(); } @Override public void promptToSaveAcqusition(String name, boolean prompt) throws MMScriptException { MMAcquisition acq = getAcquisition(name); getAcquisition(name).promptToSave(prompt); } public void snapAndAddToImage5D() { if (core_.getCameraDevice().length() == 0) { ReportingUtils.showError("No camera configured"); return; } try { if (this.isLiveModeOn()) { copyFromLiveModeToAlbum(simpleDisplay_); } else { doSnap(true); } } catch (Exception ex) { ReportingUtils.logError(ex); } } public void setAcquisitionEngine(AcquisitionWrapperEngine eng) { engine_ = eng; } public void suspendLiveMode() { liveModeSuspended_ = isLiveModeOn(); enableLiveMode(false); } public void resumeLiveMode() { if (liveModeSuspended_) { enableLiveMode(true); } } @Override public Autofocus getAutofocus() { return afMgr_.getDevice(); } @Override public void showAutofocusDialog() { if (afMgr_.getDevice() != null) { afMgr_.showOptionsDialog(); } } @Override public AutofocusManager getAutofocusManager() { return afMgr_; } public void selectConfigGroup(String groupName) { configPad_.setGroup(groupName); } public String regenerateDeviceList() { Cursor oldc = Cursor.getDefaultCursor(); Cursor waitc = new Cursor(Cursor.WAIT_CURSOR); setCursor(waitc); StringBuffer resultFile = new StringBuffer(); MicroscopeModel.generateDeviceListFile(resultFile, core_); //MicroscopeModel.generateDeviceListFile(); setCursor(oldc); return resultFile.toString(); } @Override public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException { if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) || imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) { throw new MMScriptException("Unrecognized saving class"); } ImageUtils.setImageStorageClass(imageSavingClass); if (acqControlWin_ != null) { acqControlWin_.updateSavingTypeButtons(); } } private void loadPlugins() { ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>(); ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>(); List<Class<?>> classes; try { long t1 = System.currentTimeMillis(); classes = JavaUtils.findClasses(new File("mmplugins"), 2); //System.out.println("findClasses: " + (System.currentTimeMillis() - t1)); //System.out.println(classes.size()); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == MMPlugin.class) { pluginClasses.add(clazz); } } } classes = JavaUtils.findClasses(new File("mmautofocus"), 2); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == Autofocus.class) { autofocusClasses.add(clazz); } } } } catch (ClassNotFoundException e1) { ReportingUtils.logError(e1); } for (Class<?> plugin : pluginClasses) { try { ReportingUtils.logMessage("Attempting to install plugin " + plugin.getName()); installPlugin(plugin); } catch (Exception e) { ReportingUtils.logError(e, "Failed to install the \"" + plugin.getName() + "\" plugin ."); } } for (Class<?> autofocus : autofocusClasses) { try { ReportingUtils.logMessage("Attempting to install autofocus plugin " + autofocus.getName()); installAutofocusPlugin(autofocus.getName()); } catch (Exception e) { ReportingUtils.logError("Failed to install the \"" + autofocus.getName() + "\" autofocus plugin."); } } } @Override public void logMessage(String msg) { ReportingUtils.logMessage(msg); } @Override public void showMessage(String msg) { ReportingUtils.showMessage(msg); } @Override public void logError(Exception e, String msg) { ReportingUtils.logError(e, msg); } @Override public void logError(Exception e) { ReportingUtils.logError(e); } @Override public void logError(String msg) { ReportingUtils.logError(msg); } @Override public void showError(Exception e, String msg) { ReportingUtils.showError(e, msg); } @Override public void showError(Exception e) { ReportingUtils.showError(e); } @Override public void showError(String msg) { ReportingUtils.showError(msg); } private void runHardwareWizard() { try { if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } configChanged_ = false; } boolean liveRunning = false; if (isLiveModeOn()) { liveRunning = true; enableLiveMode(false); } // unload all devices before starting configurator core_.reset(); GUIUtils.preventDisplayAdapterChangeExceptions(); // run Configurator ConfiguratorDlg2 cfg2 = null; try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_); } finally { setCursor(Cursor.getDefaultCursor()); } if (cfg2 == null) { ReportingUtils.showError("Failed to launch Hardware Configuration Wizard"); return; } cfg2.setVisible(true); GUIUtils.preventDisplayAdapterChangeExceptions(); // re-initialize the system with the new configuration file sysConfigFile_ = cfg2.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); GUIUtils.preventDisplayAdapterChangeExceptions(); if (liveRunning) { enableLiveMode(liveRunning); } } catch (Exception e) { ReportingUtils.showError(e); } } private void autofocusNow() { if (afMgr_.getDevice() != null) { new Thread() { @Override public void run() { try { boolean lmo = isLiveModeOn(); if (lmo) { enableLiveMode(false); } afMgr_.getDevice().fullFocus(); if (lmo) { enableLiveMode(true); } } catch (MMException ex) { ReportingUtils.logError(ex); } } }.start(); // or any other method from Autofocus.java API } } } class BooleanLock extends Object { private boolean value; public BooleanLock(boolean initialValue) { value = initialValue; } public BooleanLock() { this(false); } public synchronized void setValue(boolean newValue) { if (newValue != value) { value = newValue; notifyAll(); } } public synchronized boolean waitToSetTrue(long msTimeout) throws InterruptedException { boolean success = waitUntilFalse(msTimeout); if (success) { setValue(true); } return success; } public synchronized boolean waitToSetFalse(long msTimeout) throws InterruptedException { boolean success = waitUntilTrue(msTimeout); if (success) { setValue(false); } return success; } public synchronized boolean isTrue() { return value; } public synchronized boolean isFalse() { return !value; } public synchronized boolean waitUntilTrue(long msTimeout) throws InterruptedException { return waitUntilStateIs(true, msTimeout); } public synchronized boolean waitUntilFalse(long msTimeout) throws InterruptedException { return waitUntilStateIs(false, msTimeout); } public synchronized boolean waitUntilStateIs( boolean state, long msTimeout) throws InterruptedException { if (msTimeout == 0L) { while (value != state) { wait(); } return true; } long endTime = System.currentTimeMillis() + msTimeout; long msRemaining = msTimeout; while ((value != state) && (msRemaining > 0L)) { wait(msRemaining); msRemaining = endTime - System.currentTimeMillis(); } return (value == state); } }
package org.mskcc.portal.util; import org.mskcc.portal.model.GeneticEventImpl.CNA; import org.mskcc.portal.model.GeneticEventImpl.MRNA; import org.mskcc.portal.model.*; import org.mskcc.portal.oncoPrintSpecLanguage.*; import org.mskcc.cgds.model.CaseList; import org.mskcc.cgds.model.GeneticProfile; import java.io.IOException; import java.util.*; /** * Generates the Genomic OncoPrint. * * @author Ethan Cerami, Arthur Goldberg. */ public class MakeOncoPrint { public static int CELL_WIDTH = 8; public static int CELL_HEIGHT = 18; // support OncoPrints in both SVG and HTML; only HTML will have extra textual info, // such as legend, %alteration public enum OncoPrintType { SVG, HTML } /** * Generate the OncoPrint in HTML or SVG. * @param geneList List of Genes. * @param mergedProfile Merged Data Profile. * @param caseSets All Case Sets for this Cancer Study. * @param caseSetId Selected Case Set ID. * @param zScoreThreshold Z-Score Threshhold * @param theOncoPrintType OncoPrint Type. * @param showAlteredColumns Show only the altered columns. * @param geneticProfileIdSet IDs for all Genomic Profiles. * @param profileList List of all Genomic Profiles. * @throws IOException IO Error. */ public static String makeOncoPrint(String geneList, ProfileData mergedProfile, ArrayList<CaseList> caseSets, String caseSetId, double zScoreThreshold, OncoPrintType theOncoPrintType, boolean showAlteredColumns, HashSet<String> geneticProfileIdSet, ArrayList<GeneticProfile> profileList, boolean includeCaseSetDescription, boolean includeLegend ) throws IOException { StringBuffer out = new StringBuffer(); ParserOutput theOncoPrintSpecParserOutput = OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(geneList, geneticProfileIdSet, profileList, zScoreThreshold); ArrayList<String> listOfGenes = theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes(); String[] listOfGeneNames = new String[listOfGenes.size()]; listOfGeneNames = listOfGenes.toArray(listOfGeneNames); ProfileDataSummary dataSummary = new ProfileDataSummary(mergedProfile, theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold); ArrayList<GeneWithScore> geneWithScoreList = dataSummary.getGeneFrequencyList(); ArrayList<String> mergedCaseList = mergedProfile.getCaseIdList(); // TODO: make the gene sort order a user param, then call a method in ProfileDataSummary to sort GeneticEvent matrix[][] = ConvertProfileDataToGeneticEvents.convert (dataSummary, listOfGeneNames, theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold); // Sort Columns via Cascade Sorter ArrayList<EnumSet<CNA>> CNAsortOrder = new ArrayList<EnumSet<CNA>>(); CNAsortOrder.add(EnumSet.of(CNA.amplified)); CNAsortOrder.add(EnumSet.of(CNA.homoDeleted)); CNAsortOrder.add(EnumSet.of(CNA.Gained)); CNAsortOrder.add(EnumSet.of(CNA.HemizygouslyDeleted)); // combined because these are represented by the same color in the OncoPring CNAsortOrder.add(EnumSet.of(CNA.diploid, CNA.None)); ArrayList<EnumSet<MRNA>> MRNAsortOrder = new ArrayList<EnumSet<MRNA>>(); MRNAsortOrder.add(EnumSet.of(MRNA.upRegulated)); MRNAsortOrder.add(EnumSet.of(MRNA.downRegulated)); // combined because these are represented by the same color in the OncoPrint MRNAsortOrder.add(EnumSet.of(MRNA.Normal, MRNA.notShown)); GeneticEventComparator comparator = new GeneticEventComparator( CNAsortOrder, MRNAsortOrder, GeneticEventComparator.defaultMutationsSortOrder()); CascadeSortOfMatrix sorter = new CascadeSortOfMatrix(comparator); for (GeneticEvent[] row : matrix) { for (GeneticEvent element : row) { element.setGeneticEventComparator(comparator); } } matrix = (GeneticEvent[][]) sorter.sort(matrix); // optionally, show only columns with alterations // depending on showAlteredColumns, find last column with alterations int numColumnsToShow = matrix[0].length; if (showAlteredColumns) { // identify last column with an alteration // make HTML OncoPrint: not called if there are no genes // have oncoPrint shows nothing when no cases are modified numColumnsToShow = 0; firstAlteration: { // iterate through cases from the end, stopping at first case with alterations // (the sort order could sort unaltered cases before altered ones) for (int j = matrix[0].length - 1; 0 <= j; j // check all genes to determine if a case is altered for (int i = 0; i < matrix.length; i++) { GeneticEvent event = matrix[i][j]; if (dataSummary.isGeneAltered(event.getGene(), event.caseCaseId())) { numColumnsToShow = j + 1; break firstAlteration; } } } } } // support both SVG and HTML oncoPrints switch (theOncoPrintType) { case SVG: writeSVGOncoPrint(matrix, numColumnsToShow, out, mergedCaseList, geneWithScoreList); break; // exit the switch case HTML: int spacing = 0; int padding = 1; // the images are 4x bigger than this, which is necessary to create the necessary // design; but width and height scale them down, so that the OncoPrint fits // TODO: move these constants elsewhere, or derive from images directly int width = 6; int height = 17; writeHTMLOncoPrint(caseSets, caseSetId, matrix, numColumnsToShow, showAlteredColumns, theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), dataSummary, out, spacing, padding, width, height, includeCaseSetDescription, includeLegend); break; // exit the switch } return out.toString(); } static void writeSVGOncoPrint(GeneticEvent matrix[][], int numColumnsToShow, StringBuffer out, ArrayList<String> mergedCaseList, ArrayList<GeneWithScore> geneWithScoreList) { int windowWidth = 300 + (CELL_WIDTH * mergedCaseList.size()); int windowHeight = 50 + (CELL_HEIGHT * geneWithScoreList.size()); out.append("<?xml version=\"1.0\"?>\n" + "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n" + " \"http: "<svg onload=\"init(evt)\" xmlns=\"http: "version=\"1.1\" \n" + " width=\"" + windowWidth + "\" height=\"" + windowHeight + "\">\n"); // Output One Gene per Row int x = 0; int y = 25; out.append("<g font-family=\"Verdana\">"); for (int i = 0; i < matrix.length; i++) { GeneticEvent rowEvent = matrix[i][0]; x = 120; out.append("<text x=\"30\" y = \"" + (y + 15) + "\" fill = \"black\" " + "font-size = \"16\">\n" + rowEvent.getGene().toUpperCase() + "</text>"); for (int j = 0; j < numColumnsToShow; j++) { GeneticEvent event = matrix[i][j]; String style = getCopyNumberStyle(event); String mRNAStyle = getMRNAStyle(event); boolean isMutated = event.isMutated(); int block_height = CELL_HEIGHT - 2; out.append("\n<rect x=\"" + x + "\" y=\"" + y + "\" width=\"5\" stroke='" + mRNAStyle + "' height=\"" + block_height + "\" fill=\"" + style + "\"\n" + " fill-opacity=\"1.0\"/>"); if (isMutated) { out.append("\n<rect x='" + x + "' y='" + (y + 5) + "' fill='green' width='5' height='6'/>"); } x += CELL_WIDTH; } y += CELL_HEIGHT; } out.append("</g>"); out.append("</svg>\n"); } /** * Generates an OncoPrint in HTML. * @param caseSets List of all Case Sets. * @param caseSetId Selected Case Set ID. * @param matrix Matrix of Genomic Events. * @param numColumnsToShow Number of Columns to Show. * @param showAlteredColumns Flag to show only altered columns. * @param theOncoPrintSpecification The OncoPrint Spec. Object. * @param dataSummary Data Summary Object. * @param out HTML Out. * @param cellspacing Cellspacing. * @param cellpadding Cellpadding. * @param width Width. * @param height Height. */ static void writeHTMLOncoPrint(ArrayList<CaseList> caseSets, String caseSetId, GeneticEvent matrix[][], int numColumnsToShow, boolean showAlteredColumns, OncoPrintSpecification theOncoPrintSpecification, ProfileDataSummary dataSummary, StringBuffer out, int cellspacing, int cellpadding, int width, int height, boolean includeCaseSetDescription, boolean includeLegend) { out.append("<script type=\"text/javascript\" src=\"js/jquery.min.js\"></script>\n" + "<script type=\"text/javascript\" src=\"js/jquery.tipTip.minified.js\"></script>") ; out.append("<script type=\"text/javascript\">\n"+ "$(document).ready(function(){ \n" + "$(\".oncoprint_help\").tipTip({defaultPosition: \"right\", delay:\"100\", edgeOffset: 25});\n" + "});\n" + "</script>\n"); out.append("<div class=\"oncoprint\">\n"); if (includeCaseSetDescription) { for (CaseList caseSet : caseSets) { if (caseSetId.equals(caseSet.getStableId())) { out.append( "<p>Case Set: " + caseSet.getName() + ": " + caseSet.getDescription() + "</p>"); } } } // stats on pct alteration out.append("<p>Altered in " + dataSummary.getNumCasesAffected() + " (" + alterationValueToString(dataSummary.getPercentCasesAffected()) + ") of cases." + "</p>"); // output table header out.append( "\n<table cellspacing='" + cellspacing + "' cellpadding='" + cellpadding + "'>\n" + "<thead>\n" ); int columnWidthOfLegend = 80; // heading that indicates columns are cases // span multiple columns like legend String caseHeading; int numCases = matrix[0].length; String rightArrow = " &rarr;"; if (showAlteredColumns) { caseHeading = pluralize(dataSummary.getNumCasesAffected(), " case") + " with altered genes, out of " + pluralize(numCases, " total case") + rightArrow; } else { caseHeading = "All " + pluralize(numCases, " case") + rightArrow; } out.append("\n<tr><th></th><th valign='bottom' width=\"50\">Total altered</th>\n<th colspan='" + columnWidthOfLegend + "' align='left'>" + caseHeading + "</th>\n</tr>"); out.append("</thead>"); for (int i = 0; i < matrix.length; i++) { GeneticEvent rowEvent = matrix[i][0]; // new row out.append("<tr>"); // output cell with gene name, CSS does left justified out.append("<td>" + rowEvent.getGene().toUpperCase() + "</td>\n"); // output total % altered, right justified out.append("<td style=\" text-align: right\">"); out.append(alterationValueToString(dataSummary.getPercentCasesWhereGeneIsAltered (rowEvent.getGene()))); out.append("</td>\n"); // for each case for (int j = 0; j < numColumnsToShow; j++) { GeneticEvent event = matrix[i][j]; // get level of each datatype; concatenate to make image name // color could later could be in configuration file GeneticEventImpl.CNA CNAlevel = event.getCnaValue(); GeneticEventImpl.MRNA MRNAlevel = event.getMrnaValue(); // construct filename of icon representing this gene's genetic alteration event StringBuffer iconFileName = new StringBuffer(); // TODO: fix; IMHO this is wrong; diploid should be different from None String cnaName = CNAlevel.name(); if (cnaName.equals("None")) { cnaName = "diploid"; } iconFileName.append(cnaName); iconFileName.append("-"); iconFileName.append(MRNAlevel.name()); iconFileName.append("-"); if (event.isMutated()) { iconFileName.append("mutated"); } else { iconFileName.append("normal"); } iconFileName.append(".png"); out.append("<td class='op_data_cell'>" //+ IMG(iconFileName.toString(), width, height, event.caseCaseId()) // temporary tooltip = event.toString()+"\n"+event.caseCaseId() + IMG(iconFileName.toString(), width, height, event.toString()+"&lt;br/&gt;"+event.caseCaseId()) + "</td>\n"); } // TODO: learn how to fix: maybe Caitlin knows // ugly hack to make table wide enough to fit legend for (int c = numColumnsToShow; c < columnWidthOfLegend; c++) { out.append("<td></td>\n"); } } out.append ("\n"); // write table with legend out.append("</tr>"); if (includeLegend) { out.append("<tr>"); writeLegend(out, theOncoPrintSpecification.getUnionOfPossibleLevels(), 2, columnWidthOfLegend, width, height, cellspacing, cellpadding, width, 0.75f); out.append("</table>"); out.append("</div>"); } } // pluralize a count + name; dumb, because doesn't consider adding 'es' to pluralize static String pluralize(int num, String s) { if (num == 1) { return new String(num + s); } else { return new String(num + s + "s"); } } /** * format percentage * <p/> * if value == 0 return "--" * case value * 0: return "--" * 0<value<=0.01: return "<1%" * 1<value: return "<value>%" * * @param value * @return */ static String alterationValueToString(double value) { // in oncoPrint show 0 percent as 0%, not -- if (0.0 < value && value <= 0.01) { return "<1%"; } // if( 1.0 < value ){ Formatter f = new Formatter(); f.format("%.0f", value * 100.0); return f.out().toString() + "%"; } // directory containing images static String imageDirectory = "images/oncoPrint/"; static String IMG(String theImage, int width, int height) { return IMG(theImage, width, height, null); } static String IMG(String theImage, int width, int height, String toolTip) { StringBuffer sb = new StringBuffer(); sb.append("<img src='" + imageDirectory + theImage + "' alt='" + theImage + // TODO: FOR PRODUCTION; real ALT, should be description of genetic alteration "' width='" + width + "' height='" + height+"'"); if (null != toolTip) { sb.append(" class=\"oncoprint_help\" title=\"" + toolTip + "\""); } return sb.append("/>").toString(); } /** * write legend for HTML OncoPrint * * @param out writer for the output * @param width width of an icon * @param height height of an icon * @param cellspacing TABLE attribute * @param cellpadding TABLE attribute * @param horizontalSpaceAfterDescription * blank space, in pixels, after each description */ public static void writeLegend(StringBuffer out, OncoPrintGeneDisplaySpec allPossibleAlterations, int colsIndented, int colspan, int width, int height, int cellspacing, int cellpadding, int horizontalSpaceAfterDescription, float gap) { int rowHeight = (int) ((1.0 + gap) * height); // indent in enclosing table // for horiz alignment, skip colsIndented columns for (int i = 0; i < colsIndented; i++) { out.append("<td></td>"); } // TODO: FIX; LOOKS BAD WHEN colspan ( == number of columns == cases) is small out.append("<td colspan='" + colspan + "'>"); // output table header out.append( "\n<table cellspacing='" + cellspacing + "' cellpadding='" + cellpadding + "'>" + "\n<tbody>"); out.append("\n<tr>"); /* * TODO: make this data driven; use enumerations */ // { "amplified-notShown-normal", "Amplification" } if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration, GeneticTypeLevel.Amplified)) { outputLegendEntry(out, "amplified-notShown-normal", "Amplification", rowHeight, width, height, horizontalSpaceAfterDescription); } // { "homoDeleted-notShown-normal", "Homozygous Deletion" }, if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration, GeneticTypeLevel.HomozygouslyDeleted)) { outputLegendEntry(out, "homoDeleted-notShown-normal", "Homozygous Deletion", rowHeight, width, height, horizontalSpaceAfterDescription); } // { "Gained-notShown-normal", "Gain" }, if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration, GeneticTypeLevel.Gained)) { outputLegendEntry(out, "Gained-notShown-normal", "Gain", rowHeight, width, height, horizontalSpaceAfterDescription); } // { "HemizygouslyDeleted-notShown-normal", "Hemizygous Deletion" }, if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration, GeneticTypeLevel.HemizygouslyDeleted)) { outputLegendEntry(out, "HemizygouslyDeleted-notShown-normal", "Hemizygous Deletion", rowHeight, width, height, horizontalSpaceAfterDescription); } // { "diploid-upRegulated-normal", "Up-regulation" }, ResultDataTypeSpec theResultDataTypeSpec = allPossibleAlterations .getResultDataTypeSpec(GeneticDataTypes.Expression); if (null != theResultDataTypeSpec && (null != theResultDataTypeSpec.getCombinedGreaterContinuousDataTypeSpec())) { outputLegendEntry(out, "diploid-upRegulated-normal", "Up-regulation", rowHeight, width, height, horizontalSpaceAfterDescription); } // { "diploid-downRegulated-normal", "Down-regulation" }, theResultDataTypeSpec = allPossibleAlterations.getResultDataTypeSpec (GeneticDataTypes.Expression); if (null != theResultDataTypeSpec && (null != theResultDataTypeSpec.getCombinedLesserContinuousDataTypeSpec())) { outputLegendEntry(out, "diploid-downRegulated-normal", "Down-regulation", rowHeight, width, height, horizontalSpaceAfterDescription); } // { "diploid-notShown-mutated", "Mutation" }, if (allPossibleAlterations.satisfy(GeneticDataTypes.Mutation, GeneticTypeLevel.Mutated)) { outputLegendEntry(out, "diploid-notShown-mutated", "Mutation", rowHeight, width, height, horizontalSpaceAfterDescription); } out.append("</tr>\n"); if (allPossibleAlterations.satisfy(GeneticDataTypes.CopyNumberAlteration)) { out.append("<tr>\n"); out.append("<td colspan='" + colspan / 4 + "' style=\"vertical-align:bottom\" >" + "<div class=\"tiny\"> Copy number alterations are putative.<br/></div></td>\n"); out.append("</tr>"); } out.append("</tbody></table></td></tr>"); } private static void outputLegendEntry(StringBuffer out, String imageName, String imageDescription, int rowHeight, int width, int height, int horizontalSpaceAfterDescription) { out.append("<td height='" + rowHeight + "' style=\"vertical-align:bottom\" >" + IMG(imageName + ".png", width, height)); out.append("</td>\n"); out.append("<td height='" + rowHeight + "' style=\"vertical-align:bottom\" >" + imageDescription); // add some room after description out.append("</td>\n"); out.append("<td width='" + horizontalSpaceAfterDescription + "'></td>\n"); } /** * Gets the Correct Copy Number color for OncoPrint. */ private static String getCopyNumberStyle(GeneticEvent event) { switch (event.getCnaValue()) { case amplified: return "red"; case Gained: return "lightpink"; case HemizygouslyDeleted: return "lightblue"; case homoDeleted: return "blue"; case diploid: case None: return "lightgray"; } // TODO: throw exception return "shouldNotBeReached"; // never reached } /** * Gets the Correct mRNA color. * Displayed in the rectangle boundary. */ private static String getMRNAStyle(GeneticEvent event) { switch (event.getMrnaValue()) { case upRegulated: // if the mRNA is UpRegulated, then pink boundary; return "#FF9999"; case notShown: // white is the default, not showing mRNA expression level return "white"; case downRegulated: // downregulated, then blue boundary return "#6699CC"; } // TODO: throw exception return "shouldNotBeReached"; // never reached } }
package net.md_5.bungee; import net.md_5.bungee.reconnect.SQLReconnectHandler; import net.md_5.bungee.scheduler.BungeeScheduler; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.providers.netty.NettyAsyncHttpProvider; import com.ning.http.client.providers.netty.NettyAsyncHttpProviderConfig; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelException; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.MultithreadEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import net.md_5.bungee.config.Configuration; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ReconnectHandler; import net.md_5.bungee.api.config.ConfigurationAdapter; import net.md_5.bungee.api.config.ListenerInfo; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import net.md_5.bungee.api.scheduler.TaskScheduler; import net.md_5.bungee.command.*; import net.md_5.bungee.config.YamlConfig; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.packet.DefinedPacket; import net.md_5.bungee.protocol.packet.Packet3Chat; import net.md_5.bungee.protocol.packet.PacketFAPluginMessage; import net.md_5.bungee.protocol.Vanilla; import net.md_5.bungee.scheduler.BungeeThreadPool; import net.md_5.bungee.util.CaseInsensitiveMap; /** * Main BungeeCord proxy class. */ public class BungeeCord extends ProxyServer { /** * Current operation state. */ public volatile boolean isRunning; /** * Configuration. */ public final Configuration config = new Configuration(); /** * Localization bundle. */ public final ResourceBundle bundle = ResourceBundle.getBundle( "messages_en" ); /** * Thread pools. */ public final ScheduledThreadPoolExecutor executors = new BungeeThreadPool( new ThreadFactoryBuilder().setNameFormat( "Bungee Pool Thread #%1$d" ).build() ); public final MultithreadEventLoopGroup eventLoops = new NioEventLoopGroup( 0, new ThreadFactoryBuilder().setNameFormat( "Netty IO Thread #%1$d" ).build() ); /** * locations.yml save thread. */ private final Timer saveThread = new Timer( "Reconnect Saver" ); private final Timer metricsThread = new Timer( "Metrics Thread" ); /** * Server socket listener. */ private Collection<Channel> listeners = new HashSet<>(); /** * Fully qualified connections. */ private final Map<String, UserConnection> connections = new CaseInsensitiveMap<>(); private final ReadWriteLock connectionLock = new ReentrantReadWriteLock(); /** * Plugin manager. */ @Getter public final PluginManager pluginManager = new PluginManager( this ); @Getter @Setter private ReconnectHandler reconnectHandler; @Getter @Setter private ConfigurationAdapter configurationAdapter = new YamlConfig(); private final Collection<String> pluginChannels = new HashSet<>(); @Getter private final File pluginsFolder = new File( "plugins" ); @Getter private final TaskScheduler scheduler = new BungeeScheduler(); @Getter private final AsyncHttpClient httpClient = new AsyncHttpClient( new NettyAsyncHttpProvider( new AsyncHttpClientConfig.Builder().setAsyncHttpClientProviderConfig( new NettyAsyncHttpProviderConfig().addProperty( NettyAsyncHttpProviderConfig.BOSS_EXECUTOR_SERVICE, executors ) ).setExecutorService( executors ).build() ) ); { // TODO: Proper fallback when we interface the manager getPluginManager().registerCommand( null, new CommandReload() ); getPluginManager().registerCommand( null, new CommandEnd() ); getPluginManager().registerCommand( null, new CommandList() ); getPluginManager().registerCommand( null, new CommandServer() ); getPluginManager().registerCommand( null, new CommandIP() ); getPluginManager().registerCommand( null, new CommandAlert() ); getPluginManager().registerCommand( null, new CommandBungee() ); getPluginManager().registerCommand( null, new CommandPerms() ); getPluginManager().registerCommand( null, new CommandSend() ); getPluginManager().registerCommand( null, new CommandFind() ); registerChannel( "BungeeCord" ); } public static BungeeCord getInstance() { return (BungeeCord) ProxyServer.getInstance(); } /** * Starts a new instance of BungeeCord. * * @param args command line arguments, currently none are used * @throws Exception when the server cannot be started */ public static void main(String[] args) throws Exception { Calendar deadline = Calendar.getInstance(); deadline.set( 2013, 7, 1 ); // year, month, date if ( Calendar.getInstance().after( deadline ) ) { System.err.println( "*** Warning, this build is outdated ***" ); System.err.println( "*** Please download a new build from http: System.err.println( "*** You will get NO support regarding this build ***" ); System.err.println( "*** Server will start in 15 seconds ***" ); Thread.sleep( TimeUnit.SECONDS.toMillis( 15 ) ); } BungeeCord bungee = new BungeeCord(); ProxyServer.setInstance( bungee ); bungee.getLogger().info( "Enabled BungeeCord version " + bungee.getVersion() ); bungee.start(); BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); while ( bungee.isRunning ) { String line = br.readLine(); if ( line != null ) { boolean handled = getInstance().getPluginManager().dispatchCommand( ConsoleCommandSender.getInstance(), line ); if ( !handled ) { System.err.println( "Command not found" ); } } } } /** * Start this proxy instance by loading the configuration, plugins and * starting the connect thread. * * @throws Exception */ @Override public void start() throws Exception { pluginsFolder.mkdir(); pluginManager.detectPlugins( pluginsFolder ); config.load(); if ( reconnectHandler == null ) { reconnectHandler = new SQLReconnectHandler(); } isRunning = true; pluginManager.loadAndEnablePlugins(); startListeners(); saveThread.scheduleAtFixedRate( new TimerTask() { @Override public void run() { getReconnectHandler().save(); } }, 0, TimeUnit.MINUTES.toMillis( 5 ) ); metricsThread.scheduleAtFixedRate( new Metrics(), 0, TimeUnit.MINUTES.toMillis( Metrics.PING_INTERVAL ) ); } public void startListeners() { for ( final ListenerInfo info : config.getListeners() ) { ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().info( "Listening on " + info.getHost() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new ServerBootstrap() .channel( NioServerSocketChannel.class ) .childAttr( PipelineUtils.LISTENER, info ) .childHandler( PipelineUtils.SERVER_CHILD ) .group( eventLoops ) .localAddress( info.getHost() ) .bind().addListener( listener ); } } public void stopListeners() { for ( Channel listener : listeners ) { getLogger().log( Level.INFO, "Closing listener {0}", listener ); try { listener.close().syncUninterruptibly(); } catch ( ChannelException ex ) { getLogger().severe( "Could not close listen thread" ); } } listeners.clear(); } @Override public void stop() { new Thread( "Shutdown Thread" ) { @Override public void run() { BungeeCord.this.isRunning = false; httpClient.close(); executors.shutdown(); stopListeners(); getLogger().info( "Closing pending connections" ); connectionLock.readLock().lock(); try { getLogger().info( "Disconnecting " + connections.size() + " connections" ); for ( UserConnection user : connections.values() ) { user.disconnect( getTranslation( "restart" ) ); } } finally { connectionLock.readLock().unlock(); } getLogger().info( "Closing IO threads" ); eventLoops.shutdown(); try { eventLoops.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); } catch ( InterruptedException ex ) { } getLogger().info( "Saving reconnect locations" ); reconnectHandler.save(); reconnectHandler.close(); saveThread.cancel(); metricsThread.cancel(); // TODO: Fix this shit getLogger().info( "Disabling plugins" ); for ( Plugin plugin : pluginManager.getPlugins() ) { plugin.onDisable(); getScheduler().cancel( plugin ); } getLogger().info( "Thankyou and goodbye" ); System.exit( 0 ); } }.start(); } /** * Broadcasts a packet to all clients that is connected to this instance. * * @param packet the packet to send */ public void broadcast(DefinedPacket packet) { connectionLock.readLock().lock(); try { for ( UserConnection con : connections.values() ) { con.unsafe().sendPacket( packet ); } } finally { connectionLock.readLock().unlock(); } } @Override public String getName() { return "BungeeCord"; } @Override public String getVersion() { return ( BungeeCord.class.getPackage().getImplementationVersion() == null ) ? "unknown" : BungeeCord.class.getPackage().getImplementationVersion(); } @Override public String getTranslation(String name) { String translation = "<translation '" + name + "' missing>"; try { translation = bundle.getString( name ); } catch ( MissingResourceException ex ) { } return translation; } @Override public Logger getLogger() { return BungeeLogger.instance; } @Override @SuppressWarnings("unchecked") public Collection<ProxiedPlayer> getPlayers() { connectionLock.readLock().lock(); try { return (Collection) new HashSet<>( connections.values() ); } finally { connectionLock.readLock().unlock(); } } @Override public int getOnlineCount() { return connections.size(); } @Override public ProxiedPlayer getPlayer(String name) { connectionLock.readLock().lock(); try { return connections.get( name ); } finally { connectionLock.readLock().unlock(); } } @Override public Map<String, ServerInfo> getServers() { return config.getServers(); } @Override public ServerInfo getServerInfo(String name) { return getServers().get( name ); } @Override @Synchronized("pluginChannels") public void registerChannel(String channel) { pluginChannels.add( channel ); } @Override @Synchronized("pluginChannels") public void unregisterChannel(String channel) { pluginChannels.remove( channel ); } @Override @Synchronized("pluginChannels") public Collection<String> getChannels() { return Collections.unmodifiableCollection( pluginChannels ); } public PacketFAPluginMessage registerChannels() { return new PacketFAPluginMessage( "REGISTER", Util.format( pluginChannels, "\00" ).getBytes() ); } @Override public byte getProtocolVersion() { return Vanilla.PROTOCOL_VERSION; } @Override public String getGameVersion() { return Vanilla.GAME_VERSION; } @Override public ServerInfo constructServerInfo(String name, InetSocketAddress address, boolean restricted) { return new BungeeServerInfo( name, address, restricted ); } @Override public CommandSender getConsole() { return ConsoleCommandSender.getInstance(); } @Override public void broadcast(String message) { getConsole().sendMessage( message ); broadcast( new Packet3Chat( message ) ); } public void addConnection(UserConnection con) { connectionLock.writeLock().lock(); try { connections.put( con.getName(), con ); } finally { connectionLock.writeLock().unlock(); } } public void removeConnection(UserConnection con) { connectionLock.writeLock().lock(); try { connections.remove( con.getName() ); } finally { connectionLock.writeLock().unlock(); } } }
package net.md_5.bungee; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.GsonBuilder; import net.md_5.bungee.api.Favicon; import net.md_5.bungee.api.ServerPing; import net.md_5.bungee.api.Title; import net.md_5.bungee.module.ModuleManager; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.chat.ComponentSerializer; import net.md_5.bungee.log.BungeeLogger; import net.md_5.bungee.scheduler.BungeeScheduler; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.gson.Gson; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.github.waterfallmc.waterfall.conf.WaterfallConfiguration; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelException; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.util.ResourceLeakDetector; import net.md_5.bungee.conf.Configuration; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.net.InetSocketAddress; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.Properties; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import jline.console.ConsoleReader; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ReconnectHandler; import net.md_5.bungee.api.config.ConfigurationAdapter; import net.md_5.bungee.api.config.ListenerInfo; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import net.md_5.bungee.command.*; import net.md_5.bungee.compress.CompressFactory; import net.md_5.bungee.conf.YamlConfig; import net.md_5.bungee.forge.ForgeConstants; import net.md_5.bungee.log.LoggingOutputStream; import net.md_5.bungee.netty.PipelineUtils; import net.md_5.bungee.protocol.DefinedPacket; import net.md_5.bungee.protocol.Protocol; import net.md_5.bungee.protocol.ProtocolConstants; import net.md_5.bungee.protocol.packet.Chat; import net.md_5.bungee.protocol.packet.PluginMessage; import net.md_5.bungee.query.RemoteQuery; import net.md_5.bungee.util.CaseInsensitiveMap; import org.fusesource.jansi.AnsiConsole; /** * Main BungeeCord proxy class. */ public class BungeeCord extends ProxyServer { /** * Current operation state. */ public volatile boolean isRunning; /** * Configuration. */ @Getter public final Configuration config = new WaterfallConfiguration(); /** * Localization bundle. */ public ResourceBundle bundle; public EventLoopGroup eventLoops; /** * locations.yml save thread. */ private final Timer saveThread = new Timer( "Reconnect Saver" ); /** * Server socket listener. */ private final Collection<Channel> listeners = new HashSet<>(); /** * Fully qualified connections. */ private final Map<String, UserConnection> connections = new CaseInsensitiveMap<>(); // Used to help with packet rewriting private final Map<UUID, UserConnection> connectionsByOfflineUUID = new HashMap<>(); private final ReadWriteLock connectionLock = new ReentrantReadWriteLock(); /** * Plugin manager. */ @Getter public final PluginManager pluginManager = new PluginManager( this ); @Getter @Setter private ReconnectHandler reconnectHandler; @Getter @Setter private ConfigurationAdapter configurationAdapter = new YamlConfig(); private final Collection<String> pluginChannels = new HashSet<>(); @Getter private final File pluginsFolder = new File( "plugins" ); @Getter private final BungeeScheduler scheduler = new BungeeScheduler(); @Getter private final ConsoleReader consoleReader; @Getter private final Logger logger; public final Gson gson = new GsonBuilder() .registerTypeAdapter( ServerPing.PlayerInfo.class, new PlayerInfoSerializer( ProtocolConstants.MINECRAFT_1_7_6 ) ) .registerTypeAdapter( Favicon.class, Favicon.getFaviconTypeAdapter() ).create(); public final Gson gsonLegacy = new GsonBuilder() .registerTypeAdapter( ServerPing.PlayerInfo.class, new PlayerInfoSerializer( ProtocolConstants.MINECRAFT_1_7_2 ) ) .registerTypeAdapter( Favicon.class, Favicon.getFaviconTypeAdapter() ).create(); @Getter private ConnectionThrottle joinThrottle; private final ModuleManager moduleManager = new ModuleManager(); private final File messagesFile = new File( "messages.properties" ); { // TODO: Proper fallback when we interface the manager getPluginManager().registerCommand( null, new CommandReload() ); getPluginManager().registerCommand( null, new CommandEnd() ); getPluginManager().registerCommand( null, new CommandIP() ); getPluginManager().registerCommand( null, new CommandBungee() ); getPluginManager().registerCommand( null, new CommandPerms() ); registerChannel( "BungeeCord" ); } public static BungeeCord getInstance() { return (BungeeCord) ProxyServer.getInstance(); } @SuppressFBWarnings("DM_DEFAULT_ENCODING") public BungeeCord() throws IOException { // Java uses ! to indicate a resource inside of a jar/zip/other container. Running Bungee from within a directory that has a ! will cause this to muck up. Preconditions.checkState( new File( "." ).getAbsolutePath().indexOf( '!' ) == -1, "Cannot use BungeeCord in directory with ! in path." ); try { bundle = ResourceBundle.getBundle( "messages" ); } catch ( MissingResourceException ex ) { bundle = ResourceBundle.getBundle( "messages", Locale.ENGLISH ); } // This is a workaround for quite possibly the weirdest bug I have ever encountered in my life! // When jansi attempts to extract its natives, by default it tries to extract a specific version, // using the loading class's implementation version. Normally this works completely fine, // however when on Windows certain characters such as - and : can trigger special behaviour. // Furthermore this behaviour only occurs in specific combinations due to the parsing done by jansi. // For example test-test works fine, but test-test-test does not! In order to avoid this all together but // still keep our versions the same as they were, we set the override property to the essentially garbage version // BungeeCord. This version is only used when extracting the libraries to their temp folder. System.setProperty( "library.jansi.version", "BungeeCord" ); AnsiConsole.systemInstall(); consoleReader = new ConsoleReader(); consoleReader.setExpandEvents( false ); consoleReader.addCompleter( new ConsoleCommandCompleter( this ) ); logger = new BungeeLogger( this ); System.setErr( new PrintStream( new LoggingOutputStream( logger, Level.SEVERE ), true ) ); System.setOut( new PrintStream( new LoggingOutputStream( logger, Level.INFO ), true ) ); if ( !Boolean.getBoolean( "net.md_5.bungee.native.disable" ) ) { if ( EncryptionUtil.nativeFactory.load() ) { logger.info( "Using OpenSSL based native cipher." ); } else { logger.info( "Using standard Java JCE cipher. To enable the OpenSSL based native cipher, please make sure you are using 64 bit Ubuntu or Debian with libssl installed." ); } if ( CompressFactory.zlib.load() ) { logger.info( "Using native code compressor" ); } else { logger.info( "Using standard Java compressor. To enable zero copy compression, run on 64 bit Linux" ); } } reloadMessages(); } @Override public void reloadMessages() { try // Make sure the translation file is up to date { Properties messages = new Properties(); if ( messagesFile.exists() ) { try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(messagesFile), Charsets.UTF_8))) { messages.load(reader); } } // Check for new entries int newEntries = 0; for ( String key : bundle.keySet() ) { if ( !messages.containsKey( key ) ) { messages.put( key, bundle.getObject(key) ); newEntries++; } } if ( newEntries > 0 ) { // We need to save the file to add the new entries try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(messagesFile), Charsets.UTF_8))) { messages.store(writer, "Waterfall messages, last updated for " + getVersion() ); } } } catch ( Exception ex ) { getLogger().log( Level.SEVERE, "Could not update messages", ex ); } // Load the messages from the configuration file try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream( messagesFile ), Charsets.UTF_8))) { bundle = new PropertyResourceBundle(reader); } catch ( Exception ex ) { getLogger().log( Level.SEVERE, "Could not reload messages", ex ); } } /** * Start this proxy instance by loading the configuration, plugins and * starting the connect thread. * * @throws Exception */ @Override @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") public void start() throws Exception { System.setProperty( "java.net.preferIPv4Stack", "true" ); // Minecraft does not support IPv6 System.setProperty( "io.netty.selectorAutoRebuildThreshold", "0" ); // Seems to cause Bungee to stop accepting connections if ( System.getProperty( "io.netty.leakDetectionLevel" ) == null ) { ResourceLeakDetector.setLevel( ResourceLeakDetector.Level.DISABLED ); // Eats performance } eventLoops = PipelineUtils.newEventLoopGroup( 0, new ThreadFactoryBuilder().setNameFormat( "Netty IO Thread #%1$d" ).build() ); File moduleDirectory = new File( "modules" ); moduleManager.load( this, moduleDirectory ); pluginManager.detectPlugins( moduleDirectory ); pluginsFolder.mkdir(); pluginManager.detectPlugins( pluginsFolder ); pluginManager.loadPlugins(); config.load(); registerChannel( ForgeConstants.FML_TAG ); registerChannel( ForgeConstants.FML_HANDSHAKE_TAG ); registerChannel( ForgeConstants.FORGE_REGISTER ); isRunning = true; pluginManager.enablePlugins(); joinThrottle = new ConnectionThrottle( config.getJoinThrottle() ); startListeners(); saveThread.scheduleAtFixedRate( new TimerTask() { @Override public void run() { if ( getReconnectHandler() != null ) { getReconnectHandler().save(); } } }, 0, TimeUnit.MINUTES.toMillis( 5 ) ); } public void startListeners() { for ( final ListenerInfo info : config.getListeners() ) { ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().log( Level.INFO, "Listening on {0}", info.getHost() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new ServerBootstrap() .channel( PipelineUtils.getServerChannel() ) .option( ChannelOption.SO_REUSEADDR, true ) // TODO: Move this elsewhere! .childOption( ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024 * 10 ) .childOption( ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1024 * 1024 * 1 ) .childAttr( PipelineUtils.LISTENER, info ) .childHandler( PipelineUtils.SERVER_CHILD ) .group( eventLoops ) .localAddress( info.getHost() ) .bind().addListener( listener ); if ( info.isQueryEnabled() ) { ChannelFutureListener bindListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().log( Level.INFO, "Started query on {0}", future.channel().localAddress() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new RemoteQuery( this, info ).start( PipelineUtils.getDatagramChannel(), new InetSocketAddress( info.getHost().getAddress(), info.getQueryPort() ), eventLoops, bindListener ); } } } public void stopListeners() { for ( Channel listener : listeners ) { getLogger().log( Level.INFO, "Closing listener {0}", listener ); try { listener.close().syncUninterruptibly(); } catch ( ChannelException ex ) { getLogger().severe( "Could not close listen thread" ); } } listeners.clear(); } @Override public void stop() { stop( getTranslation( "restart" ) ); } @Override public void stop(final String reason) { new Thread( "Shutdown Thread" ) { @Override @SuppressFBWarnings("DM_EXIT") @SuppressWarnings("TooBroadCatch") public void run() { BungeeCord.this.isRunning = false; stopListeners(); getLogger().info( "Closing pending connections" ); connectionLock.readLock().lock(); try { getLogger().log( Level.INFO, "Disconnecting {0} connections", connections.size() ); for ( UserConnection user : connections.values() ) { user.disconnect( reason ); } } finally { connectionLock.readLock().unlock(); } getLogger().info( "Closing IO threads" ); eventLoops.shutdownGracefully(); try { eventLoops.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS ); } catch ( InterruptedException ex ) { } if ( reconnectHandler != null ) { getLogger().info( "Saving reconnect locations" ); reconnectHandler.save(); reconnectHandler.close(); } saveThread.cancel(); // TODO: Fix this shit getLogger().info( "Disabling plugins" ); for ( Plugin plugin : Lists.reverse( new ArrayList<>( pluginManager.getPlugins() ) ) ) { try { plugin.onDisable(); for ( Handler handler : plugin.getLogger().getHandlers() ) { handler.close(); } } catch ( Throwable t ) { getLogger().log( Level.SEVERE, "Exception disabling plugin " + plugin.getDescription().getName(), t ); } getScheduler().cancel( plugin ); plugin.getExecutorService().shutdownNow(); } getLogger().info( "Thank you and goodbye" ); // Need to close loggers after last message! for ( Handler handler : getLogger().getHandlers() ) { handler.close(); } System.exit( 0 ); } }.start(); } /** * Broadcasts a packet to all clients that is connected to this instance. * * @param packet the packet to send */ public void broadcast(DefinedPacket packet) { connectionLock.readLock().lock(); try { for ( UserConnection con : connections.values() ) { con.unsafe().sendPacket( packet ); } } finally { connectionLock.readLock().unlock(); } } @Override public String getName() { return "Waterfall"; } @Override public String getVersion() { return ( BungeeCord.class.getPackage().getImplementationVersion() == null ) ? "unknown" : BungeeCord.class.getPackage().getImplementationVersion(); } @Override public String getTranslation(String name, Object... args) { String translation = "<translation '" + name + "' missing>"; try { translation = MessageFormat.format( bundle.getString( name ), args ); } catch ( MissingResourceException ex ) { } return translation; } @Override public Collection<ProxiedPlayer> getPlayers() { connectionLock.readLock().lock(); try { return Collections.unmodifiableCollection( new HashSet<ProxiedPlayer>( connections.values() ) ); } finally { connectionLock.readLock().unlock(); } } @Override public int getOnlineCount() { return connections.size(); } @Override public ProxiedPlayer getPlayer(String name) { connectionLock.readLock().lock(); try { return connections.get( name ); } finally { connectionLock.readLock().unlock(); } } public UserConnection getPlayerByOfflineUUID(UUID name) { connectionLock.readLock().lock(); try { return connectionsByOfflineUUID.get( name ); } finally { connectionLock.readLock().unlock(); } } @Override public ProxiedPlayer getPlayer(UUID uuid) { connectionLock.readLock().lock(); try { for ( ProxiedPlayer proxiedPlayer : connections.values() ) { if ( proxiedPlayer.getUniqueId().equals( uuid ) ) { return proxiedPlayer; } } return null; } finally { connectionLock.readLock().unlock(); } } @Override public Map<String, ServerInfo> getServers() { return config.getServers(); } @Override public ServerInfo getServerInfo(String name) { return getServers().get( name ); } @Override @Synchronized("pluginChannels") public void registerChannel(String channel) { pluginChannels.add( channel ); } @Override @Synchronized("pluginChannels") public void unregisterChannel(String channel) { pluginChannels.remove( channel ); } @Override @Synchronized("pluginChannels") public Collection<String> getChannels() { return Collections.unmodifiableCollection( pluginChannels ); } public PluginMessage registerChannels() { return new PluginMessage( "REGISTER", Util.format( pluginChannels, "\00" ).getBytes( Charsets.UTF_8 ), false ); } @Override public int getProtocolVersion() { return Protocol.supportedVersions.get( Protocol.supportedVersions.size() - 1 ); } @Override public String getGameVersion() { return "1.8"; } @Override public ServerInfo constructServerInfo(String name, InetSocketAddress address, String motd, boolean restricted) { return new BungeeServerInfo( name, address, motd, restricted ); } @Override public CommandSender getConsole() { return ConsoleCommandSender.getInstance(); } @Override public void broadcast(String message) { broadcast( TextComponent.fromLegacyText( message ) ); } @Override public void broadcast(BaseComponent... message) { getConsole().sendMessage( BaseComponent.toLegacyText( message ) ); broadcast( new Chat( ComponentSerializer.toString( message ) ) ); } @Override public void broadcast(BaseComponent message) { getConsole().sendMessage( message.toLegacyText() ); broadcast( new Chat( ComponentSerializer.toString( message ) ) ); } public void addConnection(UserConnection con) { connectionLock.writeLock().lock(); try { connections.put( con.getName(), con ); connectionsByOfflineUUID.put( con.getPendingConnection().getOfflineId(), con ); } finally { connectionLock.writeLock().unlock(); } } public void removeConnection(UserConnection con) { connectionLock.writeLock().lock(); try { // TODO See #1218 if ( connections.get( con.getName() ) == con ) { connections.remove( con.getName() ); connectionsByOfflineUUID.remove( con.getPendingConnection().getOfflineId() ); } } finally { connectionLock.writeLock().unlock(); } } @Override public Collection<String> getDisabledCommands() { return config.getDisabledCommands(); } @Override public Collection<ProxiedPlayer> matchPlayer(final String partialName) { Preconditions.checkNotNull( partialName, "partialName" ); ProxiedPlayer exactMatch = getPlayer( partialName ); if ( exactMatch != null ) { return Collections.singleton( exactMatch ); } return Sets.newHashSet( Iterables.filter( getPlayers(), new Predicate<ProxiedPlayer>() { @Override public boolean apply(ProxiedPlayer input) { return ( input == null ) ? false : input.getName().toLowerCase().startsWith( partialName.toLowerCase() ); } } ) ); } @Override public Title createTitle() { return new BungeeTitle(); } }
package py4j.reflection; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import py4j.Py4JException; /** * <p> * The reflection engine is responsible for accessing the classes, the instances * and members in a JVM. * </p> * * @author Barthelemy Dagenais * */ public class ReflectionEngine { public static int cacheSize = 100; private final Logger logger = Logger.getLogger(ReflectionEngine.class .getName()); public final static Object RETURN_VOID = new Object(); private static ThreadLocal<LRUCache<MethodDescriptor, MethodInvoker>> cacheHolder = new ThreadLocal<LRUCache<MethodDescriptor, MethodInvoker>>() { @Override protected LRUCache<MethodDescriptor, MethodInvoker> initialValue() { return new LRUCache<MethodDescriptor, MethodInvoker>(cacheSize); } }; public Object createArray(String fqn, int[] dimensions) { Class<?> clazz = null; Object returnObject = null; try { clazz = TypeUtil.forName(fqn); returnObject = Array.newInstance(clazz, dimensions); } catch (Exception e) { logger.log(Level.WARNING, "Class FQN does not exist: " + fqn, e); throw new Py4JException(e); } return returnObject; } private MethodInvoker getBestConstructor( List<Constructor<?>> acceptableConstructors, Class<?>[] parameters) { MethodInvoker lowestCost = null; for (Constructor<?> constructor : acceptableConstructors) { MethodInvoker temp = MethodInvoker.buildInvoker(constructor, parameters); int cost = temp.getCost(); if (cost == -1) { continue; } else if (cost == 0) { lowestCost = temp; break; } else if (lowestCost == null || cost < lowestCost.getCost()) { lowestCost = temp; } } return lowestCost; } private MethodInvoker getBestMethod(List<Method> acceptableMethods, Class<?>[] parameters) { MethodInvoker lowestCost = null; for (Method method : acceptableMethods) { MethodInvoker temp = MethodInvoker.buildInvoker(method, parameters); int cost = temp.getCost(); if (cost == -1) { continue; } else if (cost == 0) { lowestCost = temp; break; } else if (lowestCost == null || cost < lowestCost.getCost()) { lowestCost = temp; } } return lowestCost; } public Class<?> getClass(Class<?> clazz, String name) { Class<?> memberClass = null; try { for (Class<?> tempClass : clazz.getClasses()) { if (tempClass.getSimpleName().equals(name)) { memberClass = tempClass; break; } } } catch (Exception e) { memberClass = null; } return memberClass; } private Class<?>[] getClassParameters(Object[] parameters) { int size = parameters.length; Class<?>[] classes = new Class<?>[size]; for (int i = 0; i < size; i++) { if (parameters[i] == null) { classes[i] = null; } else { classes[i] = parameters[i].getClass(); } } return classes; } public MethodInvoker getConstructor(Class<?> clazz, Class<?>[] parameters) { MethodDescriptor mDescriptor = new MethodDescriptor(clazz.getName(), clazz, parameters); MethodInvoker mInvoker = null; List<Constructor<?>> acceptableConstructors = null; LRUCache<MethodDescriptor, MethodInvoker> cache = cacheHolder.get(); mInvoker = cache.get(mDescriptor); if (mInvoker == null) { acceptableConstructors = getConstructorsByLength(clazz, parameters.length); if (acceptableConstructors.size() == 1) { mInvoker = MethodInvoker.buildInvoker(acceptableConstructors .get(0), parameters); } else { mInvoker = getBestConstructor(acceptableConstructors, parameters); } if (mInvoker != null && mInvoker.getCost() != -1) { cache.put(mDescriptor, mInvoker); } else { String errorMessage = "Constructor " + clazz.getName() + "(" + Arrays.toString(parameters) + ") does not exist"; logger.log(Level.WARNING, errorMessage); throw new Py4JException(errorMessage); } } return mInvoker; } public MethodInvoker getConstructor(String classFQN, Object[] parameters) { Class<?> clazz = null; try { clazz = Class.forName(classFQN); } catch (Exception e) { logger.log(Level.WARNING, "Class FQN does not exist: " + classFQN, e); throw new Py4JException(e); } return getConstructor(clazz, getClassParameters(parameters)); } private List<Constructor<?>> getConstructorsByLength(Class<?> clazz, int length) { List<Constructor<?>> methods = new ArrayList<Constructor<?>>(); for (Constructor<?> constructor : clazz.getConstructors()) { if (constructor.getParameterTypes().length == length) { methods.add(constructor); } } return methods; } /** * * @param clazz * @param name * @return The field or null if a field with this name does not exist in * this class or in its hierarchy. */ public Field getField(Class<?> clazz, String name) { Field field = null; try { field = clazz.getField(name); if (!Modifier.isPublic(field.getModifiers()) && !field.isAccessible()) { field = null; } } catch (NoSuchFieldException e) { field = null; } catch (Exception e) { field = null; } return field; } /** * * @param obj * @param name * @return The field or null if a field with this name does not exist in the * class of this object or in its hierarchy. */ public Field getField(Object obj, String name) { return getField(obj.getClass(), name); } public Field getField(String classFQN, String name) { Class<?> clazz = null; try { clazz = Class.forName(classFQN); } catch (Exception e) { logger.log(Level.WARNING, "Class FQN does not exist: " + classFQN, e); throw new Py4JException(e); } return getField(clazz, name); } /** * <p>Wrapper around Field.get</p> * @param obj * @param field * @return */ public Object getFieldValue(Object obj, Field field) { Object fieldValue = null; try { fieldValue = field.get(obj); } catch (Exception e) { logger.log(Level.SEVERE, "Error while fetching field value of " + field, e); throw new Py4JException(e); } return fieldValue; } /** * <p>Wrapper around Field.set</p> * @param obj * @param field * @param value */ public void setFieldValue(Object obj, Field field, Object value) { try { field.set(obj, value); } catch (Exception e) { logger.log(Level.SEVERE, "Error while setting field value of " + field, e); throw new Py4JException(e); } } public Method getMethod(Class<?> clazz, String name) { Method m = null; try { for (Method tempMethod : clazz.getMethods()) { if (tempMethod.getName().equals(name)) { m = tempMethod; break; } } } catch (Exception e) { m = null; } return m; } public MethodInvoker getMethod(Class<?> clazz, String name, Class<?>[] parameters) { MethodDescriptor mDescriptor = new MethodDescriptor(name, clazz, parameters); MethodInvoker mInvoker = null; List<Method> acceptableMethods = null; LRUCache<MethodDescriptor, MethodInvoker> cache = cacheHolder.get(); mInvoker = cache.get(mDescriptor); if (mInvoker == null) { acceptableMethods = getMethodsByNameAndLength(clazz, name, parameters.length); if (acceptableMethods.size() == 1) { mInvoker = MethodInvoker.buildInvoker(acceptableMethods.get(0), parameters); } else { mInvoker = getBestMethod(acceptableMethods, parameters); } if (mInvoker != null && mInvoker.getCost() != -1) { cache.put(mDescriptor, mInvoker); } else { String errorMessage = "Method " + name + "(" + Arrays.toString(parameters) + ") does not exist"; logger.log(Level.WARNING, errorMessage); throw new Py4JException(errorMessage); } } return mInvoker; } public MethodInvoker getMethod(Object object, String name, Object[] parameters) { return getMethod(object.getClass(), name, getClassParameters(parameters)); } public MethodInvoker getMethod(String classFQN, String name, Object[] parameters) { Class<?> clazz = null; try { clazz = Class.forName(classFQN); } catch (Exception e) { logger.log(Level.WARNING, "Class FQN does not exist: " + classFQN, e); throw new Py4JException(e); } return getMethod(clazz, name, getClassParameters(parameters)); } private List<Method> getMethodsByNameAndLength(Class<?> clazz, String name, int length) { List<Method> methods = new ArrayList<Method>(); for (Method method : clazz.getMethods()) { if (method.getName().equals(name) && method.getParameterTypes().length == length) { methods.add(method); } } return methods; } public Object invoke(Object object, MethodInvoker invoker, Object[] parameters) { Object returnObject = null; returnObject = invoker.invoke(object, parameters); if (invoker.isVoid()) { returnObject = RETURN_VOID; } return returnObject; } }
package ifc.util; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XNameReplace; import com.sun.star.util.XChangesBatch; import com.sun.star.util.XChangesListener; import com.sun.star.util.XChangesNotifier; import java.io.PrintWriter; import lib.StatusException; import lib.MultiMethodTest; /** * Test the XChangesNotifier interface. To produce some changes, * XChangesBatch is used. * @see com.sun.star.util.XChangesNotifier * @see com.sun.star.util.XChangesBatch */ public class _XChangesNotifier extends MultiMethodTest { public XChangesNotifier oObj = null; private XChangesBatch xBatch = null; private Object changeElement = null; private Object originalElement = null; private String elementName = null; private XPropertySet xProp = null; private XNameReplace xNameReplace = null; private _XChangesNotifier.MyChangesListener xListener = null; /** * Own implementation of the XChangesListener interface * @see com.sun.star.util.XChangesListener */ private static class MyChangesListener implements XChangesListener { /** Just lo a call of the listener **/ boolean bChangesOccured = false; /** A change did occur * @param changesEvent The event. **/ public void changesOccurred(com.sun.star.util.ChangesEvent changesEvent) { bChangesOccured = true; } /** Disposing of the listener * @param eventObject The event. **/ public void disposing(com.sun.star.lang.EventObject eventObject) { bChangesOccured = true; } /** * Reset the listener */ public void reset() { bChangesOccured = false; } /** * Has the listener been called? * @return True, if the listener has been called. */ public boolean didChangesOccur() { return bChangesOccured; } } /** * Before the test: get the 'XChangesNotifier.ChangesBatch' object relation * and create the listener. */ protected void before() { xBatch = (XChangesBatch)tEnv.getObjRelation("XChangesNotifier.ChangesBatch"); changeElement = tEnv.getObjRelation("XChangesNotifier.ChangeElement"); originalElement = tEnv.getObjRelation("XChangesNotifier.OriginalElement"); elementName = (String)tEnv.getObjRelation("XChangesNotifier.PropertyName"); xProp = (XPropertySet)tEnv.getObjRelation("XChangesNotifier.PropertySet"); try { if (originalElement == null && xProp != null) originalElement = xProp.getPropertyValue(elementName); } catch(com.sun.star.uno.Exception e) { throw new StatusException("Could not get property '" + elementName + "'.", e); } // or get an XNameReplace xNameReplace = (XNameReplace)tEnv.getObjRelation("XChangesNotifier.NameReplace"); try { if (originalElement == null && xNameReplace != null) originalElement = xNameReplace.getByName(elementName); } catch(com.sun.star.uno.Exception e) { throw new StatusException("Could not get element by name '" + elementName + "'.", e); } if (changeElement == null || originalElement == null || elementName == null || (xProp == null && xNameReplace == null) || xBatch == null) { log.println( changeElement == null?"Missing property 'XChangesNotifier.ChangeElement'\n":"" + originalElement == null?"Missing property 'XChangesNotifier.OriginalElement'\n":"" + elementName == null?"Missing property 'XChangesNotifier.PropertyName'\n":"" + xProp == null?"Missing property 'XChangesNotifier.PropertySet'":"" + xNameReplace == null?"Missing property 'XChangesNotifier.NameReplace'":"" + xBatch == null?"Missing property 'XChangesNotifier.ChangesBatch'":"" ); throw new StatusException("Some needed object relations are missing.", new Exception()); } xListener = new _XChangesNotifier.MyChangesListener(); } /** test addChangesListener **/ public void _addChangesListener() { oObj.addChangesListener(xListener); tRes.tested("addChangesListener()", true); } /** test removeChangesListener **/ public void _removeChangesListener() { requiredMethod("addChangesListener()"); boolean result = true; result &= commitChanges(); result &= xListener.didChangesOccur(); if (!result) log.println("Listener has not been called."); oObj.removeChangesListener(xListener); xListener.reset(); result &= redoChanges(); boolean result2 = xListener.didChangesOccur(); if (result2) log.println("Removed listener has been called."); tRes.tested("removeChangesListener()", result && !result2); } /** * Commit a change, using an implementation of the XChangesBatch interface. * @return true, if changing worked. */ private boolean commitChanges() { if (!executeChange(changeElement)) return false; if (!xBatch.hasPendingChanges()) return false; try { xBatch.commitChanges(); } catch(com.sun.star.lang.WrappedTargetException e) { e.printStackTrace((PrintWriter)log); return false; } return true; } /** * Redo the change, using an implementation of the XChangesBatch interface. * @return true, if changing worked. */ private boolean redoChanges() { if (!executeChange(originalElement)) return false; if (!xBatch.hasPendingChanges()) return false; try { xBatch.commitChanges(); } catch(com.sun.star.lang.WrappedTargetException e) { e.printStackTrace((PrintWriter)log); return false; } return true; } /** * Execute the change, use XPropertySet or XNameReplace * @return False, if changing did throw an exception. */ private boolean executeChange(Object element) throws StatusException { if (xProp != null) { try { xProp.setPropertyValue(elementName, element); } catch(com.sun.star.uno.Exception e) { e.printStackTrace((PrintWriter)log); return false; } } else if (xNameReplace != null) { try { xNameReplace.replaceByName(elementName, element); } catch(com.sun.star.uno.Exception e) { e.printStackTrace((PrintWriter)log); return false; } } return true; } }
package com.tradehero.route; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import com.tradehero.route.internal.RouterProcessor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; public class Router { private static final String TAG = "Router"; private static boolean debug = true; protected final Map<String, RouterOptions> routes = new HashMap<String, RouterOptions>(); protected final Map<String, RouterParams> cachedRoutes = new HashMap<String, RouterParams>(); private Context context; /** * Creates a new Router */ public Router() { } private static final Router router = new Router(); /** * A globally accessible Router instance that will work for * most use cases. */ public static Router getInstance() { return router; } /** * Creates a new Router * * @param context {@link android.content.Context} that all {@link android.content.Intent}s * generated by the router will use */ public Router(Context context) { this.setContext(context); } /** * @param context {@link android.content.Context} that all {@link android.content.Intent}s * generated by the router will use */ public void setContext(Context context) { this.context = context; } /** * @return The context for the router */ public Context getContext() { return this.context; } /** * Map a URL to a callback * * @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id" * @param callback {@link RouterCallback} instance which contains the code to execute when the URL * is opened */ public void map(String format, RouterCallback callback) { RouterOptions options = new RouterOptions(); options.setCallback(callback); this.map(format, null, options); } /** * Map a URL to open an {@link android.app.Activity} * * @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id" * @param klass The {@link android.app.Activity} class to be opened with the URL */ public void map(String format, Class<? extends Activity> klass) { this.map(format, klass, null); } /** * Map a URL to open an {@link android.app.Activity} * * @param format The URL being mapped; for example, "users/:id" or "groups/:id/topics/:topic_id" * @param klass The {@link android.app.Activity} class to be opened with the URL * @param options The {@link RouterOptions} to be used for more granular and customized options * for when the URL is opened */ public void map(String format, Class<? extends Activity> klass, RouterOptions options) { if (options == null) { options = new RouterOptions(); } options.setOpenClass(klass); this.routes.put(format, options); } public void openExternal(String url) { this.openExternal(url, this.context); } public void openExternal(String url, Context context) { this.openExternal(url, null, context); } public void openExternal(String url, Bundle extras) { this.openExternal(url, extras, this.context); } public void openExternal(String url, Bundle extras, Context context) { if (context == null) { throw new RuntimeException("You need to supply a context for Router " + this.toString()); } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); this.addFlagsToIntent(intent, context); if (extras != null) { intent.putExtras(extras); } context.startActivity(intent); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * * @param url The URL; for example, "users/16" or "groups/5/topics/20" */ public void open(String url) { this.open(url, this.context); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @param extras The {@link android.os.Bundle} which contains the extras to be assigned to the * generated {@link android.content.Intent} */ public void open(String url, Bundle extras) { this.open(url, extras, this.context); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @param context The context which is used in the generated {@link android.content.Intent} */ public void open(String url, Context context) { this.open(url, null, context); } /** * Open a map'd URL set using {@link #map(String, Class)} or {@link #map(String, RouterCallback)} * * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @param extras The {@link android.os.Bundle} which contains the extras to be assigned to the * generated {@link android.content.Intent} * @param context The context which is used in the generated {@link android.content.Intent} */ public void open(String url, Bundle extras, Context context) { if (context == null) { throw new RuntimeException("You need to supply a context for Router " + this.toString()); } RouterParams params = this.paramsForUrl(url); RouterOptions options = params.routerOptions; if (options.getCallback() != null) { options.getCallback().run(params.openParams); return; } Intent intent = this.intentFor(context, url); if (intent == null) { // Means the options weren't opening a new activity return; } if (extras != null) { intent.putExtras(extras); } context.startActivity(intent); } /* * Allows Intents to be spawned regardless of what context they were opened with. */ private void addFlagsToIntent(Intent intent, Context context) { if (context == this.context) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } } /** * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @return The {@link android.content.Intent} for the url */ public Intent intentFor(String url) { RouterParams params = this.paramsForUrl(url); RouterOptions options = params.routerOptions; Intent intent = new Intent(); if (options.getDefaultParams() != null) { for (Entry<String, String> entry : options.getDefaultParams().entrySet()) { intent.putExtra(entry.getKey(), entry.getValue()); } } for (Entry<String, String> entry : params.openParams.entrySet()) { intent.putExtra(entry.getKey(), entry.getValue()); } return intent; } /** * @param url The URL to check * @return Whether or not the URL refers to an anonymous callback function */ public boolean isCallbackUrl(String url) { RouterParams params = this.paramsForUrl(url); RouterOptions options = params.routerOptions; return options.getCallback() != null; } /** * @param context The context which is spawning the intent * @param url The URL; for example, "users/16" or "groups/5/topics/20" * @return The {@link android.content.Intent} for the url, with the correct {@link * android.app.Activity} set, or null. */ public Intent intentFor(Context context, String url) { RouterParams params = this.paramsForUrl(url); RouterOptions options = params.routerOptions; if (options.getCallback() != null) { return null; } Intent intent = intentFor(url); intent.setClass(context, options.getOpenClass()); this.addFlagsToIntent(intent, context); return intent; } /* * Takes a url (i.e. "/users/16/hello") and breaks it into a {@link RouterParams} instance where * each of the parameters (like ":id") has been parsed. */ protected RouterParams paramsForUrl(String url) { if (this.cachedRoutes.get(url) != null) { return this.cachedRoutes.get(url); } String[] givenParts = url.split("/"); RouterOptions openOptions = null; RouterParams openParams = null; for (Entry<String, RouterOptions> entry : this.routes.entrySet()) { String routerUrl = entry.getKey(); RouterOptions routerOptions = entry.getValue(); String[] routerParts = routerUrl.split("/"); if (routerParts.length != givenParts.length) { continue; } Map<String, String> givenParams = urlToParamsMap(givenParts, routerParts); if (givenParams == null) { continue; } openOptions = routerOptions; openParams = new RouterParams(); openParams.openParams = givenParams; openParams.routerOptions = routerOptions; break; } if (openOptions == null) { throw new RouteNotFoundException("No route found for url " + url); } this.cachedRoutes.put(url, openParams); return openParams; } /** * @param givenUrlSegments An array representing the URL path attempting to be opened (i.e. * ["users", "42"]) * @param routerUrlSegments An array representing a possible URL match for the router (i.e. * ["users", ":id"]) * @return A map of URL parameters if it's a match (i.e. {"id" => "42"}) or null if there is no * match */ private Map<String, String> urlToParamsMap(String[] givenUrlSegments, String[] routerUrlSegments) { Map<String, String> formatParams = new HashMap<String, String>(); for (int index = 0; index < routerUrlSegments.length; index++) { String routerPart = routerUrlSegments[index]; String givenPart = givenUrlSegments[index]; if (routerPart.charAt(0) == ':') { String key = routerPart.substring(1, routerPart.length()); formatParams.put(key, givenPart); continue; } if (!routerPart.equals(givenPart)) { return null; } } return formatParams; } static final Map<Class<?>, Method> INJECTORS = new LinkedHashMap<Class<?>, Method>(); static final Map<Class<?>, Method> SAVERS = new LinkedHashMap<Class<?>, Method>(); static final Method NO_OP = null; public void inject(Activity activity) { Bundle extras = activity.getIntent() != null ? activity.getIntent().getExtras() : null; inject(activity, extras); } public void inject(Object target, Bundle extras) { Class<?> targetClass = target.getClass(); try { if (debug) Log.d(TAG, "Looking up injector for " + targetClass.getName()); Method inject = findInjectorForClass(targetClass); if (inject != null) { inject.invoke(null, target, extras); } } catch (RuntimeException e) { throw e; } catch (Exception e) { Throwable t = e; if (t instanceof InvocationTargetException) { t = t.getCause(); } throw new RuntimeException("Unable to inject for " + target, t); } } /** * Save POJO to bundle with hierarchy * @param extras * @param parcelables */ public void save(Bundle extras, Object... parcelables) { if (parcelables == null) return; boolean flat = false; int length = parcelables.length; if (length > 1 && parcelables[length - 1] instanceof Boolean) { flat = (Boolean) parcelables[length - 1]; --length; } for (int i = 0; i< length; ++i) { saveSingle(extras, parcelables[i], flat); } } /** * Save POJO to bundle without hierarchy * @param extras * @param parcelables */ public void saveFlat(Bundle extras, Object... parcelables) { for (Object parcelable: parcelables) { saveSingle(extras, parcelable, true); } } public void saveSingle(Bundle extras, Object parcelable, boolean flat) { Class<?> targetClass = parcelable.getClass(); try { if (debug) Log.d(TAG, "Looking up saver for " + targetClass.getName()); Method inject = findSaverForClass(targetClass); if (inject != null) { inject.invoke(null, parcelable, extras, flat); } } catch (RuntimeException e) { throw e; } catch (Exception e) { Throwable t = e; if (t instanceof InvocationTargetException) { t = t.getCause(); } throw new RuntimeException("Unable to inject for " + parcelable, t); } } private static Method findInjectorForClass(Class<?> cls) throws NoSuchMethodException { Method inject = INJECTORS.get(cls); if (inject != null) { if (debug) Log.d(TAG, "HIT: Cached in injector map."); return inject; } String clsName = cls.getName(); if (clsName.startsWith("android.") || clsName.startsWith("java.")) { if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); return NO_OP; } try { Class<?> injector = Class.forName(clsName + RouterProcessor.SUFFIX); inject = injector.getMethod("inject", cls, Bundle.class); if (debug) Log.d(TAG, "HIT: Class loaded injection class."); } catch (ClassNotFoundException e) { if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); // TODO: consider parent to be injected too? inject = findInjectorForClass(cls.getSuperclass()); } INJECTORS.put(cls, inject); return inject; } private static Method findSaverForClass(Class<?> cls) throws NoSuchMethodException { Method inject = SAVERS.get(cls); if (inject != null) { if (debug) Log.d(TAG, "HIT: Cached in saver map."); return inject; } String clsName = cls.getName(); if (clsName.startsWith("android.") || clsName.startsWith("java.")) { if (debug) Log.d(TAG, "MISS: Reached framework class. Abandoning search."); return NO_OP; } try { Class<?> injector = Class.forName(clsName + RouterProcessor.SUFFIX); inject = injector.getMethod("save", cls, Bundle.class, boolean.class); if (debug) Log.d(TAG, "HIT: Class loaded injection class."); } catch (ClassNotFoundException e) { if (debug) Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName()); } SAVERS.put(cls, inject); return inject; } public Router registerRoutes(Class<?>... targets) { for (Class<?> target: targets) { if (Activity.class.isAssignableFrom(target) && target.isAnnotationPresent(Routable.class)) { Routable routable = target.getAnnotation(Routable.class); if (debug) Log.d(TAG, routable.toString()); String[] routes = routable.value(); if (routes != null) { for (String route: routes) { @SuppressWarnings("unchecked") Class<? extends Activity> activityTarget = (Class<? extends Activity>) target; map(route, activityTarget); } } } } return this; } }
package com.wonderpush.sdk; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; class CacheUtil { protected static final int MAX_SOUND_FILE_SIZE = 1 * 1024 * 1024; // 1 MB protected static final int MAX_LARGEICON_FILE_SIZE = 2 * 1024 * 1024; // 2 MB protected static final int MAX_BIGPICTURE_FILE_SIZE = 5 * 1024 * 1024; // 5 MB protected static final int MAX_SOUND_CACHE_SIZE = 10 * MAX_SOUND_FILE_SIZE; protected static final int MAX_LARGEICON_CACHE_SIZE = 5 * MAX_LARGEICON_FILE_SIZE; protected static final int MAX_BIGPICTURE_CACHE_SIZE = 3 * MAX_BIGPICTURE_FILE_SIZE; static class FetchWork { final Uri uri; final int maxFileSize; final String cacheSubfolder; final int maxCacheSize; final String logPrefix; static class AsyncTask extends android.os.AsyncTask<FetchWork, Void, File[]> { @Override protected File[] doInBackground(FetchWork... fetchWorks) { File[] rtn = new File[fetchWorks.length]; for (int i = 0; i < fetchWorks.length; ++i) { rtn[i] = fetchWorks[i].execute(); } return rtn; } } public FetchWork(Uri uri, int maxFileSize, String cacheSubfolder, int maxCacheSize, String logPrefix) { this.uri = uri; this.maxFileSize = maxFileSize; this.cacheSubfolder = cacheSubfolder; this.maxCacheSize = maxCacheSize; this.logPrefix = logPrefix; } public File execute() { return doFetch(this); } } static class FetchResult { private final File result; private final FetchWork work; private FetchResult(File result, FetchWork work) { this.result = result; this.work = work; } public static FetchResult immediate(@Nullable File result) { return new FetchResult(result, null); } public static FetchResult workTask(@NonNull FetchWork work) { return new FetchResult(null, work); } public boolean needsWork() { return work != null; } public File getResult() { return result; } public FetchWork getWork() { return work; } } protected static FetchResult fetchSound(Uri uri, String logPrefix) { return fetch(new FetchWork(uri, MAX_SOUND_FILE_SIZE, "sounds", MAX_SOUND_CACHE_SIZE, logPrefix)); } protected static FetchResult fetchLargeIcon(Uri uri, String logPrefix) { return fetch(new FetchWork(uri, MAX_LARGEICON_FILE_SIZE, "largeIcons", MAX_LARGEICON_CACHE_SIZE, logPrefix)); } protected static FetchResult fetchBigPicture(Uri uri, String logPrefix) { return fetch(new FetchWork(uri, MAX_BIGPICTURE_FILE_SIZE, "bigPictures", MAX_BIGPICTURE_CACHE_SIZE, logPrefix)); } private static FetchResult fetch(FetchWork work) { File cached = getCachedFile(work); if (cached == null || isUsable(work, cached)) { return FetchResult.immediate(cached); } else { return FetchResult.workTask(work); } } private static boolean isUsable(FetchWork work, @NonNull File cached) { // TODO handle caching return cached.exists(); } private static File getCachedFile(FetchWork work) { String scheme = work.uri.getScheme() == null ? null : work.uri.getScheme().toLowerCase(Locale.ROOT); if ("http".equals(scheme) || "https".equals(scheme)) { try { String filename = Integer.toHexString(work.uri.toString().hashCode()); File cacheLargeIconsDir = new File(WonderPush.getApplicationContext().getCacheDir(), work.cacheSubfolder); cacheLargeIconsDir.mkdirs(); final File cached = new File(cacheLargeIconsDir, filename); return cached; } catch (Exception ex) { Log.e(WonderPush.TAG, work.logPrefix + ": Failed to fetch from URI " + work.uri, ex); } } return null; } private static File doFetch(FetchWork work) { try { File cached = getCachedFile(work); // returns null on invalid work request if (cached != null && !isUsable(work, cached)) { boolean success = false; try { WonderPush.logDebug(work.logPrefix + ": Will open URL: " + work.uri); URLConnection conn = new URL(work.uri.toString()).openConnection(); InputStream is = (InputStream) conn.getContent(); WonderPush.logDebug(work.logPrefix + ": Content-Type: " + conn.getContentType()); WonderPush.logDebug(work.logPrefix + ": Content-Length: " + conn.getContentLength() + " bytes"); if (conn.getContentLength() > work.maxFileSize) { throw new RuntimeException(work.logPrefix + " file too large (" + conn.getContentLength() + " is over " + work.maxFileSize + " bytes)"); } FileOutputStream outputStream = new FileOutputStream(cached); int read, ttl = 0; byte[] buffer = new byte[2048]; while ((read = is.read(buffer)) != -1) { ttl += read; if (ttl > work.maxFileSize) { throw new RuntimeException(work.logPrefix + " file too large (max " + work.maxFileSize + " bytes allowed)"); } outputStream.write(buffer, 0, read); } outputStream.close(); success = true; WonderPush.logDebug(work.logPrefix + ": Finished reading " + ttl + " bytes"); } catch (IOException ex) { Log.e(WonderPush.TAG, "Error while fetching resource " + work.uri, ex); } if (!success) { cached.delete(); cached = null; } expireCache(work.cacheSubfolder, work.maxCacheSize); } return cached; } catch (Exception ex) { Log.e(WonderPush.TAG, work.logPrefix + ": Failed to fetch from URI " + work.uri, ex); return null; } } private static void expireCache(String cacheSubfolder, int maxCacheSize) { File dir = new File(WonderPush.getApplicationContext().getCacheDir(), cacheSubfolder); if (!dir.isDirectory()) return; // Sort from most recently modified to least recently modified File[] files = dir.listFiles(); Arrays.sort(files, new Comparator<File>() { @Override public int compare(File lhs, File rhs) { // TODO Once minSdkVersion is 19, we can return Long.compare(rhs.lastModified(), lhs.lastModified()) long lvalue = lhs.lastModified(); long rvalue = rhs.lastModified(); if (rvalue == lvalue) return 0; if (rvalue < lvalue) return -1; return 1; } }); int totalSize = 0; for (File file : files) { totalSize += file.length(); // Delete any older files above the desired limit if (totalSize > maxCacheSize) { file.delete(); } } } }
package org.ilrt.mca.dao; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.vocabulary.RDF; import org.apache.log4j.Logger; import org.ilrt.mca.dao.delegate.ActiveMapDelegateImpl; import org.ilrt.mca.dao.delegate.ContactsDelegateImpl; import org.ilrt.mca.dao.delegate.Delegate; import org.ilrt.mca.dao.delegate.DirectoryDelegateImpl; import org.ilrt.mca.dao.delegate.FeedDelegateImpl; import org.ilrt.mca.dao.delegate.HtmlFragmentDelegateImpl; import org.ilrt.mca.dao.delegate.KmlMapDelegateImpl; import org.ilrt.mca.domain.BaseItem; import org.ilrt.mca.domain.Item; import org.ilrt.mca.rdf.Repository; import org.ilrt.mca.vocab.MCA_REGISTRY; import javax.ws.rs.core.MultivaluedMap; import org.ilrt.mca.dao.delegate.EventDelegateImpl; /** * @author Mike Jones (mike.a.jones@bristol.ac.uk) */ public class ItemDaoImpl extends AbstractDao implements ItemDao { public ItemDaoImpl(Repository repository) throws Exception { this.repository = repository; findItemsSparql = loadSparql("/sparql/findItems.rql"); } @Override public Item findItem(String id, MultivaluedMap<String, String> parameters) { // get the model based on the id and any parameters passed Model model = findModel(id, parameters); if (model == null || model.isEmpty()) { log.error("Unable to construct a model"); return null; } // hand work to a delegate if possible Resource resource = model.getResource(id); Delegate delegate = findDelegate(resource); if (delegate != null) { log.debug("Using delegate: " + delegate.getClass().getName()); return delegate.createItem(resource, parameters); } log.debug("We don't have delegate, defaulting to basic object"); // fallback BaseItem item = new BaseItem(); getBasicDetails(resource, item); return item; } @Override public Model findModel(String id, MultivaluedMap<String, String> parameters) { Model model = repository.find("id", id, findItemsSparql); if (model.isEmpty()) { return null; } // hand work to a delegate if possible Resource resource = model.getResource(id); Delegate delegate = findDelegate(resource); if (delegate != null) { return delegate.createModel(resource, parameters); } return model; } private Delegate findDelegate(Resource resource) { if (resource.hasProperty(RDF.type)) { String type = resource.getProperty(RDF.type).getResource().getURI(); if (type.equals(MCA_REGISTRY.KmlMapSource.getURI())) { return new KmlMapDelegateImpl(repository); } else if (type.equals(MCA_REGISTRY.News.getURI()) || type.equals(MCA_REGISTRY.FeedItem.getURI())) { return new FeedDelegateImpl(repository); } else if (type.equals(MCA_REGISTRY.HtmlFragment.getURI())) { return new HtmlFragmentDelegateImpl(repository); } else if (type.equals(MCA_REGISTRY.ActiveMapSource.getURI())) { return new ActiveMapDelegateImpl(repository); } else if (type.equals(MCA_REGISTRY.Contact.getURI())) { return new ContactsDelegateImpl(repository); } else if (type.equals(MCA_REGISTRY.Directory.getURI())) { return new DirectoryDelegateImpl(repository); } else if (type.equals(MCA_REGISTRY.EventCalendar.getURI())) { return new EventDelegateImpl(repository); } log.debug("Haven't found an appropriate delegate"); } return null; } private String findItemsSparql = null; private Repository repository; Logger log = Logger.getLogger(ItemDaoImpl.class); }
package com.picture.choosepictest; import java.io.File; import java.io.FileNotFoundException; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private static final String TAG = "ChoosePicTest/MainActivity"; private static final int TAKE_PHOTO = 1; private static final int CROP_PHOTO = 2; private Button mTakePhoto; private Button mCropPhoto; private ImageView mPicture; private Uri mImageUri; private Uri mCropImageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPicture = (ImageView) findViewById(R.id.picture); mTakePhoto = (Button) findViewById(R.id.take_photo); mCropPhoto = (Button) findViewById(R.id.crop_photo); mTakePhoto.setOnClickListener(this); mCropPhoto.setOnClickListener(this); mImageUri = resetFile("output_image.jpg"); mCropImageUri = resetFile("output_cropped_image.jpg"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "requestCode is " + requestCode + ", resultCode is " + resultCode); switch (requestCode) { case TAKE_PHOTO: if (resultCode == RESULT_OK) { Log.i(TAG, "Take a photo from camera and save."); updateImage(mImageUri); } break; case CROP_PHOTO: if (resultCode == RESULT_OK) { Log.i(TAG, "Crop the image and save."); updateImage(mCropImageUri); } break; default: break; } super.onActivityResult(requestCode, resultCode, data); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.take_photo: doTakePhoto(); break; case R.id.crop_photo: doCropPhoto(); break; default: break; } } private void doTakePhoto() { try { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); startActivityForResult(intent, TAKE_PHOTO); } catch (ActivityNotFoundException anfe) { String errorMessage = "Your device doesn't support the crop action!"; Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT).show(); } } private void doCropPhoto() { try { Intent intent = new Intent("com.android.camera.action.CROP");
package com.html5parser.insertionModes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Queue; import java.util.Stack; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.html5parser.algorithms.AdjustForeignAttributes; import com.html5parser.algorithms.AdjustMathMLAttributes; import com.html5parser.algorithms.AdjustSVGAttributes; import com.html5parser.algorithms.AdoptionAgencyAlgorithm; import com.html5parser.algorithms.ElementInScope; import com.html5parser.algorithms.GenerateAllImpliedEndTagsThoroughly; import com.html5parser.algorithms.GenerateImpliedEndTags; import com.html5parser.algorithms.GenericRawTextElementParsing; import com.html5parser.algorithms.InsertAnHTMLElement; import com.html5parser.algorithms.InsertCharacter; import com.html5parser.algorithms.InsertComment; import com.html5parser.algorithms.InsertForeignElement; import com.html5parser.algorithms.ListOfActiveFormattingElements; import com.html5parser.classes.InsertionMode; import com.html5parser.classes.ParserContext; import com.html5parser.classes.Token; import com.html5parser.classes.Token.TokenType; import com.html5parser.classes.TokenizerState; import com.html5parser.classes.token.TagToken; import com.html5parser.constants.HTML5Elements; import com.html5parser.constants.Namespace; import com.html5parser.factories.InsertionModeFactory; import com.html5parser.factories.TokenizerStateFactory; import com.html5parser.interfaces.IInsertionMode; import com.html5parser.parseError.ParseErrorType; public class InBody implements IInsertionMode { public ParserContext process(ParserContext parserContext) { InsertionModeFactory factory = InsertionModeFactory.getInstance(); Token token = parserContext.getTokenizerContext().getCurrentToken(); TokenType tokenType = token.getType(); Stack<Element> openElementStack = parserContext.getOpenElements(); /* * A character token that is U+0000 NULL Parse error. Ignore the token. */ if (tokenType == TokenType.character && token.getIntValue() == 0x000) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); } /* * A character token that is one of U+0009 CHARACTER TABULATION, "LF" * (U+000A), "FF" (U+000C), "CR" (U+000D), or U+0020 SPACE Reconstruct * the active formatting elements, if any. Insert the token's character. */ else if (token.isSpaceCharacter()) { ListOfActiveFormattingElements.reconstruct(parserContext); InsertCharacter.run(parserContext, token); } /* * Any other character token Reconstruct the active formatting * elements,if any. Insert the token's character. Set the frameset-ok * flag to "not ok". */ else if (tokenType == TokenType.character) { ListOfActiveFormattingElements.reconstruct(parserContext); InsertCharacter.run(parserContext, token); parserContext.setFlagFramesetOk(false); } /* * A comment token Insert a comment. */ else if (tokenType == TokenType.comment) { InsertComment.run(parserContext, token); } /* * A DOCTYPE token Parse error. Ignore the token. */ else if (tokenType == TokenType.DOCTYPE) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } /* * A start tag whose tag name is "html" Parse error. If there is a * template element on the stack of open elements, then ignore the * token. Otherwise, for each attribute on the token, check to see if * the attribute is already present on the top element of the stack of * open elements. If it is not, add the attribute and its corresponding * value to that element. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("html")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); if (parserContext.openElementsContain("template")) { return parserContext; } else { List<TagToken.Attribute> attriList = ((TagToken) token) .getAttributes(); Element topOpenElement = parserContext.getOpenElements().peek(); for (int i = 0; i < attriList.size(); i++) { if (!topOpenElement .hasAttribute(attriList.get(i).getName())) { topOpenElement.setAttribute(attriList.get(i).getName(), attriList.get(i).getValue()); } } } } /* * A start tag whose tag name is one of: "base", "basefont", "bgsound", * "link", "meta", "noframes", "script", "style", "template", "title" An * end tag whose tag name is "template" Process the token using the * rules for the "in head" insertion mode. */ else if ((tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title" })) || (tokenType == TokenType.end_tag && token.getValue().equals( "template"))) { IInsertionMode inHead = factory .getInsertionMode(InsertionMode.in_head); parserContext = inHead.process(parserContext); } /* * A start tag whose tag name is "body" Parse error. If the second * element on the stack of open elements is not a body element, if the * stack of open elements has only one node on it, or if there is a * template element on the stack of open elements, then ignore the * token. (fragment case) Otherwise, set the frameset-ok flag to * "not ok"; then, for each attribute on the token, check to see if the * attribute is already present on the body element (the second element) * on the stack of open elements, and if it is not, add the attribute * and its corresponding value to that element. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("body")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); if (parserContext.getOpenElements().size() > 1) { Element top = parserContext.getOpenElements().pop(); Element secondTop = parserContext.getOpenElements().peek(); parserContext.getOpenElements().push(top); if (!secondTop.getNodeName().equals("body") || parserContext.openElementsContain("template")) { return parserContext; } else { parserContext.setFlagFramesetOk(false); List<TagToken.Attribute> attriList = ((TagToken) token) .getAttributes(); for (int i = 0; i < attriList.size(); i++) { if (!secondTop.hasAttribute(attriList.get(i).getName())) { secondTop.setAttribute(attriList.get(i).getName(), attriList.get(i).getValue()); } } } } else if (parserContext.getOpenElements().size() == 1) { return parserContext; } } /* * A start tag whose tag name is "frameset" Parse error. If the stack of * open elements has only one node on it, or if the second element on * the stack of open elements is not a body element, then ignore the * token. (fragment case) If the frameset-ok flag is set to "not ok", * ignore the token. Otherwise, run the following steps: Remove the * second element on the stack of open elements from its parent node, if * it has one. Pop all the nodes from the bottom of the stack of open * elements, from the current node up to, but not including, the root * html element. Insert an HTML element for the token. Switch the * insertion mode to "in frameset". */ else if (tokenType == TokenType.start_tag && token.getValue().equals("frameset")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); if (parserContext.getOpenElements().size() > 1) { Element top = parserContext.getOpenElements().pop(); Element secondTop = parserContext.getOpenElements().peek(); parserContext.getOpenElements().push(top); if (!secondTop.getNodeName().equals("body")) { return parserContext; } } else if (parserContext.getOpenElements().size() == 1) { return parserContext; } if (!parserContext.isFlagFramesetOk()) { return parserContext; } else { if (parserContext.getOpenElements().size() > 1) { Element top = parserContext.getOpenElements().pop(); parserContext.getOpenElements().pop(); parserContext.getOpenElements().push(top); } while (parserContext.getOpenElements().size() > 0) { Element top = parserContext.getOpenElements().peek(); if (!top.getNodeName().equals("html")) { parserContext.getOpenElements().pop(); } } InsertAnHTMLElement.run(parserContext, token); parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_frameset)); } } /* * An end-of-file token If there is a node in the stack of open elements * that is not either a dd element, a dt element, an li element, a p * element, a tbody element, a td element, a tfoot element, a th * element, a thead element, a tr element, the body element, or the html * element, then this is a parse error. * * If the stack of template insertion modes is not empty, then process * the token using the rules for the "in template" insertion mode. * Otherwise, stop parsing. */ else if (tokenType == TokenType.end_of_file) { if (!parserContext.getOpenElements().isEmpty()) { ArrayList<Element> stack = new ArrayList<Element>(); stack.addAll(parserContext.getOpenElements()); boolean flag = true; for (Element element : stack) { String name = element.getNodeName(); if (!isOneOf(name, new String[] { "dd", "dt", "li", "p", "tbody", "td", "tfoot", "th", "thead", "tr", "body", "html" })) { flag = false; break; } } if (!flag) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); } } if (!parserContext.getTemplateInsertionModes().isEmpty()) { IInsertionMode inTemplate = factory .getInsertionMode(InsertionMode.in_template); parserContext = inTemplate.process(parserContext); } else { parserContext.setFlagStopParsing(true); } } /* * An end tag whose tag name is "body" If the stack of open elements * does not have a body element in scope, this is a parse error; ignore * the token. Otherwise, if there is a node in the stack of open * elements that is not either a dd element, a dt element, an li * element, an optgroup element, an option element, a p element, an rb * element, an rp element, an rt element, an rtc element, a tbody * element, a td element, a tfoot element, a th element, a thead * element, a tr element, the body element, or the html element, then * this is a parse error. Switch the insertion mode to "after body". */ else if (tokenType == TokenType.end_tag && token.getValue().equals("body")) { if (!ElementInScope.isInScope(parserContext, "body")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } else { ArrayList<Element> list = new ArrayList<Element>(); list.addAll(parserContext.getOpenElements()); for (Element element : list) { if (!isOneOf(element.getNodeName(), new String[] { "dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc", "tbody", "td", "tfoot", "th", "thead", "tr", "body", "html" })) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); break; } } parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.after_body)); } } /* * An end tag whose tag name is "html" If the stack of open elements * does not have a body element in scope, this is a parse error; ignore * the token. Otherwise, if there is a node in the stack of open * elements that is not either a dd element, a dt element, an li * element, an optgroup element, an option element, a p element, an rb * element, an rp element, an rt element, an rtc element, a tbody * element, a td element, a tfoot element, a th element, a thead * element, a tr element, the body element, or the html element, then * this is a parse error. Switch the insertion mode to "after body". * Reprocess the token. */ else if (tokenType == TokenType.end_tag && token.getValue().equals("html")) { if (!ElementInScope.isInScope(parserContext, "body")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } else { ArrayList<Element> list = new ArrayList<Element>(); list.addAll(parserContext.getOpenElements()); for (Element element : list) { if (!isOneOf(element.getNodeName(), new String[] { "dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc", "tbody", "td", "tfoot", "th", "thead", "tr", "body", "html" })) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); break; } } parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.after_body)); parserContext.setFlagReconsumeToken(true); } } /* * A start tag whose tag name is one of: "address", "article", "aside", * "blockquote", "center", "details", "dialog", "dir", "div", "dl", * "fieldset", "figcaption", "figure", "footer", "header", "hgroup", * "main", "nav", "ol", "p", "section", "summary", "ul" If the stack of * open elements has a p element in button scope, then close a p * element. Insert an HTML element for the token. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "address", "article", "aside", "blockquote", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "main", "nav", "ol", "p", "section", "summary", "ul" })) { if (ElementInScope.isInButtonScope(parserContext, "p")) closeApElement(parserContext); InsertAnHTMLElement.run(parserContext, token); } /* * A start tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", * "h6" If the stack of open elements has a p element in button scope, * then close a p element. If the current node is an HTML element whose * tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then this * is a parse error; pop the current node off the stack of open * elements. Insert an HTML element for the token. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "h1", "h2", "h3", "h4", "h5", "h6" })) { if (ElementInScope.isInButtonScope(parserContext, "p")) closeApElement(parserContext); if (isOneOf(parserContext.getCurrentNode().getTagName(), new String[] { "h1", "h2", "h3", "h4", "h5", "h6" })) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); parserContext.getOpenElements().pop(); } InsertAnHTMLElement.run(parserContext, token); } /* * A start tag whose tag name is one of: "pre", "listing" If the stack * of open elements has a p element in button scope, then close a p * element. Insert an HTML element for the token. If the next token is a * "LF" (U+000A) character token, then ignore that token and move on to * the next one. (Newlines at the start of pre blocks are ignored as an * authoring convenience.) Set the frameset-ok flag to "not ok". */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "pre", "listing" })) { if (ElementInScope.isInButtonScope(parserContext, "p")) { closeApElement(parserContext); } InsertAnHTMLElement.run(parserContext, token); Queue<Token> tokenQueue = parserContext.getTokenizerContext() .getTokens(); if (!tokenQueue.isEmpty()) { Token nexToken = tokenQueue.peek(); if (nexToken.getValue().equals("LF")) { tokenQueue.poll(); } } parserContext.setFlagFramesetOk(false); } /* * A start tag whose tag name is "form" If the form element pointer is * not null, and there is no template element on the stack of open * elements, then this is a parse error; ignore the token. Otherwise: If * the stack of open elements has a p element in button scope, then * close a p element. Insert an HTML element for the token, and, if * there is no template element on the stack of open elements, set the * form element pointer to point to the element created. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("form")) { if (parserContext.getFormElementPointer() != null && parserContext.openElementsContain("template")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } else { if (ElementInScope.isInButtonScope(parserContext, "p")) { closeApElement(parserContext); } Element element = InsertAnHTMLElement.run(parserContext, token); if (!(!parserContext.getOpenElements().isEmpty() && parserContext .openElementsContain("template"))) { parserContext.setFormElementPointer(element); } } } /* * TODO A start tag whose tag name is "li" Run these steps: Set the * frameset-ok flag to "not ok". Initialize node to be the current node * (the bottommost node of the stack). Loop: If node is an li element, * then run these substeps: Generate implied end tags, except for li * elements. If the current node is not an li element, then this is a * parse error. Pop elements from the stack of open elements until an li * element has been popped from the stack. Jump to the step labeled done * below. If node is in the special category, but is not an address, * div, or p element, then jump to the step labeled done below. * Otherwise, set node to the previous entry in the stack of open * elements and return to the step labeled loop. Done: If the stack of * open elements has a p element in button scope, then close a p * element. Finally, insert an HTML element for the token. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("li")) { parserContext.setFlagFramesetOk(false); Node node = parserContext.getCurrentNode(); if (isOneOf( node.getNodeName(), new String( "applet, area, article, aside, base, basefont, bgsound, " + "blockquote, body, br, button, caption, center, col, colgroup, dd, " + "details, dir, dl, dt, embed, fieldset, figcaption, figure, " + "footer, form, frame, frameset, h1, h2, h3, h4, h5, h6, head, header, " + "hgroup, hr, html, iframe, img, input, isindex, li, link, listing, " + "main, marquee, meta, nav, noembed, noframes, noscript, object, ol, " + "param, plaintext, pre, script, section, select, source, style, " + "summary, table, tbody, td, template, textarea, tfoot, th, thead, " + "title, tr, track, ul, wbr, xmp, mi, mo, mn, ms, mtext, annotation-xml, " + "foreignObject, desc, title").split(", "))) { done(parserContext); } else { if (parserContext.getOpenElements().size() > 1) { Element buttomNode = parserContext.getOpenElements().pop(); Node previousEntry = parserContext.getOpenElements().peek(); parserContext.getOpenElements().push(buttomNode); loop(parserContext, previousEntry); } } InsertAnHTMLElement.run(parserContext, token); } /* * A start tag whose tag name is one of: "dd", "dt" Run these steps: Set * the frameset-ok flag to "not ok". Initialize node to be the current * node (the bottommost node of the stack). * * Loop: If node is a dd element, then run these substeps: * * Generate implied end tags, except for dd elements. * * If the current node is not a dd element, then this is a parse error. * * Pop elements from the stack of open elements until a dd element has * been popped from the stack. * * Jump to the step labeled done below. * * If node is a dt element, then run these substeps: * * Generate implied end tags, except for dt elements. * * If the current node is not a dt element, then this is a parse error. * * Pop elements from the stack of open elements until a dt element has * been popped from the stack. * * Jump to the step labeled done below. * * If node is in the special category, but is not an address, div, or p * element, then jump to the step labeled done below. * * Otherwise, set node to the previous entry in the stack of open * elements and return to the step labeled loop. * * Done: If the stack of open elements has a p element in button scope, * then close a p element. * * Finally, insert an HTML element for the token. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "dd", "dt" })) { // TODO } /* * start tag whose tag name is "plaintext" If the stack of open elements * has a p element in button scope, then close a p element. Insert an * HTML element for the token. Switch the tokenizer to the PLAINTEXT * state. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("plaintext")) { if (ElementInScope.isInButtonScope(parserContext, "p")) { closeApElement(parserContext); } InsertAnHTMLElement.run(parserContext, token); TokenizerStateFactory tokenStateFactory = TokenizerStateFactory .getInstance(); parserContext.getTokenizerContext().setNextState( tokenStateFactory.getState(TokenizerState.PLAINTEXT_state)); } /* * A start tag whose tag name is "button" If the stack of open elements * has a button element in scope, then run these substeps: Parse error. * Generate implied end tags. Pop elements from the stack of open * elements until a button element has been popped from the stack. * Reconstruct the active formatting elements, if any. Insert an HTML * element for the token. Set the frameset-ok flag to "not ok". */ else if (tokenType == TokenType.start_tag && token.getValue().equals("button")) { if (ElementInScope.isInScope(parserContext, "button")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); GenerateImpliedEndTags.run(parserContext); while (!parserContext.getOpenElements().isEmpty()) { Element element = parserContext.getOpenElements().pop(); if (element.getNodeName().equals("button")) { break; } } } if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } InsertAnHTMLElement.run(parserContext, token); parserContext.setFlagFramesetOk(false); } /* * An end tag whose tag name is one of: "address", "article", "aside", * "blockquote", "button", "center", "details", "dialog", "dir", "div", * "dl", "fieldset", "figcaption", "figure", "footer", "header", * "hgroup", "listing", "main", "nav", "ol", "pre", "section", * "summary", "ul" If the stack of open elements does not have an * element in scope that is an HTML element and with the same tag name * as that of the token, then this is a parse error; ignore the token. * Otherwise, run these steps: Generate implied end tags. If the current * node is not an HTML element with the same tag name as that of the * token, then this is a parse error. Pop elements from the stack of * open elements until an HTML element with the same tag name as the * token has been popped from the stack. */ else if (tokenType == TokenType.end_tag && isOneOf(token.getValue(), new String[] { "address", "article", "aside", "blockquote", "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "main", "nav", "ol", "pre", "section", "summary", "ul" })) { if (!ElementInScope.isInScope(parserContext, token.getValue())) { parserContext .addParseErrors(ParseErrorType.UnexpectedInputCharacter); } else { GenerateImpliedEndTags.run(parserContext); if (!parserContext.getCurrentNode().getNodeName() .equals(token.getValue())) parserContext .addParseErrors(ParseErrorType.UnexpectedToken); while (true) { Element element = parserContext.getOpenElements().pop(); if (element.getNodeName().equals(token.getValue())) { break; } } } // List<Element> list = new ArrayList<Element>(); // list.addAll(parserContext.getOpenElements()); // for (Element element : list) { // if (!element.getNamespaceURI().equals( // list.remove(element); // boolean flag = false; // for (Element element : list) { // if (element.getNodeName().equals(token.getValue())) { // flag = true; // String[] elementsInHTMLns = { "applet", "caption", "html", // "table", // "td", "th", "marquee", "object", "template" }; // if (!(isOneOf(token.getValue(), elementsInHTMLns) && flag)) { // parserContext.addParseErrors(ParseErrorType.UnexpectedToken); // return parserContext; // } else { // GenerateImpliedEndTags.run(parserContext); // if (!parserContext.getCurrentNode().getNamespaceURI() // || !parserContext.getCurrentNode().getNodeName() // .equals(token.getValue())) { // parserContext // .addParseErrors(ParseErrorType.UnexpectedToken); // while (!parserContext.getOpenElements().isEmpty()) { // Element element = parserContext.getOpenElements().pop(); // if (element.getNamespaceURI().equals( // && element.getNodeName().equals(token.getValue())) { // break; } /* * An end tag whose tag name is "form" If there is no template element * on the stack of open elements, then run these substeps: Let node be * the element that the form element pointer is set to, or null if it is * not set to an element. Set the form element pointer to null. * Otherwise, let node be null. If node is null or if the stack of open * elements does not have node in scope, then this is a parse error; * abort these steps and ignore the token. Generate implied end tags. If * the current node is not node, then this is a parse error. Remove node * from the stack of open elements. If there is a template element on * the stack of open elements, then run these substeps instead: If the * stack of open elements does not have a form element in scope, then * this is a parse error; abort these steps and ignore the token. * Generate implied end tags. If the current node is not a form element, * then this is a parse error. Pop elements from the stack of open * elements until a form element has been popped from the stack. */ else if (tokenType == TokenType.end_tag && token.getValue().equals("form")) { if (!parserContext.openElementsContain("template")) { Node node = parserContext.getFormElementPointer() != null ? parserContext .getFormElementPointer() : null; if (parserContext.getFormElementPointer() != null) { parserContext.setFormElementPointer(null); } if (node == null || !ElementInScope.isInScope(parserContext, node.getNodeName())) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } GenerateImpliedEndTags.run(parserContext); if (parserContext.getCurrentNode() != node) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); } openElementStack .removeElementAt(openElementStack.indexOf(node)); } else { if (ElementInScope.isInScope(parserContext, "form")) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } GenerateImpliedEndTags.run(parserContext); if (!parserContext.getCurrentNode().getNodeName() .equals("form")) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); } while (!parserContext.getOpenElements().isEmpty()) { Element element = parserContext.getOpenElements().pop(); if (element.getNodeName().equals("form")) { break; } } } } /* * An end tag whose tag name is "p" If the stack of open elements does * not have a p element in button scope, then this is a parse error; * insert an HTML element for a "p" start tag token with no attributes. * Close a p element. */ else if (tokenType == TokenType.end_tag && token.getValue().equals("p")) { if (!ElementInScope.isInButtonScope(parserContext, "p")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); InsertAnHTMLElement.run(parserContext, new TagToken( TokenType.start_tag, "p")); } closeApElement(parserContext); } /* * An end tag whose tag name is "li" If the stack of open elements does * not have an li element in list item scope, then this is a parse * error; ignore the token. Otherwise, run these steps: Generate implied * end tags, except for li elements. If the current node is not an li * element, then this is a parse error. Pop elements from the stack of * open elements until an li element has been popped from the stack. */ else if (tokenType == TokenType.end_tag && token.getValue().equals("li")) { if (!ElementInScope.isInListItemScope(parserContext, "li")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } else { GenerateImpliedEndTags.run(parserContext, "li"); if (!parserContext.getCurrentNode().getNodeName().equals("li")) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); } while (!parserContext.getOpenElements().isEmpty()) { Element element = parserContext.getOpenElements().pop(); if (element.getNodeName().equals("li")) { break; } } } } /* * An end tag whose tag name is one of: "dd", "dt" If the stack of open * elements does not have an element in scope that is an HTML element * and with the same tag name as that of the token, then this is a parse * error; ignore the token. Otherwise, run these steps: Generate implied * end tags, except for HTML elements with the same tag name as the * token. If the current node is not an HTML element with the same tag * name as that of the token, then this is a parse error. Pop elements * from the stack of open elements until an HTML element with the same * tag name as the token has been popped from the stack. */ else if (tokenType == TokenType.end_tag && isOneOf(token.getValue(), new String[] { "dd", "dt" })) { if (!ElementInScope.isInScope(parserContext, token.getValue())) { parserContext .addParseErrors(ParseErrorType.UnexpectedInputCharacter); } else { GenerateImpliedEndTags.run(parserContext, token.getValue()); if (!parserContext.getCurrentNode().getNodeName() .equals(token.getValue())) parserContext .addParseErrors(ParseErrorType.UnexpectedToken); while (true) { Element element = parserContext.getOpenElements().pop(); if (element.getNodeName().equals(token.getValue())) { break; } } } // List<Element> list = new ArrayList<Element>(); // list.addAll(parserContext.getOpenElements()); // for (Element element : list) { // if (!element.getNamespaceURI().equals( // list.remove(element); // boolean flag = false; // for (Element element : list) { // if (element.getNodeName().equals(token.getValue())) { // flag = true; // String[] elementsInHTMLns = { "applet", "caption", "html", // "table", // "td", "th", "marquee", "object", "template" }; // if (!(isOneOf(token.getValue(), elementsInHTMLns) && flag)) { // parserContext.addParseErrors(ParseErrorType.UnexpectedToken); // return parserContext; // } else { // GenerateImpliedEndTags.run(parserContext, token.getValue()); // if (!parserContext.getCurrentNode().getNamespaceURI() // || !parserContext.getCurrentNode().getNodeName() // .equals(token.getValue())) { // parserContext // .addParseErrors(ParseErrorType.UnexpectedToken); // while (!parserContext.getOpenElements().isEmpty()) { // Element element = parserContext.getOpenElements().pop(); // if (element.getNamespaceURI().equals( // && element.getNodeName().equals(token.getValue())) { // break; } /* * An end tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", * "h6" If the stack of open elements does not have an element in scope * that is an HTML element and whose tag name is one of "h1", "h2", * "h3", "h4", "h5", or "h6", then this is a parse error; ignore the * token. Otherwise, run these steps: Generate implied end tags. If the * current node is not an HTML element with the same tag name as that of * the token, then this is a parse error. Pop elements from the stack of * open elements until an HTML element whose tag name is one of "h1", * "h2", "h3", "h4", "h5", or "h6" has been popped from the stack. */ else if (tokenType == TokenType.end_tag && isOneOf(token.getValue(), new String[] { "h1", "h2", "h3", "h4", "h5", "h6" })) { if (!ElementInScope.isInScope(parserContext, "h1,h2,h3,h4,h5,h6")) { parserContext .addParseErrors(ParseErrorType.UnexpectedInputCharacter); } else { GenerateImpliedEndTags.run(parserContext); if (!parserContext.getCurrentNode().getNodeName() .equals(token.getValue())) parserContext .addParseErrors(ParseErrorType.UnexpectedToken); while (true) { Element element = parserContext.getOpenElements().pop(); if (isOneOf(element.getNodeName(), new String[] { "h1", "h2", "h3", "h4", "h5", "h6" })) { break; } } } // List<Element> list = new ArrayList<Element>(); // list.addAll(parserContext.getOpenElements()); // boolean flag = true; // for (Element e : list) { // if (ElementInScope.isInScope(parserContext, e.getNodeName()) // && e.getNamespaceURI().equals( // && isOneOf(e.getNodeName(), new String[] { "h1", "h2", // "h3", "h4", "h5", "h6" })) { // flag = false; // break; // if (flag) { // parserContext.addParseErrors(ParseErrorType.UnexpectedToken); // return parserContext; // } else { // if (!parserContext.getCurrentNode().getNamespaceURI() // || !parserContext.getCurrentNode().getNodeName() // .equals(token.getValue())) { // parserContext // .addParseErrors(ParseErrorType.UnexpectedToken); // while (!parserContext.getOpenElements().isEmpty()) { // Element element = parserContext.getOpenElements().pop(); // if (isOneOf(element.getNodeName(), new String[] { "h1", // "h2", "h3", "h4", "h5", "h6" })) { // break; } /* * An end tag whose tag name is "sarcasm" Take a deep breath, then act * as described in the "any other end tag" entry below. */ else if (tokenType == TokenType.end_tag && token.getValue().equals("sarcasm")) { anyOtherEndTag(parserContext); } else if (tokenType == TokenType.start_tag && token.getValue().equals("a")) { ArrayList<Element> list = parserContext .getActiveFormattingElements(); List<Element> sublist = list.subList(list.lastIndexOf(null) + 1, list.size()); for (Element e : sublist) if (e.getNodeName().equals("a")) { parserContext .addParseErrors(ParseErrorType.UnexpectedToken); parserContext = AdoptionAgencyAlgorithm.Run(parserContext, token.getValue()); list = parserContext.getActiveFormattingElements(); if (list.size() < 1) break; Element last = list.get(list.size() - 1); if(last == null) break; if (last.getNodeName().equals("a")) parserContext.getActiveFormattingElements() .remove(last); last = parserContext.getOpenElements().peek(); if (last.getNodeName().equals("a")) parserContext.getOpenElements().pop(); } ListOfActiveFormattingElements.reconstruct(parserContext); Element e = InsertAnHTMLElement.run(parserContext, token); ListOfActiveFormattingElements.push(parserContext, e); } /* * A start tag whose tag name is one of: "b", "big", "code", "em", * "font", "i", "s", "small", "strike", "strong", "tt", "u" Reconstruct * the active formatting elements, if any. * * Insert an HTML element for the token. Push onto the list of active * formatting elements that element. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u" })) { ListOfActiveFormattingElements.reconstruct(parserContext); Element e = InsertAnHTMLElement.run(parserContext, token); ListOfActiveFormattingElements.push(parserContext, e); } /* * A start tag whose tag name is "nobr" Reconstruct the active * formatting elements, if any. * * If the stack of open elements has a nobr element in scope, then this * is a parse error; run the adoption agency algorithm for the tag name * "nobr", then once again reconstruct the active formatting elements, * if any. * * Insert an HTML element for the token. Push onto the list of active * formatting elements that element. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("nobr")) { if (ElementInScope.isInScope(parserContext, token.getValue())) parserContext.addParseErrors(ParseErrorType.UnexpectedToken); AdoptionAgencyAlgorithm.Run(parserContext, token.getValue()); ListOfActiveFormattingElements.reconstruct(parserContext); Element e = InsertAnHTMLElement.run(parserContext, token); ListOfActiveFormattingElements.push(parserContext, e); } /* * An end tag whose tag name is one of: "a", "b", "big", "code", "em", * "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" Run * the adoption agency algorithm for the token's tag name. */ else if (tokenType == TokenType.end_tag && isOneOf(token.getValue(), new String[] { "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" })) { AdoptionAgencyAlgorithm.Run(parserContext, token.getValue()); } /* * A start tag whose tag name is one of: "applet", "marquee", "object" * Reconstruct the active formatting elements, if any. Insert an HTML * element for the token. Insert a marker at the end of the list of * active formatting elements. Set the frameset-ok flag to "not ok". */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "applet", "marquee", "object" })) { if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } InsertAnHTMLElement.run(parserContext, token); ListOfActiveFormattingElements.insertMarker(parserContext); parserContext.setFlagFramesetOk(false); } /* * An end tag token whose tag name is one of: "applet", "marquee", * "object" If the stack of open elements does not have an element in * scope that is an HTML element and with the same tag name as that of * the token, then this is a parse error; ignore the token. Otherwise, * run these steps: Generate implied end tags. If the current node is * not an HTML element with the same tag name as that of the token, then * this is a parse error. Pop elements from the stack of open elements * until an HTML element with the same tag name as the token has been * popped from the stack. Clear the list of active formatting elements * up to the last marker. */ else if (tokenType == TokenType.end_tag && isOneOf(token.getValue(), new String[] { "applet", "marquee", "object" })) { if (!ElementInScope.isInScope(parserContext, token.getValue())) { parserContext .addParseErrors(ParseErrorType.UnexpectedInputCharacter); } else { GenerateImpliedEndTags.run(parserContext); if (!parserContext.getCurrentNode().getNodeName() .equals(token.getValue())) parserContext .addParseErrors(ParseErrorType.UnexpectedToken); while (!parserContext.getOpenElements().isEmpty()) { Element element = parserContext.getOpenElements().pop(); if (element.getNodeName().equals(token.getValue())) { break; } } } // List<Element> list = new ArrayList<Element>(); // list.addAll(parserContext.getOpenElements()); // boolean flag = true; // for (Element e : list) { // if (ElementInScope.isInScope(parserContext, e.getNodeName()) // && e.getNamespaceURI().equals( // && e.getNodeName().equals(token.getValue())) { // flag = false; // break; // if (flag) { // parserContext.addParseErrors(ParseErrorType.UnexpectedToken); // return parserContext; // } else { // GenerateImpliedEndTags.run(parserContext); // if (!parserContext.getCurrentNode().getNamespaceURI() // || !parserContext.getCurrentNode().getNodeName() // .equals(token.getValue())) { // parserContext // .addParseErrors(ParseErrorType.UnexpectedToken); // while (!parserContext.getOpenElements().isEmpty()) { // Element element = parserContext.getOpenElements().pop(); // if (element.getNodeName().equals(token.getValue())) { // break; // ListOfActiveFormattingElements.clear(parserContext); } /* * A start tag whose tag name is "table" TODO If the Document is not set * to quirks mode, and the stack of open elements has a p element in * button scope, then close a p element. Insert an HTML element for the * token. Set the frameset-ok flag to "not ok". Switch the insertion * mode to "in table". */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "table" })) { // TODO InsertAnHTMLElement.run(parserContext, token); parserContext.setFlagFramesetOk(false); parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_table)); } /* * An end tag whose tag name is "br"Parse error. Act as described in the * next entry,as if this was a "br" start tag token, rather than an end * tag token.A start tag whose tag name is one of: "area", "br", * "embed", "img", "keygen", "wbr"Reconstruct the active formatting * elements, if any.Insert an HTML element for the token.Immediately pop * the current node off the stack of open elements.Acknowledge the * token's self-closing flag, if it is set.Set the frameset-ok flag to * "not ok". */ else if ((tokenType == TokenType.end_tag && isOneOf(token.getValue(), new String[] { "br" })) || (tokenType == TokenType.start_tag && isOneOf( token.getValue(), new String[] { "area", "br", "embed", "img", "keygen", "wbr" }))) { if (token.getValue().equals("br")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); } if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } InsertAnHTMLElement.run(parserContext, token); parserContext.getOpenElements().pop(); ((TagToken) token).setFlagAcknowledgeSelfClosingTag(true); parserContext.setFlagFramesetOk(false); } /* * A start tag whose tag name is "input" Reconstruct the active * formatting elements, if any. Insert an HTML element for the token. * Immediately pop the current node off the stack of open elements. * Acknowledge the token's self-closing flag, if it is set. If the token * does not have an attribute with the name "type", or if it does, but * that attribute's value is not an ASCII case-insensitive match for the * string "hidden", then: set the frameset-ok flag to "not ok". */ else if (tokenType == TokenType.start_tag && token.getValue().equals("input")) { if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } InsertAnHTMLElement.run(parserContext, token); parserContext.getOpenElements().pop(); ((TagToken) token).setFlagAcknowledgeSelfClosingTag(true); } /* * A start tag whose tag name is one of: "param", "source", "track" * Insert an HTML element for the token. Immediately pop the current * node off the stack of open elements. Acknowledge the token's * self-closing flag, if it is set. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "param", "source", "track" })) { InsertAnHTMLElement.run(parserContext, token); parserContext.getOpenElements().pop(); ((TagToken) token).setFlagAcknowledgeSelfClosingTag(true); } /* * A start tag whose tag name is "hr" If the stack of open elements has * a p element in button scope, then close a p element. Insert an HTML * element for the token. Immediately pop the current node off the stack * of open elements. Acknowledge the token's self-closing flag, if it is * set. Set the frameset-ok flag to "not ok". */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "hr" })) { if (ElementInScope.isInButtonScope(parserContext, "p")) closeApElement(parserContext); InsertAnHTMLElement.run(parserContext, token); parserContext.getOpenElements().pop(); ((TagToken) token).setFlagAcknowledgeSelfClosingTag(true); parserContext.setFlagFramesetOk(false); } /* * A start tag whose tag name is "image" Parse error. Change the token's * tag name to "img" and reprocess it. (Don't ask.) */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "image" })) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); token.setValue("img"); parserContext.getTokenizerContext().setCurrentToken(token); parserContext.setFlagReconsumeToken(true); } /* * A start tag whose tag name is "isindex" Parse error. * * If there is no template element on the stack of open elements and the * form element pointer is not null, then ignore the token. * * Otherwise: * * Acknowledge the token's self-closing flag, if it is set. * * Set the frameset-ok flag to "not ok". * * If the stack of open elements has a p element in button scope, then * close a p element. * * Insert an HTML element for a "form" start tag token with no * attributes, and, if there is no template element on the stack of open * elements, set the form element pointer to point to the element * created. * * If the token has an attribute called "action", set the action * attribute on the resulting form element to the value of the "action" * attribute of the token. * * Insert an HTML element for an "hr" start tag token with no * attributes. Immediately pop the current node off the stack of open * elements. * * Reconstruct the active formatting elements, if any. * * Insert an HTML element for a "label" start tag token with no * attributes. * * Insert characters (see below for what they should say). * * Insert an HTML element for an "input" start tag token with all the * attributes from the "isindex" token except "name", "action", and * "prompt", and with an attribute named "name" with the value * "isindex". (This creates an input element with the name attribute set * to the magic balue "isindex".) Immediately pop the current node off * the stack of open elements. * * Insert more characters (see below for what they should say). * * Pop the current node (which will be the label element created * earlier) off the stack of open elements. * * Insert an HTML element for an "hr" start tag token with no * attributes. Immediately pop the current node off the stack of open * elements. * * Pop the current node (which will be the form element created earlier) * off the stack of open elements, and, if there is no template element * on the stack of open elements, set the form element pointer back to * null. * * Prompt: If the token has an attribute with the name "prompt", then * the first stream of characters must be the same string as given in * that attribute, and the second stream of characters must be empty. * Otherwise, the two streams of character tokens together should, * together with the input element, express the equivalent of * "This is a searchable index. Enter search keywords: (input field)" in * the user's preferred language. */ /* * A start tag whose tag name is "textarea" Run these steps: Insert an * HTML element for the token. If the next token is a "LF" (U+000A) * character token, then ignore that token and move on to the next one. * (Newlines at the start of textarea elements are ignored as an * authoring convenience.) Switch the tokenizer to the RCDATA state. Let * the original insertion mode be the current insertion mode. Set the * frameset-ok flag to "not ok". Switch the insertion mode to "text". */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "textarea" })) { InsertAnHTMLElement.run(parserContext, token); Token nextToken = parserContext.getTokenizerContext().getTokens() .peek(); if (nextToken != null && nextToken.getValue().equals( String.valueOf(Character.toChars(0x000A)))) { parserContext.getTokenizerContext().getTokens().poll(); } TokenizerStateFactory tokenStateFactory = TokenizerStateFactory .getInstance(); parserContext.getTokenizerContext().setNextState( tokenStateFactory.getState(TokenizerState.RCDATA_state)); parserContext.setOriginalInsertionMode(parserContext .getInsertionMode()); parserContext.setFlagFramesetOk(false); parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.text)); } /* * A start tag whose tag name is "xmp" If the stack of open elements has * a p element in button scope, then close a p element. Reconstruct the * active formatting elements, if any. Set the frameset-ok flag to * "not ok". Follow the generic raw text element parsing algorithm. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "xmp" })) { if (ElementInScope.isInButtonScope(parserContext, "p")) closeApElement(parserContext); if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } parserContext.setFlagFramesetOk(false); GenericRawTextElementParsing.run(parserContext, (TagToken) token); } /* * A start tag whose tag name is "iframe" Set the frameset-ok flag to * "not ok". Follow the generic raw text element parsing algorithm. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "iframe" })) { parserContext.setFlagFramesetOk(false); GenericRawTextElementParsing.run(parserContext, (TagToken) token); } /* * A start tag whose tag name is "noembed" A start tag whose tag name is * "noscript", if the scripting flag is enabled Follow the generic raw * text element parsing algorithm. */ else if ((tokenType == TokenType.start_tag && token.getValue().equals( "noembed")) || (tokenType == TokenType.start_tag && token.getValue().equals("noscript") && parserContext .isFlagScripting())) { GenericRawTextElementParsing.run(parserContext, (TagToken) token); } /* * A start tag whose tag name is "select" Reconstruct the active * formatting elements, if any. Insert an HTML element for the token. * Set the frameset-ok flag to "not ok". TODO If the insertion mode is * one of "in table", "in caption", "in table body", "in row", or * "in cell", then switch the insertion mode to "in select in table". * Otherwise, switch the insertion mode to "in select". */ else if ((tokenType == TokenType.start_tag && token.getValue().equals( "select"))) { if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } InsertAnHTMLElement.run(parserContext, token); parserContext.setFlagFramesetOk(false); IInsertionMode currentMode = parserContext.getInsertionMode(); if (currentMode instanceof InTable || currentMode instanceof InCaption || currentMode instanceof InTableBody || currentMode instanceof InRow || currentMode instanceof InCell) { parserContext.setInsertionMode(factory.getInsertionMode(InsertionMode.in_select_in_table)); }else { parserContext.setInsertionMode(factory.getInsertionMode(InsertionMode.in_select)); } } /* * A start tag whose tag name is one of: "optgroup", "option" If the * current node is an option element, then pop the current node off the * stack of open elements. Reconstruct the active formatting elements, * if any. Insert an HTML element for the token. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "optgroup", "option" })) { if (parserContext.getOpenElements().peek().getNodeName() .equals("option")) { parserContext.getOpenElements().pop(); } if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } InsertAnHTMLElement.run(parserContext, token); } /* * A start tag whose tag name is one of: "rb", "rp", "rtc" If the stack * of open elements has a ruby element in scope, then generate implied * end tags. If the current node is not then a ruby element, this is a * parse error. Insert an HTML element for the token. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "rb", "rp", "rtc" })) { if (ElementInScope.isInScope(parserContext, "ruby")) { GenerateImpliedEndTags.run(parserContext); } if (!parserContext.getCurrentNode().getNodeName().equals("ruby")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); } InsertAnHTMLElement.run(parserContext, token); } /* * A start tag whose tag name is "rt" If the stack of open elements has * a ruby element in scope, then generate implied end tags, except for * rtc elements. If the current node is not then a ruby element or an * rtc element, this is a parse error. Insert an HTML element for the * token. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("rt")) { if (ElementInScope.isInScope(parserContext, "ruby")) { GenerateImpliedEndTags.run(parserContext, "rtc"); } if (!parserContext.getCurrentNode().getNodeName().equals("ruby") || !parserContext.getCurrentNode().getNodeName() .equals("rtc")) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); } InsertAnHTMLElement.run(parserContext, token); } /* * A start tag whose tag name is "math" Reconstruct the active * formatting elements, if any. Adjust MathML attributes for the token. * (This fixes the case of MathML attributes that are not all * lowercase.) Adjust foreign attributes for the token. (This fixes the * use of namespaced attributes, in particular XLink.) Insert a foreign * element for the token, in the MathML namespace. If the token has its * self-closing flag set, pop the current node off the stack of open * elements and acknowledge the token's self-closing flag. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("math")) { if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } AdjustMathMLAttributes.run((TagToken) token); AdjustForeignAttributes.run((TagToken) token); InsertForeignElement.run(parserContext, token, Namespace.MathML); parserContext.getOpenElements().pop(); ((TagToken) token).setFlagAcknowledgeSelfClosingTag(true); } /* * A start tag whose tag name is "svg" Reconstruct the active formatting * elements, if any. Adjust SVG attributes for the token. (This fixes * the case of SVG attributes that are not all lowercase.) Adjust * foreign attributes for the token. (This fixes the use of namespaced * attributes, in particular XLink in SVG.) Insert a foreign element for * the token, in the SVG namespace. If the token has its self-closing * flag set, pop the current node off the stack of open elements and * acknowledge the token's self-closing flag. */ else if (tokenType == TokenType.start_tag && token.getValue().equals("svg")) { if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } AdjustSVGAttributes.run((TagToken) token); AdjustForeignAttributes.run((TagToken) token); InsertForeignElement.run(parserContext, token, Namespace.SVG); parserContext.getOpenElements().pop(); ((TagToken) token).setFlagAcknowledgeSelfClosingTag(true); } /* * A start tag whose tag name is one of: "caption", "col", "colgroup", * "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr" Parse * error. Ignore the token. */ else if (tokenType == TokenType.start_tag && isOneOf(token.getValue(), new String[] { "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr" })) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); return parserContext; } /* * Any other start tag Reconstruct the active formatting elements, if * any. Insert an HTML element for the token. */ else if (tokenType == TokenType.start_tag) { if (!parserContext.getActiveFormattingElements().isEmpty()) { ListOfActiveFormattingElements.reconstruct(parserContext); } InsertAnHTMLElement.run(parserContext, token); } else if (tokenType == TokenType.end_tag) { anyOtherEndTag(parserContext); } return parserContext; } public void anyOtherEndTag(ParserContext parserContext) { Token token = parserContext.getTokenizerContext().getCurrentToken(); // Any other end tag // Run these steps: // 1 Initialize node to be the current node (the bottommost node of the // stack). ArrayList<Element> stack = new ArrayList<>(); stack.addAll(parserContext.getOpenElements()); // 2 Loop: If node is an HTML element with the same tag name as the // token, then: for (int i = stack.size() - 1; i >= 0; i Element node = stack.get(i); if (node.getNodeName().equals(token.getValue())) { // 2.1 Generate implied end tags, except for HTML elements with // the same tag name as the token. GenerateAllImpliedEndTagsThoroughly.run(parserContext, token.getValue()); // 2.2 If node is not the current node, then this is a parse // error. if (!node.equals(parserContext.getCurrentNode())) parserContext .addParseErrors(ParseErrorType.UnexpectedToken); // 2.3 Pop all the nodes from the current node up to node, // including node, then stop these steps. while (true) { Element e = parserContext.getOpenElements().pop(); if (e.equals(node)) return; } } // 3 Otherwise, if node is in the special category, then this is a // parse error; ignore the token, and abort these steps. else if (Arrays.asList(HTML5Elements.SPECIAL).contains( node.getNodeName())) { parserContext.addParseErrors(ParseErrorType.UnexpectedToken); return; } // 4 Set node to the previous entry in the stack of open elements. // 5 Return to the step labeled loop. } } private void closeApElement(ParserContext parserContext) { // it means that the user agent must run the following steps: // Generate implied end tags, except for p elements. // If the current node is not a p element, then this is a parse error. // Pop elements from the stack of open elements until a p element has // been popped from the stack. GenerateImpliedEndTags.run(parserContext, "p"); if (!parserContext.getCurrentNode().getNodeName().equals("p")) parserContext.addParseErrors(ParseErrorType.UnexpectedToken); while (!parserContext.getOpenElements().isEmpty()) { Element e = parserContext.getOpenElements().pop(); if (e.getNodeName().equals("p")) return; } } private Boolean isOneOf(String value, String[] values) { for (String s : values) if (s.equals(value)) return true; return false; } private void loop(ParserContext parserContext,Node node){ while (node.getNodeName().equals("li")) { GenerateImpliedEndTags.run(parserContext, "li"); if(!parserContext.getCurrentNode().getNodeName().equals("li")){ parserContext.addParseErrors(ParseErrorType.UnexpectedToken); } while (!parserContext.getOpenElements().isEmpty()) { Element element = parserContext.getOpenElements().pop(); if (element.getNodeName().equals("li")){ break; } } done(parserContext); break; } } private void done(ParserContext parserContext){ if (ElementInScope.isInButtonScope(parserContext, "p")) { closeApElement(parserContext); } } }
package ru.matevosyan; public class Account { private double value; private String requisites; public double getValue() { return value; } public void setValue(double value) { this.value = value; } public void setRequisites(String requisites) { this.requisites = requisites; } public String getRequisites() { return requisites; } public Account(double value, String requisites) { this.value = value; this.requisites = requisites; } }
package com.kafka; /*import org.apache.avro.file.FileReader; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.mapred.FsInput; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.Configuration; import java.io.File; import java.io.IOException; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.io.DatumReader; import org.apache.avro.specific.SpecificDatumReader; */ public class Generateschemaavro { public static void main(String[] args) // throws IOException { /* final GenericDatumReader<Object> reader = new GenericDatumReader<Object>() ; // final Path path = new Path(args[0]); // final FsInput input = new FsInput(path, new Configuration()); // FileReader<Object> fileReader = DataFileReader.openReader(input, reader); File input = new File("C:\\Users\\sumeet.agrawal\\workspace\\test.avro\\test.avro"); FileReader<Object> fileReader = DataFileReader.openReader(input, reader); try{ final Schema schema1 = fileReader.getSchema(); System.out.println(schema1); } finally { fileReader.close(); } */ } }
package Problem371To380; import java.util.*; public class InsertDeleteGetRandomO1 { /* 380. Insert Delete GetRandom O(1) Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. Example: // Init an empty set. RandomizedSet randomSet = new RandomizedSet(); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomSet.insert(1); // Returns false as 2 does not exist in the set. randomSet.remove(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomSet.insert(2); // getRandom should return either 1 or 2 randomly. randomSet.getRandom(); // Removes 1 from the set, returns true. Set now contains [2]. randomSet.remove(1); // 2 was already in the set, so return false. randomSet.insert(2); // Since 2 is the only number in the set, getRandom always return 2. randomSet.getRandom(); */ /* Solutions: Due to O(1) insert and remove, cannot use Array, OR WE CAN ADD AND REMOVE ELM AT LAST INDEX, WHICH RANDOM WILL BE O(1) Due to O(1) getRandom, cannot use LinkedList, or at least cannot only use LinkedList Use HashSet to check if elm is contained or removed from list Use LinkedList to insert and remove elm, which time is O(1) Use HashMap connect with LinkedList which key is index, value is val in list, could get random in O(1) */ class RandomizedSet { /** Initialize your data structure here. */ private List<Integer> list; //Key is val, val is the index private HashMap<Integer, Integer> map; public RandomizedSet() { list = new ArrayList<>(); map = new HashMap<>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if (map.containsKey(val)) return false; //Use list.size() as the newest index in map map.put(val, list.size()); list.add(val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { if (!map.containsKey(val)) return false; //swap the val if not the last one, so that list.remove will be O(1) int index = map.get(val); if (index < list.size() - 1) { Integer last = list.get(list.size() - 1); //Only need to swap last value to index of val, no need care about last index due to will remove it list.set(index, last); //Update map as well map.put(last, index); } list.remove(list.size() - 1); map.remove(val); return true; } /** Get a random element from the set. */ public int getRandom() { int random = (int)(Math.random() * list.size()); return list.get(random); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ /** Follow up, what if the array could contains duplicate numbers Change HashMap to <Integer, LinkedList> when insert, always return true, and append index after list when remove, remove any or last index in the list */ }
package br.com.blackhubos.eventozero.factory; import java.util.HashSet; import java.util.Optional; import java.util.Set; import com.google.common.base.Preconditions; import org.bukkit.entity.Player; public class EventHandler { private final Set<Event> events; public EventHandler() { this.events = new HashSet<>(); } public Optional<Event> getEventByName(final String name) { for (final Event e : this.getEvents()) { if (e.getEventName().equals(name)) { return Optional.of(e); } } return Optional.empty(); } public Optional<Event> getEventByPlayer(final Player player) { for (final Event e : this.getEvents()) { if (e.hasPlayerJoined(player)) { return Optional.of(e); } } return Optional.empty(); } public Set<Event> getEvents() { return this.events; } public void loadEvent(final Event event) { Preconditions.checkNotNull(event, "Event is null"); this.events.add(event); } }
package ru.matevosyan.Figures; import ru.matevosyan.exceptions.ImpossibleMoveException; import ru.matevosyan.models.Cell; import ru.matevosyan.models.Figure; import java.util.Arrays; public class Bishop extends Figure { /** * Bishop name. */ private final String name = "Bishop"; /** * bishopWay is array that hold bishop steps. */ private Cell[] bishopWay = new Cell[7]; /** * countWay is variable that count how many steps bishop run. */ private int countWay = 0; /** * Bishop constructor invoke parent constructor which assign Cell position. * @param position Bishop position */ public Bishop(Cell position) { super(position); } @Override public String toString() { return String.format("%s", Arrays.toString(this.bishopWay)); } /** * Method way find the bishop movement and assign to Cell array which is returning in the end. * And we get all the way that bishop is getting. * @param dist the way that we want to get. * @return bishopWay that is actually array of cell or array of movement. * @throws ImpossibleMoveException throw when move is imposable. */ @Override public Cell[] way(Cell dist) throws ImpossibleMoveException { Cell bishopStep = new Cell(); int i = 0; if (Math.abs(dist.getX() - this.position.getX()) == Math.abs(dist.getY() - this.position.getY())) { /** * Get Cell distance X and Y getting from passing to method way. */ int distX = dist.getX(); int distY = dist.getY(); /** * Get Cell current position X and Y getting from passing to method way. */ int currentDistX = this.position.getX(); int currentDistY = this.position.getY(); /** * BishopStepsX = |distX-sourceX|-> it is figure steps. */ int bishopStepsX = Math.abs(distX - currentDistX); /** * BishopStepsY = |distY-sourceY|-> it is figure steps. */ int bishopStepsY = Math.abs(distY - currentDistY); /** * Example. * if dist = 0.7 from 6.1 then we go from 6.1 when distX < sourceX then increment distX while dist = source * and else distX > sourceX then decrement distX while dist = source and the same way we can use distY */ if (bishopStepsX != 0 & bishopStepsY != 0) { do { if (distX < currentDistX & distY < currentDistY) { this.bishopWay[i++] = new Cell(currentDistX--, currentDistY--); if (distX == currentDistX & distY == currentDistY) { this.bishopWay[i++] = dist; } } else if (distX < currentDistX & distY > currentDistY) { this.bishopWay[i++] = new Cell(currentDistX--, currentDistY++); if (distX == currentDistX & distY == currentDistY) { this.bishopWay[i++] = dist; } } else if (distX > currentDistX & distY > currentDistY) { this.bishopWay[i++] = new Cell(currentDistX++, currentDistY++); if (distX == currentDistX & distY == currentDistY) { this.bishopWay[i++] = dist; } } else if (distX > currentDistX & distY < currentDistY) { this.bishopWay[i++] = new Cell(currentDistX++, currentDistY if (distX == currentDistX & distY == currentDistY) { this.bishopWay[i++] = dist; } } countWay++; } while (distX != currentDistX); } else { throw new ImpossibleMoveException("You can't move that way!!!"); } } else { throw new ImpossibleMoveException("You can't move that way!!!"); } countWay = countWay + 1; Cell[] finalBishopWay = new Cell[countWay]; System.arraycopy(this.bishopWay, 0, finalBishopWay, 0, finalBishopWay.length); return finalBishopWay; } /** * Override clone method in Figure class which is actually abstract. * @param destination the way that we want to get. * @return new bishop instance. * @throws FigureNotFoundException that is men that clone can not find figure in destination position. */ @Override public Figure clone(Cell destination) { return new Bishop(destination); } }
package net.tomp2p.relay; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.tomp2p.Utils2; import net.tomp2p.futures.BaseFuture; import net.tomp2p.futures.BaseFutureListener; import net.tomp2p.futures.FutureBootstrap; import net.tomp2p.futures.FutureChannelCreator; import net.tomp2p.futures.FutureDirect; import net.tomp2p.futures.FuturePeerConnection; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerMaker; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.rpc.ObjectDataReply; import org.junit.Assert; import org.junit.Test; public class TestRelay { @Test public void testSetupRelayPeers() throws Exception { final Random rnd = new Random(42); final int nrOfNodes = 200; Peer master = null; Peer unreachablePeer = null; try { // setup test peers Peer[] peers = Utils2.createNodes(nrOfNodes, rnd, 4001); master = peers[0]; List<FutureBootstrap> tmp = new ArrayList<FutureBootstrap>(nrOfNodes); for (int i = 0; i < peers.length; i++) { new RelayRPC(peers[i]); if (peers[i] != master) { FutureBootstrap res = peers[i].bootstrap().setPeerAddress(master.getPeerAddress()).start(); tmp.add(res); } } for (FutureBootstrap fm : tmp) { fm.awaitUninterruptibly(); Assert.assertTrue("Bootrapping test peers failed", fm.isSuccess()); } // Test setting up relay peers unreachablePeer = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(5000).makeAndListen(); RelayManager manager = new RelayManager(unreachablePeer, master.getPeerAddress()); RelayFuture rf = manager.setupRelays(); rf.awaitUninterruptibly(); Assert.assertTrue(rf.isSuccess()); Assert.assertEquals(manager, rf.relayManager()); Assert.assertTrue(manager.getRelayAddresses().size() > 0); Assert.assertTrue(manager.getRelayAddresses().size() <= PeerAddress.MAX_RELAYS); Assert.assertEquals(manager.getRelayAddresses().size(), unreachablePeer.getPeerAddress().getPeerSocketAddresses().length); } finally { if (master != null) { unreachablePeer.shutdown().await(); master.shutdown().await(); } } } @Test public void testRelay() throws Exception { final Random rnd = new Random(42); final int nrOfNodes = 200; Peer master = null; try { // setup test peers Peer[] peers = Utils2.createNodes(nrOfNodes, rnd, 4001); master = peers[0]; List<FutureBootstrap> tmp = new ArrayList<FutureBootstrap>(nrOfNodes); for (int i = 0; i < peers.length; i++) { new RelayRPC(peers[i]); if (peers[i] != master) { FutureBootstrap res = peers[i].bootstrap().setPeerAddress(master.getPeerAddress()).start(); tmp.add(res); } } for (FutureBootstrap fm : tmp) { fm.awaitUninterruptibly(); Assert.assertTrue("Bootrapping test peers failed", fm.isSuccess()); } // Test setting up relay peers Peer slave = new PeerMaker(Number160.createHash(rnd.nextInt())).ports(13337).makeAndListen(); // Ping peer before setting up relays // System.out.println("Ping unreachable peer before setting up relays"); // BaseFuture f1 = // peers[rnd.nextInt(nrOfNodes)].ping().setPeerAddress(slave.getPeerAddress()).start(); // f1.awaitUninterruptibly(); // Assert.assertFalse(f1.isSuccess()); RelayManager manager = new RelayManager(slave, master.getPeerAddress()); RelayFuture rf = manager.setupRelays(); rf.awaitUninterruptibly(); Assert.assertTrue(rf.isSuccess()); //Check if flags are set correctly //Assert.assertTrue(slave.getPeerAddress().isRelay()); //TODO Assert.assertFalse(slave.getPeerAddress().isFirewalledTCP()); Assert.assertFalse(slave.getPeerAddress().isFirewalledUDP()); // Ping the unreachable peer from any peer System.out.print("Send UDP ping to unreachable peer"); BaseFuture f2 = peers[rnd.nextInt(nrOfNodes)].ping().setPeerAddress(slave.getPeerAddress()).start(); f2.awaitUninterruptibly(); Assert.assertTrue(f2.isSuccess()); System.out.println("...done"); System.out.print("Send TCP ping to unreachable peer"); BaseFuture f3 = peers[rnd.nextInt(nrOfNodes)].ping().setTcpPing().setPeerAddress(slave.getPeerAddress()).start(); f3.awaitUninterruptibly(); Assert.assertTrue(f3.isSuccess()); System.out.println("...done"); System.out.print("Send direct message to unreachable peer"); final String request = "Hello "; final String response = "World!"; slave.setObjectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { Assert.assertEquals(request.toString(), request); return response; } }); FutureDirect fd = peers[rnd.nextInt(nrOfNodes)].sendDirect(slave.getPeerAddress()).setObject(request).start(); fd.addListener(new BaseFutureListener<FutureDirect>() { @Override public void operationComplete(FutureDirect future) throws Exception { Assert.assertEquals(response, future.object()); } @Override public void exceptionCaught(Throwable t) throws Exception { Assert.fail(t.getMessage()); } }); fd.awaitUninterruptibly(); System.out.println("...done"); Thread.sleep(100); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testRelayRPC() throws Exception { Peer master = null; Peer slave = null; try { final Random rnd = new Random(42); Peer[] peers = Utils2.createNodes(2, rnd, 4000); master = peers[0]; // the relay peer new RelayRPC(master); // register relayRPC ioHandler slave = peers[1]; // create channel creator FutureChannelCreator fcc = slave.getConnectionBean().reservation().create(1, PeerAddress.MAX_RELAYS); fcc.awaitUninterruptibly(); RelayConnectionFuture rcf = new RelayRPC(slave).setupRelay(master.getPeerAddress(), fcc.getChannelCreator()); rcf.awaitUninterruptibly(); //Check if permanent peer connection was created Assert.assertTrue(rcf.isSuccess()); FuturePeerConnection fpc = rcf.futurePeerConnection(); Assert.assertEquals(master.getPeerAddress(), fpc.getObject().remotePeer()); Assert.assertTrue(fpc.getObject().channelFuture().channel().isActive()); Assert.assertTrue(fpc.getObject().channelFuture().channel().isOpen()); } finally { master.shutdown().await(); slave.shutdown().await(); } } }
package ch.openech.xml.write; import static ch.openech.xml.read.StaxEch.*; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class EchSchema { private static Map<String, EchSchema> contexts = new HashMap<String, EchSchema>(); private final Map<Integer, String> namespaceURIs = new HashMap<Integer, String>(); private final Map<Integer, String> namespaceLocations = new HashMap<Integer, String>(); private final Map<Integer, Integer> namespaceVersions = new HashMap<Integer, Integer>(); private final Map<Integer, Integer> namespaceMinorVersions = new HashMap<Integer, Integer>(); private final int rootNumber; private String version; private String openEchNamespaceLocation; private WriterEch0020 writerEch0020; private WriterEch0112 writerEch0112; private WriterEch0148 writerEch0148; public EchSchema() { this.rootNumber = 0; this.version = null; } private EchSchema(int rootNumber, String version) { read(rootNumber, version); this.rootNumber = rootNumber; this.version = version; } public static EchSchema getNamespaceContext(int rootNumber, String version) { String location = EchNamespaceUtil.schemaLocation(rootNumber, version); if (!contexts.containsKey(location)) { EchSchema namespaceContext = new EchSchema(rootNumber, version); try { namespaceContext.read(location); contexts.put(location, namespaceContext); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return contexts.get(location); } public static EchSchema getNamespaceContext(ch.openech.dm.EchSchema schema) { return getNamespaceContext(schema.getSchemaNumber(), schema.getVersion() + "." + schema.getMinorVersion()); } private void read(int rootNumber, String version) { int pos = version.indexOf('.'); String major = version.substring(0, pos); String minor = version.substring(pos + 1); String rootNamespaceURI = EchNamespaceUtil.schemaURI(rootNumber, major); String rootNamespaceLocation = EchNamespaceUtil.schemaLocation(rootNamespaceURI, minor); try { read(rootNamespaceLocation); if (rootNumber == 20) { readOpenEch(WriterOpenEch.URI); } } catch (Exception x) { // TODO x.printStackTrace(); } } public String getVersion() { return version; } public String getNamespaceURI(int namespaceNumber) { return namespaceURIs.get(namespaceNumber); } public String getNamespaceLocation(int namespaceNumber) { return namespaceLocations.get(namespaceNumber); } public int getNamespaceVersion(int namespaceNumber) { return namespaceVersions.get(namespaceNumber); } public int getNamespaceMinorVersion(int namespaceNumber) { return namespaceMinorVersions.get(namespaceNumber); } public Set<Integer> getNamespaceNumbers() { return namespaceURIs.keySet(); } public String getOpenEchNamespaceLocation() { return openEchNamespaceLocation; } private void read(String namespaceLocation) throws XMLStreamException, IOException { if (namespaceLocations.containsValue(namespaceLocation)) return; registerLocation(namespaceLocation); process(namespaceLocation); } private void readOpenEch(String openEchNamespaceLocation) throws XMLStreamException, IOException { this.openEchNamespaceLocation = openEchNamespaceLocation; process(openEchNamespaceLocation); } private void process(String namespaceLocation) throws XMLStreamException, IOException { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xml = null; try { xml = inputFactory.createXMLEventReader(new URL(namespaceLocation).openStream()); process(xml); } catch (Exception e) { // this could happen in SBB ;) InputStream stream = EchNamespaceUtil.getLocalCopyOfSchema(namespaceLocation); xml = inputFactory.createXMLEventReader(stream); process(xml); } } private void registerLocation(String namespaceLocation) { int namespaceNumber = EchNamespaceUtil.extractSchemaNumber(namespaceLocation); String namespaceURI = EchNamespaceUtil.schemaURI(namespaceLocation); int namespaceVersion = EchNamespaceUtil.extractSchemaMajorVersion(namespaceLocation); int namespaceMinorVersion = EchNamespaceUtil.extractSchemaMinorVersion(namespaceLocation); namespaceURIs.put(namespaceNumber, namespaceURI); namespaceLocations.put(namespaceNumber, namespaceLocation); namespaceVersions.put(namespaceNumber, namespaceVersion); namespaceMinorVersions.put(namespaceNumber, namespaceMinorVersion); } private void process(XMLEventReader xml) throws XMLStreamException, IOException { while (true) { XMLEvent event = xml.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); String startName = startElement.getName().getLocalPart(); if (startName.equals("schema")) { imports(xml); } else skip(xml); } else if (event.isEndElement() || event.isEndDocument()) { return; } // else skip } } private void imports(XMLEventReader xml) throws XMLStreamException, IOException { while (true) { XMLEvent event = xml.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); String startName = startElement.getName().getLocalPart(); if (startName.equals("import")) { imprt(startElement); skip(xml); } else skip(xml); } else if (event.isEndElement()) { return; } // else skip } } private void imprt(StartElement startElement) throws XMLStreamException, IOException { String schemaLocation = startElement.getAttributeByName(new QName("schemaLocation")).getValue(); read(schemaLocation); } public WriterEch0020 getWriterEch0020() { if (writerEch0020 == null) { writerEch0020 = new WriterEch0020(this); // 1100 - 1400ms } return writerEch0020; } public WriterEch0112 getWriterEch0112() { if (writerEch0112 == null) { writerEch0112 = new WriterEch0112(this); } return writerEch0112; } public WriterEch0148 getWriterEch0148() { if (writerEch0148 == null) { writerEch0148 = new WriterEch0148(this); // 1100 - 1400ms } return writerEch0148; } public boolean birthPlaceMustNotBeUnknown() { return getNamespaceVersion(20) > 1; // !StringUtils.equals(ewkVersion, "1.0", "1.1"); } public boolean contactHasValidTill() { return getNamespaceVersion(20) > 1 || getNamespaceMinorVersion(20) > 1; // !StringUtils.equals(ewkVersion, "1.0", "2.0", "2.1"); } /* Ab Version 1.1 und 2.2 kann bei Vormundschaftliche Massnahme * angegeben werden, ob das Sorgerecht beinhatlet ist */ public boolean gardianMeasureRelationshipHasCare() { return getNamespaceVersion(20) == 1 && getNamespaceMinorVersion(20) > 0 || getNamespaceVersion(20) == 2 && getNamespaceMinorVersion(20) > 1 || getNamespaceVersion(20) > 2; } /* Ab Version 1.1 und 2.2 */ public boolean renewPermitHasTill() { return getNamespaceVersion(20) == 1 && getNamespaceMinorVersion(20) > 0 || getNamespaceVersion(20) == 2 && getNamespaceMinorVersion(20) > 1 || getNamespaceVersion(20) > 2; } /* In den alten Versionen musste bei der Korrektur der Berufsdaten mindestens * Ein Beruf angegeben werden. Das war wahrscheinlich falsch, aber das * XML verlangt es so. */ public boolean correctOccupationMustHaveOccupation() { return getNamespaceVersion(20) > 1 || getNamespaceMinorVersion(20) > 1; // !StringUtils.equals(ewkVersion, "1.0", "2.0", "2.1"); } public boolean additionalCorrectEvents() { return getNamespaceVersion(20) > 1 || getNamespaceMinorVersion(20) > 1; // !StringUtils.equals(ewkVersion, "1.0", "2.0", "2.1"); } /* Ab Version 2.0 wird residencePermitDetailed von eCH 6 nicht mehr verwendet * sondern nur noch residencePermit */ public boolean residencePermitDetailed() { return getNamespaceVersion(20) == 1; // return StringUtils.equals(ewkVersion, "1.0", "1.1"); } /* In den Versionen 2.0 und 2.1 wurden bei eventCorrectRelationship die Namen * der Eltern mitgeliefert. */ public boolean correctRelationshipPersonIncludesParents() { return getNamespaceVersion(20) == 1 || getNamespaceMinorVersion(20) == 2; // return StringUtils.equals(ewkVersion, "1.0", "1.1", "2.2"); } public boolean keyDeliveryPossible() { return getNamespaceVersion(20) > 1; // return !StringUtils.equals(ewkVersion, "1.0", "1.1"); } /* Die Auswahl des Paragraphen wurde bei eCH0021 in * der 3. Version reduziert auf ein paar wenige */ public boolean reducedBasedOnLawCode() { return getNamespaceVersion(20) > 1; // return ewkVersion.compareTo("2.0") >= 0; } /* basedOnLaw bei gardianMeasure wurde mit Version 2.1 nicht mehr zwingend */ public boolean basedOnLawCodeRequired() { return getNamespaceVersion(20) == 1 || getNamespaceVersion(20) == 2 && getNamespaceMinorVersion(20) == 0; } /* basedOnLawAddOn gibt es ab Version 2.3 */ public boolean basedOnLawAddOn() { return getNamespaceVersion(20) >= 2 && getNamespaceMinorVersion(20) >= 3; } /* Ab 2.3 ist bei eventGardianMeasure und eventChangeGardian die * relationship optional */ public boolean gardianRelationshipOptional() { return getNamespaceVersion(20) >= 2 && getNamespaceMinorVersion(20) >= 3; } /* Ab 2.3 gibt es einen 10. Typ von Beziehung */ public boolean typeOfRelationship10Exsists() { return getNamespaceVersion(20) >= 2 && getNamespaceMinorVersion(20) >= 3; } /* * Beim Wechsel des Namens konnten bei den alten Versionen * auch die Namen der Eltern gewechselt werden */ public boolean changeNameWithParents() { return getNamespaceVersion(20) < 2; // return ewkVersion.compareTo("2.0") < 0; } public boolean extensionAvailable() { return getNamespaceVersion(20) > 1 || getNamespaceMinorVersion(20) > 0; } /* * separationTill in maritalData existiert erst ab der 5. Version von eCH 11 */ public boolean separationTillAvailable() { return getNamespaceVersion(11) >= 5; } public boolean kindOfEmploymentMandatory() { return getNamespaceVersion(21) < 4; } public boolean occupationValidTillAvailable() { return getNamespaceVersion(21) >= 4; } public boolean addressesAreBusiness() { return rootNumber == 148; } }
package com.change_vision.astah.extension.plugin.uml2c.codegenerator; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import com.change_vision.astah.extension.plugin.uml2c.cmodule.AbstractCModule; import com.change_vision.jude.api.inf.AstahAPI; class CodeGenerator { private static final String TEMPLATE_ENCODING = "UTF-8"; //"UTF-8", "Windows-31J" private static final String OUTPUT_ENCODING = "UTF-8"; //"UTF-8", "Windows-31J" public CodeGenerator(AbstractCModule cModule) { this.cModule = cModule; Velocity.setProperty("file.resource.loader.path", getTemplateSearchDirPath()); //Velocity.setProperty("runtime.log.error.stacktrace", "true"); //Velocity.setProperty("runtime.log.warn.stacktrace", "true"); //Velocity.setProperty("runtime.log.info.stacktrace", "true"); Velocity.init(); } public void outputCode(String codePath, String templatePath) throws IOException { VelocityContext context = new VelocityContext(); context.put("cModule", cModule); Template template = Velocity.getTemplate(templatePath, TEMPLATE_ENCODING); File file = new File(codePath); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), OUTPUT_ENCODING))); template.merge(context, pw); pw.close(); } public String getCModuleName() { return cModule.getName(); } public String getTemplateSearchDirPath() { return getAstahConfigPath() + ",."; } private String getAstahConfigPath() { String edition; try { edition = AstahAPI.getAstahAPI().getProjectAccessor().getAstahEdition(); } catch (ClassNotFoundException e) { e.printStackTrace(); return ""; } String userHomeDir = System.getProperty("user.home"); return userHomeDir + "/.astah/" + edition; } public String getTemplateDirPath() { return templateDirPath; } private AbstractCModule cModule; private static final String templateDirPath = "plugins/uml2c/"; }
// checkstyle: Checks Java source code for adherence to a set of rules. // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Restricts the number of executable statements to a specified limit * (default = 30). * @author Simon Harris */ public final class ExecutableStatementCountCheck extends Check { /** default threshold */ private static final int DEFAULT_MAX = 30; /** threshold to report error for */ private int max; /** Stack of method contexts. */ private final FastStack<Context> contextStack = FastStack.newInstance(); /** Current method context. */ private Context context; /** Constructs a <code>ExecutableStatementCountCheck</code>. */ public ExecutableStatementCountCheck() { setMax(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, TokenTypes.SLIST, }; } @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.SLIST}; } /** * Gets the maximum threshold. * @return the maximum threshold. */ public int getMax() { return max; } /** * Sets the maximum threshold. * @param max the maximum threshold. */ public void setMax(int max) { this.max = max; } @Override public void beginTree(DetailAST rootAST) { context = null; contextStack.clear(); } @Override public void visitToken(DetailAST ast) { switch (ast.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: case TokenTypes.INSTANCE_INIT: case TokenTypes.STATIC_INIT: visitMemberDef(ast); break; case TokenTypes.SLIST: visitSlist(ast); break; default: throw new IllegalStateException(ast.toString()); } } @Override public void leaveToken(DetailAST ast) { switch (ast.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: case TokenTypes.INSTANCE_INIT: case TokenTypes.STATIC_INIT: leaveMemberDef(ast); break; case TokenTypes.SLIST: // Do nothing break; default: throw new IllegalStateException(ast.toString()); } } /** * Process the start of the member definition. * @param ast the token representing the member definition. */ private void visitMemberDef(DetailAST ast) { contextStack.push(context); context = new Context(ast); } /** * Process the end of a member definition. * * @param ast the token representing the member definition. */ private void leaveMemberDef(DetailAST ast) { final int count = context.getCount(); if (count > getMax()) { log(ast.getLineNo(), ast.getColumnNo(), "executableStatementCount", count, getMax()); } context = contextStack.pop(); } /** * Process the end of a statement list. * * @param ast the token representing the statement list. */ private void visitSlist(DetailAST ast) { if (context != null) { // find member AST for the statement list final DetailAST contextAST = context.getAST(); DetailAST parent = ast.getParent(); while (parent != null) { final int type = parent.getType(); if ((type == TokenTypes.CTOR_DEF) || (type == TokenTypes.METHOD_DEF) || (type == TokenTypes.INSTANCE_INIT) || (type == TokenTypes.STATIC_INIT)) { if (parent == contextAST) { context.addCount(ast.getChildCount() / 2); } break; } parent = parent.getParent(); } } } /** * Class to encapsulate counting information about one member. * @author Simon Harris */ private static class Context { /** Member AST node. */ private final DetailAST ast; /** Counter for context elements. */ private int count; /** * Creates new member context. * @param ast member AST node. */ public Context(DetailAST ast) { this.ast = ast; count = 0; } /** * Increase count. * @param count the count increment. */ public void addCount(int count) { this.count += count; } /** * Gets the member AST node. * @return the member AST node. */ public DetailAST getAST() { return ast; } /** * Gets the count. * @return the count. */ public int getCount() { return count; } } }
package de.aima13.whoami.modules; import de.aima13.whoami.Analyzable; import de.aima13.whoami.GlobalData; import de.aima13.whoami.Whoami; import de.aima13.whoami.support.DataSourceManager; import org.farng.mp3.MP3File; import org.farng.mp3.TagException; import org.farng.mp3.id3.AbstractID3v2; import org.farng.mp3.id3.ID3v1; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; import java.sql.*; import java.util.*; /** * favourite Music, created 16.10.14. * * @author Inga Miadowicz * @version 1.1 */ public class Music implements Analyzable { List<Path> musicDatabases = new ArrayList<>(); List<Path> localFiles = new ArrayList<>(); //Liste von MP3-Dateien List<Path> browserFiles = new ArrayList<>(); //Liste der Browser-DB List<Path> exeFiles = new ArrayList<>(); //Liste der Musikprogramme ArrayList<String> fileArtist = new ArrayList<>(); // Artists direkt aus Dateien ArrayList<String> fileGenre = new ArrayList<>(); ArrayList<String> urls = new ArrayList<>(); Map<String, Integer> mapMaxApp = new HashMap<>(); Map<String, Integer> mapMaxGen = new HashMap<>(); ResultSet mostVisited = null; public String html = ""; //Output als HTML in String public String favArtist = ""; public String favGenre = ""; public String onlService = ""; //Genutzte Onlinedienste (siehe: MY_SEARCH_DELIVERY_URLS) public String cltProgram = ""; //Installierte Programme String stmtGenre = ""; //Kommentar zum Genre nach Kategorie String Qualität = ""; //Kommentar zu flac-Dateien long nrAudio = 0; //Anzahl der Audiodateien private static final String[] MY_SEARCH_DELIEVERY_URLS = {"youtube.com", "myvideo.de", "dailymotion.com", "soundcloud.com", "deezer.com", "spotify.com", "play.google.com"}; private static final String[] MY_SEARCH_DELIVERY_EXES = {"Deezer.exe", "spotify.exe", "Amazon Music.exe", "SWYH.exe", "iTunes.exe", "napster.exe", "simfy.exe"}; private static final String[] MY_SEARCH_DELIVERY_NAMES = {"Deezer", "Spotify", "Amazon Music", "Stream What You Hear", "iTunes", "napster", "simfy"}; private static final String TITLE = "Musikgeschmack"; String[] arrayGenre = { // Position im Array ist die ID des id3Tag: // z.B. GenreID ist 3: Genre zu 3 ist "Dance" //Dies sind die offiziellen ID3v1 Genres. "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk", "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock", "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno", "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental", "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "Alternative Rock", "Bass", "Soul", "Punk", "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", "Darkwave", "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult", "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave", "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical", "Rock & Roll", "Hard Rock", //These were made up by the authors of Winamp but backported into the ID3 spec. "Folk", "Folk-Rock", "National Folk", "Swing", "Fast Fusion", "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock", "Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus", "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson", "Opera", "Chamber Music", "Sonata", "Symphony", "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba", "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock", "Drum Solo", "A capella", "Euro-House", "Dance Hall", //These were also invented by the Winamp folks but ignored by the ID3 authors. "Goa", "Drum & Bass", "Club-House", "Hardcore", "Terror", "Indie", "BritPop", "Negerpunk", "Polsk Punk", "Beat", "Christian Gangsta Rap", "Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock", "Merengue", "Salsa", "Thrash Metal", "Anime", "Jpop", "Synthpop" }; @Override public void run() { getFilter(); if (Whoami.getTimeProgress() < 300) { this.readId3Tag(); } if (Whoami.getTimeProgress() < 100) { this.scoreFavArtist(); } if (Whoami.getTimeProgress() < 100) { this.scoreFavGenre(); } if (Whoami.getTimeProgress() < 100) { this.checkNativeClients(MY_SEARCH_DELIVERY_EXES, MY_SEARCH_DELIVERY_NAMES); } if (Whoami.getTimeProgress() < 300) { readBrowser(MY_SEARCH_DELIEVERY_URLS); } } @Override public List<String> getFilter() { List<String> filterMusic = new ArrayList<>(); // Audiodateien filterMusic.add("**.mp3"); filterMusic.add("**.wav"); filterMusic.add("**.wma"); filterMusic.add("**.aac"); filterMusic.add("**.ogg"); filterMusic.add("**.flac"); filterMusic.add("**.rm"); filterMusic.add("**.M4a"); filterMusic.add("**.vox"); filterMusic.add("**.m4b"); // Browser-history filterMusic.add("**Google/Chrome**History"); filterMusic.add("**Firefox**places.sqlite"); // installierte Programme filterMusic.add("**spotify.exe"); filterMusic.add("**iTunes.exe"); filterMusic.add("**SWYH.exe"); filterMusic.add("**simfy.exe"); filterMusic.add("**napster.exe"); filterMusic.add("**Amazon*Music.exe"); filterMusic.add("**Deezer.exe"); return filterMusic; } @Override public void setFileInputs(List<Path> files) throws Exception { long count = 0; if (!(files == null)) { musicDatabases = files; } else { throw new IllegalArgumentException("Auf dem Dateisystem konnten keine " + "Informationen zu Musik gefunden werden."); } String username = System.getProperty("user.name"); GlobalData.getInstance().proposeData("Benutzername", username); //Spalte die Liste in drei Unterlisten: for (Path element : musicDatabases) { String path = element.toString(); if (element.toString().contains(".mp3") || element.toString().contains(".MP3")) { localFiles.add(element); count++; //Kommentar zu ".flac-Dateien" abgeben if(element.toString().endsWith(".flac")) { Qualität = "Du bist ein richtiger Audiofan und legst wert auf die maximale " + "Qualität deiner Musiksammlung! "; } //Entferne Musik zu PC-Spielen (aus Steam), Beispielmusik und // Audiodateien die nicht auf Metadaten untersucht werden if(element.toString().contains("Steam") || element.toString().contains("Kalimba" + ".mp3") || element.toString().contains("Sleep Away.mp3") || element.toString().contains("Maid with the Flaxen " + "Hair.mp3") || element.toString().contains("$RJLQJ56.mp3") || element .toString().contains("$IJLQJ56.mp3") || element.toString().endsWith("" + ".wav") || element.toString().endsWith(".wma") || element.toString() .endsWith(".aac") || element.toString().endsWith(".ogg") || element.toString ().endsWith(".flac") || element.toString().endsWith(".rm") || element .toString().endsWith(".M4a") || element.toString().endsWith(".vox") || element.toString().endsWith("m4b")) { localFiles.remove(element); } } else if (element.toString().contains(".exe")) { exeFiles.add(element); } else if (path.contains(".sqlite") || (path.endsWith("\\History") && path.contains (username))) { browserFiles.add(element); } } musicDatabases.clear(); nrAudio = count; } ///// Output-Dateien vorbereiten ///////////////////// @Override public String getHtml() { StringBuilder buffer = new StringBuilder(); // Ergebnistabelle buffer.append("<table>"); if (!(favArtist.equals(""))) { buffer.append("<tr><td>Lieblingskünstler:</td>" + "<td>" + favArtist + "</td></tr>"); } if (!(favGenre.equals(""))) { buffer.append("<tr>" + "<td>Lieblingsgenre:</td>" + "<td>" + favGenre + "</td>" + "</tr>"); } if (!(cltProgram.equals(""))) { buffer.append("<tr>" + "<td>Musikprogramme:</td>" + "<td>" + cltProgram + "</td>" + "</tr>"); } if (!(onlService.equals(""))) { buffer.append("<tr>" + "<td>Onlinestreams:</td>" + "<td>" + onlService + "</td>" + "</tr>"); } buffer.append("</table>"); // Abschlussfazit des Musikmoduls if (favGenre.equals("") && onlService.equals("") && cltProgram.equals("") && favArtist .equals("")) { buffer.append("Es wurden keine Informationen gefunden um den scheinbar " + "sehr geheimen Musikgeschmack des Users zu analysieren."); } else if (!(onlService.equals("")) && !(favArtist.equals("")) && !(favGenre.equals("")) && !(cltProgram.equals(""))) { buffer.append("<br /><b>Fazit:</b> Dein Computer enthält Informationen zu allem " + "was wir gesucht haben. <br />Musik scheint ein wichtiger Teil deines Lebens " + "zu sein. <br />" + "Insgesamt haben wir " + nrAudio + " Musikdateien " + "gefunden." + Qualität + stmtGenre); } else if (onlService.equals("") && cltProgram.equals("") && !(favGenre.equals(""))) { buffer.append("<br /><b>Fazit:</b> Das Modul konnte weder online noch nativ " + "herausfinden wie du Musik hörst. Du scheinst dies über einen nicht sehr " + "verbreiteten Weg zu machen. Nichts desto trotz konnten wir deinen Geschmack " + "analysieren: <br />" + "Insgesamt haben wir " + nrAudio + " Musikdateien " + "gefunden." + Qualität + stmtGenre); } else if (favGenre.equals("") && favArtist.equals("")) { buffer.append("<br /><b>Fazit:</b> Es konnten keine Informationen dazu gefunden " + "werden was du hörst. Deine Lieblingsgenre und Lieblingkünstler bleiben eine " + "offene Frage..."); if (!(onlService.equals("")) || !(cltProgram.equals(""))) { buffer.append(" Aber Musik hörst du über " + onlService + ", " + cltProgram + "."); if(nrAudio != 0){ buffer.append("Insgesamt haben wir zusätzlich " + nrAudio + " Musikdateien " + "gefunden." + Qualität); } } } else { buffer.append("<br /><b>Fazit:</b> Zwar konnten einige Informationen über " + "dich nicht herausgefunden werden, <br />aber einiges wissen wir."); if (!(onlService.equals(""))) { buffer.append("<br />Du hörst über " + onlService + " online Musik."); } if (!(cltProgram.equals(""))) { buffer.append("<br />Auf deinem PC benutzt du zum Musik hören " + cltProgram + "."); } if (!(favArtist.equals(""))) { buffer.append( "Deine Lieblingsband ist " + favArtist + "."); } if (!(favGenre.equals(""))) { buffer.append("<br />" + stmtGenre); } if(!(localFiles.isEmpty())){ buffer.append("Insgesamt haben wir " + nrAudio + " Musikdateien gefunden." + Qualität); } } html = buffer.toString(); return html; } @Override public String getReportTitle() { return TITLE; } @Override public String getCsvPrefix() { return TITLE; } @Override public SortedMap<String, String> getCsvContent() { SortedMap<String, String> csvData = new TreeMap<>(); if (!(favArtist.equals(""))) { csvData.put("Lieblingskünstler", favArtist); } if (!(favGenre.equals(""))) { csvData.put("Lieblingsgenre", favGenre); } if (!(onlService.equals(""))) { csvData.put("Onlineservices", onlService); } if (!(cltProgram.equals(""))) { csvData.put("Musikprogramme", cltProgram); } return csvData; } ///// Analysiere Audidateien ///////////// /** * Sucht aus der Liste aller Genres (FileGenre) das Lieblingsgenre heraus und speichert dies * global in der Variable favGenre * @return void * @param */ public void scoreFavGenre() { int max = 0; int count; fileGenre.removeAll(Arrays.asList("", null)); for (String each : fileGenre) { //Einige ID3-Tags sind fehlerhaft und die ID wird in der Form "(XX)"als String // gespeichert. Hier wird nochmal geguckt ob das Genre zugeordnet werden kann. if (each.startsWith("(")) { String str; str = each.replaceAll("\\D+", ""); short gId = Short.parseShort(str); each = arrayGenre[gId]; } count = 0; if (mapMaxGen.containsKey(each)) { count = mapMaxGen.get(each); mapMaxGen.remove(each); } count++; mapMaxGen.put(each, count); } Iterator it = mapMaxGen.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); if ((int) (pairs.getValue()) > max && !(pairs.equals("Other")) && !(pairs.toString() .contains("Other"))) { favGenre = (String) pairs.getKey(); max = (int) (pairs.getValue()); } it.remove(); } getCategory(); if (favGenre.equals("Emo")) { GlobalData.getInstance().changeScore("Selbstmordgefährung", 50); } else if (favGenre.equals("Dance") || favGenre.equals("Disco")) { GlobalData.getInstance().changeScore("Selbstmordgefährung", -20); } else if (favGenre.equals("Chillout")) { GlobalData.getInstance().changeScore("Faulenzerfaktor", 40); } } public String getCategory() { StringBuilder statementToGenre = new StringBuilder(); if (favGenre.equals("Top 40") || favGenre.equals("House") || favGenre.equals("Drum & " + "Bass") || favGenre.equals("Euro-House")) { statementToGenre.append("Dein Musikgeschmack ist nicht gerade " + "aussagekräftig.<br />Du scheinst nicht wirklich auszuwählen was " + "dir gefällt,<br />sondern orientierst dich an Listen und Freunden.<br />" + "Was dich charaktierisitert ist wahrscheinlich das Mainstream-Opfer"); } else if (favGenre.equals("Dance") || favGenre.equals("Disco") || favGenre.equals("Dancehall") || favGenre.equals("Samba") || favGenre.equals("Tango") || favGenre.equals("Club") || favGenre.equals("Swing") || favGenre.equals("Latin") || favGenre.equals("Salsa") || favGenre.equals("Eurodance") || favGenre.equals("Pop")) { statementToGenre.append("Deinem Musikstil, " + favGenre + ", " + "nach zu urteilen,<br />schwingst du zumindest gerne dein Tanzbein oder bist " + "sogar eine richtige Dancing Queen! <3"); } else if (favGenre.equals("Techno") || favGenre.equals("Industrial") || favGenre.equals ("Acid Jazz") || favGenre.equals("Rave") || favGenre.equals("Psychedelic") || favGenre.equals("Dream") || favGenre.equals("Elecronic") || favGenre .equals("Techno-Industrial") || favGenre.equals("Space") || favGenre.equals("Acid") || favGenre.equals("Trance") || favGenre.equals("Fusion") || favGenre.equals("Euro-Techno") || favGenre.equals("Hardcore Techno") || favGenre .equals("Goa") || favGenre.equals("Fast Fusion") || favGenre.equals("Synthpop") || favGenre.equals("Dub") || favGenre.equals("Psytrance") || favGenre.equals ("Dubstep") || favGenre.equals("Psybient")) { statementToGenre.append("Dein Musikstil lässt darauf schließen, " + "<br />dass wenn man dich grob einer Richtung zuordnet du am ehesten einem Raver " + "entsprichst."); } else if (favGenre.equals("Retro") || favGenre.equals("Polka") || favGenre.equals ("Country") || favGenre.equals("Oldies") || favGenre.equals("Native US") || favGenre.equals("Southern Rock") || favGenre.equals("Instrumental") || favGenre .equals("Classical") || favGenre.equals("Gospel") || favGenre.equals("Folklore") || favGenre.equals("A capella") || favGenre.equals("Symphony") || favGenre.equals("Sonata") || favGenre.equals("Opera") || favGenre.equals ("National Folk") || favGenre.equals("Avantgarde") || favGenre.equals("Baroque") || favGenre.equals("World Music") || favGenre.equals("Neoclassical")) { statementToGenre.append("Dein Musikstil" + favGenre + " ist eher von " + "traditioneller Natur und verrät uns, dass du in der Zeit stehen geblieben bist."); } else if (favGenre.equals("Christian Rap") || favGenre.equals("Pop-Folk") || favGenre .equals("Christian Rock") || favGenre.equals("Contemporary Christian") || favGenre.equals("Christian Gangsta Rap") || favGenre.equals("Terror") || favGenre .equals("Jpop") || favGenre.equals("Math Rock") || favGenre.equals("Emo") || favGenre.equals("New Romantic")) { statementToGenre.append("Über Geschmack lässt sich ja bekanntlich streiten. " + "Aber " + favGenre + " - Dein Ernst?!"); } else if (favGenre.equals("Post-Rock") || favGenre.equals("Classic Rock") || favGenre .equals("Metal") || favGenre.equals("Rock") || favGenre.equals("Death Metal") || favGenre.equals("Hard Rock") || favGenre.equals("Alternative Rock") || favGenre .equals("Instrumental Rock") || favGenre.equals("Darkwave") || favGenre.equals ("Gothic") || favGenre.equals("Folk Rock") || favGenre.equals("Symphonic Rock") || favGenre.equals("Gothic Rock") || favGenre .equals("Progressive Rock") || favGenre.equals("Black Metal") || favGenre.equals ("Heavy Metal") || favGenre.equals("Punk Rock") || favGenre.equals("Rythmic " + "Soul") || favGenre.equals("Thrash Metal") || favGenre.equals("Garage Rock") || favGenre.equals("Space Rock") || favGenre.equals("Industro-Goth") || favGenre .equals("Garage") || favGenre.equals("Art Rock")) { statementToGenre.append(favGenre + "? In dir steckt bestimmt ein Headbanger! Yeah \\m/ !!!"); } else if (favGenre.equals("Chillout") || favGenre.equals("Reggea") || favGenre.equals ("Trip-Hop") || favGenre.equals("Hip-Hop")) { statementToGenre.append("Deine Szene ist wahrscheinlich die Hip Hop Szene.<br />Du bist ein " + "sehr relaxter Mensch <br />und vermutlich gehören die Baggy Pants " + "zu deinen Lieblingskleidungstücken?"); } else if (favGenre.equals("Blues") || favGenre.equals("Jazz") || favGenre.equals("Vocal") || favGenre.equals("Jazz & Funk") || favGenre.equals("Soul") || favGenre.equals ("Ambient") || favGenre.equals("Illbient") || favGenre.equals("Lounge")) { statementToGenre.append("Deinem Lieblingsgenre zu urteilen beschreibt sich dieses " + "Modul als wahren Kenner.<br />Vermutlich spielst du selber mindestens ein " + "Instrument <br />und verbringt dein Leben am liebsten entspannt mit einem " + "Glas Rotwein."); } else if (favGenre.equals("Gangsta") || favGenre.equals("Rap")) { statementToGenre.append("Du hörst Rap. Vielleicht bis du sogar ein übler " + "Gangstarapper"); } else if (favGenre.equals("Ska") || favGenre.equals("Acid Punk") || favGenre.equals("Punk") || favGenre.equals("Polsk Punk") || favGenre.equals("Negerpunk") || favGenre .equals("Post-Punk")) { statementToGenre.append("Deine Musiklieblingsrichtung ist Punk oder zumindest eine" + "Strömung des Punks. "); } else if (favGenre.equals("Funk") || favGenre.equals("New Age") || favGenre.equals ("Grunge") || favGenre.equals("New Wave") || favGenre.equals("Rock & Roll") || favGenre.equals("BritPop") || favGenre.equals("Indie") || favGenre.equals("Porn " + "Groove") || favGenre.equals("Chanson") || favGenre.equals("Folk") || favGenre .equals("Experimental") || favGenre.equals("Neue Deutsche Welle") || favGenre .equals("Indie Rock") || favGenre.equals("Alternative")) { statementToGenre.append("Dein Musikgeschmack, " + favGenre + ", " + "zeugt auf jeden Fall von Geschmack und Stil."); } else if (favGenre.equals("Podcast") || favGenre.equals("Audio Theatre") || favGenre.equals ("Audiobook") || favGenre.equals("Speech") || favGenre.equals("Satire") || favGenre.equals("Soundtrack") || favGenre.equals("Sound Clip") || favGenre.equals ("Comedy") || favGenre.equals("Cabaret") || favGenre.equals("Showtunes") || favGenre.equals("Trailer") || favGenre.equals("Musical")) { statementToGenre.append("Die Audiodatei lässt sich einer Art Literatur zuordnen. " + "<br />Du bist entweder sehr Literaturbegeistert und liebst Soundtracks und Co" + "<br />oder eine sehr faule Leseratte, die sich lieber alles vorlesen lässt. <br />" + "Wie auch immer du bist, " + "wahrscheinlich ein ziemlich belesener Mensch. "); } else if (favGenre.equals("Other") || favGenre.equals("Andere")) { statementToGenre.append("Du hast anscheinend mehr MP3-Files in deiner " + "Spielebibliothek <br/ >als sonst auf dem PC. Das Genre dieser Dateien wird " + "als <br />'" + favGenre + "betitelt."); } else { statementToGenre.append("Dein Musikgeschmack " + favGenre + " <br />ist auf jeden " + "Fall ziemlich " + "extravagant."); } stmtGenre = statementToGenre.toString(); return stmtGenre; } /** * Sucht aus einer Liste aller Artisten des Lieblingsartisten heraus. Dieser wird global in * der Variable favArtist gespeichert. * @param * @return void */ public void scoreFavArtist() { int count; int max = 0; fileArtist.removeAll(Arrays.asList("", null)); for (String each : fileArtist) { count = 0; if (mapMaxApp.containsKey(each)) { count = mapMaxApp.get(each); mapMaxApp.remove(each); } count++; mapMaxApp.put(each, count); } Iterator it = mapMaxApp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); if ((int) (pairs.getValue()) > max) { favArtist = (String) pairs.getKey(); max = (int) (pairs.getValue()); } it.remove(); } } /** * Liest den ID3 Tag von gefundenen MP3- und FLAC-Dateien aus * * @param * @return void * @remark benutzt Bibliothek "jid3lib-0.5.4.jar" * @exception org.farng.mp3.TagException, FileNotFoundException, * UnsupportedOperationException, IOException, Exception */ public void readId3Tag() { String genre = ""; //Name of Genre int count = 0; if (!(localFiles.isEmpty())){ for (Path file : localFiles) { try { String fileLocation = file.toAbsolutePath().toString(); //Get path to file MP3File mp3file = new MP3File(fileLocation); //create new object from ID3tag-package if (mp3file.hasID3v2Tag()) { AbstractID3v2 tagv2 = mp3file.getID3v2Tag(); //Fill ArrayList<String> with Artists and Genres fileArtist.add(tagv2.getLeadArtist()); genre = tagv2.getSongGenre(); //Da die Genres bei dieser Version als String gespeichert sind, // kann das Feld auch unsinnige Genres enthalten. Gleicht das Genre nicht // einem der bekannten aus der Liste wird es nicht aufgenommen for(int i = 0; i<arrayGenre.length; i++){ if(genre == arrayGenre[i]){ fileGenre.add(genre); } } } else if (mp3file.hasID3v1Tag()) { ID3v1 tagv1 = mp3file.getID3v1Tag(); fileArtist.add(tagv1.getArtist()); //Fill List of Type String with artist // Map Genre-ID zu Genre-Name short gId = tagv1.getGenre(); //Get Genre ID try { genre = arrayGenre[gId]; // Genre zur ID } catch (ArrayIndexOutOfBoundsException e) { // Die Genre-ID existiert offiziell nicht } fileGenre.add(genre); //Fill List of Type String with genre } } catch (TagException e) { } catch (FileNotFoundException e) { //Dateipfad existiert nicht oder der Zugriff wurde verweigert } catch (UnsupportedOperationException e) { //MP3-File Objekt kann nicht gebildet werden } catch (IOException e) { } catch (Exception e) { } } } } ///// Analysiere Musikprogramme ////////// public void checkNativeClients(String exes[], String names[]) { for (Path currentExe : exeFiles) { for(int i = 0; i < exes.length; i++) { if (currentExe.toString().endsWith(exes[i])) { if(cltProgram.equals("")){ cltProgram = names[i]; } else if(!(cltProgram.contains(names[i]))){ cltProgram += ", " + names[i]; } } } } } ///// Analysiere Browserverlauf ////////// public void readBrowser(String searchUrl[]) { for (Path db : browserFiles) { try { mostVisited = dbExtraction(db, MY_SEARCH_DELIEVERY_URLS); if(mostVisited != null) { while (mostVisited.next()) { String urlName = ""; urlName = mostVisited.getString("host"); if (urlName != null && !urlName.equals("")) { if (!(urls.contains(urlName))) { urls.add(urlName); } } } } } catch (SQLException e) { //Ergebnis ist leer } finally { if (mostVisited != null) { try { mostVisited.close(); mostVisited.getStatement().close(); } catch (SQLException e) { //Keine DB } } } } for (int i = 0; i < urls.size(); i++) { for(int j = 0; j < searchUrl.length; j++){ if(urls.get(i).contains(searchUrl[j]) && !(onlService.contains(searchUrl[j]))){ if (onlService.isEmpty()) { onlService += searchUrl[j]; // erster Dienst } else { onlService += ", " + searchUrl[j]; // weitere Dienste werden mit Komma // angehangen } } } } } private ResultSet dbExtraction(Path sqliteDb, String searchUrl[]) { DataSourceManager dbManager; try { dbManager = new DataSourceManager(sqliteDb); if (sqliteDb.toString().contains("Firefox")) { String sqlStatement = "SELECT host " + "FROM moz_hosts " + "WHERE host LIKE '" + searchUrl[0] + "'"; for (int i = 1; i < searchUrl.length; i++) { sqlStatement += " OR host LIKE '" + searchUrl[i] + "'"; } mostVisited = dbManager.querySqlStatement(sqlStatement); } else if (sqliteDb.toString().contains("Chrome")) { String sqlStatement = "SELECT url AS host " + "FROM urls " + "WHERE host LIKE '%" + searchUrl[0] + "%'"; for (int i = 1; i < searchUrl.length; i++) { sqlStatement += " OR host LIKE '%" + searchUrl[i] + "%'"; } mostVisited = dbManager.querySqlStatement(sqlStatement); } } catch (ClassNotFoundException | SQLException | NullPointerException e) { } return mostVisited; } }
package com.codebutler.android_websockets; import android.os.Handler; import android.os.HandlerThread; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import org.apache.http.*; import org.apache.http.client.HttpResponseException; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.message.BasicLineParser; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import javax.net.SocketFactory; import javax.net.ssl.SSLException; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.URI; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.util.List; public class WebSocketClient { private static final String TAG = "WebSocketClient"; private URI mURI; private Listener mListener; private Socket mSocket; private Thread mThread; private HandlerThread mHandlerThread; private Handler mHandler; private List<BasicNameValuePair> mExtraHeaders; private HybiParser mParser; private boolean mIsConnected; private final Object mSendLock = new Object(); private static SSLSocketFactory sSSLSocketFactory = null; /** * Note: Keystore will only be initialized once; calling the function again will have no effect. */ public static void setKeystore(InputStream keyStoreInputStream, String keyStorePassword) throws GeneralSecurityException, IOException { if (sSSLSocketFactory != null) return; KeyStore trusted = KeyStore.getInstance("BKS"); // Initialize the keystore with the provided trusted certificates trusted.load(keyStoreInputStream, keyStorePassword.toCharArray()); // Pass the keystore to the SSLSocketFactory. The factory is responsible // for the verification of the server certificate. sSSLSocketFactory = new SSLSocketFactory(trusted); // Hostname verification from certificate // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 sSSLSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } public WebSocketClient(URI uri, Listener listener, List<BasicNameValuePair> extraHeaders) { mURI = uri; mListener = listener; mExtraHeaders = extraHeaders; mParser = new HybiParser(this); mIsConnected = false; mHandlerThread = new HandlerThread("websocket-thread"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper()); } public Listener getListener() { return mListener; } public void connect() { if (mThread != null && mThread.isAlive()) { return; } mThread = new Thread(new Runnable() { @Override public void run() { try { int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getScheme().equals("wss") ? 443 : 80); String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath(); if (!TextUtils.isEmpty(mURI.getQuery())) { path += "?" + mURI.getQuery(); } String originScheme = mURI.getScheme().equals("wss") ? "https" : "http"; URI origin = new URI(originScheme, "//" + mURI.getHost(), null); if (mURI.getScheme().equals("wss")) { if (sSSLSocketFactory == null) throw new RuntimeException("Need to call setKeystore() before connecting"); mSocket = sSSLSocketFactory.connectSocket( null, mURI.getHost(), port, null, 0, new BasicHttpParams()); } else { SocketFactory factory = SocketFactory.getDefault(); mSocket = factory.createSocket(mURI.getHost(), port); } PrintWriter out = new PrintWriter(mSocket.getOutputStream()); out.print("GET " + path + " HTTP/1.1\r\n"); out.print("Upgrade: websocket\r\n"); out.print("Connection: Upgrade\r\n"); out.print("Host: " + mURI.getHost() + "\r\n"); out.print("Origin: " + origin.toString() + "\r\n"); out.print("Sec-WebSocket-Key: " + createSecret() + "\r\n"); out.print("Sec-WebSocket-Version: 13\r\n"); if (mExtraHeaders != null) { for (NameValuePair pair : mExtraHeaders) { out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue())); } } out.print("\r\n"); out.flush(); HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream()); // Read HTTP response status line. StatusLine statusLine = parseStatusLine(readLine(stream)); if (statusLine == null) { throw new HttpException("Received no reply from server."); } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } // Read HTTP response headers. String line; while (!TextUtils.isEmpty(line = readLine(stream))) { Header header = parseHeader(line); if (header.getName().equals("Sec-WebSocket-Accept")) { // FIXME: Verify the response... } } mIsConnected = true; mListener.onConnect(); // Now decode websocket frames. mParser.start(stream); } catch (EOFException ex) { Log.d(TAG, "WebSocket EOF!", ex); mIsConnected = false; mListener.onDisconnect(0, "EOF; " + ex); } catch (SSLException ex) { // Connection reset by peer Log.d(TAG, "Websocket SSL error!", ex); mIsConnected = false; mListener.onDisconnect(0, "SSL; " + ex); } catch (Exception ex) { mListener.onError(ex); } } }); mThread.start(); } public void disconnect() { if (mSocket != null) { mHandler.post(new Runnable() { @Override public void run() { try { mSocket.close(); mSocket = null; } catch (IOException ex) { Log.d(TAG, "Error while disconnecting", ex); mListener.onError(ex); } } }); } } public void send(String data) { sendFrame(mParser.frame(data)); } public void send(byte[] data) { sendFrame(mParser.frame(data)); } public boolean isConnected() { return mIsConnected; } private StatusLine parseStatusLine(String line) { if (TextUtils.isEmpty(line)) { return null; } return BasicLineParser.parseStatusLine(line, new BasicLineParser()); } private Header parseHeader(String line) { return BasicLineParser.parseHeader(line, new BasicLineParser()); } // Can't use BufferedReader because it buffers past the HTTP data. private String readLine(HybiParser.HappyDataInputStream reader) throws IOException { int readChar = reader.read(); if (readChar == -1) { return null; } StringBuilder string = new StringBuilder(""); while (readChar != '\n') { if (readChar != '\r') { string.append((char) readChar); } readChar = reader.read(); if (readChar == -1) { return null; } } return string.toString(); } private String createSecret() { byte[] nonce = new byte[16]; for (int i = 0; i < 16; i++) { nonce[i] = (byte) (Math.random() * 256); } return Base64.encodeToString(nonce, Base64.DEFAULT).trim(); } void sendFrame(final byte[] frame) { mHandler.post(new Runnable() { @Override public void run() { try { synchronized (mSendLock) { OutputStream outputStream = mSocket.getOutputStream(); outputStream.write(frame); outputStream.flush(); } } catch (IOException e) { mListener.onError(e); } catch (NullPointerException e) { /* ignore; probably in the process of shutting down */ } } }); } public interface Listener { public void onConnect(); public void onMessage(String message); public void onMessage(byte[] data); public void onDisconnect(int code, String reason); public void onError(Exception error); } }
package com.parc.ccn.network; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import javax.xml.stream.XMLStreamException; import com.parc.ccn.CCNBase; import com.parc.ccn.Library; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.WirePacket; import com.parc.ccn.data.query.CCNFilterListener; import com.parc.ccn.data.query.CCNInterestListener; import com.parc.ccn.data.query.Interest; import com.parc.ccn.data.util.InterestTable; import com.parc.ccn.data.util.InterestTable.Entry; import com.parc.ccn.security.keys.KeyManager; /** * Interface to the ccnd. Most clients, * and the CCN library, will use this as the "CCN". * * @author smetters, rasmusse * */ public class CCNNetworkManager implements Runnable { public static final int DEFAULT_AGENT_PORT = 4485; public static final String DEFAULT_AGENT_HOST = "localhost"; public static final String PROP_AGENT_PORT = "ccn.agent.port"; public static final String PROP_AGENT_HOST = "ccn.agent.host"; public static final String PROP_TAP = "ccn.tap"; public static final String ENV_TAP = "CCN_TAP"; // match C library public static final int MAX_PAYLOAD = 8800; // number of bytes in UDP payload public static final int SOCKET_TIMEOUT = 1000; // period to wait in ms. public static final int PERIOD = 2000; // period for occasional ops in ms. public static final int MAX_PERIOD = PERIOD * 16; public static final String KEEPALIVE_NAME = "/HereIAm"; /** * Static singleton. */ protected Thread _thread = null; // the main processing thread protected ExecutorService _threadpool = null; // pool service for callback threads protected DatagramChannel _channel = null; // for use by run thread only! protected Selector _selector = null; protected Throwable _error = null; // Marks error state of socket protected boolean _run = true; protected KeyManager _keyManager; protected ContentObject _keepalive; protected FileOutputStream _tapStreamOut = null; protected FileOutputStream _tapStreamIn = null; // Tables of interests/filters: users must synchronize on collection protected InterestTable<InterestRegistration> _myInterests = new InterestTable<InterestRegistration>(); protected InterestTable<Filter> _myFilters = new InterestTable<Filter>(); private Timer _periodicTimer = null; /** * @author rasmusse * Do scheduled writes. */ private class PeriodicWriter extends TimerTask { public void run() { heartbeat(); // Library.logger().finest("Refreshing interests (size " + _myInterests.size() + ")"); // Re-express interests that need to be re-expressed long ourTime = new Date().getTime(); try { synchronized (_myInterests) { for (Entry<InterestRegistration> entry : _myInterests.values()) { InterestRegistration reg = entry.value(); if (ourTime > reg.nextRefresh) { Library.logger().finer("Refresh interest: " + reg.interest.name()); // Temporarily back out refresh period decay to allow the repository // to work with an "eavesdropping interest" //reg.nextRefreshPeriod = (reg.nextRefreshPeriod * 2) > MAX_PERIOD ? MAX_PERIOD //: reg.nextRefreshPeriod * 2; reg.nextRefresh += reg.nextRefreshPeriod; write(reg.interest); } } } } catch (XMLStreamException xmlex) { Library.logger().severe("Processing thread failure (Malformed datagram): " + xmlex.getMessage()); Library.warningStackTrace(xmlex); } } } // Send heartbeat private void heartbeat() { try { ByteBuffer heartbeat = ByteBuffer.allocate(1); _channel.write(heartbeat); } catch (IOException io) { // We do not see errors on send typically even if // agent is gone, so log each but do not track Library.logger().warning("Error sending heartbeat packet: " + io.getMessage()); } } // Generic superclass for registration objects that may have a listener // Handles invalidation and pending delivery consistently to enable // subclass to call listener callback without holding any library locks, // yet avoid delivery to a cancelled listener. protected abstract class ListenerRegistration implements Runnable { protected Object listener; protected CCNNetworkManager manager; public Semaphore sema = null; public Object owner = null; protected boolean deliveryPending = false; protected long id; public abstract void deliver(); public void invalidate() { // There may be a pending delivery in progress, and it doesn't // happen while holding this lock because that would give the // application callback code power to block library processing. // Instead, we use a flag that is checked and set under this lock // to be sure that on exit from invalidate() there will be // no future deliveries based on the now-invalid registration. while (true) { synchronized (this) { // Make invalid, this will prevent any new delivery that comes // along from doing anything. this.listener = null; this.sema = null; // Return only if no delivery is in progress now (or if we are // called out of our own handler) if (!deliveryPending || (Thread.currentThread().getId() == id)) { return; } } Thread.yield(); } } public void run() { id = Thread.currentThread().getId(); synchronized (this) { // Mark us pending delivery, so that any invalidate() that comes // along will not return until delivery has finished this.deliveryPending = true; } try { // Delivery may synchronize on this object to access data structures // but should hold no locks when calling the listener deliver(); } catch (Exception ex) { Library.logger().warning("failed delivery: " + ex.toString()); } finally { synchronized(this) { this.deliveryPending = false; } } } // Equality based on listener if present, so multiple objects can // have the same interest registered without colliding public boolean equals(Object obj) { if (obj instanceof ListenerRegistration) { ListenerRegistration other = (ListenerRegistration)obj; if (this.owner == other.owner) { if (null == this.listener && null == other.listener){ return super.equals(obj); } else if (null != this.listener && null != other.listener) { return this.listener.equals(other.listener); } } } return false; } public int hashCode() { if (null != this.listener) { if (null != owner) { return owner.hashCode() + this.listener.hashCode(); } else { return this.listener.hashCode(); } } else { return super.hashCode(); } } } /** * Record of Interest * @field interest Interest itself * @field listener Listener to be notified of data matching the Interest. The * listener must be set (non-null) for cases of standing Interest that holds * until canceled by the application. The listener should be null when a * thread is blocked waiting for data, in which case the thread will be * blocked on semaphore. * @field semaphore used to block thread waiting for data or null if none * @field data data for waiting thread * @field lastRefresh last time this interest was refreshed * @field data Holds data responsive to the interest for a waiting thread * @author jthornto * */ protected class InterestRegistration extends ListenerRegistration { public final Interest interest; protected ArrayList<ContentObject> data = new ArrayList<ContentObject>(1); protected long nextRefresh; protected long nextRefreshPeriod = PERIOD; // All internal client interests must have an owner public InterestRegistration(CCNNetworkManager mgr, Interest i, CCNInterestListener l, Object owner) { manager = mgr; interest = i; listener = l; this.owner = owner; if (null == listener) { sema = new Semaphore(0); } nextRefresh = new Date().getTime() + nextRefreshPeriod; } // Add a copy of data, not the original data object, so that // the recipient cannot disturb the buffers of the sender // We need this even when data comes from network, since receive // buffer will be reused while recipient thread may proceed to read // from buffer it is handed /** * Return true if data was added */ public synchronized boolean add(ContentObject obj) { boolean hasData = (null == data); if (!hasData) this.data.add(obj.clone()); return !hasData; } /** * This used to be called just data, but its similarity * to a simple accessor made the fact that it cleared the data * really confusing and error-prone... * Pull the available data out for processing. * @return */ public synchronized ArrayList<ContentObject> popData() { ArrayList<ContentObject> result = this.data; this.data = new ArrayList<ContentObject>(1); return result; } public void deliver() { try { if (null != this.listener) { // Standing interest: call listener callback ArrayList<ContentObject> results = null; CCNInterestListener listener = null; synchronized (this) { if (this.data.size() > 0) { results = this.data; this.data = new ArrayList<ContentObject>(1); listener = (CCNInterestListener)this.listener; } } // Call into client code without holding any library locks if (null != results) { Library.logger().finer("Interest callback (" + results.size() + " data) for: " + this.interest.name()); synchronized (this) { // DKS -- dynamic interests, unregister the interest here and express new one if we have one // previous interest is final, can't update it this.deliveryPending = false; } manager.unregisterInterest(this); // paul r. note - contract says interest will be gone after the call into user's code. // Eventually this may be modified for "pipelining". // DKS TODO tension here -- what object does client use to cancel? // Original implementation had expressInterest return a descriptor // used to cancel it, perhaps we should go back to that. Otherwise // we may need to remember at least the original interest for cancellation, // or a fingerprint representation that doesn't include the exclude filter. // DKS even more interesting -- how do we update our interest? Do we? // it's final now to avoid contention, but need to change it or change // the registration. Interest updatedInterest = listener.handleContent(results, interest); // Possibly we should optimize here for the case where the same interest is returned back // (now we would unregister it, then reregister it) but need to be careful that the timing // behavior is right if we do that if (null != updatedInterest) { Library.logger().finer("Interest callback: updated interest to express: " + updatedInterest.name()); // luckily we saved the listener // if we want to cancel this one before we get any data, we need to remember the // updated interest in the listener manager.expressInterest(this.owner, updatedInterest, listener); } } else { Library.logger().finer("Interest callback skipped (no data) for: " + this.interest.name()); } } else { synchronized (this) { if (null != this.sema) { Library.logger().finer("Data consumes pending get: " + this.interest.name()); // Waiting thread will pickup data -- wake it up // If this interest came from net or waiting thread timed out, // then no thread will be waiting but no harm is done Library.logger().finest("releasing " + this.sema); this.sema.release(); } } if (null == this.sema) { // this is no longer valid registration Library.logger().finer("Interest callback skipped (not valid) for: " + this.interest.name()); } } } catch (Exception ex) { Library.logger().warning("failed to deliver data: " + ex.toString()); Library.warningStackTrace(ex); } } public void run() { synchronized (this) { // For now only one piece of data may be delivered per InterestRegistration // This might change when "pipelining" is implemented if (deliveryPending) return; } super.run(); } } /** * Record of a filter describing portion of namespace for which this * application can respond to interests. * @author jthornto * */ protected class Filter extends ListenerRegistration { public ContentName name; protected boolean deliveryPending = false; protected ArrayList<Interest> interests= new ArrayList<Interest>(1); public Filter(CCNNetworkManager mgr, ContentName n, CCNFilterListener l, Object o) { name = n; listener = l; owner = o; manager = mgr; } public synchronized void add(Interest i) { interests.add(i); } public void deliver() { try { ArrayList<Interest> results = null; CCNFilterListener listener = null; synchronized (this) { if (this.interests.size() > 0) { results = interests; interests = new ArrayList<Interest>(1); listener = (CCNFilterListener)this.listener; } } if (null != results) { // Call into client code without holding any library locks Library.logger().finer("Filter callback (" + results.size() + " interests) for: " + name); listener.handleInterests(results); } else { Library.logger().finer("Filter callback skipped (no interests) for: " + name); } } catch (RuntimeException ex) { Library.logger().warning("failed to deliver interest: " + ex.toString()); } } } public CCNNetworkManager() throws IOException { // Determine port at which to contact agent int port = DEFAULT_AGENT_PORT; String host = DEFAULT_AGENT_HOST; String portval = System.getProperty(PROP_AGENT_PORT); if (null != portval) { try { port = new Integer(portval); } catch (Exception ex) { throw new IOException("Invalid port '" + portval + "' specified in " + PROP_AGENT_PORT); } Library.logger().warning("Non-standard CCN agent port " + port + " per property " + PROP_AGENT_PORT); } String hostval = System.getProperty(PROP_AGENT_HOST); if (null != hostval && hostval.length() > 0) { host = hostval; Library.logger().warning("Non-standard CCN agent host " + host + " per property " + PROP_AGENT_HOST); } Library.logger().info("Contacting CCN agent at " + host + ":" + port); String tapname = System.getProperty(PROP_TAP); if (null == tapname) { tapname = System.getenv(ENV_TAP); } if (null != tapname) { long msecs = new Date().getTime(); long secs = msecs/1000; msecs = msecs % 1000; String unique_tapname = tapname + "-T" + Thread.currentThread().getId() + "-" + secs + "-" + msecs; setTap(unique_tapname); } // Socket is to belong exclusively to run thread started here _channel = DatagramChannel.open(); _channel.connect(new InetSocketAddress(host, port)); _channel.configureBlocking(false); _selector = Selector.open(); _channel.register(_selector, SelectionKey.OP_READ); heartbeat(); // Create callback threadpool and main processing thread _threadpool = Executors.newCachedThreadPool(); _thread = new Thread(this); _thread.start(); // Create timer for heartbeats and other periodic behavior _periodicTimer = new Timer(true); _periodicTimer.scheduleAtFixedRate(new PeriodicWriter(), PERIOD, PERIOD); } /** * * @param putWait - wait for all puts to be output before * shutting down the server. */ public void shutdown() { Library.logger().info("Shutdown requested"); _run = false; if (_periodicTimer != null) _periodicTimer.cancel(); _selector.wakeup(); try { setTap(null); } catch (IOException io) { // Ignore since we're shutting down } } /** * Turn on writing of all packets to a file for test/debug * Overrides any previous setTap or environment/property setting. * Pass null to turn off tap. * @param filename */ public void setTap(String pathname) throws IOException { // Turn off any active tap if (null != _tapStreamOut) { FileOutputStream closingStream = _tapStreamOut; _tapStreamOut = null; closingStream.close(); } if (null != _tapStreamIn) { FileOutputStream closingStream = _tapStreamIn; _tapStreamIn = null; closingStream.close(); } if (pathname != null && pathname.length() > 0) { _tapStreamOut = new FileOutputStream(new File(pathname + "_out")); _tapStreamIn = new FileOutputStream(new File(pathname + "_in")); Library.logger().info("Tap writing to " + pathname); } } public ContentObject put(ContentObject co) throws IOException, InterruptedException { try { write(co); } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } return co; //return CCNRepositoryManager.getRepositoryManager().put(name, signedInfo, signature, content); } public ContentObject get(Interest interest, long timeout) throws IOException, InterruptedException { Library.logger().fine("get: " + interest.name()); InterestRegistration reg = new InterestRegistration(this, interest, null, null); expressInterest(reg); Library.logger().finest("blocking for " + interest.name() + " on " + reg.sema); // Await data to consume the interest if (timeout == CCNBase.NO_TIMEOUT) reg.sema.acquire(); // currently no timeouts else reg.sema.tryAcquire(timeout, TimeUnit.MILLISECONDS); Library.logger().finest("unblocked for " + interest.name() + " on " + reg.sema); // Typically the main processing thread will have registered the interest // which must be undone here, but no harm if never registered unregisterInterest(reg); ArrayList<ContentObject> result = reg.popData(); return result.size() > 0 ? result.get(0) : null; } /** * We express interests to the ccnd and register them within the network manager */ public void expressInterest( Object caller, Interest interest, CCNInterestListener callbackListener) throws IOException { if (null == callbackListener) { throw new NullPointerException("expressInterest: callbackListener cannot be null"); } Library.logger().fine("expressInterest: " + interest.name()); InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); expressInterest(reg); } private void expressInterest(InterestRegistration reg) throws IOException { try { registerInterest(reg); write(reg.interest); } catch (XMLStreamException e) { unregisterInterest(reg); throw new IOException(e.getMessage()); } } /** * Cancel this query with all the repositories we sent * it to. */ public void cancelInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { if (null == callbackListener) { throw new NullPointerException("cancelInterest: callbackListener cannot be null"); } Library.logger().fine("cancelInterest: " + interest.name()); // Remove interest from repeated presentation to the network. unregisterInterest(caller, interest, callbackListener); } /** * Register a standing interest filter with callback to receive any * matching interests seen */ public void setInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) { //Library.logger().fine("setInterestFilter: " + filter); synchronized (_myFilters) { _myFilters.add(filter, new Filter(this, filter, callbackListener, caller)); } } /** * Unregister a standing interest filter */ public void cancelInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) { Library.logger().fine("cancelInterestFilter: " + filter); synchronized (_myFilters) { Entry<Filter> found = _myFilters.remove(filter, new Filter(this, filter, callbackListener, caller)); if (null != found) { found.value().invalidate(); } } } protected void write(ContentObject data) throws XMLStreamException { WirePacket packet = new WirePacket(data); writeInner(packet); Library.logger().finest("Wrote content object: " + data.name()); } protected void write(Interest interest) throws XMLStreamException { WirePacket packet = new WirePacket(interest); writeInner(packet); } private void writeInner(WirePacket packet) throws XMLStreamException { try { byte[] bytes = packet.encode(); ByteBuffer datagram = ByteBuffer.wrap(bytes); synchronized (_channel) { int result = _channel.write(datagram); Library.logger().finest("Wrote datagram (" + datagram.position() + " bytes, result " + result + ")"); if (null != _tapStreamOut) { try { _tapStreamOut.write(bytes); } catch (IOException io) { Library.logger().warning("Unable to write packet to tap stream for debugging"); } } } } catch (IOException io) { // We do not see errors on send typically even if // agent is gone, so log each but do not track Library.logger().warning("Error sending packet: " + io.toString()); } } /** * Pass things on to the network stack. */ InterestRegistration registerInterest(InterestRegistration reg) { // Add to standing interests table Library.logger().finest("registerInterest for " + reg.interest.name() + " and obj is " + _myInterests.hashCode()); synchronized (_myInterests) { _myInterests.add(reg.interest, reg); } return reg; } // purposes we should unregister the InterestRegistration we already have void unregisterInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); unregisterInterest(reg); } /** * @param reg - registration to unregister * * Important Note: This can indirectly need to obtain the lock for "reg" with the lock on * "myInterests" held. Therefore it can't be called when holding the lock for "reg". */ void unregisterInterest(InterestRegistration reg) { synchronized (_myInterests) { Entry<InterestRegistration> found = _myInterests.remove(reg.interest, reg); if (null != found) { found.value().invalidate(); } } } // Thread method: this thread will handle reading datagrams and // the periodic re-expressing of standing interests public void run() { if (! _run) { Library.logger().warning("CCNSimpleNetworkManager run() called after shutdown"); return; } // Allocate datagram buffer: want to wrap array to ensure backed by // array to permit decoding byte[] buffer = new byte[MAX_PAYLOAD]; ByteBuffer datagram = ByteBuffer.wrap(buffer); WirePacket packet = new WirePacket(); Library.logger().info("CCNSimpleNetworkManager processing thread started"); while (_run) { try { try { if (_selector.select(SOCKET_TIMEOUT) != 0) { // Note: we're selecting on only one channel to get // the ability to use wakeup, so there is no need to // inspect the selected-key set datagram.clear(); // make ready for new read synchronized (_channel) { _channel.read(datagram); // queue readers and writers } Library.logger().finest("Read datagram (" + datagram.position() + " bytes)"); _selector.selectedKeys().clear(); if (null != _error) { Library.logger().info("Receive error cleared"); _error = null; } datagram.flip(); // make ready to decode if (null != _tapStreamIn) { byte [] b = new byte[datagram.limit()]; datagram.get(b); _tapStreamIn.write(b); datagram.rewind(); } packet.clear(); packet.decode(datagram); } else { // This was a timeout or wakeup, no data packet.clear(); if (!_run) { // exit immediately if wakeup for shutdown break; } } } catch (IOException io) { // We see IOException on receive every time if agent is gone // so track it to log only start and end of outages if (null == _error) { Library.logger().info("Unable to receive from agent: is it still running?"); } _error = io; packet.clear(); } if (!_run) { // exit immediately if wakeup for shutdown break; } // If we got a data packet, hand it back to all the interested // parties (registered interests and getters). for (ContentObject co : packet.data()) { Library.logger().fine("Data from net: " + co.name()); // SystemConfiguration.logObject("Data from net:", co); deliverData(co); // External data never goes back to network, never held onto here // External data never has a thread waiting, so no need to release sema } for (Interest interest : packet.interests()) { Library.logger().fine("Interest from net: " + interest.name()); InterestRegistration oInterest = new InterestRegistration(this, interest, null, null); deliverInterest(oInterest); // External interests never go back to network } // for interests } catch (Exception ex) { Library.logger().severe("Processing thread failure (UNKNOWN): " + ex.getMessage()); Library.warningStackTrace(ex); } } _threadpool.shutdown(); Library.logger().info("Shutdown complete"); } // Internal delivery of interests to pending filter listeners protected void deliverInterest(InterestRegistration ireg) throws XMLStreamException { // Call any listeners with matching filters synchronized (_myFilters) { for (Filter filter : _myFilters.getValues(ireg.interest.name())) { if (filter.owner != ireg.owner) { Library.logger().finer("Schedule delivery for interest: " + ireg.interest.name()); filter.add(ireg.interest); _threadpool.execute(filter); } } } } // Deliver data to blocked getters and registered interests protected void deliverData(ContentObject co) throws XMLStreamException { synchronized (_myInterests) { for (InterestRegistration ireg : _myInterests.getValues(co)) { if (ireg.add(co)) { // this is a copy of the data _threadpool.execute(ireg); } } } } }
package com.nasageek.utexasutilities; import android.app.Application; import org.acra.*; import org.acra.annotation.*; import org.acra.ReportField; @ReportsCrashes( formKey = "", // This is required for backward compatibility but not used customReportContent = { ReportField.ANDROID_VERSION, ReportField.APP_VERSION_CODE, ReportField.APP_VERSION_NAME, ReportField.BRAND, ReportField.BUILD, ReportField.PACKAGE_NAME, ReportField.INSTALLATION_ID, ReportField.PHONE_MODEL, ReportField.PRODUCT, ReportField.REPORT_ID, ReportField.STACK_TRACE, ReportField.USER_APP_START_DATE, ReportField.USER_CRASH_DATE, ReportField.CUSTOM_DATA}, httpMethod = org.acra.sender.HttpSender.Method.PUT, reportType = org.acra.sender.HttpSender.Type.JSON, formUri = "http://utexasutilities.cloudant.com/acra-utexasutilities/_design/acra-storage/_update/report", formUriBasicAuthLogin = "spereacedidayestallynner", formUriBasicAuthPassword = "UAIwd5vciiGtWOGqsqYMJxnY" //formUriBasicAuthLogin = "releasereporter", //formUriBasicAuthPassword = "raebpcorterpxayszsword" ) public class UTilitiesApplication extends Application { @Override public void onCreate() { super.onCreate(); // The following line triggers the initialization of ACRA ACRA.init(this); } }
package com.redhat.ceylon.compiler.typechecker.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Util { /** * Is the second scope contained by the first scope? */ public static boolean contains(Scope outer, Scope inner) { while (inner!=null) { if (inner.equals(outer)) { return true; } inner = inner.getContainer(); } return false; } /** * Get the class or interface that "this" and "super" * refer to. */ public static ClassOrInterface getContainingClassOrInterface(Scope scope) { while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { return (ClassOrInterface) scope; } scope = scope.getContainer(); } return null; } /** * Get the class or interface that "outer" refers to. */ public static ProducedType getOuterClassOrInterface(Scope scope) { Boolean foundInner = false; while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { if (foundInner) { return ((ClassOrInterface) scope).getType(); } else { foundInner = true; } } scope = scope.getContainer(); } return null; } /** * Convenience method to bind a single type argument * to a toplevel type declaration. */ public static ProducedType producedType(TypeDeclaration declaration, ProducedType typeArgument) { return declaration.getProducedType(null, Collections.singletonList(typeArgument)); } /** * Convenience method to bind a list of type arguments * to a toplevel type declaration. */ public static ProducedType producedType(TypeDeclaration declaration, ProducedType... typeArguments) { return declaration.getProducedType(null, Arrays.asList(typeArguments)); } static boolean isResolvable(Declaration declaration) { return declaration.getName()!=null && !(declaration instanceof Setter) && //return getters, not setters !(declaration instanceof Class && Character.isLowerCase(declaration.getName().charAt(0))); //don't return the type associated with an object dec } static boolean isParameter(Declaration d) { return d instanceof Parameter || d instanceof TypeParameter; } static boolean notOverloaded(Declaration d) { return !(d instanceof Functional) || !((Functional) d).isOverloaded() || ((Functional) d).isAbstraction(); } static boolean hasMatchingSignature(List<ProducedType> signature, Declaration d) { if (d instanceof Class && ((Class) d).isAbstract()) { return false; } if (d instanceof Functional) { Functional f = (Functional) d; if (f.isAbstraction()) { return false; } else { List<ParameterList> pls = f.getParameterLists(); if (pls!=null && !pls.isEmpty()) { List<Parameter> params = pls.get(0).getParameters(); if (signature.size()!=params.size()) { return false; } else { for (int i=0; i<params.size(); i++) { TypeDeclaration paramType = params.get(i).getTypeDeclaration(); TypeDeclaration sigType = signature.get(i).getDeclaration(); if (sigType==null || paramType==null) return false; if (sigType instanceof UnknownType || paramType instanceof UnknownType) return false; if (!erase(sigType).inherits(erase(paramType))) { return false; } } return true; } } } } return signature==null; } static boolean isNamed(String name, Declaration d) { String dname = d.getName(); return dname!=null && dname.equals(name); } private static TypeDeclaration erase(TypeDeclaration paramType) { if (paramType instanceof TypeParameter) { if ( paramType.getSatisfiedTypes().isEmpty() ) { return paramType.getExtendedTypeDeclaration(); } else { return paramType.getSatisfiedTypeDeclarations().get(0); } } else { return paramType; } } static boolean isNameMatching(String startingWith, Declaration d) { return d.getName()!=null && d.getName().toLowerCase().startsWith(startingWith.toLowerCase()); } /** * Collect together type arguments given a list of * type arguments to a declaration and the receiving * type. * * @return a map of type parameter to type argument * * @param declaration a declaration * @param receivingType the receiving produced type * of which the declaration is a member * @param typeArguments explicit or inferred type * arguments of the declaration */ static Map<TypeParameter,ProducedType> arguments(Declaration declaration, ProducedType receivingType, List<ProducedType> typeArguments) { Map<TypeParameter, ProducedType> map = getArgumentsOfOuterType(receivingType); //now turn the type argument tuple into a //map from type parameter to argument if (declaration instanceof Generic) { Generic g = (Generic) declaration; for (int i=0; i<g.getTypeParameters().size(); i++) { if (typeArguments.size()>i) { map.put(g.getTypeParameters().get(i), typeArguments.get(i)); } } } return map; } public static Map<TypeParameter, ProducedType> getArgumentsOfOuterType( ProducedType receivingType) { Map<TypeParameter, ProducedType> map = new HashMap<TypeParameter, ProducedType>(); //make sure we collect all type arguments //from the whole qualified type! ProducedType dt = receivingType; while (dt!=null) { map.putAll(dt.getTypeArguments()); dt = dt.getQualifyingType(); } return map; } static <T> List<T> list(List<T> list, T element) { List<T> result = new ArrayList<T>(); result.addAll(list); result.add(element); return result; } /** * Helper method for eliminating duplicate types from * lists of types that form a union type, taking into * account that a subtype is a "duplicate" of its * supertype. */ public static void addToUnion(List<ProducedType> list, ProducedType pt) { if (pt==null) { return; } ProducedType selfType = pt.getDeclaration().getSelfType(); if (selfType!=null) { pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type } if (pt.getDeclaration() instanceof UnionType) { for (ProducedType t: pt.getDeclaration().getCaseTypes() ) { addToUnion( list, t.substitute(pt.getTypeArguments()) ); } } else { Boolean included = pt.isWellDefined(); if (included) { for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) { ProducedType t = iter.next(); if (pt.isSubtypeOf(t)) { included = false; break; } //TODO: I think in some very rare occasions // this can cause stack overflows! else if (pt.isSupertypeOf(t)) { iter.remove(); } } } if (included) { list.add(pt); } } } /** * Helper method for eliminating duplicate types from * lists of types that form an intersection type, taking * into account that a supertype is a "duplicate" of its * subtype. */ public static void addToIntersection(List<ProducedType> list, ProducedType pt, Unit unit) { if (pt==null) { return; } ProducedType selfType = pt.getDeclaration().getSelfType(); if (selfType!=null) { pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type } if (pt.getDeclaration() instanceof IntersectionType) { for (ProducedType t: pt.getDeclaration().getSatisfiedTypes() ) { addToIntersection(list, t.substitute(pt.getTypeArguments()), unit); } } else { //implement the rule that Foo&Bar==Bottom if //there exists some Baz of Foo | Bar //i.e. the intersection of disjoint types is //empty for (ProducedType supertype: pt.getSupertypes()) { List<TypeDeclaration> ctds = supertype.getDeclaration().getCaseTypeDeclarations(); if (ctds!=null) { TypeDeclaration ctd=null; for (TypeDeclaration ct: ctds) { if (pt.getSupertype(ct)!=null) { ctd = ct; break; } } if (ctd!=null) { for (TypeDeclaration ct: ctds) { if (ct!=ctd) { for (ProducedType t: list) { if (t.getSupertype(ct)!=null) { list.clear(); list.add( new BottomType(unit).getType() ); return; } } } } } } } Boolean included = pt.isWellDefined(); if (included) { for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) { ProducedType t = iter.next(); if (pt.isSupertypeOf(t)) { included = false; break; } //TODO: I think in some very rare occasions // this can cause stack overflows! else if (pt.isSubtypeOf(t)) { iter.remove(); } else if ( pt.getDeclaration().equals(t.getDeclaration()) ) { //canonicalize T<InX,OutX>&T<InY,OutY> to T<InX|InY,OutX&OutY> TypeDeclaration td = pt.getDeclaration(); List<ProducedType> args = new ArrayList<ProducedType>(); for (int i=0; i<td.getTypeParameters().size(); i++) { TypeParameter tp = td.getTypeParameters().get(i); ProducedType pta = pt.getTypeArguments().get(tp); ProducedType ta = t.getTypeArguments().get(tp); if (tp.isContravariant()) { args.add(unionType(pta, ta, unit)); } else if (tp.isCovariant()) { args.add(intersectionType(pta, ta, unit)); } else { TypeDeclaration ptad = pta.getDeclaration(); TypeDeclaration tad = ta.getDeclaration(); if ( !(ptad instanceof TypeParameter) && !(tad instanceof TypeParameter) && !ptad.equals(tad) ) { //if the two type arguments have provably //different types, then the meet of the //two intersected invariant types is empty //TODO: this is too weak, we should really // recursively search for type parameter // arguments and if we don't find any // we can reduce to Bottom list.clear(); args.add( new BottomType(unit).getType() ); return; } else { //TODO: this is not correct: the intersection // of two different instantiations of an // invariant type is actually Bottom // unless the type arguments are equivalent // or are type parameters that might // represent equivalent types at runtime. // Therefore, a method T x(T y) of Inv<T> // should have the signature: // Foo&Bar x(Foo|Bar y) // on the intersection Inv<Foo>&Inv<Bar>. // But this code gives it the more // restrictive signature: // Foo&Bar x(Foo&Bar y) args.add(intersectionType(pta, ta, unit)); } } } iter.remove(); //TODO: broken handling of member types! list.add( td.getProducedType(pt.getQualifyingType(), args) ); return; } else { //Unit unit = pt.getDeclaration().getUnit(); TypeDeclaration nd = unit.getNothingDeclaration(); if (pt.getDeclaration() instanceof Class && t.getDeclaration() instanceof Class || pt.getDeclaration() instanceof Interface && t.getDeclaration().equals(nd) || //t.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing") || t.getDeclaration() instanceof Interface && pt.getDeclaration().equals(nd)) { //pt.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing")) { //the meet of two classes unrelated by inheritance, or //of Nothing with an interface type is empty list.clear(); list.add( unit.getBottomDeclaration().getType() ); return; } } } } if (included) { list.add(pt); } } } public static String formatPath(List<String> path) { StringBuilder sb = new StringBuilder(); for (int i=0; i<path.size(); i++) { sb.append(path.get(i)); if (i<path.size()-1) sb.append('.'); } return sb.toString(); } static boolean addToSupertypes(List<ProducedType> list, ProducedType st) { for (ProducedType et: list) { if (st.getDeclaration().equals(et.getDeclaration()) && //return both a type and its self type st.isExactly(et)) { return false; } } list.add(st); return true; } public static ProducedType unionType(ProducedType lhst, ProducedType rhst, Unit unit) { List<ProducedType> list = new ArrayList<ProducedType>(); addToUnion(list, rhst); addToUnion(list, lhst); UnionType ut = new UnionType(unit); ut.setCaseTypes(list); return ut.getType(); } public static ProducedType intersectionType(ProducedType lhst, ProducedType rhst, Unit unit) { List<ProducedType> list = new ArrayList<ProducedType>(); addToIntersection(list, rhst, unit); addToIntersection(list, lhst, unit); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.canonicalize().getType(); } public static boolean isElementOfUnion(UnionType ut, TypeDeclaration td) { for (TypeDeclaration ct: ut.getCaseTypeDeclarations()) { if (ct.equals(td)) return true; } return false; } public static boolean isElementOfIntersection(IntersectionType ut, TypeDeclaration td) { for (TypeDeclaration ct: ut.getSatisfiedTypeDeclarations()) { if (ct.equals(td)) return true; } return false; } static Declaration lookupMember(List<Declaration> members, String name, List<ProducedType> signature, boolean includeParameters) { List<Declaration> results = new ArrayList<Declaration>(); Declaration inexactMatch = null; for (Declaration d: members) { if (isResolvable(d) && isNamed(name, d) && (includeParameters || !isParameter(d))) { if (signature==null) { //no argument types: either a type //declaration, an attribute, or a method //reference - don't return overloaded //forms of the declaration (instead //return the "abstraction" of them) if (notOverloaded(d)) { //by returning the first thing we //find, we implement the rule that //parameters hide attributes with //the same name in the body of a //class (a bit of a hack solution) return d; } } else { if (notOverloaded(d)) { //we have found either a non-overloaded //declaration, or the "abstraction" //which of all the overloaded forms //of the declaration inexactMatch = d; } if (hasMatchingSignature(signature, d)) { //we have found an exactly matching //overloaded declaration results.add(d); } } } } switch (results.size()) { case 0: //no exact match, so return the non-overloaded //declaration or the "abstraction" of the //overloaded declaration return inexactMatch; case 1: //exactly one exact match, so return it return results.get(0); default: //more than one matching overloaded declaration, //so return the "abstraction" of the overloaded //declaration return inexactMatch; } } }
package com.redhat.ceylon.compiler.typechecker.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Util { /** * Is the second scope contained by the first scope? */ public static boolean contains(Scope outer, Scope inner) { while (inner!=null) { if (inner.equals(outer)) { return true; } inner = inner.getContainer(); } return false; } /** * Get the class or interface that "this" and "super" * refer to. */ public static ClassOrInterface getContainingClassOrInterface(Scope scope) { while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { return (ClassOrInterface) scope; } scope = scope.getContainer(); } return null; } /** * Get the class or interface that "outer" refers to. */ public static ProducedType getOuterClassOrInterface(Scope scope) { Boolean foundInner = false; while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { if (foundInner) { return ((ClassOrInterface) scope).getType(); } else { foundInner = true; } } scope = scope.getContainer(); } return null; } /** * Convenience method to bind a single type argument * to a toplevel type declaration. */ public static ProducedType producedType(TypeDeclaration declaration, ProducedType typeArgument) { return declaration.getProducedType(null, Collections.singletonList(typeArgument)); } /** * Convenience method to bind a list of type arguments * to a toplevel type declaration. */ public static ProducedType producedType(TypeDeclaration declaration, ProducedType... typeArguments) { return declaration.getProducedType(null, Arrays.asList(typeArguments)); } static boolean isResolvable(Declaration declaration) { return declaration.getName()!=null && !(declaration instanceof Setter) && //return getters, not setters !(declaration instanceof Class && Character.isLowerCase(declaration.getName().charAt(0))); //don't return the type associated with an object dec } static boolean isParameter(Declaration d) { return d instanceof Parameter || d instanceof TypeParameter; } static boolean notOverloaded(Declaration d) { return !(d instanceof Functional) || !((Functional) d).isOverloaded() || ((Functional) d).isAbstraction(); } static boolean hasMatchingSignature(List<ProducedType> signature, Declaration d) { if (d instanceof Class && ((Class) d).isAbstract()) { return false; } if (d instanceof Functional) { Functional f = (Functional) d; if (f.isAbstraction()) { return false; } else { List<ParameterList> pls = f.getParameterLists(); if (pls!=null && !pls.isEmpty()) { List<Parameter> params = pls.get(0).getParameters(); if (signature.size()!=params.size()) { return false; } else { for (int i=0; i<params.size(); i++) { //ignore optionality for resolving overloads, since //all all Java method params are treated as optional TypeDeclaration paramType = definiteTypeDec(d.getUnit(), params.get(i).getType()); TypeDeclaration sigType = definiteTypeDec(d.getUnit(), signature.get(i)); if (sigType==null || paramType==null) return false; if (sigType instanceof UnknownType || paramType instanceof UnknownType) return false; if (!erase(sigType).inherits(erase(paramType))) { return false; } } return true; } } else { return false; } } } else { return false; } } static boolean betterMatch(Declaration d, Declaration r) { if (d instanceof Functional && r instanceof Functional) { List<ParameterList> dpls = ((Functional) d).getParameterLists(); List<ParameterList> rpls = ((Functional) r).getParameterLists(); if (dpls!=null&&!dpls.isEmpty() && rpls!=null&&!rpls.isEmpty()) { List<Parameter> dpl = dpls.get(0).getParameters(); List<Parameter> rpl = rpls.get(0).getParameters(); if (dpl.size()==rpl.size()) { for (int i=0; i<dpl.size(); i++) { TypeDeclaration paramType = definiteTypeDec(d.getUnit(), dpl.get(i).getType()); TypeDeclaration otherType = definiteTypeDec(d.getUnit(), rpl.get(i).getType()); if (otherType==null || paramType==null) return false; if (otherType instanceof UnknownType || paramType instanceof UnknownType) return false; if (!erase(paramType).inherits(erase(otherType))) { return false; } } return true; } } } return false; } private static TypeDeclaration definiteTypeDec(Unit unit, ProducedType pt) { return unit.getDefiniteType(pt).getDeclaration(); } static boolean isNamed(String name, Declaration d) { String dname = d.getName(); return dname!=null && dname.equals(name); } private static TypeDeclaration erase(TypeDeclaration paramType) { if (paramType instanceof TypeParameter) { if ( paramType.getSatisfiedTypes().isEmpty() ) { return paramType.getExtendedTypeDeclaration(); } else { //TODO: is this actually correct? What is Java's // rule here? return paramType.getSatisfiedTypeDeclarations().get(0); } } else if (paramType instanceof UnionType || paramType instanceof IntersectionType) { //TODO: this is pretty sucky, cos in theory a // union or intersection might be assignable // to the parameter type with a typecast return paramType.getUnit().getObjectDeclaration(); } else { return paramType; } } static boolean isNameMatching(String startingWith, Declaration d) { return d.getName()!=null && d.getName().toLowerCase().startsWith(startingWith.toLowerCase()); } /** * Collect together type arguments given a list of * type arguments to a declaration and the receiving * type. * * @return a map of type parameter to type argument * * @param declaration a declaration * @param receivingType the receiving produced type * of which the declaration is a member * @param typeArguments explicit or inferred type * arguments of the declaration */ static Map<TypeParameter,ProducedType> arguments(Declaration declaration, ProducedType receivingType, List<ProducedType> typeArguments) { Map<TypeParameter, ProducedType> map = getArgumentsOfOuterType(receivingType); //now turn the type argument tuple into a //map from type parameter to argument if (declaration instanceof Generic) { Generic g = (Generic) declaration; for (int i=0; i<g.getTypeParameters().size(); i++) { if (typeArguments.size()>i) { map.put(g.getTypeParameters().get(i), typeArguments.get(i)); } } } return map; } public static Map<TypeParameter, ProducedType> getArgumentsOfOuterType( ProducedType receivingType) { Map<TypeParameter, ProducedType> map = new HashMap<TypeParameter, ProducedType>(); //make sure we collect all type arguments //from the whole qualified type! ProducedType dt = receivingType; while (dt!=null) { map.putAll(dt.getTypeArguments()); dt = dt.getQualifyingType(); } return map; } static <T> List<T> list(List<T> list, T element) { List<T> result = new ArrayList<T>(); result.addAll(list); result.add(element); return result; } /** * Helper method for eliminating duplicate types from * lists of types that form a union type, taking into * account that a subtype is a "duplicate" of its * supertype. */ public static void addToUnion(List<ProducedType> list, ProducedType pt) { if (pt==null) { return; } ProducedType selfType = pt.getDeclaration().getSelfType(); if (selfType!=null) { pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type } if (pt.getDeclaration() instanceof UnionType) { for (ProducedType t: pt.getDeclaration().getCaseTypes() ) { addToUnion( list, t.substitute(pt.getTypeArguments()) ); } } else { Boolean included = pt.isWellDefined(); if (included) { for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) { ProducedType t = iter.next(); if (pt.isSubtypeOf(t)) { included = false; break; } //TODO: I think in some very rare occasions // this can cause stack overflows! else if (pt.isSupertypeOf(t)) { iter.remove(); } } } if (included) { list.add(pt); } } } /** * Helper method for eliminating duplicate types from * lists of types that form an intersection type, taking * into account that a supertype is a "duplicate" of its * subtype. */ public static void addToIntersection(List<ProducedType> list, ProducedType pt, Unit unit) { if (pt==null) { return; } ProducedType selfType = pt.getDeclaration().getSelfType(); if (selfType!=null) { pt = selfType.substitute(pt.getTypeArguments()); //canonicalize type with self type to the self type } if (pt.getDeclaration() instanceof IntersectionType) { for (ProducedType t: pt.getDeclaration().getSatisfiedTypes() ) { addToIntersection(list, t.substitute(pt.getTypeArguments()), unit); } } else { //implement the rule that Foo&Bar==Bottom if //there exists some Baz of Foo | Bar //i.e. the intersection of disjoint types is //empty for (ProducedType supertype: pt.getSupertypes()) { List<TypeDeclaration> ctds = supertype.getDeclaration().getCaseTypeDeclarations(); if (ctds!=null) { TypeDeclaration ctd=null; for (TypeDeclaration ct: ctds) { if (pt.getSupertype(ct)!=null) { ctd = ct; break; } } if (ctd!=null) { for (TypeDeclaration ct: ctds) { if (ct!=ctd) { for (ProducedType t: list) { if (t.getSupertype(ct)!=null) { list.clear(); list.add( new BottomType(unit).getType() ); return; } } } } } } } Boolean included = pt.isWellDefined(); if (included) { for (Iterator<ProducedType> iter = list.iterator(); iter.hasNext();) { ProducedType t = iter.next(); if (pt.isSupertypeOf(t)) { included = false; break; } //TODO: I think in some very rare occasions // this can cause stack overflows! else if (pt.isSubtypeOf(t)) { iter.remove(); } else if ( pt.getDeclaration().equals(t.getDeclaration()) ) { //canonicalize T<InX,OutX>&T<InY,OutY> to T<InX|InY,OutX&OutY> TypeDeclaration td = pt.getDeclaration(); List<ProducedType> args = new ArrayList<ProducedType>(); for (int i=0; i<td.getTypeParameters().size(); i++) { TypeParameter tp = td.getTypeParameters().get(i); ProducedType pta = pt.getTypeArguments().get(tp); ProducedType ta = t.getTypeArguments().get(tp); if (tp.isContravariant()) { args.add(unionType(pta, ta, unit)); } else if (tp.isCovariant()) { args.add(intersectionType(pta, ta, unit)); } else { TypeDeclaration ptad = pta.getDeclaration(); TypeDeclaration tad = ta.getDeclaration(); if ( !(ptad instanceof TypeParameter) && !(tad instanceof TypeParameter) && !ptad.equals(tad) ) { //if the two type arguments have provably //different types, then the meet of the //two intersected invariant types is empty //TODO: this is too weak, we should really // recursively search for type parameter // arguments and if we don't find any // we can reduce to Bottom list.clear(); args.add( new BottomType(unit).getType() ); return; } else { //TODO: this is not correct: the intersection // of two different instantiations of an // invariant type is actually Bottom // unless the type arguments are equivalent // or are type parameters that might // represent equivalent types at runtime. // Therefore, a method T x(T y) of Inv<T> // should have the signature: // Foo&Bar x(Foo|Bar y) // on the intersection Inv<Foo>&Inv<Bar>. // But this code gives it the more // restrictive signature: // Foo&Bar x(Foo&Bar y) args.add(intersectionType(pta, ta, unit)); } } } iter.remove(); //TODO: broken handling of member types! list.add( td.getProducedType(pt.getQualifyingType(), args) ); return; } else { //Unit unit = pt.getDeclaration().getUnit(); TypeDeclaration nd = unit.getNothingDeclaration(); if (pt.getDeclaration() instanceof Class && t.getDeclaration() instanceof Class || pt.getDeclaration() instanceof Interface && t.getDeclaration().equals(nd) || //t.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing") || t.getDeclaration() instanceof Interface && pt.getDeclaration().equals(nd)) { //pt.getDeclaration().getQualifiedNameString().equals("ceylon.language.Nothing")) { //the meet of two classes unrelated by inheritance, or //of Nothing with an interface type is empty list.clear(); list.add( unit.getBottomDeclaration().getType() ); return; } } } } if (included) { list.add(pt); } } } public static String formatPath(List<String> path) { StringBuilder sb = new StringBuilder(); for (int i=0; i<path.size(); i++) { sb.append(path.get(i)); if (i<path.size()-1) sb.append('.'); } return sb.toString(); } static boolean addToSupertypes(List<ProducedType> list, ProducedType st) { for (ProducedType et: list) { if (st.getDeclaration().equals(et.getDeclaration()) && //return both a type and its self type st.isExactly(et)) { return false; } } list.add(st); return true; } public static ProducedType unionType(ProducedType lhst, ProducedType rhst, Unit unit) { List<ProducedType> list = new ArrayList<ProducedType>(); addToUnion(list, rhst); addToUnion(list, lhst); UnionType ut = new UnionType(unit); ut.setCaseTypes(list); return ut.getType(); } public static ProducedType intersectionType(ProducedType lhst, ProducedType rhst, Unit unit) { List<ProducedType> list = new ArrayList<ProducedType>(); addToIntersection(list, rhst, unit); addToIntersection(list, lhst, unit); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.canonicalize().getType(); } public static boolean isElementOfUnion(UnionType ut, TypeDeclaration td) { for (TypeDeclaration ct: ut.getCaseTypeDeclarations()) { if (ct.equals(td)) return true; } return false; } public static boolean isElementOfIntersection(IntersectionType ut, TypeDeclaration td) { for (TypeDeclaration ct: ut.getSatisfiedTypeDeclarations()) { if (ct.equals(td)) return true; } return false; } public static Declaration lookupMember(List<Declaration> members, String name, List<ProducedType> signature, boolean includeParameters) { List<Declaration> results = new ArrayList<Declaration>(); Declaration inexactMatch = null; for (Declaration d: members) { if (isResolvable(d) && isNamed(name, d) && (includeParameters || !isParameter(d))) { if (signature==null) { //no argument types: either a type //declaration, an attribute, or a method //reference - don't return overloaded //forms of the declaration (instead //return the "abstraction" of them) if (notOverloaded(d)) { //by returning the first thing we //find, we implement the rule that //parameters hide attributes with //the same name in the body of a //class (a bit of a hack solution) return d; } } else { if (notOverloaded(d)) { //we have found either a non-overloaded //declaration, or the "abstraction" //which of all the overloaded forms //of the declaration inexactMatch = d; } if (hasMatchingSignature(signature, d)) { //we have found an exactly matching //overloaded declaration for (Iterator<Declaration> i = results.iterator(); i.hasNext();) { if (betterMatch(d,i.next())) { i.remove(); } } results.add(d); } } } } switch (results.size()) { case 0: //no exact match, so return the non-overloaded //declaration or the "abstraction" of the //overloaded declaration return inexactMatch; case 1: //exactly one exact match, so return it return results.get(0); default: //more than one matching overloaded declaration, //so return the "abstraction" of the overloaded //declaration return inexactMatch; } } }
package com.tom_e_white.chickenalerts; import java.util.Calendar; import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator; import com.luckycatlabs.sunrisesunset.dto.Location; public class AlertTimeCalculator { private Location location = new Location("51.868383", "-3.151789"); // Crickhowell private int offsetInMinutes = 30; public Calendar calculateNextAlert(Calendar cal) { SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, cal.getTimeZone()); Calendar alertTime = calculator.getOfficialSunsetCalendarForDate(cal); alertTime.add(Calendar.MINUTE, offsetInMinutes); if (alertTime.before(cal)) { Calendar calCopy = Calendar.getInstance(cal.getTimeZone()); calCopy.setTime(cal.getTime()); calCopy.add(Calendar.DATE, 1); alertTime = calculator.getOfficialSunsetCalendarForDate(calCopy); alertTime.add(Calendar.MINUTE, offsetInMinutes); } return alertTime; } }
package com.wavify.jmeter.protocol.amf.sampler; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.net.ssl.SSLContext; import org.apache.jmeter.protocol.http.control.Cookie; import org.apache.jmeter.protocol.http.control.CookieManager; import org.apache.jmeter.samplers.AbstractSampler; import org.apache.jmeter.samplers.Entry; import org.apache.jmeter.samplers.Interruptible; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.AbstractProperty; import org.apache.jmeter.testelement.property.CollectionProperty; import org.apache.jmeter.testelement.property.FloatProperty; import org.apache.jmeter.testelement.property.IntegerProperty; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.NullProperty; import org.apache.jmeter.testelement.property.ObjectProperty; import org.apache.jmeter.testelement.property.PropertyIterator; import org.apache.jmeter.testelement.property.StringProperty; import org.apache.jmeter.util.JsseSSLManager; import org.apache.jmeter.util.SSLManager; import flex.messaging.io.amf.client.AMFConnection; import flex.messaging.io.amf.client.exceptions.ClientStatusException; import flex.messaging.io.amf.client.exceptions.ServerStatusException; import flex.messaging.messages.AcknowledgeMessage; import flex.messaging.messages.CommandMessage; import flex.messaging.messages.RemotingMessage; public class AMFSampler extends AbstractSampler implements Interruptible { private static final long serialVersionUID = 1L; public static final String COOKIE_MANAGER = "HTTPSampler.cookie_manager"; public static final String ADDRESS_PROP = "amf_address"; public static final String SERVICE_PROP = "amf_service"; public static final String METHOD_PROP = "amf_method"; public static final String ARGUMENT_PROP = "amf_argument"; private AMFConnection connection; public void setAddress(String address) { setProperty(ADDRESS_PROP, address); } public void setService(String service) { setProperty(SERVICE_PROP, service); } public void setMethod(String method) { setProperty(METHOD_PROP, method); } private CollectionProperty convertCollectionArgument(Collection<?> collection) { CollectionProperty properties = new CollectionProperty(); properties.setName("COLLECTION"); for (Object object : collection) { if (object == null) { properties.addProperty(new NullProperty()); } else if (object instanceof Integer) { properties.addProperty(new IntegerProperty("INT", (Integer) object)); } else if (object instanceof Float) { properties.addProperty(new FloatProperty("FLOAT", (Float) object)); } else if (object instanceof String) { properties.addProperty(new StringProperty("STRING", (String) object)); } else if (object instanceof Collection) { properties.addProperty(this .convertCollectionArgument((Collection<?>) object)); } else { properties.addProperty(new ObjectProperty("Object", object)); } } return properties; } public void setArguments(List<?> arguments) { CollectionProperty property = convertCollectionArgument(arguments); property.setName(ARGUMENT_PROP); setProperty(property); } public void setCookieManager(CookieManager cookieManager) { setProperty(new ObjectProperty(COOKIE_MANAGER, cookieManager)); } public String getAddress() { return getPropertyAsString(ADDRESS_PROP); } public String getService() { return getPropertyAsString(SERVICE_PROP); } public String getMethod() { return getPropertyAsString(METHOD_PROP); } public List<Object> getArguments() { JMeterProperty prop = getProperty(ARGUMENT_PROP); ArrayList<Object> arguments = new ArrayList<Object>(); if (prop instanceof CollectionProperty) { CollectionProperty collection = (CollectionProperty) prop; PropertyIterator iterator = collection.iterator(); while (iterator.hasNext()) { JMeterProperty property = iterator.next(); if (property instanceof NullProperty) { arguments.add(null); } else if (property instanceof IntegerProperty) { arguments.add(property.getIntValue()); } else if (property instanceof FloatProperty) { arguments.add(property.getFloatValue()); } else if (property instanceof StringProperty) { arguments.add(property.getStringValue()); } else if (property instanceof CollectionProperty) { arguments.add(convertCollectionValue((CollectionProperty) property)); } else { arguments.add(property.getObjectValue()); } } } return arguments; } private Collection<?> convertCollectionValue(CollectionProperty collection) { Collection<?> values = (Collection<?>) collection.getObjectValue(); Collection<Object> items = new ArrayList<Object>(); Iterator<?> iterator = values.iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (obj instanceof JMeterProperty) { AbstractProperty property = (AbstractProperty) obj; if (property instanceof NullProperty) { items.add(null); } else if (property instanceof StringProperty) { items.add(property.getStringValue()); } else if (property instanceof ObjectProperty) { items.add(property.getObjectValue()); } else if (property instanceof IntegerProperty) { items.add(property.getIntValue()); } else if (property instanceof FloatProperty) { items.add(property.getFloatValue()); } } } return items; } public CookieManager getCookieManager() { return (CookieManager) getProperty(COOKIE_MANAGER).getObjectValue(); } public void addTestElement(TestElement el) { if (el instanceof CookieManager) { setCookieManager((CookieManager) el); } else { super.addTestElement(el); } } @Override public SampleResult sample(Entry e) { SampleResult result = process(); result.setSampleLabel(getName()); return result; } Object ping(AMFConnection connection) throws ClientStatusException, ServerStatusException { CommandMessage ping = new CommandMessage(); ping.setOperation(CommandMessage.CLIENT_PING_OPERATION); HashMap<String, Object> headers = new HashMap<String, Object>(); headers.put("DSMessagingVersion", 1); headers.put("DSId", null); ping.setHeaders(headers); ping.setMessageId(UUID.randomUUID().toString().toUpperCase()); return connection.call(null, ping); } Object call(AMFConnection connection, String destination, String method, Object... arguments) throws ClientStatusException, ServerStatusException { RemotingMessage message = new RemotingMessage(); message.setDestination(destination); message.setOperation(method); HashMap<String, Object> headers = new HashMap<String, Object>(); headers.put("DSId", null); headers.put("DSEndpoint", "globalamf"); message.setHeaders(headers); message.setMessageId(UUID.randomUUID().toString().toUpperCase()); message.setClientId("42EA657F-7A69-4623-9A9D-F5BFBD904E24"); message.setBody(arguments); return connection.call(null, new Object[] { message }); } AMFSamplerResult process() { AMFSamplerResult result = new AMFSamplerResult(); String address = getAddress(); String service = getService(); String method = getMethod(); result.setContentType(service + ": " + method); if (connection != null) { connection.close(); connection = null; } if (address.startsWith("https")) { connection = new AMFSConnection(); } else { connection = new AMFConnection(); } // Set cookie to connection CookieManager cookieManager = getCookieManager(); if (cookieManager != null) { CollectionProperty properties = cookieManager.getCookies(); PropertyIterator iterator = properties.iterator(); StringBuffer buffer = new StringBuffer(); while (iterator.hasNext()) { JMeterProperty property = iterator.next(); Cookie cookie = (Cookie) property.getObjectValue(); buffer.append(String.format("%s=%s", cookie.getName(), cookie.getValue())); } connection.addHttpRequestHeader(AMFConnection.COOKIE, buffer.toString()); } if (address.startsWith("https")) { JsseSSLManager sslManager = (JsseSSLManager) SSLManager.getInstance(); try { SSLContext context = sslManager.getContext(); AMFSConnection sslConnection = (AMFSConnection) connection; sslConnection.setSSLFactory(context.getSocketFactory()); } catch (GeneralSecurityException e) { } } try { connection.connect(address); ping(connection); List<Object> arguments = getArguments(); AcknowledgeMessage message = (AcknowledgeMessage) call(connection, service, method, arguments.toArray()); result.setResult(message.getBody()); result.setMessageID(message.getMessageId()); result.setResponseHeaders(message.getHeaders().toString()); result.setResponseData(message.toString().getBytes()); result.setResponseMessage(message.toString()); result.setSuccessful(true); } catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); if (e instanceof ServerStatusException) { result.setErrorMsg(((ServerStatusException) e).getData().toString()); } else { result.setErrorMsg(e.getMessage()); } result.setResult(result.getErrorMsg()); result.setResponseMessage(result.getErrorMsg()); result.setSuccessful(false); } return result; } @Override public boolean interrupt() { AMFConnection conn = connection; if (conn != null) { connection = null; conn.close(); } return conn != null; } }
package nl.xservices.plugins; import android.content.pm.FeatureInfo; import android.content.pm.PackageManager; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.os.Build; import android.util.Log; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; public class Flashlight extends CordovaPlugin { private static final String ACTION_AVAILABLE = "available"; private static final String ACTION_SWITCH_ON = "switchOn"; private static final String ACTION_SWITCH_OFF = "switchOff"; private static Boolean capable; private boolean releasing; private Camera mCamera; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d("Flashlight", "Plugin Called: " + action); try { if (action.equals(ACTION_SWITCH_ON)) { // When switching on immediately after checking for isAvailable, // the release method may still be running, so wait a bit. while (releasing) { Thread.sleep(10); } mCamera = Camera.open(); if (Build.VERSION.SDK_INT >= 11) { // honeycomb // required for (at least) the Nexus 5 mCamera.setPreviewTexture(new SurfaceTexture(0)); } toggleTorch(true, callbackContext); return true; } else if (action.equals(ACTION_SWITCH_OFF)) { toggleTorch(false, callbackContext); releaseCamera(); return true; } else if (action.equals(ACTION_AVAILABLE)) { if (capable == null) { mCamera = Camera.open(); capable = isCapable(); releaseCamera(); } callbackContext.success(capable ? 1 : 0); return true; } else { callbackContext.error("flashlight." + action + " is not a supported function."); return false; } } catch (Exception e) { callbackContext.error(e.getMessage()); return false; } } private boolean isCapable() { final PackageManager packageManager = this.cordova.getActivity().getPackageManager(); for (final FeatureInfo feature : packageManager.getSystemAvailableFeatures()) { if (PackageManager.FEATURE_CAMERA_FLASH.equalsIgnoreCase(feature.name)) { return true; } } return false; } private void toggleTorch(boolean switchOn, CallbackContext callbackContext) { final Camera.Parameters mParameters = mCamera.getParameters(); if (isCapable()) { mParameters.setFlashMode(switchOn ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF); mCamera.setParameters(mParameters); mCamera.startPreview(); callbackContext.success(); } else { callbackContext.error("Device is not capable of using the flashlight. Please test with flashlight.available()"); } } private void releaseCamera() { releasing = true; // we need to release the camera, so other apps can use it new Thread(new Runnable() { public void run() { if (mCamera != null) { mCamera.setPreviewCallback(null); mCamera.stopPreview(); mCamera.release(); } releasing = false; } }).start(); } }
package de.lmu.ifi.dbs.preprocessing; import de.lmu.ifi.dbs.data.RealVector; import de.lmu.ifi.dbs.database.AssociationID; import de.lmu.ifi.dbs.database.Database; import de.lmu.ifi.dbs.distance.Distance; import de.lmu.ifi.dbs.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.utilities.QueryResult; import de.lmu.ifi.dbs.utilities.output.Format; import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.utilities.optionhandling.DoubleParameter; import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.utilities.optionhandling.constraints.GreaterEqualConstraint; import de.lmu.ifi.dbs.utilities.optionhandling.constraints.LessEqualConstraint; import de.lmu.ifi.dbs.utilities.optionhandling.constraints.ParameterConstraint; import java.util.ArrayList; import java.util.List; /** * Preprocessor for PreDeCon local dimensionality and locally weighted matrix * assignment to objects of a certain database. * * @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public class PreDeConPreprocessor<D extends Distance<D>> extends ProjectedDBSCANPreprocessor<D> { /** * The default value for delta. */ public static final double DEFAULT_DELTA = 0.01; /** * Option string for parameter delta. */ public static final String DELTA_P = "delta"; /** * Description for parameter delta. */ public static final String DELTA_D = "a double between 0 and 1 specifying the threshold for small Eigenvalues (default is delta = " + DEFAULT_DELTA + ")."; /** * The threshold for small eigenvalues. */ protected double delta; /** * The kappa value for generating the variance vector. */ private final int kappa = 50; /** * Provides a new Preprocessor that computes the clocal dimensionality and locally weighted matrix * of objects of a certain database. */ public PreDeConPreprocessor() { super(); // this.debug = true; ArrayList<ParameterConstraint<Number>> deltaCons = new ArrayList<ParameterConstraint<Number>>(); deltaCons.add(new GreaterEqualConstraint(0)); deltaCons.add(new LessEqualConstraint(1)); DoubleParameter delta = new DoubleParameter(DELTA_P, DELTA_D, deltaCons); delta.setDefaultValue(DEFAULT_DELTA); optionHandler.put(DELTA_P, delta); } /** * This method implements the type of variance analysis to be computed for a given point. * <p/> * Example1: for 4C, this method should implement a PCA for the given point. * Example2: for PreDeCon, this method should implement a simple axis-parallel variance analysis. * * @param id the given point * @param neighbors the neighbors as query results of the given point * @param database the database for which the preprocessing is performed */ protected void runVarianceAnalysis(Integer id, List<QueryResult<D>> neighbors, Database<RealVector> database) { StringBuffer msg = new StringBuffer(); int referenceSetSize = neighbors.size(); RealVector obj = database.get(id); if (debug) { msg.append("\n\nreferenceSetSize = " + referenceSetSize); msg.append("\ndelta = " + delta); } if (referenceSetSize == 0) { throw new RuntimeException("Reference Set Size = 0. This should never happen!"); } // prepare similarity matrix int dim = obj.getDimensionality(); Matrix simMatrix = new Matrix(dim, dim, 0); for (int i = 0; i < dim; i++) { simMatrix.set(i, i, 1); } // prepare projected dimensionality int projDim = 0; // start variance analyis double[] sum = new double[dim]; for (QueryResult<D> neighbor : neighbors) { RealVector o = database.get(neighbor.getID()); for (int d = 0; d < dim; d++) { sum[d] = + Math.pow(obj.getValue(d + 1).doubleValue() - o.getValue(d + 1).doubleValue(), 2.0); } } for (int d = 0; d < dim; d++) { if (Math.sqrt(sum[d]) / referenceSetSize <= delta) { if (debug) { msg.append("\nsum[" + d + "]= " + sum[d]); msg.append("\n Math.sqrt(sum[d]) / referenceSetSize)= " + Math.sqrt(sum[d]) / referenceSetSize); } // projDim++; simMatrix.set(d, d, kappa); } else { // bug in paper? projDim++; } } if (projDim == 0) { if (debug) { // msg.append("\nprojDim == 0!"); } projDim = dim; } if (debug) { msg.append("\nprojDim " + database.getAssociation(AssociationID.LABEL, id) + ": " + projDim); msg.append("\nsimMatrix " + database.getAssociation(AssociationID.LABEL, id) + ": " + simMatrix.toString(Format.NF4)); debugFine(msg.toString()); } // set the associations database.associate(AssociationID.LOCAL_DIMENSIONALITY, id, projDim); database.associate(AssociationID.LOCALLY_WEIGHTED_MATRIX, id, simMatrix); } /** * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[]) */ public String[] setParameters(String[] args) throws ParameterException { String[] remainingParameters = super.setParameters(args); delta = (Double) optionHandler.getOptionValue(DELTA_P); return remainingParameters; } /** * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#getAttributeSettings() */ public List<AttributeSettings> getAttributeSettings() { List<AttributeSettings> attributeSettings = super.getAttributeSettings(); AttributeSettings mySettings = attributeSettings.get(0); mySettings.addSetting(DELTA_P, Double.toString(delta)); return attributeSettings; } /** * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#description() */ public String description() { StringBuffer description = new StringBuffer(); description.append(PreDeConPreprocessor.class.getName()); description.append(" computes the projected dimension of objects of a certain database according to the PreDeCon algorithm.\n"); description.append("The variance analysis is based on epsilon range queries.\n"); description.append(optionHandler.usage("", false)); return description.toString(); } }
package dr.app.beauti.siteModelsPanel; import dr.app.beauti.BeautiApp; import dr.app.beauti.components.dnds.DnDsComponentOptions; import dr.app.beauti.options.PartitionSubstitutionModel; import dr.app.beauti.types.BinaryModelType; import dr.app.beauti.types.DiscreteSubstModelType; import dr.app.beauti.types.FrequencyPolicyType; import dr.app.beauti.types.MicroSatModelType; import dr.app.beauti.util.PanelUtils; import dr.app.gui.components.WholeNumberField; import dr.app.util.OSType; import dr.evolution.datatype.DataType; import dr.evolution.datatype.Microsatellite; import dr.evomodel.substmodel.AminoAcidModelType; import dr.evomodel.substmodel.NucModelType; import jam.panels.OptionsPanel; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.event.*; import java.util.EnumSet; import java.util.logging.Logger; /** * @author Alexei Drummond * @author Walter Xie */ public class PartitionModelPanel extends OptionsPanel { // Components private static final long serialVersionUID = -1645661616353099424L; private JComboBox nucSubstCombo = new JComboBox(EnumSet.range( NucModelType.HKY, NucModelType.TN93).toArray()); private JComboBox aaSubstCombo = new JComboBox(AminoAcidModelType.values()); private JComboBox binarySubstCombo = new JComboBox(BinaryModelType.values()); private JCheckBox useAmbiguitiesTreeLikelihoodCheck = new JCheckBox( "Use ambiguities in the tree likelihood associated with this model"); private JComboBox frequencyCombo = new JComboBox(FrequencyPolicyType .values()); private JComboBox heteroCombo = new JComboBox(new String[] { "None", "Gamma", "Invariant Sites", "Gamma + Invariant Sites" }); private JComboBox gammaCatCombo = new JComboBox(new String[] { "4", "5", "6", "7", "8", "9", "10" }); private JLabel gammaCatLabel; private JComboBox codingCombo = new JComboBox(new String[] { "Off", "2 partitions: positions (1 + 2), 3", "3 partitions: positions 1, 2, 3" }); private JCheckBox substUnlinkCheck = new JCheckBox( "Unlink substitution rate parameters across codon positions"); private JCheckBox heteroUnlinkCheck = new JCheckBox( "Unlink rate heterogeneity model across codon positions"); private JCheckBox freqsUnlinkCheck = new JCheckBox( "Unlink base frequencies across codon positions"); private JButton setSRD06Button; //TODO public static final boolean ENABLE_ROBUST_COUNTING = false; private JButton setDndsButton; private boolean setDndsButtonClicked = false; private JCheckBox dolloCheck = new JCheckBox("Use Stochastic Dollo Model"); // private JComboBox dolloCombo = new JComboBox(new String[]{"Analytical", // "Sample"}); private JComboBox discreteTraitSiteModelCombo = new JComboBox( DiscreteSubstModelType.values()); private JCheckBox activateBSSVS = new JCheckBox( // "Activate BSSVS" "Infer social network with BSSVS"); private JTextField microsatName = new JTextField(); private WholeNumberField microsatMax = new WholeNumberField(2, Integer.MAX_VALUE); private WholeNumberField microsatMin = new WholeNumberField(1, Integer.MAX_VALUE); private JComboBox rateProportionCombo = new JComboBox( MicroSatModelType.RateProportionality.values()); private JComboBox mutationBiasCombo = new JComboBox( MicroSatModelType.MutationalBias.values()); private JComboBox phaseCombo = new JComboBox(MicroSatModelType.Phase .values()); JCheckBox shareMicroSatCheck = new JCheckBox( "Share one microsatellite among all substitution model(s)"); protected final PartitionSubstitutionModel model; @SuppressWarnings("serial") public PartitionModelPanel(final PartitionSubstitutionModel partitionModel) { super(12, (OSType.isMac() ? 6 : 24)); this.model = partitionModel; initCodonPartitionComponents(); PanelUtils.setupComponent(nucSubstCombo); nucSubstCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setNucSubstitutionModel((NucModelType) nucSubstCombo .getSelectedItem()); } }); nucSubstCombo .setToolTipText("<html>Select the type of nucleotide substitution model.</html>"); PanelUtils.setupComponent(aaSubstCombo); aaSubstCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setAaSubstitutionModel((AminoAcidModelType) aaSubstCombo .getSelectedItem()); } }); aaSubstCombo .setToolTipText("<html>Select the type of amino acid substitution model.</html>"); PanelUtils.setupComponent(binarySubstCombo); binarySubstCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model .setBinarySubstitutionModel((BinaryModelType) binarySubstCombo .getSelectedItem()); useAmbiguitiesTreeLikelihoodCheck.setSelected(binarySubstCombo .getSelectedItem() == BinaryModelType.BIN_COVARION); useAmbiguitiesTreeLikelihoodCheck.setEnabled(binarySubstCombo .getSelectedItem() != BinaryModelType.BIN_COVARION); } }); binarySubstCombo .setToolTipText("<html>Select the type of binary substitution model.</html>"); PanelUtils.setupComponent(useAmbiguitiesTreeLikelihoodCheck); useAmbiguitiesTreeLikelihoodCheck.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model .setUseAmbiguitiesTreeLikelihood(useAmbiguitiesTreeLikelihoodCheck .isSelected()); } }); useAmbiguitiesTreeLikelihoodCheck .setToolTipText("<html>Detemine useAmbiguities in &lt treeLikelihood &gt .</html>"); PanelUtils.setupComponent(frequencyCombo); frequencyCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setFrequencyPolicy((FrequencyPolicyType) frequencyCombo .getSelectedItem()); } }); frequencyCombo .setToolTipText("<html>Select the policy for determining the base frequencies.</html>"); PanelUtils.setupComponent(heteroCombo); heteroCombo .setToolTipText("<html>Select the type of site-specific rate<br>heterogeneity model.</html>"); heteroCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { boolean gammaHetero = heteroCombo.getSelectedIndex() == 1 || heteroCombo.getSelectedIndex() == 3; model.setGammaHetero(gammaHetero); model.setInvarHetero(heteroCombo.getSelectedIndex() == 2 || heteroCombo.getSelectedIndex() == 3); if (gammaHetero) { gammaCatLabel.setEnabled(true); gammaCatCombo.setEnabled(true); } else { gammaCatLabel.setEnabled(false); gammaCatCombo.setEnabled(false); } if (codingCombo.getSelectedIndex() != 0) { heteroUnlinkCheck .setEnabled(heteroCombo.getSelectedIndex() != 0); heteroUnlinkCheck.setSelected(heteroCombo .getSelectedIndex() != 0); } } }); PanelUtils.setupComponent(gammaCatCombo); gammaCatCombo .setToolTipText("<html>Select the number of categories to use for<br>the discrete gamma rate heterogeneity model.</html>"); gammaCatCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setGammaCategories(gammaCatCombo.getSelectedIndex() + 4); } }); Action setSRD06Action = new AbstractAction("Use SRD06 Model") { public void actionPerformed(ActionEvent actionEvent) { setSRD06Model(); } }; setSRD06Button = new JButton(setSRD06Action); PanelUtils.setupComponent(setSRD06Button); setSRD06Button .setToolTipText("<html>Sets the SRD06 model as described in<br>" + "Shapiro, Rambaut & Drummond (2006) <i>MBE</i> <b>23</b>: 7-9.</html>"); //TODO class ListenSetDndsButton implements ActionListener { public void actionPerformed(ActionEvent ev) { if (!setDndsButtonClicked) { setDndsCounting(); setDndsButton.setText("Default"); setDndsButtonClicked = true; } else if (setDndsButtonClicked) { removeDnDsCounting(); setDndsButton .setText("Use robust counting for dN/dS estimation"); setDndsButtonClicked = false; } else { System.err.println("bad juju"); } } }// END: ListenSetDndsButton setDndsButton = new JButton("Use robust counting for dN/dS estimation"); setDndsButton.addActionListener(new ListenSetDndsButton()); PanelUtils.setupComponent(setDndsButton); setDndsButton.setToolTipText("<html>TODO</html>"); PanelUtils.setupComponent(dolloCheck); dolloCheck.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { model.setDolloModel(true); } }); dolloCheck.setEnabled(true); dolloCheck .setToolTipText("<html>Activates a Stochastic Dollo model as described in<br>" + "Alekseyenko, Lee & Suchard (2008) <i>Syst Biol</i> <b>57</b>: 772-784.</html>"); PanelUtils.setupComponent(discreteTraitSiteModelCombo); discreteTraitSiteModelCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model .setDiscreteSubstType((DiscreteSubstModelType) discreteTraitSiteModelCombo .getSelectedItem()); } }); PanelUtils.setupComponent(activateBSSVS); activateBSSVS.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setActivateBSSVS(activateBSSVS.isSelected()); } }); activateBSSVS .setToolTipText("<html>Actives Bayesian stochastic search variable selection on the rates as decribed in<br>" + "Lemey, Rambaut, Drummond & Suchard (2009) <i>PLoS Computational Biology</i> <b>5</b>: e1000520</html>"); microsatName.setColumns(30); microsatName.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { model.getMicrosatellite().setName(microsatName.getText()); } }); microsatMax.setColumns(10); microsatMax.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { model.getMicrosatellite().setMax( Integer.parseInt(microsatMax.getText())); } }); microsatMin.setColumns(10); microsatMin.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { model.getMicrosatellite().setMin( Integer.parseInt(microsatMin.getText())); } }); PanelUtils.setupComponent(shareMicroSatCheck); shareMicroSatCheck.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model.getOptions().shareMicroSat = shareMicroSatCheck .isSelected(); if (shareMicroSatCheck.isSelected()) { model.getOptions().shareMicroSat(); } else { model.getOptions().unshareMicroSat(); } setOptions(); } }); PanelUtils.setupComponent(rateProportionCombo); rateProportionCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model .setRatePorportion((MicroSatModelType.RateProportionality) rateProportionCombo .getSelectedItem()); } }); // rateProportionCombo.setToolTipText("<html>Select the type of microsatellite substitution model.</html>"); PanelUtils.setupComponent(mutationBiasCombo); mutationBiasCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model .setMutationBias((MicroSatModelType.MutationalBias) mutationBiasCombo .getSelectedItem()); } }); PanelUtils.setupComponent(phaseCombo); phaseCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setPhase((MicroSatModelType.Phase) phaseCombo .getSelectedItem()); } }); setupPanel(); setOpaque(false); } /** * Sets the components up according to the partition model - but does not * layout the top level options panel. */ public void setOptions() { if (SiteModelsPanel.DEBUG) { String modelName = (model == null) ? "null" : model.getName(); Logger.getLogger("dr.app.beauti").info( "ModelsPanel.setModelOptions(" + modelName + ")"); } if (model == null) { return; } int dataType = model.getDataType().getType(); switch (dataType) { case DataType.NUCLEOTIDES: nucSubstCombo.setSelectedItem(model.getNucSubstitutionModel()); frequencyCombo.setSelectedItem(model.getFrequencyPolicy()); break; case DataType.AMINO_ACIDS: aaSubstCombo.setSelectedItem(model.getAaSubstitutionModel()); break; case DataType.TWO_STATES: case DataType.COVARION: binarySubstCombo .setSelectedItem(model.getBinarySubstitutionModel()); useAmbiguitiesTreeLikelihoodCheck.setSelected(model .isUseAmbiguitiesTreeLikelihood()); break; case DataType.GENERAL: discreteTraitSiteModelCombo.setSelectedItem(model .getDiscreteSubstType()); activateBSSVS.setSelected(model.isActivateBSSVS()); break; case DataType.MICRO_SAT: microsatName.setText(model.getMicrosatellite().getName()); microsatMax.setText(Integer.toString(model.getMicrosatellite() .getMax())); microsatMin.setText(Integer.toString(model.getMicrosatellite() .getMin())); shareMicroSatCheck.setSelected(model.getOptions().shareMicroSat); rateProportionCombo.setSelectedItem(model.getRatePorportion()); mutationBiasCombo.setSelectedItem(model.getMutationBias()); phaseCombo.setSelectedItem(model.getPhase()); shareMicroSatCheck.setEnabled(model.getOptions() .getPartitionSubstitutionModels(Microsatellite.INSTANCE) .size() > 1); break; default: throw new IllegalArgumentException("Unknown data type"); } if (model.isGammaHetero() && !model.isInvarHetero()) { heteroCombo.setSelectedIndex(1); } else if (!model.isGammaHetero() && model.isInvarHetero()) { heteroCombo.setSelectedIndex(2); } else if (model.isGammaHetero() && model.isInvarHetero()) { heteroCombo.setSelectedIndex(3); } else { heteroCombo.setSelectedIndex(0); } gammaCatCombo.setSelectedIndex(model.getGammaCategories() - 4); if (model.getCodonHeteroPattern() == null) { codingCombo.setSelectedIndex(0); } else if (model.getCodonHeteroPattern().equals("112")) { codingCombo.setSelectedIndex(1); } else { codingCombo.setSelectedIndex(2); } substUnlinkCheck.setSelected(model.isUnlinkedSubstitutionModel()); heteroUnlinkCheck.setSelected(model.isUnlinkedHeterogeneityModel()); freqsUnlinkCheck.setSelected(model.isUnlinkedFrequencyModel()); dolloCheck.setSelected(model.isDolloModel()); } // TODO private void setDndsCounting() { nucSubstCombo.setSelectedIndex(0); frequencyCombo.setSelectedIndex(0); heteroCombo.setSelectedIndex(0); gammaCatCombo.setOpaque(true); codingCombo.setSelectedIndex(2); substUnlinkCheck.setSelected(true); heteroUnlinkCheck.setSelected(false); freqsUnlinkCheck.setSelected(true); DnDsComponentOptions comp = (DnDsComponentOptions) model.getOptions() .getComponentOptions(DnDsComponentOptions.class); // Add model to ComponentOptions comp.addPartition(model); } private void removeDnDsCounting() { DnDsComponentOptions comp = (DnDsComponentOptions) model.getOptions() .getComponentOptions(DnDsComponentOptions.class); // Remove model from ComponentOptions comp.removePartition(model); nucSubstCombo.setSelectedIndex(0); frequencyCombo.setSelectedIndex(0); heteroCombo.setSelectedIndex(0); gammaCatCombo.setOpaque(true); codingCombo.setSelectedIndex(0); substUnlinkCheck.setSelected(true); heteroUnlinkCheck.setSelected(false); freqsUnlinkCheck.setSelected(true); }// END: removeDnDsCounting() /** * Configure this panel for the Shapiro, Rambaut and Drummond 2006 codon * position model */ private void setSRD06Model() { nucSubstCombo.setSelectedIndex(0); heteroCombo.setSelectedIndex(1); codingCombo.setSelectedIndex(1); substUnlinkCheck.setSelected(true); heteroUnlinkCheck.setSelected(true); } /** * Lays out the appropriate components in the panel for this partition * model. */ private void setupPanel() { switch (model.getDataType().getType()) { case DataType.NUCLEOTIDES: addComponentWithLabel("Substitution Model:", nucSubstCombo); addComponentWithLabel("Base frequencies:", frequencyCombo); addComponentWithLabel("Site Heterogeneity Model:", heteroCombo); heteroCombo.setSelectedIndex(0); gammaCatLabel = addComponentWithLabel( "Number of Gamma Categories:", gammaCatCombo); gammaCatCombo.setEnabled(false); addSeparator(); addComponentWithLabel("Partition into codon positions:", codingCombo); JPanel panel2 = new JPanel(); panel2.setOpaque(false); panel2.setLayout(new BoxLayout(panel2, BoxLayout.PAGE_AXIS)); panel2.setBorder(BorderFactory .createTitledBorder("Link/Unlink parameters:")); panel2.add(substUnlinkCheck); panel2.add(heteroUnlinkCheck); panel2.add(freqsUnlinkCheck); addComponent(panel2); addComponent(setSRD06Button); if (ENABLE_ROBUST_COUNTING) { addComponent(setDndsButton); } break; case DataType.AMINO_ACIDS: addComponentWithLabel("Substitution Model:", aaSubstCombo); addComponentWithLabel("Site Heterogeneity Model:", heteroCombo); heteroCombo.setSelectedIndex(0); gammaCatLabel = addComponentWithLabel( "Number of Gamma Categories:", gammaCatCombo); gammaCatCombo.setEnabled(false); break; case DataType.TWO_STATES: case DataType.COVARION: addComponentWithLabel("Substitution Model:", binarySubstCombo); addComponentWithLabel("Base frequencies:", frequencyCombo); addComponentWithLabel("Site Heterogeneity Model:", heteroCombo); heteroCombo.setSelectedIndex(0); gammaCatLabel = addComponentWithLabel( "Number of Gamma Categories:", gammaCatCombo); gammaCatCombo.setEnabled(false); addSeparator(); addComponentWithLabel("", useAmbiguitiesTreeLikelihoodCheck); break; case DataType.GENERAL: addComponentWithLabel("Discrete Trait Substitution Model:", discreteTraitSiteModelCombo); addComponent(activateBSSVS); break; case DataType.MICRO_SAT: addComponentWithLabel("Microsatellite Name:", microsatName); addComponentWithLabel("Max of Length:", microsatMax); addComponentWithLabel("Min of Length:", microsatMin); addComponent(shareMicroSatCheck); addSeparator(); addComponentWithLabel("Rate Proportionality:", rateProportionCombo); addComponentWithLabel("Mutational Bias:", mutationBiasCombo); addComponentWithLabel("Phase:", phaseCombo); break; default: throw new IllegalArgumentException("Unknown data type"); } if (BeautiApp.advanced) { addSeparator(); addComponent(dolloCheck); } setOptions(); } /** * Initializes and binds the components related to modeling codon positions. */ private void initCodonPartitionComponents() { PanelUtils.setupComponent(substUnlinkCheck); substUnlinkCheck.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setUnlinkedSubstitutionModel(substUnlinkCheck .isSelected()); } }); substUnlinkCheck.setEnabled(false); substUnlinkCheck.setToolTipText("" + "<html>Gives each codon position partition different<br>" + "substitution model parameters.</html>"); PanelUtils.setupComponent(heteroUnlinkCheck); heteroUnlinkCheck.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setUnlinkedHeterogeneityModel(heteroUnlinkCheck .isSelected()); } }); heteroUnlinkCheck.setEnabled(heteroCombo.getSelectedIndex() != 0); heteroUnlinkCheck .setToolTipText("<html>Gives each codon position partition different<br>rate heterogeneity model parameters.</html>"); PanelUtils.setupComponent(freqsUnlinkCheck); freqsUnlinkCheck.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { model.setUnlinkedFrequencyModel(freqsUnlinkCheck.isSelected()); } }); freqsUnlinkCheck.setEnabled(false); freqsUnlinkCheck .setToolTipText("<html>Gives each codon position partition different<br>nucleotide frequency parameters.</html>"); PanelUtils.setupComponent(codingCombo); codingCombo .setToolTipText("<html>Select how to partition the codon positions.</html>"); codingCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { switch (codingCombo.getSelectedIndex()) { case 0: model.setCodonHeteroPattern(null); break; case 1: model.setCodonHeteroPattern("112"); break; default: model.setCodonHeteroPattern("123"); break; } if (codingCombo.getSelectedIndex() != 0) { // codon position // partitioning substUnlinkCheck.setEnabled(true); heteroUnlinkCheck .setEnabled(heteroCombo.getSelectedIndex() != 0); freqsUnlinkCheck.setEnabled(true); substUnlinkCheck.setSelected(true); heteroUnlinkCheck.setSelected(heteroCombo .getSelectedIndex() != 0); freqsUnlinkCheck.setSelected(true); } else { substUnlinkCheck.setEnabled(false); substUnlinkCheck.setSelected(false); heteroUnlinkCheck.setEnabled(false); heteroUnlinkCheck.setSelected(false); freqsUnlinkCheck.setEnabled(false); freqsUnlinkCheck.setSelected(false); } } }); } }
package dr.evomodel.treelikelihood; import dr.evolution.alignment.PatternList; import dr.evolution.datatype.DataType; import dr.evolution.tree.NodeRef; import dr.evomodel.tree.TreeModel; import dr.inference.model.AbstractModel; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.inference.model.Parameter; /** * AbstractTreeLikelihood - a base class for likelihood calculators of sites on a tree. * * @version $Id: AbstractTreeLikelihood.java,v 1.16 2005/06/07 16:27:39 alexei Exp $ * * @author Andrew Rambaut */ public abstract class AbstractTreeLikelihood extends AbstractModel implements Likelihood { public AbstractTreeLikelihood(String name, PatternList patternList, TreeModel treeModel) { super(name); this.patternList = patternList; this.dataType = patternList.getDataType(); patternCount = patternList.getPatternCount(); stateCount = dataType.getStateCount(); patternWeights = patternList.getPatternWeights(); this.treeModel = treeModel; addModel(treeModel); nodeCount = treeModel.getNodeCount(); updateNode = new boolean[nodeCount]; for (int i = 0; i < nodeCount; i++) { updateNode[i] = true; } likelihoodKnown = false; } /** * Sets the partials from a sequence in an alignment. */ protected final void setStates(LikelihoodCore likelihoodCore, PatternList patternList, int sequenceIndex, int nodeIndex) { int i; int[] states = new int[patternCount]; for (i = 0; i < patternCount; i++) { states[i] = patternList.getPatternState(sequenceIndex, i); } likelihoodCore.setNodeStates(nodeIndex, states); } /** * Sets the partials from a sequence in an alignment. */ protected final void setPartials(LikelihoodCore likelihoodCore, PatternList patternList, int categoryCount, int sequenceIndex, int nodeIndex) { int i, j; double[] partials = new double[patternCount * stateCount]; boolean[] stateSet; int v = 0; for (i = 0; i < patternCount; i++) { int state = patternList.getPatternState(sequenceIndex, i); stateSet = dataType.getStateSet(state); for (j = 0; j < stateCount; j++) { if (stateSet[j]) { partials[v] = 1.0; } else { partials[v] = 0.0; } v++; } } likelihoodCore.setNodePartials(nodeIndex, partials); } /** * Set update flag for a node and its children */ protected void updateNode(NodeRef node) { updateNode[node.getNumber()] = true; likelihoodKnown = false; } /** * Set update flag for a node and its direct children */ protected void updateNodeAndChildren(NodeRef node) { updateNode[node.getNumber()] = true; for (int i = 0; i < treeModel.getChildCount(node); i++) { NodeRef child = treeModel.getChild(node, i); updateNode[child.getNumber()] = true; } likelihoodKnown = false; } /** * Set update flag for a node and all its descendents */ protected void updateNodeAndDescendents(NodeRef node) { updateNode[node.getNumber()] = true; for (int i = 0; i < treeModel.getChildCount(node); i++) { NodeRef child = treeModel.getChild(node, i); updateNodeAndDescendents(child); } likelihoodKnown = false; } /** * Set update flag for all nodes */ protected void updateAllNodes() { for (int i = 0; i < nodeCount; i++) { updateNode[i] = true; } likelihoodKnown = false; } /** * Set update flag for a pattern */ protected void updatePattern(int i) { if (updatePattern != null) { updatePattern[i] = true; } likelihoodKnown = false; } /** * Set update flag for all patterns */ protected void updateAllPatterns() { if (updatePattern != null) { for (int i = 0; i < patternCount; i++) { updatePattern[i] = true; } } likelihoodKnown = false; } public final double[] getPatternWeights() { return patternWeights; } // ParameterListener IMPLEMENTATION protected void handleParameterChangedEvent(Parameter parameter, int index) { // do nothing } // Model IMPLEMENTATION protected void handleModelChangedEvent(Model model, Object object, int index) { likelihoodKnown = false; } /** * Stores the additional state other than model components */ protected void storeState() { storedLikelihoodKnown = likelihoodKnown; storedLogLikelihood = logLikelihood; } /** * Restore the additional stored state */ protected void restoreState() { likelihoodKnown = storedLikelihoodKnown; logLikelihood = storedLogLikelihood; } protected void acceptState() { } // nothing to do // Likelihood IMPLEMENTATION public final Model getModel() { return this; } public final double getLogLikelihood() { if (!likelihoodKnown) { logLikelihood = calculateLogLikelihood(); likelihoodKnown = true; } return logLikelihood; } /** * Forces a complete recalculation of the likelihood next time getLikelihood is called */ public void makeDirty() { likelihoodKnown = false; updateAllNodes(); updateAllPatterns(); } protected abstract double calculateLogLikelihood(); public String toString() { return getClass().getName() + "(" + getLogLikelihood() + ")"; } // Loggable IMPLEMENTATION /** * @return the log columns. */ public dr.inference.loggers.LogColumn[] getColumns() { return new dr.inference.loggers.LogColumn[] { new LikelihoodColumn(getId()) }; } private class LikelihoodColumn extends dr.inference.loggers.NumberColumn { public LikelihoodColumn(String label) { super(label); } public double getDoubleValue() { return getLogLikelihood(); } } // INSTANCE VARIABLES /** the tree */ protected TreeModel treeModel = null; /** the patternList */ protected PatternList patternList = null; protected DataType dataType = null; /** the pattern weights */ protected double[] patternWeights; /** the number of patterns */ protected int patternCount; /** the number of states in the data */ protected int stateCount; /** the number of nodes in the tree */ protected int nodeCount; /** Flags to specify which patterns are to be updated */ protected boolean [] updatePattern = null; /** Flags to specify which nodes are to be updated */ protected boolean[] updateNode; private double logLikelihood; private double storedLogLikelihood; private boolean likelihoodKnown = false; private boolean storedLikelihoodKnown = false; }
package dr.evomodelxml.continuous; import dr.evomodel.continuous.LatentFactorModel; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.treelikelihood.TreeTraitParserUtilities; import dr.inference.model.CompoundParameter; import dr.inference.model.MatrixParameter; import dr.xml.*; import java.util.List; /** * @author Max Tolkoff * @author Marc Suchard */ public class LatentFactorModelParser extends AbstractXMLObjectParser { public final static String LATENT_FACTOR_MODEL = "latentFactorModel"; public final static String NUMBER_OF_FACTORS = "factorNumber"; public final static String FACTORS = "factors"; public final static String DATA = "data"; public final static String LOADINGS = "loadings"; public static final String PRECISION = "precision"; public String getParserName() { return LATENT_FACTOR_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { // Parameter latent = null; CompoundParameter factors = (CompoundParameter) xo.getChild(FACTORS).getChild(CompoundParameter.class); TreeTraitParserUtilities utilities = new TreeTraitParserUtilities(); String traitName = TreeTraitParserUtilities.DEFAULT_TRAIT_NAME; TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); TreeTraitParserUtilities.TraitsAndMissingIndices returnValue = utilities.parseTraitsFromTaxonAttributes(xo, traitName, treeModel, true); CompoundParameter dataParameter = returnValue.traitParameter; List<Integer> missingIndices = returnValue.missingIndices; traitName = returnValue.traitName; // MatrixParameter data = (MatrixParameter) xo.getChild(DATA).getChild(MatrixParameter.class); MatrixParameter loadings = (MatrixParameter) xo.getChild(LOADINGS).getChild(MatrixParameter.class); MatrixParameter precision = (MatrixParameter) xo.getChild(PRECISION).getChild(MatrixParameter.class); int numFactors = xo.getAttribute(NUMBER_OF_FACTORS, 4); return new LatentFactorModel(dataParameter, factors, loadings, precision, numFactors); } private static final XMLSyntaxRule[] rules = { AttributeRule.newIntegerRule(NUMBER_OF_FACTORS), new ElementRule(TreeModel.class), new ElementRule(FACTORS, new XMLSyntaxRule[]{ new ElementRule(CompoundParameter.class), }), new ElementRule(LOADINGS, new XMLSyntaxRule[]{ new ElementRule(MatrixParameter.class) }), new ElementRule(PRECISION, new XMLSyntaxRule[]{ new ElementRule(MatrixParameter.class) }), }; // <latentFactorModel> // <factors> // <parameter idref="factors"/> // </factors> // </latentFactorModel> public XMLSyntaxRule[] getSyntaxRules() { return rules; } @Override public String getParserDescription() { return "Sets up a latent factor model, with starting guesses for the loadings and factor matrices as well as the data for the factor analysis"; } @Override public Class getReturnType() { return LatentFactorModel.class; } }
/** * @author Merv Fansler * @author Kevin Fisher * @author Mike Sims * @author Josh Wakefield * @since February 19, 2015 * @version 0.2.0 */ package edu.millersville.cs.bitsplease.view; import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import edu.millersville.cs.bitsplease.model.*; /*** * Primary GUI component where all user interact occurs. All other view * components are owned by UMLEditorPane. */ public class UMLEditorPane extends BorderPane implements EventHandler<MouseEvent> { // Subcomponents private ToolbarPane toolbarPane; private DocumentViewPane documentViewPane; private PropertiesPane propertiesPane; // Drag State Variables private Boolean isMoving = false; private UMLObjectSymbol dragTarget; private double dragOffsetX = 0.0; private double dragOffsetY = 0.0; private boolean isRelating = false; /** * Default Construct for UMLEditor Pane */ public UMLEditorPane() { super(); // create Document View Pane documentViewPane = new DocumentViewPane(); this.setCenter(documentViewPane); documentViewPane.addEventHandler(MouseEvent.MOUSE_CLICKED, this); documentViewPane.addEventHandler(MouseEvent.MOUSE_DRAGGED, this); documentViewPane.addEventHandler(MouseEvent.MOUSE_RELEASED, this); // create and add Menu UMLMenu pumlMenu = new UMLMenu(); pumlMenu.setDocument(documentViewPane); this.setTop(pumlMenu); // create and add Toolbar Pane toolbarPane = new ToolbarPane(); this.setLeft(toolbarPane); // create and add Properties Pane propertiesPane = new PropertiesPane(documentViewPane.getSelectedUMLSymbol()); this.setRight(propertiesPane); } /** * initialization method for contextMenu * @return instance of context Menu to be displayed when you right click on an object */ private ContextMenu createEditingContextMenu() { ContextMenu editingContextMenu = new ContextMenu(); //create generic contextMenu items //MenuItem cut = new MenuItem("Cut"); //MenuItem copy = new MenuItem("Copy"); //MenuItem paste = new MenuItem("Paste"); MenuItem delete = new MenuItem("Delete"); delete.setOnAction(event -> { documentViewPane.removeUMLSymbol(documentViewPane.getSelectedUMLSymbol().getValue()); }); MenuItem exit = new MenuItem("Exit"); exit.setOnAction(event -> { editingContextMenu.hide(); }); exit.setAccelerator(new KeyCodeCombination(KeyCode.ESCAPE)); //Used to determine if the selected object is a UMLCLassSymbol and if it is then //adds the menu options that are specific to a UMLClassSymbol to the context menu //otherwise those options are not added to the context menu if (documentViewPane.getSelectedUMLSymbol().getValue() instanceof UMLClassSymbol) { UMLClassSymbol targetObj = (UMLClassSymbol) documentViewPane.getSelectedUMLSymbol().getValue(); MenuItem addAttr = new MenuItem("Add Attribute"); addAttr.setOnAction(event -> { targetObj.addAttribute("+attribute:type"); }); MenuItem deleteAttr = new MenuItem("Delete Attribute"); deleteAttr.setOnAction(event -> { targetObj.deleteAttribute(); }); MenuItem addOper = new MenuItem("Add Operation"); addOper.setOnAction(event -> { targetObj.addOperation("-operation():type"); }); MenuItem deleteOper = new MenuItem("Delete Operation"); deleteOper.setOnAction(event -> { targetObj.deleteOperation(); }); //add all items to the contextMenu for a UMLClassSymbol editingContextMenu.getItems().addAll(delete, new SeparatorMenuItem(), addAttr, deleteAttr, new SeparatorMenuItem(), addOper, deleteOper, new SeparatorMenuItem(), exit); } else { //add all items to the contextMenu for non-UMLClassSymbol's editingContextMenu.getItems().addAll(delete, new SeparatorMenuItem(), exit); } return editingContextMenu; } private ContextMenu createObjsContextMenu(MouseEvent e) { ContextMenu createObjContextMenu = new ContextMenu(); //create contextMenu items MenuItem createClass = new MenuItem("Create Class"); createClass.setOnAction(event -> { UMLClassSymbol c = new UMLClassSymbol(new Point2D(e.getX()-85,e.getY()-60), 100, 100); documentViewPane.addUMLSymbol(c); documentViewPane.setSelectedUMLSymbol(c); }); MenuItem createInterface = new MenuItem("Create Interface"); createInterface.setOnAction(event -> { UMLInterfaceSymbol i = new UMLInterfaceSymbol(new Point2D(e.getX()-85, e.getY()-30)); documentViewPane.addUMLSymbol(i); documentViewPane.setSelectedUMLSymbol(i); }); MenuItem createUseCase = new MenuItem("Create Use Case"); createUseCase.setOnAction(event -> { UMLUseCaseSymbol use = new UMLUseCaseSymbol(new Point2D(e.getX()-85, e.getY()-30)); documentViewPane.addUMLSymbol(use); documentViewPane.setSelectedUMLSymbol(use); }); MenuItem createUser = new MenuItem("Create User"); createUser.setOnAction(event -> { UMLUserSymbol u = new UMLUserSymbol(new Point2D(e.getX()-45,e.getY()-15)); documentViewPane.addUMLSymbol(u); documentViewPane.setSelectedUMLSymbol(u); }); MenuItem exit = new MenuItem("Exit"); exit.setOnAction(event -> { createObjContextMenu.hide(); }); exit.setAccelerator(new KeyCodeCombination(KeyCode.ESCAPE)); createObjContextMenu.getItems().addAll(createClass, new SeparatorMenuItem(), createInterface, new SeparatorMenuItem(), createUseCase, new SeparatorMenuItem(), createUser, new SeparatorMenuItem(), exit); return createObjContextMenu; } /** * @return reference to ToolbarPane instance */ public ToolbarPane getToolBarPane() { return toolbarPane; } /** * @return reference to DocumentViewPane instance */ public DocumentViewPane getDocumentViewPane() { return documentViewPane; } /** * @return reference to PropertiesPane instance */ public PropertiesPane getPropertiesPane() { return propertiesPane; } /** * Provides MouseEvent handling for all subcomponent panes * @see javafx.event.EventHandler#handle(javafx.event.Event) */ @SuppressWarnings("static-access") @Override public void handle(MouseEvent e) { ContextMenu createObjsContextMenu = createObjsContextMenu(e); if (e.getEventType() == MouseEvent.MOUSE_CLICKED) { switch (toolbarPane.getCurrentEditorMode().getValue()) { case CREATE_CLASS: if (e.getButton().equals(e.getButton().PRIMARY)) { UMLClassSymbol c = new UMLClassSymbol(new Point2D(e.getX()-85,e.getY()-60), 100, 100); documentViewPane.addUMLSymbol(c); documentViewPane.setSelectedUMLSymbol(c); } else { createObjsContextMenu.show(documentViewPane, e.getScreenX(), e.getScreenY()); } break; case SELECT: // selecting items ContextMenu editingContextMenu = createEditingContextMenu(); documentViewPane.setSelectedUMLSymbol(resolveUMLSymbolParent((Node) e.getTarget())); if (documentViewPane.getSelectedUMLSymbol().getValue() instanceof UMLClassSymbol) { UMLClassSymbol toEdit = (UMLClassSymbol) resolveUMLSymbolParent((Node) e.getTarget()); documentViewPane.setSelectedUMLSymbol(toEdit); if (toEdit.isSelected()) { if (e.getClickCount() == 2) { toEdit.setEditableUMLClassSymbol(); } if (e.getButton().equals(e.getButton().SECONDARY)) { editingContextMenu.show(toEdit, e.getScreenX(), e.getScreenY()); } } } else if (documentViewPane.getSelectedUMLSymbol().getValue() instanceof UMLInterfaceSymbol) { UMLInterfaceSymbol toEdit = (UMLInterfaceSymbol) resolveUMLSymbolParent((Node) e.getTarget()); documentViewPane.setSelectedUMLSymbol(toEdit); if (toEdit.isSelected()) { if (e.getClickCount() == 2) { toEdit.setEditableUMLInterfaceSymbol(); } if (e.getButton().equals(e.getButton().SECONDARY)) { editingContextMenu.show(toEdit, e.getScreenX(), e.getScreenY()); } } } else if (documentViewPane.getSelectedUMLSymbol().getValue() instanceof UMLUseCaseSymbol) { UMLUseCaseSymbol toEdit = (UMLUseCaseSymbol) resolveUMLSymbolParent((Node) e.getTarget()); documentViewPane.setSelectedUMLSymbol(toEdit); if (toEdit.isSelected()) { if (e.getClickCount() == 2) { toEdit.setEditableUMLUseCaseSymbol(); } if (e.getButton().equals(e.getButton().SECONDARY)) { editingContextMenu.show(toEdit, e.getScreenX(), e.getScreenY()); } } } else if (documentViewPane.getSelectedUMLSymbol().getValue() instanceof UMLUserSymbol) { if (e.getButton().equals(e.getButton().SECONDARY)) { editingContextMenu.show(documentViewPane.getSelectedUMLSymbol().getValue(), e.getScreenX(), e.getScreenY()); } } else if (e.getTarget().equals(documentViewPane)) { if (e.getButton().equals(e.getButton().SECONDARY)) { createObjsContextMenu.show(documentViewPane, e.getScreenX(), e.getScreenY()); } } break; case CREATE_INTERFACE: if (e.getButton().equals(e.getButton().PRIMARY)) { UMLInterfaceSymbol i = new UMLInterfaceSymbol(new Point2D(e.getX() -85, e.getY() -40)); documentViewPane.addUMLSymbol(i); documentViewPane.setSelectedUMLSymbol(i); } else { createObjsContextMenu.show(documentViewPane, e.getScreenX(), e.getScreenY()); } break; case CREATE_USER: if (e.getButton().equals(e.getButton().PRIMARY)) { UMLUserSymbol u = new UMLUserSymbol(new Point2D(e.getX()-50,e.getY()-20)); documentViewPane.addUMLSymbol(u); documentViewPane.setSelectedUMLSymbol(u); } else { createObjsContextMenu.show(documentViewPane, e.getScreenX(), e.getScreenY()); } break; case CREATE_USE_CASE: if (e.getButton().equals(e.getButton().PRIMARY)) { UMLUseCaseSymbol use = new UMLUseCaseSymbol(new Point2D(e.getX()-85, e.getY()-30)); documentViewPane.addUMLSymbol(use); documentViewPane.setSelectedUMLSymbol(use); } else { createObjsContextMenu.show(documentViewPane, e.getScreenX(), e.getScreenY()); } break; case DELETE: documentViewPane.setSelectedUMLSymbol(null); UMLSymbol toDelete = resolveUMLSymbolParent((Node)e.getTarget()); if (toDelete != null) { if (e.getButton().equals(e.getButton().PRIMARY)) { documentViewPane.removeUMLSymbol(toDelete); documentViewPane.getChildren().remove(toDelete); } // destroy event, since target object is now removed e.consume(); } break; default: break; } } else if (e.getEventType() == MouseEvent.MOUSE_DRAGGED) { switch (toolbarPane.getCurrentEditorMode().getValue()) { case SELECT: if (!isMoving) { dragTarget = resolveUMLObjectSymbolParent((Node)e.getTarget()); if (e.getButton().equals(e.getButton().PRIMARY)) { if (dragTarget != null) { // begin dragging object documentViewPane.setSelectedUMLSymbol(dragTarget); // compute offsets, so drag does not snap to origin dragOffsetX = ((UMLObjectSymbol)documentViewPane.getSelectedUMLSymbol().getValue()).getX() - e.getX(); dragOffsetY = ((UMLObjectSymbol)documentViewPane.getSelectedUMLSymbol().getValue()).getY() - e.getY(); // set state isMoving = true; } } } else { dragTarget.setLayoutX(e.getX() + dragOffsetX); dragTarget.setLayoutY(e.getY() + dragOffsetY); //TODO: this could be made automatic with binding documentViewPane.refreshRelations((UMLObjectSymbol) documentViewPane.getSelectedUMLSymbol().getValue()); } break; case CREATE_ASSOCIATION: case CREATE_AGGREGATION: case CREATE_COMPOSITION: case CREATE_GENERALIZATION: case CREATE_DEPENDENCY: if (!isRelating) { if (e.getButton().equals(e.getButton().PRIMARY)) { dragTarget = resolveUMLObjectSymbolParent((Node)e.getTarget()); isRelating = (dragTarget != null); } } break; default: isMoving = false; isRelating = false; dragTarget = null; } } else if (e.getEventType() == MouseEvent.MOUSE_RELEASED) { switch (toolbarPane.getCurrentEditorMode().getValue()) { case CREATE_ASSOCIATION: case CREATE_DEPENDENCY: case CREATE_AGGREGATION: case CREATE_COMPOSITION: case CREATE_GENERALIZATION: if (isRelating) { UMLObjectSymbol dragRelease = resolveUMLObjectSymbolParent((Node)e.getPickResult().getIntersectedNode()); if (dragRelease != null) { documentViewPane.addUMLSymbol( new UMLRelationSymbol(dragTarget, dragRelease, toolbarPane.getCurrentEditorMode().getValue().getRelationType())); } } break; default: break; } isRelating = false; isMoving = false; dragTarget = null; } } /** * Utility to traverse scene graph and identify ancestor UMLSymbol * @author Merv Fansler * @param target initial node to test for ancestor UMLSymbol * @return UMLSymbol ancestor, otherwise null */ private UMLSymbol resolveUMLSymbolParent(Node target) { UMLSymbol result; if (target != null) { if (target instanceof UMLSymbol) { result = (UMLSymbol)target; } else if (target instanceof DocumentViewPane) { result = null; } else { result = resolveUMLSymbolParent(target.getParent()); } } else { result = null; } return result; } /** * Utility to traverse scene graph and identify ancestor UMLObjectSymbol * @author Merv Fansler * @param target initial node to test for ancestor UMLObjectSymbol * @return UMLSymbol ancestor, otherwise null */ private UMLObjectSymbol resolveUMLObjectSymbolParent(Node target) { UMLObjectSymbol result; if (target != null) { if (target instanceof UMLObjectSymbol) { result = (UMLObjectSymbol)target; } else if (target instanceof DocumentViewPane) { result = null; } else { result = resolveUMLObjectSymbolParent(target.getParent()); } } else { result = null; } return result; } }
package fi.cie.chiru.servicefusionar.serviceApi; import gl.GLFactory; import gl.scenegraph.MeshComponent; import util.IO; import util.Vec; import android.content.ClipData; import android.graphics.Color; import android.graphics.Typeface; import android.util.Log; import android.view.View; import android.view.View.DragShadowBuilder; import android.widget.RelativeLayout; import android.widget.TextView; import commands.ui.CommandInUiThread; public class TextPopUp { private static final String LOG_TAG = "TextPopUp"; private String text; private TextView tv; private ServiceManager serviceManager; private Vec position; private boolean textVisible; private boolean textCreated; private MeshComponent textComponent; public TextPopUp(ServiceManager serviceManager) { this.serviceManager = serviceManager; textVisible = false; textCreated = false; } public void setDragText(String text) { this.text = text; } public void setPosition(Vec position) { this.position = position; } public void visible() { if(!textCreated) { createTextComponent(); textCreated = true; } if(!textVisible) { serviceManager.getSetup().world.add(textComponent); textVisible = true; } else { serviceManager.getSetup().world.remove(textComponent); textVisible = false; } } private void createTextComponent() { tv = new TextView(serviceManager.getSetup().myTargetActivity); tv.setId(generateUniqueId()); tv.setText(this.text); tv.setTextColor(Color.BLACK); tv.setBackgroundColor(Color.LTGRAY); tv.setTextSize(25); tv.setTypeface(Typeface.MONOSPACE); textComponent = GLFactory.getInstance().newTexturedSquare(this.text, IO.loadBitmapFromView(tv)); serviceManager.getSetup().world.add(textComponent); textComponent.setPosition(new Vec(this.position)); textComponent.setRotation(new Vec(90.0f, 0.0f, 180.0f)); textComponent.setScale(new Vec(0.5f, 1.0f, 1.0f)); textComponent.setOnLongClickCommand(new DragTextPopUpObject(tv)); } private int generateUniqueId() { int id = 0; RelativeLayout root = (RelativeLayout) serviceManager.getSetup().getGuiSetup().getMainContainerView(); while(root.findViewById(++id) != null ); return id; } private class DragTextPopUpObject extends CommandInUiThread { private TextView v; public DragTextPopUpObject(TextView DraggedItem) { v = DraggedItem; } // @Override public void executeInUiThread() { RelativeLayout root = (RelativeLayout) serviceManager.getSetup().getGuiSetup().getMainContainerView(); // if(root.findViewById(v.getId())== null) // root.addView(v); root.removeView(v); root.addView(v); v.setVisibility(View.GONE); // if(text.isEmpty()) text = (String)v.getText(); View.DragShadowBuilder shadow = new DragShadowBuilder(v); ClipData data = ClipData.newPlainText("DragData", text); v.startDrag(data, shadow, null, 0); } } }
package net.lucenews.controller; import java.util.*; import net.lucenews.*; import net.lucenews.atom.*; import net.lucenews.model.*; import net.lucenews.model.exception.*; import net.lucenews.view.*; import org.apache.lucene.document.*; import org.apache.lucene.index.*; import org.apache.lucene.misc.ChainedFilter; import org.apache.lucene.search.*; import org.w3c.dom.*; public class FacetController extends Controller { public static void doGet (LuceneContext c) throws Exception { LuceneWebService service = c.getService(); LuceneIndexManager manager = service.getIndexManager(); LuceneRequest request = c.getRequest(); LuceneResponse response = c.getResponse(); LuceneIndex[] indices = manager.getIndices( request.getIndexNames() ); String[] facets = request.getFacets(); // Atom feed Feed feed = new Feed(); // DOM Document org.w3c.dom.Document document = XMLController.newDocument(); // load the readers IndexReader[] readers = new IndexReader[ indices.length ]; for (int i = 0; i < indices.length; i++) { readers[ i ] = indices[ i ].getIndexReader(); } MultiReader reader = new MultiReader( readers ); // build the query Query query = null; if ( c.getOpenSearchQuery() != null && c.getOpenSearchQuery().getSearchTerms() != null ) { query = c.getQueryParser().parse( c.getOpenSearchQuery().getSearchTerms() ); } else { query = new MatchAllDocsQuery(); } // build the filter Filter[] filters = null; if ( c.getFilter() == null ) { filters = new Filter[]{ new QueryFilter( query ) }; } else { filters = new Filter[]{ new QueryFilter( query ), c.getFilter() }; } Filter filter = new ChainedFilter( filters, ChainedFilter.AND ); BitSet bits = filter.bits( reader ); // build an entry for each facet for (String facet : facets) { Entry entry = new Entry(); entry.setTitle( facet ); Element div = document.createElement("div"); div.setAttribute( "xmlns", XMLController.getXHTMLNamespace() ); Element dl = document.createElement("dl"); TermEnum termEnumeration = reader.terms( new Term( facet, "" ) ); while ( termEnumeration.term() != null ) { if ( !termEnumeration.term().field().equals( facet ) ) { break; } TermDocs termDocuments = reader.termDocs( termEnumeration.term() ); String name = termEnumeration.term().text(); int count = 0; while ( termDocuments.next() ) { if ( bits.get( termDocuments.doc() ) ) { count++; } } // only mention facets with more than one hit if ( count > 0 ) { Element dt = document.createElement("dt"); dt.appendChild( document.createTextNode( name ) ); dl.appendChild( dt ); Element dd = document.createElement("dd"); dd.appendChild( document.createTextNode( String.valueOf( count ) ) ); dl.appendChild( dd ); } termEnumeration.next(); } div.appendChild( dl ); entry.setContent( Content.xhtml( div ) ); feed.addEntry( entry ); } // put back the readers for (int i = 0; i < indices.length; i++) { indices[ i ].putIndexReader( readers[ i ] ); } AtomView.process( c, feed ); } }
package Php; public class StringFunctions extends FileFunctions { public static String str_replace(String search,String replace,String subject){ return subject.replaceAll(search, replace); } //For Replacing Multiple Values with one private static String str_replace(String search[],String replace,String subject,boolean isCaseSensitive) { int min=0,start=0,toReplace=0,pos; //Finding the first value to replace while(start<subject.length()){ min=subject.length(); for (int i = 0; i < search.length; i++) { //Getting the position of first occurance of the replacing value starting from index start. pos=isCaseSensitive?strpos(substr(subject, start), search[i]):stripos(substr(subject, start), search[i]); if(pos!=-1&&pos<min){ min=pos; toReplace=i; } } if(min==subject.length()) return subject; else{ subject=subject.replaceFirst((isCaseSensitive?"":"(?i)")+search[toReplace], replace); } start=min+search[toReplace].length(); } return subject; } public static String str_replace(String search[],String replace,String subject){ return str_replace(search, replace, subject, true); } public static String str_ireplace(String search,String replace,String subject){ return subject.replaceAll("(?i)"+search, replace); } public static String str_ireplace(String search[],String replace,String subject){ return str_replace(search, replace, subject, false); } public static int strlen(String string){ return string.length(); } public static String str_repeat(String string,int iterations) { if (iterations<1) { return ""; }else { return iterations==1?string:(str_repeat(string+string, (int)iterations/2)+(iterations%2==0?"":string)); } } // public static String str_repeat(String string,int iterations) { // /* // String t=""; // while(n-->0){ // t+=s; // } // return t; // */ // if(iterations<=1) // return iterations==1?string:""; // String tem="",main_temp=string; // if(iterations%2!=0){ // iterations--; // tem=string; // while(iterations>1){ // if(iterations%2==0){ // iterations/=2; // main_temp+=main_temp; // }else{ // iterations--; // tem+=main_temp; // return main_temp+tem; /* public static String str_repeat(String s,int n){ String tem,main; tem=""; main=n>0?s:""; if(n%2==0)n--; while(n>0){ if(n%2!=0){ n-=1; tem+=s; } if(n==0)break; main+=main; n/=2; } return main+tem; } */ public static String htmlspecialchars(String string) { return str_ireplace("\"", "&quot;", str_ireplace("'", "&#039;", str_ireplace("<", "&lt;", str_ireplace(">", "&gt;", str_ireplace("&", "&amp;", string))))); } public static String htmlentities(String string) { return htmlspecialchars(string); } public static String strtolower(String string) { return string.toLowerCase(); } public static String strtoupper(String string) { return string.toUpperCase(); } public static String trim(String string) { return string.trim(); } public static int strpos(String string,String find, int start) { return string.indexOf(find,start); } public static int strpos(String string,String find) { return string.indexOf(find,0); } //Something Extra public static int stripos(String string,String find, int start) { string=string.toLowerCase(); return string.indexOf(find.toLowerCase(),start); } public static int stripos(String string,String find) { string=string.toLowerCase(); return string.indexOf(find.toLowerCase(),0); } public static String substr(String string,int start,int length) { return string.substring(start, length); } public static String substr(String string,int start) { return string.substring(start); } public static String str_shuffle(String string) { int len=string.length(),tem; String st[]=string.split(""),swap; for (int i = 1; i <= len; i++) { tem=rand(1, len); swap=st[i]; st[i]=st[tem]; st[tem]=swap; } return emplode(st); } /* * Regex Methods * The pattern syntax must be in Java format and not in PHP format. * PS:I have noticed normal regex syntax works preety well. */ public static boolean preg_match(String pattern,String string) { try { return string.matches(pattern); } catch (Exception e) { return false; } } public static String preg_replace(String pattern,String replace,String string) { try { return string.replaceAll(pattern, replace); } catch (Exception e) { return ""; } } public static String[] preg_split(String pattern,String string){ try { return string.split(pattern); } catch (Exception e) { return null; } } }
package org.antlr.stringtemplate; import java.io.*; import java.util.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.antlr.stringtemplate.language.*; import antlr.*; import antlr.collections.AST; import antlr.collections.ASTEnumeration; /** A <TT>StringTemplate</TT> is a "document" with holes in it where you can stick * values. <TT>StringTemplate</TT> breaks up your template into chunks of text and * attribute expressions. <TT>StringTemplate</TT> ignores everything outside * of attribute expressions, treating it as just text to spit * out when you call <TT>StringTemplate.toString()</TT>. * */ public class StringTemplate { public static final String VERSION = "3.3a"; // August 11, 2008 public static final int REGION_IMPLICIT = 1; /** <@r>...<@end> */ public static final int REGION_EMBEDDED = 2; /** @t.r() ::= "..." defined manually by coder */ public static final int REGION_EXPLICIT = 3; /** An automatically created aggregate of properties. * * I often have lists of things that need to be formatted, but the list * items are actually pieces of data that are not already in an object. I * need ST to do something like: * * Ter=3432 * Tom=32234 * .... * * using template: * * $items:{$attr.name$=$attr.type$}$ * * This example will call getName() on the objects in items attribute, but * what if they aren't objects? I have perhaps two parallel arrays * instead of a single array of objects containing two fields. One * solution is allow Maps to be handled like properties so that it.name * would fail getName() but then see that it's a Map and do * it.get("name") instead. * * This very clean approach is espoused by some, but the problem is that * it's a hole in my separation rules. People can put the logic in the * view because you could say: "go get bob's data" in the view: * * Bob's Phone: $db.bob.phone$ * * A view should not be part of the program and hence should never be able * to go ask for a specific person's data. * * After much thought, I finally decided on a simple solution. I've * added setAttribute variants that pass in multiple property values, * with the property names specified as part of the name using a special * attribute name syntax: "name.{propName1,propName2,...}". This * object is a special kind of HashMap that hopefully prevents people * from passing a subclass or other variant that they have created as * it would be a loophole. Anyway, the ASTExpr.getObjectProperty() * method looks for Aggregate as a special case and does a get() instead * of getPropertyName. */ public static final class Aggregate { protected HashMap properties = new HashMap(); /** Allow StringTemplate to add values, but prevent the end * user from doing so. */ protected void put(String propName, Object propValue) { properties.put(propName, propValue); } public Object get(String propName) { return properties.get(propName); } public String toString() { return properties.toString(); } } /** Just an alias for ArrayList, but this way I can track whether a * list is something ST created or it's an incoming list. */ public static final class STAttributeList extends ArrayList { public STAttributeList(int size) { super(size); } public STAttributeList() { super(); } } public static final String ANONYMOUS_ST_NAME = "anonymous"; /** track probable issues like setting attribute that is not referenced. */ static boolean lintMode = false; protected List referencedAttributes = null; /** What's the name of this template? */ protected String name = ANONYMOUS_ST_NAME; private static int templateCounter=0; private static synchronized int getNextTemplateCounter() { templateCounter++; return templateCounter; } /** reset the template ID counter to 0; public so that testing routine * can access but not really of interest to the user. */ public static void resetTemplateCounter() { templateCounter = 0; } protected int templateID = getNextTemplateCounter(); /** Enclosing instance if I'm embedded within another template. * IF-subtemplates are considered embedded as well. */ protected StringTemplate enclosingInstance = null; /** If this template is an embedded template such as when you apply * a template to an attribute, then the arguments passed to this * template represent the argument context--a set of values * computed by walking the argument assignment list. For example, * <name:bold(item=name, foo="x")> would result in an * argument context of {[item=name], [foo="x"]} for this * template. This template would be the bold() template and * the enclosingInstance would point at the template that held * that <name:bold(...)> template call. When you want to get * an attribute value, you first check the attributes for the * 'self' template then the arg context then the enclosingInstance * like resolving variables in pascal-like language with nested * procedures. * * With multi-valued attributes such as <faqList:briefFAQDisplay()> * attribute "i" is set to 1..n. */ protected Map argumentContext = null; /** If this template is embedded in another template, the arguments * must be evaluated just before each application when applying * template to a list of values. The "it" attribute must change * with each application so that $names:bold(item=it)$ works. If * you evaluate once before starting the application loop then it * has a single fixed value. Eval.g saves the AST rather than evaluating * before invoking applyListOfAlternatingTemplates(). Each iteration * of a template application to a multi-valued attribute, these args * are re-evaluated with an initial context of {[it=...], [i=...]}. */ protected StringTemplateAST argumentsAST = null; /** When templates are defined in a group file format, the attribute * list is provided including information about attribute cardinality * such as present, optional, ... When this information is available, * rawSetAttribute should do a quick existence check as should the * invocation of other templates. So if you ref bold(item="foo") but * item is not defined in bold(), then an exception should be thrown. * When actually rendering the template, the cardinality is checked. * This is a Map<String,FormalArgument>. */ protected LinkedHashMap formalArguments = FormalArgument.UNKNOWN; /** How many formal arguments to this template have default values * specified? */ protected int numberOfDefaultArgumentValues = 0; /** Normally, formal parameters hide any attributes inherited from the * enclosing template with the same name. This is normally what you * want, but makes it hard to invoke another template passing in all * the data. Use notation now: <otherTemplate(...)> to say "pass in * all data". Works great. Can also say <otherTemplate(foo="xxx",...)> */ protected boolean passThroughAttributes = false; /** What group originally defined the prototype for this template? * This affects the set of templates I can refer to. super.t() must * always refer to the super of the original group. * * group base; * t ::= "base"; * * group sub; * t ::= "super.t()2" * * group subsub; * t ::= "super.t()3" */ protected StringTemplateGroup nativeGroup; /** This template was created as part of what group? Even if this * template was created from a prototype in a supergroup, its group * will be the subgroup. That's the way polymorphism works. */ protected StringTemplateGroup group; /** If this template is defined within a group file, what line number? */ protected int groupFileLine; /** Where to report errors */ StringTemplateErrorListener listener = null; /** The original, immutable pattern/language (not really used again after * initial "compilation", setup/parsing). */ protected String pattern; /** Map an attribute name to its value(s). These values are set by outside * code via st.setAttribute(name, value). StringTemplate is like self in * that a template is both the "class def" and "instance". When you * create a StringTemplate or setTemplate, the text is broken up into chunks * (i.e., compiled down into a series of chunks that can be evaluated later). * You can have multiple */ protected Map attributes; /** A Map<Class,Object> that allows people to register a renderer for * a particular kind of object to be displayed in this template. This * overrides any renderer set for this template's group. * * Most of the time this map is not used because the StringTemplateGroup * has the general renderer map for all templates in that group. * Sometimes though you want to override the group's renderers. */ protected Map attributeRenderers; /** A list of alternating string and ASTExpr references. * This is compiled to when the template is loaded/defined and walked to * write out a template instance. */ protected List chunks; /** If someone refs <@r()> in template t, an implicit * * @t.r() ::= "" * * is defined, but you can overwrite this def by defining your * own. We need to prevent more than one manual def though. Between * this var and isEmbeddedRegion we can determine these cases. */ protected int regionDefType; /** Does this template come from a <@region>...<@end> embedded in * another template? */ protected boolean isRegion; /** Set of implicit and embedded regions for this template */ protected Set regions; public static StringTemplateGroup defaultGroup = new StringTemplateGroup("defaultGroup", "."); /** Create a blank template with no pattern and no attributes */ public StringTemplate() { group = defaultGroup; // make sure has a group even if default } /** Create an anonymous template. It has no name just * chunks (which point to this anonymous template) and attributes. */ public StringTemplate(String template) { this(null, template); } public StringTemplate(String template, Class lexer) { this(); setGroup(new StringTemplateGroup("defaultGroup", lexer)); setTemplate(template); } /** Create an anonymous template with no name, but with a group */ public StringTemplate(StringTemplateGroup group, String template) { this(); if ( group!=null ) { setGroup(group); } setTemplate(template); } public StringTemplate(StringTemplateGroup group, String template, HashMap attributes) { this(group,template); this.attributes = attributes; } /** Make the 'to' template look exactly like the 'from' template * except for the attributes. This is like creating an instance * of a class in that the executable code is the same (the template * chunks), but the instance data is blank (the attributes). Do * not copy the enclosingInstance pointer since you will want this * template to eval in a context different from the examplar. */ protected void dup(StringTemplate from, StringTemplate to) { to.attributeRenderers = from.attributeRenderers; to.pattern = from.pattern; to.chunks = from.chunks; to.formalArguments = from.formalArguments; to.numberOfDefaultArgumentValues = from.numberOfDefaultArgumentValues; to.name = from.name; to.group = from.group; to.nativeGroup = from.nativeGroup; to.listener = from.listener; to.regions = from.regions; to.isRegion = from.isRegion; to.regionDefType = from.regionDefType; } /** Make an instance of this template; it contains an exact copy of * everything (except the attributes and enclosing instance pointer). * So the new template refers to the previously compiled chunks of this * template but does not have any attribute values. */ public StringTemplate getInstanceOf() { StringTemplate t = null; if ( nativeGroup!=null ) { // create a template using the native group for this template // but it's "group" is set to this.group by dup after creation so // polymorphism still works. t = nativeGroup.createStringTemplate(); } else { t = group.createStringTemplate(); } dup(this, t); return t; } public StringTemplate getEnclosingInstance() { return enclosingInstance; } public StringTemplate getOutermostEnclosingInstance() { if ( enclosingInstance!=null ) { return enclosingInstance.getOutermostEnclosingInstance(); } return this; } public void setEnclosingInstance(StringTemplate enclosingInstance) { if ( this==enclosingInstance ) { throw new IllegalArgumentException("cannot embed template "+getName()+" in itself"); } // set the parent for this template this.enclosingInstance = enclosingInstance; } public Map getArgumentContext() { return argumentContext; } public void setArgumentContext(Map ac) { argumentContext = ac; } public StringTemplateAST getArgumentsAST() { return argumentsAST; } public void setArgumentsAST(StringTemplateAST argumentsAST) { this.argumentsAST = argumentsAST; } public String getName() { return name; } public String getOutermostName() { if ( enclosingInstance!=null ) { return enclosingInstance.getOutermostName(); } return getName(); } public void setName(String name) { this.name = name; } public StringTemplateGroup getGroup() { return group; } public void setGroup(StringTemplateGroup group) { this.group = group; } public StringTemplateGroup getNativeGroup() { return nativeGroup; } public void setNativeGroup(StringTemplateGroup nativeGroup) { this.nativeGroup = nativeGroup; } /** Return the outermost template's group file line number */ public int getGroupFileLine() { if ( enclosingInstance!=null ) { return enclosingInstance.getGroupFileLine(); } return groupFileLine; } public void setGroupFileLine(int groupFileLine) { this.groupFileLine = groupFileLine; } public void setTemplate(String template) { this.pattern = template; breakTemplateIntoChunks(); } public String getTemplate() { return pattern; } public void setErrorListener(StringTemplateErrorListener listener) { this.listener = listener; } public StringTemplateErrorListener getErrorListener() { if ( listener==null ) { return group.getErrorListener(); } return listener; } public void reset() { attributes = new HashMap(); // just throw out table and make new one } public void setPredefinedAttributes() { if ( !inLintMode() ) { return; // only do this method so far in lint mode } } public void removeAttribute(String name) { if ( attributes!=null ) attributes.remove(name); } /** Set an attribute for this template. If you set the same * attribute more than once, you get a multi-valued attribute. * If you send in a StringTemplate object as a value, it's * enclosing instance (where it will inherit values from) is * set to 'this'. This would be the normal case, though you * can set it back to null after this call if you want. * If you send in a List plus other values to the same * attribute, they all get flattened into one List of values. * This will be a new list object so that incoming objects are * not altered. * If you send in an array, it is converted to an ArrayIterator. */ public void setAttribute(String name, Object value) { if ( value==null || name==null ) { return; } if ( name.indexOf('.')>=0 ) { throw new IllegalArgumentException("cannot have '.' in attribute names"); } if ( attributes==null ) { attributes = new HashMap(); } if ( value instanceof StringTemplate ) { ((StringTemplate)value).setEnclosingInstance(this); } else { // convert value if array value = ASTExpr.convertArrayToList(value); } // convert plain collections // get exactly in this scope (no enclosing) Object o = this.attributes.get(name); if ( o==null ) { // new attribute rawSetAttribute(this.attributes, name, value); return; } // it will be a multi-value attribute //System.out.println("exists: "+name+"="+o); STAttributeList v = null; if ( o.getClass() == STAttributeList.class ) { // already a list made by ST v = (STAttributeList)o; } else if ( o instanceof List ) { // existing attribute is non-ST List // must copy to an ST-managed list before adding new attribute List listAttr = (List)o; v = new STAttributeList(listAttr.size()); v.addAll(listAttr); rawSetAttribute(this.attributes, name, v); // replace attribute w/list } else { // non-list second attribute, must convert existing to ArrayList v = new STAttributeList(); // make list to hold multiple values // make it point to list now rawSetAttribute(this.attributes, name, v); // replace attribute w/list v.add(o); // add previous single-valued attribute } if ( value instanceof List ) { // flatten incoming list into existing if ( v!=value ) { // avoid weird cyclic add v.addAll((List)value); } } else { v.add(value); } } /** Convenience method to box ints */ public void setAttribute(String name, int value) { setAttribute(name, new Integer(value)); } /** Set an aggregate attribute with two values. The attribute name * must have the format: "name.{propName1,propName2}". */ public void setAttribute(String aggrSpec, Object v1, Object v2) { setAttribute(aggrSpec, new Object[] {v1,v2}); } public void setAttribute(String aggrSpec, Object v1, Object v2, Object v3) { setAttribute(aggrSpec, new Object[] {v1,v2,v3}); } public void setAttribute(String aggrSpec, Object v1, Object v2, Object v3, Object v4) { setAttribute(aggrSpec, new Object[] {v1,v2,v3,v4}); } public void setAttribute(String aggrSpec, Object v1, Object v2, Object v3, Object v4, Object v5) { setAttribute(aggrSpec, new Object[] {v1,v2,v3,v4,v5}); } /** Create an aggregate from the list of properties in aggrSpec and fill * with values from values array. This is not publically visible because * it conflicts semantically with setAttribute("foo",new Object[] {...}); */ protected void setAttribute(String aggrSpec, Object[] values) { List properties = new ArrayList(); String aggrName = parseAggregateAttributeSpec(aggrSpec, properties); if ( values==null || properties.size()==0 ) { throw new IllegalArgumentException("missing properties or values for '"+aggrSpec+"'"); } if ( values.length != properties.size() ) { throw new IllegalArgumentException("number of properties in '"+aggrSpec+"' != number of values"); } Aggregate aggr = new Aggregate(); for (int i = 0; i < values.length; i++) { Object value = values[i]; if ( value instanceof StringTemplate ) { ((StringTemplate)value).setEnclosingInstance(this); } else { value = ASTExpr.convertArrayToList(value); } aggr.put((String)properties.get(i), value); } setAttribute(aggrName, aggr); } /** Split "aggrName.{propName1,propName2}" into list [propName1,propName2] * and the aggrName. Space is allowed around ','. */ protected String parseAggregateAttributeSpec(String aggrSpec, List properties) { int dot = aggrSpec.indexOf('.'); if ( dot<=0 ) { throw new IllegalArgumentException("invalid aggregate attribute format: "+ aggrSpec); } String aggrName = aggrSpec.substring(0, dot); String propString = aggrSpec.substring(dot+1, aggrSpec.length()); boolean error = true; StringTokenizer tokenizer = new StringTokenizer(propString, "{,}", true); match: if ( tokenizer.hasMoreTokens() ) { String token = tokenizer.nextToken(); // advance to { token = token.trim(); if ( token.equals("{") ) { token = tokenizer.nextToken(); // advance to first prop name token = token.trim(); properties.add(token); token = tokenizer.nextToken(); // advance to a comma token = token.trim(); while ( token.equals(",") ) { token = tokenizer.nextToken(); // advance to a prop name token = token.trim(); properties.add(token); token = tokenizer.nextToken(); // advance to a "," or "}" token = token.trim(); } if ( token.equals("}") ) { error = false; } } } if ( error ) { throw new IllegalArgumentException("invalid aggregate attribute format: "+ aggrSpec); } return aggrName; } /** Map a value to a named attribute. Throw NoSuchElementException if * the named attribute is not formally defined in self's specific template * and a formal argument list exists. */ protected void rawSetAttribute(Map attributes, String name, Object value) { if ( formalArguments!=FormalArgument.UNKNOWN && getFormalArgument(name)==null ) { // a normal call to setAttribute with unknown attribute throw new NoSuchElementException("no such attribute: "+name+ " in template context "+ getEnclosingInstanceStackString()); } if ( value == null ) { return; } attributes.put(name, value); } /** Argument evaluation such as foo(x=y), x must * be checked against foo's argument list not this's (which is * the enclosing context). So far, only eval.g uses arg self as * something other than "this". */ public void rawSetArgumentAttribute(StringTemplate embedded, Map attributes, String name, Object value) { if ( embedded.formalArguments!=FormalArgument.UNKNOWN && embedded.getFormalArgument(name)==null ) { throw new NoSuchElementException("template "+embedded.getName()+ " has no such attribute: "+name+ " in template context "+ getEnclosingInstanceStackString()); } if ( value == null ) { return; } attributes.put(name, value); } public Object getAttribute(String name) { return get(this,name); } /** Walk the chunks, asking them to write themselves out according * to attribute values of 'this.attributes'. This is like evaluating or * interpreting the StringTemplate as a program using the * attributes. The chunks will be identical (point at same list) * for all instances of this template. */ public int write(StringTemplateWriter out) throws IOException { if ( group.debugTemplateOutput ) { group.emitTemplateStartDebugString(this,out); } int n = 0; setPredefinedAttributes(); setDefaultArgumentValues(); for (int i=0; chunks!=null && i<chunks.size(); i++) { Expr a = (Expr)chunks.get(i); int chunkN = a.write(this, out); // expr-on-first-line-with-no-output NEWLINE => NEWLINE if ( chunkN==0 && i==0 && (i+1)<chunks.size() && chunks.get(i+1) instanceof NewlineRef ) { //System.out.println("found pure first-line-blank \\n pattern"); i++; // skip next NEWLINE; continue; } // NEWLINE expr-with-no-output NEWLINE => NEWLINE // Indented $...$ have the indent stored with the ASTExpr // so the indent does not come out as a StringRef if ( chunkN==0 && (i-1)>=0 && chunks.get(i-1) instanceof NewlineRef && (i+1)<chunks.size() && chunks.get(i+1) instanceof NewlineRef ) { //System.out.println("found pure \\n blank \\n pattern"); i++; // make it skip over the next chunk, the NEWLINE } n += chunkN; } if ( group.debugTemplateOutput ) { group.emitTemplateStopDebugString(this,out); } if ( lintMode ) { checkForTrouble(); } return n; } /** Resolve an attribute reference. It can be in four possible places: * * 1. the attribute list for the current template * 2. if self is an embedded template, somebody invoked us possibly * with arguments--check the argument context * 3. if self is an embedded template, the attribute list for the enclosing * instance (recursively up the enclosing instance chain) * 4. if nothing is found in the enclosing instance chain, then it might * be a map defined in the group or the its supergroup etc... * * Attribute references are checked for validity. If an attribute has * a value, its validity was checked before template rendering. * If the attribute has no value, then we must check to ensure it is a * valid reference. Somebody could reference any random value like $xyz$; * formal arg checks before rendering cannot detect this--only the ref * can initiate a validity check. So, if no value, walk up the enclosed * template tree again, this time checking formal parameters not * attributes Map. The formal definition must exist even if no value. * * To avoid infinite recursion in toString(), we have another condition * to check regarding attribute values. If your template has a formal * argument, foo, then foo will hide any value available from "above" * in order to prevent infinite recursion. * * This method is not static so people can override functionality. */ public Object get(StringTemplate self, String attribute) { //System.out.println("### get("+self.getEnclosingInstanceStackString()+", "+attribute+")"); //System.out.println("attributes="+(self.attributes!=null?self.attributes.keySet().toString():"none")); if ( self==null ) { return null; } if ( lintMode ) { self.trackAttributeReference(attribute); } // is it here? Object o = null; if ( self.attributes!=null ) { o = self.attributes.get(attribute); } // nope, check argument context in case embedded if ( o==null ) { Map argContext = self.getArgumentContext(); if ( argContext!=null ) { o = argContext.get(attribute); } } if ( o==null && !self.passThroughAttributes && self.getFormalArgument(attribute)!=null ) { // if you've defined attribute as formal arg for this // template and it has no value, do not look up the // enclosing dynamic scopes. This avoids potential infinite // recursion. return null; } // not locally defined, check enclosingInstance if embedded if ( o==null && self.enclosingInstance!=null ) { /* System.out.println("looking for "+getName()+"."+attribute+" in super="+ enclosingInstance.getName()); */ Object valueFromEnclosing = get(self.enclosingInstance, attribute); if ( valueFromEnclosing==null ) { checkNullAttributeAgainstFormalArguments(self, attribute); } o = valueFromEnclosing; } // not found and no enclosing instance to look at else if ( o==null && self.enclosingInstance==null ) { // It might be a map in the group or supergroup... o = self.group.getMap(attribute); } return o; } /** Walk a template, breaking it into a list of * chunks: Strings and actions/expressions. */ protected void breakTemplateIntoChunks() { //System.out.println("parsing template: "+pattern); if ( pattern==null ) { return; } try { // instead of creating a specific template lexer, use // an instance of the class specified by the user. // The default is DefaultTemplateLexer. // The only constraint is that you use an ANTLR lexer // so I can use the special ChunkToken. Class lexerClass = group.getTemplateLexerClass(); Constructor ctor = lexerClass.getConstructor( new Class[] {StringTemplate.class,Reader.class} ); CharScanner chunkStream = (CharScanner) ctor.newInstance( new Object[] {this,new StringReader(pattern)} ); chunkStream.setTokenObjectClass("org.antlr.stringtemplate.language.ChunkToken"); TemplateParser chunkifier = new TemplateParser(chunkStream); chunkifier.template(this); //System.out.println("chunks="+chunks); } catch (Exception e) { String name = "<unknown>"; String outerName = getOutermostName(); if ( getName()!=null ) { name = getName(); } if ( outerName!=null && !name.equals(outerName) ) { name = name+" nested in "+outerName; } error("problem parsing template '"+name+"'", e); } } public ASTExpr parseAction(String action) { //System.out.println("parse action "+action); ActionLexer lexer = new ActionLexer(new StringReader(action.toString())); ActionParser parser = new ActionParser(lexer, this); parser.setASTNodeClass("org.antlr.stringtemplate.language.StringTemplateAST"); lexer.setTokenObjectClass("org.antlr.stringtemplate.language.StringTemplateToken"); ASTExpr a = null; try { Map options = parser.action(); AST tree = parser.getAST(); if ( tree!=null ) { if ( tree.getType()==ActionParser.CONDITIONAL ) { a = new ConditionalExpr(this,tree); } else { a = new ASTExpr(this,tree,options); } } } catch (RecognitionException re) { error("Can't parse chunk: "+action.toString(), re); } catch (TokenStreamException tse) { error("Can't parse chunk: "+action.toString(), tse); } return a; } public int getTemplateID() { return templateID; } public Map getAttributes() { return attributes; } /** Get a list of the strings and subtemplates and attribute * refs in a template. */ public List getChunks() { return chunks; } public void addChunk(Expr e) { if ( chunks==null ) { chunks = new ArrayList(); } chunks.add(e); } public void setAttributes(Map attributes) { this.attributes = attributes; } // F o r m a l A r g S t u f f public Map getFormalArguments() { return formalArguments; } public void setFormalArguments(LinkedHashMap args) { formalArguments = args; } /** Set any default argument values that were not set by the * invoking template or by setAttribute directly. Note * that the default values may be templates. Their evaluation * context is the template itself and, hence, can see attributes * within the template, any arguments, and any values inherited * by the template. * * Default values are stored in the argument context rather than * the template attributes table just for consistency's sake. */ public void setDefaultArgumentValues() { if ( numberOfDefaultArgumentValues==0 ) { return; } if ( argumentContext==null ) { argumentContext = new HashMap(); } if ( formalArguments!=FormalArgument.UNKNOWN ) { Set argNames = formalArguments.keySet(); for (Iterator it = argNames.iterator(); it.hasNext();) { String argName = (String) it.next(); // use the default value then FormalArgument arg = (FormalArgument)formalArguments.get(argName); if ( arg.defaultValueST!=null ) { Object existingValue = getAttribute(argName); if ( existingValue==null ) { // value unset? // if no value for attribute, set arg context // to the default value. We don't need an instance // here because no attributes can be set in // the arg templates by the user. argumentContext.put(argName, arg.defaultValueST); } } } } } /** From this template upward in the enclosing template tree, * recursively look for the formal parameter. */ public FormalArgument lookupFormalArgument(String name) { FormalArgument arg = getFormalArgument(name); if ( arg==null && enclosingInstance!=null ) { arg = enclosingInstance.lookupFormalArgument(name); } return arg; } public FormalArgument getFormalArgument(String name) { return (FormalArgument)formalArguments.get(name); } public void defineEmptyFormalArgumentList() { setFormalArguments(new LinkedHashMap()); } public void defineFormalArgument(String name) { defineFormalArgument(name,null); } public void defineFormalArguments(List names) { if ( names==null ) { return; } for (int i = 0; i < names.size(); i++) { String name = (String) names.get(i); defineFormalArgument(name); } } public void defineFormalArgument(String name, StringTemplate defaultValue) { if ( defaultValue!=null ) { numberOfDefaultArgumentValues++; } FormalArgument a = new FormalArgument(name,defaultValue); if ( formalArguments==FormalArgument.UNKNOWN ) { formalArguments = new LinkedHashMap(); } formalArguments.put(name, a); } /** Normally if you call template y from x, y cannot see any attributes * of x that are defined as formal parameters of y. Setting this * passThroughAttributes to true, will override that and allow a * template to see through the formal arg list to inherited values. */ public void setPassThroughAttributes(boolean passThroughAttributes) { this.passThroughAttributes = passThroughAttributes; } /** Specify a complete map of what object classes should map to which * renderer objects. */ public void setAttributeRenderers(Map renderers) { this.attributeRenderers = renderers; } /** Register a renderer for all objects of a particular type. This * overrides any renderer set in the group for this class type. */ public void registerRenderer(Class attributeClassType, AttributeRenderer renderer) { if ( attributeRenderers==null ) { attributeRenderers = new HashMap(); } attributeRenderers.put(attributeClassType, renderer); } /** What renderer is registered for this attributeClassType for * this template. If not found, the template's group is queried. */ public AttributeRenderer getAttributeRenderer(Class attributeClassType) { AttributeRenderer renderer = null; if ( attributeRenderers!=null ) { renderer = (AttributeRenderer)attributeRenderers.get(attributeClassType); } if ( renderer!=null ) { // found it! return renderer; } // we have no renderer overrides for the template or none for class arg // check parent template if we are embedded if ( enclosingInstance!=null ) { return enclosingInstance.getAttributeRenderer(attributeClassType); } // else check group return group.getAttributeRenderer(attributeClassType); } // U T I L I T Y R O U T I N E S public void error(String msg) { error(msg, null); } public void warning(String msg) { if ( getErrorListener()!=null ) { getErrorListener().warning(msg); } else { System.err.println("StringTemplate: warning: "+msg); } } public void error(String msg, Throwable e) { if ( getErrorListener()!=null ) { getErrorListener().error(msg,e); } else { if ( e!=null ) { System.err.println("StringTemplate: error: "+msg+": "+e.toString()); if ( e instanceof InvocationTargetException ) { e = ((InvocationTargetException)e).getTargetException(); } e.printStackTrace(System.err); } else { System.err.println("StringTemplate: error: "+msg); } } } /** Make StringTemplate check your work as it evaluates templates. * Problems are sent to error listener. Currently warns when * you set attributes that are not used. */ public static void setLintMode(boolean lint) { StringTemplate.lintMode = lint; } public static boolean inLintMode() { return lintMode; } /** Indicates that 'name' has been referenced in this template. */ protected void trackAttributeReference(String name) { if ( referencedAttributes==null ) { referencedAttributes = new ArrayList(); } referencedAttributes.add(name); } /** Look up the enclosing instance chain (and include this) to see * if st is a template already in the enclosing instance chain. */ public static boolean isRecursiveEnclosingInstance(StringTemplate st) { if ( st==null ) { return false; } StringTemplate p = st.enclosingInstance; if ( p==st ) { return true; // self-recursive } // now look for indirect recursion while ( p!=null ) { if ( p==st ) { return true; } p = p.enclosingInstance; } return false; } public String getEnclosingInstanceStackTrace() { StringBuffer buf = new StringBuffer(); Set seen = new HashSet(); StringTemplate p = this; while ( p!=null ) { if ( seen.contains(p) ) { buf.append(p.getTemplateDeclaratorString()); buf.append(" (start of recursive cycle)"); buf.append("\n"); buf.append("..."); break; } seen.add(p); buf.append(p.getTemplateDeclaratorString()); if ( p.attributes!=null ) { buf.append(", attributes=["); int i = 0; for (Iterator iter = p.attributes.keySet().iterator(); iter.hasNext();) { String attrName = (String) iter.next(); if ( i>0 ) { buf.append(", "); } i++; buf.append(attrName); Object o = p.attributes.get(attrName); if ( o instanceof StringTemplate ) { StringTemplate st = (StringTemplate)o; buf.append("="); buf.append("<"); buf.append(st.getName()); buf.append("()@"); buf.append(String.valueOf(st.getTemplateID())); buf.append(">"); } else if ( o instanceof List ) { buf.append("=List[.."); List list = (List)o; int n=0; for (int j = 0; j < list.size(); j++) { Object listValue = list.get(j); if ( listValue instanceof StringTemplate ) { if ( n>0 ) { buf.append(", "); } n++; StringTemplate st = (StringTemplate)listValue; buf.append("<"); buf.append(st.getName()); buf.append("()@"); buf.append(String.valueOf(st.getTemplateID())); buf.append(">"); } } buf.append("..]"); } } buf.append("]"); } if ( p.referencedAttributes!=null ) { buf.append(", references="); buf.append(p.referencedAttributes); } buf.append(">\n"); p = p.enclosingInstance; } /* if ( enclosingInstance!=null ) { buf.append(enclosingInstance.getEnclosingInstanceStackTrace()); } */ return buf.toString(); } public String getTemplateDeclaratorString() { StringBuffer buf = new StringBuffer(); buf.append("<"); buf.append(getName()); buf.append("("); buf.append(formalArguments.keySet()); buf.append(")@"); buf.append(String.valueOf(getTemplateID())); buf.append(">"); return buf.toString(); } protected String getTemplateHeaderString(boolean showAttributes) { if ( showAttributes ) { StringBuffer buf = new StringBuffer(); buf.append(getName()); if ( attributes!=null ) { buf.append(attributes.keySet()); } return buf.toString(); } return getName(); } /** A reference to an attribute with no value, must be compared against * the formal parameter to see if it exists; if it exists all is well, * but if not, throw an exception. * * Don't do the check if no formal parameters exist for this template; * ask enclosing. */ protected void checkNullAttributeAgainstFormalArguments( StringTemplate self, String attribute) { if ( self.getFormalArguments()==FormalArgument.UNKNOWN ) { // bypass unknown arg lists if ( self.enclosingInstance!=null ) { checkNullAttributeAgainstFormalArguments( self.enclosingInstance, attribute); } return; } FormalArgument formalArg = self.lookupFormalArgument(attribute); if ( formalArg == null ) { throw new NoSuchElementException("no such attribute: "+attribute+ " in template context "+getEnclosingInstanceStackString()); } } /** Executed after evaluating a template. For now, checks for setting * of attributes not reference. */ protected void checkForTrouble() { // we have table of set values and list of values referenced // compare, looking for SET BUT NOT REFERENCED ATTRIBUTES if ( attributes==null ) { return; } Set names = attributes.keySet(); Iterator iter = names.iterator(); // if in names and not in referenced attributes, trouble while ( iter.hasNext() ) { String name = (String)iter.next(); if ( referencedAttributes!=null && !referencedAttributes.contains(name) ) { warning(getName()+": set but not used: "+name); } } // can do the reverse, but will have lots of false warnings :( } /** If an instance of x is enclosed in a y which is in a z, return * a String of these instance names in order from topmost to lowest; * here that would be "[z y x]". */ public String getEnclosingInstanceStackString() { List names = new LinkedList(); StringTemplate p = this; while ( p!=null ) { String name = p.getName(); names.add(0,name+(p.passThroughAttributes?"(...)":"")); p = p.enclosingInstance; } return names.toString().replaceAll(",",""); } public boolean isRegion() { return isRegion; } public void setIsRegion(boolean isRegion) { this.isRegion = isRegion; } public void addRegionName(String name) { if ( regions==null ) { regions = new HashSet(); } regions.add(name); } /** Does this template ref or embed region name? */ public boolean containsRegionName(String name) { if ( regions==null ) { return false; } return regions.contains(name); } public int getRegionDefType() { return regionDefType; } public void setRegionDefType(int regionDefType) { this.regionDefType = regionDefType; } public String toDebugString() { StringBuffer buf = new StringBuffer(); buf.append("template-"+getTemplateDeclaratorString()+":"); buf.append("chunks="); if ( chunks!=null ) { buf.append(chunks.toString()); } buf.append("attributes=["); if ( attributes!=null ) { Set attrNames = attributes.keySet(); int n=0; for (Iterator iter = attrNames.iterator(); iter.hasNext();) { if ( n>0 ) { buf.append(','); } String name = (String) iter.next(); buf.append(name+"="); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { buf.append(((StringTemplate)value).toDebugString()); } else { buf.append(value); } n++; } buf.append("]"); } return buf.toString(); } /** Don't print values, just report the nested structure with attribute names. * Follow (nest) attributes that are templates only. */ public String toStructureString() { return toStructureString(0); } public String toStructureString(int indent) { StringBuffer buf = new StringBuffer(); for (int i=1; i<=indent; i++) { // indent buf.append(" "); } buf.append(getName()); buf.append(attributes.keySet()); buf.append(":\n"); if ( attributes!=null ) { Set attrNames = attributes.keySet(); for (Iterator iter = attrNames.iterator(); iter.hasNext();) { String name = (String) iter.next(); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { // descend buf.append(((StringTemplate)value).toStructureString(indent+1)); } else { if ( value instanceof List ) { List alist = (List)value; for (int i = 0; i < alist.size(); i++) { Object o = (Object) alist.get(i); if ( o instanceof StringTemplate ) { // descend buf.append(((StringTemplate)o).toStructureString(indent+1)); } } } else if ( value instanceof Map ) { Map m = (Map)value; Collection mvalues = m.values(); for (Iterator iterator = mvalues.iterator(); iterator.hasNext();) { Object o = (Object) iterator.next(); if ( o instanceof StringTemplate ) { // descend buf.append(((StringTemplate)o).toStructureString(indent+1)); } } } } } } return buf.toString(); } /* public String getDOTForDependencyGraph(boolean showAttributes) { StringBuffer buf = new StringBuffer(); buf.append("digraph prof {\n"); HashMap edges = new HashMap(); this.getDependencyGraph(edges, showAttributes); Set sourceNodes = edges.keySet(); // for each source template for (Iterator it = sourceNodes.iterator(); it.hasNext();) { String src = (String) it.next(); Set targetNodes = (Set)edges.get(src); // for each target template for (Iterator it2 = targetNodes.iterator(); it2.hasNext();) { String trg = (String) it2.next(); buf.append('"'); buf.append(src); buf.append('"'); buf.append("->"); buf.append('"'); buf.append(trg); buf.append("\"\n"); } } buf.append("}"); return buf.toString(); } */ /** Generate a DOT file for displaying the template enclosure graph; e.g., digraph prof { "t1" -> "t2" "t1" -> "t3" "t4" -> "t5" } */ public StringTemplate getDOTForDependencyGraph(boolean showAttributes) { String structure = "digraph StringTemplateDependencyGraph {\n" + "node [shape=$shape$, $if(width)$width=$width$,$endif$" + " $if(height)$height=$height$,$endif$ fontsize=$fontsize$];\n" + "$edges:{e|\"$e.src$\" -> \"$e.trg$\"\n}$" + "}\n"; StringTemplate graphST = new StringTemplate(structure); HashMap edges = new HashMap(); this.getDependencyGraph(edges, showAttributes); Set sourceNodes = edges.keySet(); // for each source template for (Iterator it = sourceNodes.iterator(); it.hasNext();) { String src = (String) it.next(); Set targetNodes = (Set)edges.get(src); // for each target template for (Iterator it2 = targetNodes.iterator(); it2.hasNext();) { String trg = (String) it2.next(); graphST.setAttribute("edges.{src,trg}", src, trg); } } graphST.setAttribute("shape", "none"); graphST.setAttribute("fontsize", "11"); graphST.setAttribute("height", "0"); // make height return graphST; } /** Get a list of n->m edges where template n contains template m. * The map you pass in is filled with edges: key->value. Useful * for having DOT print out an enclosing template graph. It * finds all direct template invocations too like <foo()> but not * indirect ones like <(name)()>. * * Ack, I just realized that this is done statically and hence * cannot see runtime arg values on statically included templates. * Hmm...someday figure out to do this dynamically as if we were * evaluating the templates. There will be extra nodes in the tree * because we are static like method and method[...] with args. */ public void getDependencyGraph(Map edges, boolean showAttributes) { String srcNode = this.getTemplateHeaderString(showAttributes); if ( attributes!=null ) { Set attrNames = attributes.keySet(); for (Iterator iter = attrNames.iterator(); iter.hasNext();) { String name = (String) iter.next(); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { String targetNode = ((StringTemplate)value).getTemplateHeaderString(showAttributes); putToMultiValuedMap(edges,srcNode,targetNode); ((StringTemplate)value).getDependencyGraph(edges,showAttributes); // descend } else { if ( value instanceof List ) { List alist = (List)value; for (int i = 0; i < alist.size(); i++) { Object o = (Object) alist.get(i); if ( o instanceof StringTemplate ) { String targetNode = ((StringTemplate)o).getTemplateHeaderString(showAttributes); putToMultiValuedMap(edges,srcNode,targetNode); ((StringTemplate)o).getDependencyGraph(edges,showAttributes); // descend } } } else if ( value instanceof Map ) { Map m = (Map)value; Collection mvalues = m.values(); for (Iterator iterator = mvalues.iterator(); iterator.hasNext();) { Object o = (Object) iterator.next(); if ( o instanceof StringTemplate ) { String targetNode = ((StringTemplate)o).getTemplateHeaderString(showAttributes); putToMultiValuedMap(edges,srcNode,targetNode); ((StringTemplate)o).getDependencyGraph(edges,showAttributes); // descend } } } } } } // look in chunks too for template refs for (int i = 0; chunks!=null && i < chunks.size(); i++) { Expr expr = (Expr) chunks.get(i); if ( expr instanceof ASTExpr ) { ASTExpr e = (ASTExpr)expr; AST tree = e.getAST(); AST includeAST = new CommonAST(new CommonToken(ActionEvaluator.INCLUDE,"include")); ASTEnumeration it = tree.findAllPartial(includeAST); while (it.hasMoreNodes()) { AST t = (AST) it.nextNode(); String templateInclude = t.getFirstChild().getText(); System.out.println("found include "+templateInclude); putToMultiValuedMap(edges,srcNode,templateInclude); StringTemplateGroup group = getGroup(); if ( group!=null ) { StringTemplate st = group.getInstanceOf(templateInclude); // descend into the reference template st.getDependencyGraph(edges, showAttributes); } } } } } /** Manage a hash table like it has multiple unique values. Map<Object,Set>. */ protected void putToMultiValuedMap(Map map, Object key, Object value) { HashSet bag = (HashSet)map.get(key); if ( bag==null ) { bag = new HashSet(); map.put(key, bag); } bag.add(value); } public void printDebugString() { System.out.println("template-"+getName()+":"); System.out.print("chunks="); System.out.println(chunks.toString()); if ( attributes==null ) { return; } System.out.print("attributes=["); Set attrNames = attributes.keySet(); int n=0; for (Iterator iter = attrNames.iterator(); iter.hasNext();) { if ( n>0 ) { System.out.print(','); } String name = (String) iter.next(); Object value = attributes.get(name); if ( value instanceof StringTemplate ) { System.out.print(name+"="); ((StringTemplate)value).printDebugString(); } else { if ( value instanceof List ) { ArrayList alist = (ArrayList)value; for (int i = 0; i < alist.size(); i++) { Object o = (Object) alist.get(i); System.out.print(name+"["+i+"] is "+o.getClass().getName()+"="); if ( o instanceof StringTemplate ) { ((StringTemplate)o).printDebugString(); } else { System.out.println(o); } } } else { System.out.print(name+"="); System.out.println(value); } } n++; } System.out.print("]\n"); } public String toString() { return toString(StringTemplateWriter.NO_WRAP); } public String toString(int lineWidth) { StringWriter out = new StringWriter(); // Write the output to a StringWriter StringTemplateWriter wr = group.getStringTemplateWriter(out); wr.setLineWidth(lineWidth); try { write(wr); } catch (IOException io) { error("Got IOException writing to writer "+wr.getClass().getName()); } // reset so next toString() does not wrap; normally this is a new writer // each time, but just in case they override the group to reuse the // writer. wr.setLineWidth(StringTemplateWriter.NO_WRAP); return out.toString(); } }
package gov.nih.nci.calab.service.util; import java.util.HashMap; import java.util.Map; public class CaNanoLabConstants { public static final String DOMAIN_MODEL_NAME = "caNanoLab"; public static final String CSM_APP_NAME = "caNanoLab"; public static final String DATE_FORMAT = "MM/dd/yyyy"; public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy"; // Storage element public static final String STORAGE_BOX = "Box"; public static final String STORAGE_SHELF = "Shelf"; public static final String STORAGE_RACK = "Rack"; public static final String STORAGE_FREEZER = "Freezer"; public static final String STORAGE_ROOM = "Room"; public static final String STORAGE_LAB = "Lab"; // DataStatus public static final String MASK_STATUS = "Masked"; public static final String ACTIVE_STATUS = "Active"; // for Container type public static final String OTHER = "Other"; public static final String[] DEFAULT_CONTAINER_TYPES = new String[] { "Tube", "Vial" }; // Sample Container type public static final String ALIQUOT = "Aliquot"; public static final String SAMPLE_CONTAINER = "Sample_container"; // Run Name public static final String RUN = "Run"; // File upload public static final String FILEUPLOAD_PROPERTY = "fileupload.properties"; public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles"; public static final String EMPTY = "N/A"; // File input/output type public static final String INPUT = "Input"; public static final String OUTPUT = "Output"; // zip file name public static final String ALL_FILES = "ALL_FILES"; public static final String URI_SEPERATOR = "/"; // caNanoLab property file public static final String CANANOLAB_PROPERTY = "caNanoLab.properties"; // caLAB Submission property file public static final String SUBMISSION_PROPERTY = "exception.properties"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES, BOOLEAN_NO }; public static final String DEFAULT_SAMPLE_PREFIX = "NANO-"; public static final String DEFAULT_APP_OWNER = "NCICB"; public static final String APP_OWNER; static { String appOwner = PropertyReader.getProperty(CANANOLAB_PROPERTY, "applicationOwner"); if (appOwner == null || appOwner.length() == 0) appOwner = DEFAULT_APP_OWNER; APP_OWNER = appOwner; } public static final String SAMPLE_PREFIX; static { String samplePrefix = PropertyReader.getProperty(CANANOLAB_PROPERTY, "samplePrefix"); if (samplePrefix == null || samplePrefix.length() == 0) samplePrefix = DEFAULT_SAMPLE_PREFIX; SAMPLE_PREFIX = samplePrefix; } public static final String GRID_INDEX_SERVICE_URL; static { String gridIndexServiceURL = PropertyReader.getProperty( CANANOLAB_PROPERTY, "gridIndexServiceURL"); GRID_INDEX_SERVICE_URL = gridIndexServiceURL; } /* * The following Strings are nano specific * */ public static final String COMPOSITION_DENDRIMER_TYPE = "Dendrimer"; public static final String COMPOSITION_POLYMER_TYPE = "Polymer"; public static final String COMPOSITION_LIPOSOME_TYPE = "Liposome"; public static final String COMPOSITION_CARBON_NANOTUBE_TYPE = "Carbon Nanotube"; public static final String COMPOSITION_FULLERENE_TYPE = "Fullerene"; public static final String COMPOSITION_QUANTUM_DOT_TYPE = "Quantum Dot"; public static final String COMPOSITION_METAL_PARTICLE_TYPE = "Metal Particle"; public static final String COMPOSITION_EMULSION_TYPE = "Emulsion"; public static final String COMPOSITION_COMPLEX_PARTICLE_TYPE = "Complex Particle"; public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER }; public static final String[] CARBON_NANOTUBE_WALLTYPES = new String[] { "Single (SWNT)", "Double (DWMT)", "Multiple (MWNT)" }; public static final String REPORT = "Report"; public static final String ASSOCIATED_FILE = "Other Associated File"; public static final String PROTOCOL_FILE = "Protocol File"; public static final String FOLDER_WORKFLOW_DATA = "workflow_data"; public static final String FOLDER_PARTICLE = "particles"; public static final String FOLDER_REPORT = "reports"; public static final String FOLDER_PROTOCOL = "protocols"; public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] { "Free Radicals", "Peroxide" }; public static final String[] DEFAULT_DENDRIMER_BRANCHES = new String[] { "1-2", "1-3" }; public static final String[] DEFAULT_DENDRIMER_GENERATIONS = new String[] { "0", "0.5", "1.0", "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "5.0", "5.5", "6.0", "6.5", "7.0", "7.5", "8.0", "8.5", "9.0", "9.5", "10.0" }; public static final String CHARACTERIZATION_FILE = "characterizationFile"; public static final String DNA = "DNA"; public static final String PEPTIDE = "Peptide"; public static final String SMALL_MOLECULE = "Small Molecule"; public static final String PROBE = "Probe"; public static final String ANTIBODY = "Antibody"; public static final String IMAGE_CONTRAST_AGENT = "Image Contrast Agent"; public static final String ATTACHMENT = "Attachment"; public static final String ENCAPSULATION = "Encapsulation"; public static final String[] FUNCTION_AGENT_TYPES = new String[] { DNA, PEPTIDE, SMALL_MOLECULE, PROBE, ANTIBODY, IMAGE_CONTRAST_AGENT }; public static final String[] FUNCTION_LINKAGE_TYPES = new String[] { ATTACHMENT, ENCAPSULATION }; public static final String RECEPTOR = "Receptor"; public static final String ANTIGEN = "Antigen"; public static final int MAX_VIEW_TITLE_LENGTH = 23; public static final String[] SPECIES_SCIENTIFIC = { "Mus musculus", "Homo sapiens", "Rattus rattus", "Sus scrofa", "Meriones unguiculatus", "Mesocricetus auratus", "Cavia porcellus", "Bos taurus", "Canis familiaris", "Capra hircus", "Equus Caballus", "Ovis aries", "Felis catus", "Saccharomyces cerevisiae", "Danio rerio" }; public static final String[] SPECIES_COMMON = { "Mouse", "Human", "Rat", "Pig", "Mongolian Gerbil", "Hamster", "Guinea pig", "Cattle", "Dog", "Goat", "Horse", "Sheep", "Cat", "Yeast", "Zebrafish" }; public static final String UNIT_PERCENT = "%"; public static final String UNIT_CFU = "CFU"; public static final String UNIT_RFU = "RFU"; public static final String UNIT_SECOND = "SECOND"; public static final String UNIT_MG_ML = "mg/ml"; public static final String UNIT_FOLD = "Fold"; public static final String ORGANIC_HYDROCARBON = "organic:hydrocarbon"; public static final String ORGANIC_CARBON = "organic:carbon"; public static final String ORGANIC = "organic"; public static final String INORGANIC = "inorganic"; public static final String COMPLEX = "complex"; public static final Map<String, String> PARTICLE_CLASSIFICATION_MAP; static { PARTICLE_CLASSIFICATION_MAP = new HashMap<String, String>(); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_DENDRIMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_POLYMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_FULLERENE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_CARBON_NANOTUBE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_LIPOSOME_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_EMULSION_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_METAL_PARTICLE_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP .put(COMPOSITION_QUANTUM_DOT_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP.put(COMPOSITION_COMPLEX_PARTICLE_TYPE, COMPLEX); } public static final String CSM_PI = APP_OWNER + "_PI"; public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher"; public static final String CSM_ADMIN = APP_OWNER + "_Administrator"; public static final String CSM_PUBLIC_GROUP = "Public"; public static final String[] VISIBLE_GROUPS = new String[] { CSM_PI, CSM_RESEARCHER }; public static final String AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX = "copy_"; public static final String AUTO_COPY_CHARACTERIZATION_VIEW_COLOR = "red"; public static final String UNIT_TYPE_CONCENTRATION = "Concentration"; public static final String UNIT_TYPE_CHARGE = "Charge"; public static final String UNIT_TYPE_QUANTITY = "Quantity"; public static final String UNIT_TYPE_AREA = "Area"; public static final String UNIT_TYPE_SIZE = "Size"; public static final String UNIT_TYPE_VOLUME = "Volume"; public static final String UNIT_TYPE_MOLECULAR_WEIGHT = "Molecular Weight"; public static final String UNIT_TYPE_ZETA_POTENTIAL = "Zeta Potential"; public static final String CSM_READ_ROLE = "R"; public static final String CSM_DELETE_ROLE = "D"; public static final String CSM_EXECUTE_ROLE = "E"; public static final String CSM_CURD_ROLE = "CURD"; public static final String CSM_CUR_ROLE = "CUR"; public static final String CSM_READ_PRIVILEGE = "READ"; public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE"; public static final String CSM_DELETE_PRIVILEGE = "DELETE"; public static final String CSM_CREATE_PRIVILEGE = "CREATE"; public static final String CSM_PG_SAMPLE = "sample"; public static final String CSM_PG_PROTOCOL = "protocol"; public static final String CSM_PG_PARTICLE = "nanoparticle"; public static final String CSM_PG_REPORT = "report"; public static final String PHYSICAL_ASSAY_PROTOCOL = "Physical assay"; public static final String INVITRO_ASSAY_PROTOCOL = "In Vitro assay"; public static final String PHYSICAL_CHARACTERIZATION_CATEGORY = "Physical"; public static final String IN_VITRO_CHARACTERIZATION_CATEGORY = "In Vitro"; /* image file name extension */ public static final String JPG_FILE_EXT = "jpg"; public static final String GIF_FILE_EXT = "gif"; public static final String TIF_FILE_EXT = "tif"; public static final String PNG_FILE_EXT = "png"; }
package org.apache.xerces.impl.xs; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.dv.xs.*; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.XSCMValidator; import java.util.Vector; /** * Constaints shared by traversers and validator * * @author Sandy Gao, IBM * * @version $Id$ */ public class XSConstraints { static final int OCCURRENCE_UNKNOWN = SchemaSymbols.OCCURRENCE_UNBOUNDED-1; /** * check whether derived is valid derived from base, given a subset * of {restriction, extension}. */ public static boolean checkTypeDerivationOk(XSTypeDecl derived, XSTypeDecl base, int block) { // if derived is anyType, then it's valid only if base is anyType too if (derived == SchemaGrammar.fAnyType) return derived == base; // if derived is anySimpleType, then it's valid only if the base // is ur-type if (derived == SchemaGrammar.fAnySimpleType) { return (base == SchemaGrammar.fAnyType || base == SchemaGrammar.fAnySimpleType); } // if derived is simple type if (derived.getXSType() == XSTypeDecl.SIMPLE_TYPE) { // if base is complex type if (base.getXSType() == XSTypeDecl.COMPLEX_TYPE) { // if base is anyType, change base to anySimpleType, // otherwise, not valid if (base == SchemaGrammar.fAnyType) base = SchemaGrammar.fAnySimpleType; else return false; } return checkSimpleDerivation((DatatypeValidator)derived, (DatatypeValidator)base, block); } else { return checkComplexDerivation((XSComplexTypeDecl)derived, base, block); } } /** * check whether simple type derived is valid derived from base, * given a subset of {restriction, extension}. */ public static boolean checkSimpleDerivationOk(DatatypeValidator derived, XSTypeDecl base, int block) { // if derived is anySimpleType, then it's valid only if the base // is ur-type if (derived == SchemaGrammar.fAnySimpleType) { return (base == SchemaGrammar.fAnyType || base == SchemaGrammar.fAnySimpleType); } // if base is complex type if (base.getXSType() == XSTypeDecl.COMPLEX_TYPE) { // if base is anyType, change base to anySimpleType, // otherwise, not valid if (base == SchemaGrammar.fAnyType) base = SchemaGrammar.fAnySimpleType; else return false; } return checkSimpleDerivation((DatatypeValidator)derived, (DatatypeValidator)base, block); } /** * check whether complex type derived is valid derived from base, * given a subset of {restriction, extension}. */ public static boolean checkComplexDerivationOk(XSComplexTypeDecl derived, XSTypeDecl base, int block) { // if derived is anyType, then it's valid only if base is anyType too if (derived == SchemaGrammar.fAnyType) return derived == base; return checkComplexDerivation((XSComplexTypeDecl)derived, base, block); } /** * Note: this will be a private method, and it assumes that derived is not * anySimpleType, and base is not anyType. Another method will be * introduced for public use, which will call this method. */ private static boolean checkSimpleDerivation(DatatypeValidator derived, DatatypeValidator base, int block) { // 1 They are the same type definition. if (derived == base) return true; // 2 All of the following must be true: // 2.1 restriction is not in the subset, or in the {final} of its own {base type definition}; if ((block & SchemaSymbols.RESTRICTION) != 0 || (derived.getBaseValidator().getFinalSet() & SchemaSymbols.RESTRICTION) != 0) { return false; } // 2.2 One of the following must be true: // 2.2.1 D's base type definition is B. DatatypeValidator directBase = derived.getBaseValidator(); if (directBase == base) return true; // 2.2.2 D's base type definition is not the simple ur-type definition and is validly derived from B given the subset, as defined by this constraint. if (directBase != SchemaGrammar.fAnySimpleType && checkSimpleDerivation(directBase, base, block)) { return true; } // 2.2.3 D's {variety} is list or union and B is the simple ur-type definition. if ((derived instanceof ListDatatypeValidator || derived instanceof UnionDatatypeValidator) && base == SchemaGrammar.fAnySimpleType) { return true; } // 2.2.4 B's {variety} is union and D is validly derived from a type definition in B's {member type definitions} given the subset, as defined by this constraint. if (base instanceof UnionDatatypeValidator) { Vector subUnionMemberDV = ((UnionDatatypeValidator)base).getBaseValidators(); int subUnionSize = subUnionMemberDV.size(); for (int i=0; i<subUnionSize; i++) { base = (DatatypeValidator)subUnionMemberDV.elementAt(i); if (checkSimpleDerivation(derived, base, block)) return true; } } return false; } /** * Note: this will be a private method, and it assumes that derived is not * anyType. Another method will be introduced for public use, * which will call this method. */ private static boolean checkComplexDerivation(XSComplexTypeDecl derived, XSTypeDecl base, int block) { // 2.1 B and D must be the same type definition. if (derived == base) return true; // 1 If B and D are not the same type definition, then the {derivation method} of D must not be in the subset. if ((derived.fDerivedBy & block) != 0) return false; // 2 One of the following must be true: XSTypeDecl directBase = derived.fBaseType; // 2.2 B must be D's {base type definition}. if (directBase == base) return true; // 2.3 All of the following must be true: // 2.3.1 D's {base type definition} must not be the ur-type definition. if (directBase == SchemaGrammar.fAnyType || directBase == SchemaGrammar.fAnySimpleType) { return false; } // 2.3.2 The appropriate case among the following must be true: // 2.3.2.1 If D's {base type definition} is complex, then it must be validly derived from B given the subset as defined by this constraint. if (directBase.getXSType() == XSTypeDecl.COMPLEX_TYPE) return checkComplexDerivation((XSComplexTypeDecl)directBase, base, block); // 2.3.2.2 If D's {base type definition} is simple, then it must be validly derived from B given the subset as defined in Type Derivation OK (Simple) (3.14.6). if (directBase.getXSType() == XSTypeDecl.SIMPLE_TYPE) { // if base is complex type if (base.getXSType() == XSTypeDecl.COMPLEX_TYPE) { // if base is anyType, change base to anySimpleType, // otherwise, not valid if (base == SchemaGrammar.fAnyType) base = SchemaGrammar.fAnySimpleType; else return false; } return checkSimpleDerivation((DatatypeValidator)directBase, (DatatypeValidator)base, block); } return false; } /** * check whether a value is a valid default for some type * returns the compiled form of the value */ public static Object ElementDefaultValidImmediate(XSTypeDecl type, String value) { DatatypeValidator dv = null; // e-props-correct // For a string to be a valid default with respect to a type definition the appropriate case among the following must be true: // 1 If the type definition is a simple type definition, then the string must be valid with respect to that definition as defined by String Valid (3.14.4). if (type.getXSType() == XSTypeDecl.SIMPLE_TYPE) { dv = (DatatypeValidator)type; } // 2 If the type definition is a complex type definition, then all of the following must be true: else { // 2.1 its {content type} must be a simple type definition or mixed. XSComplexTypeDecl ctype = (XSComplexTypeDecl)type; // 2.2 The appropriate case among the following must be true: // 2.2.1 If the {content type} is a simple type definition, then the string must be valid with respect to that simple type definition as defined by String Valid (3.14.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { dv = ctype.fDatatypeValidator; } // 2.2.2 If the {content type} is mixed, then the {content type}'s particle must be emptiable as defined by Particle Emptiable (3.9.6). else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { if (!ctype.fParticle.emptiable()) return null; } else { return null; } } // get the simple type declaration, and validate Object actualValue = null; if (dv != null) { try { // REVISIT: we'll be able to do this once he datatype redesign is implemented //actualValue = dv.validate(value, null); dv.validate(value, null); actualValue = value; } catch (InvalidDatatypeValueException ide) { } } return actualValue; } /** * used to check the 3 constraints against each complex type * (should be each model group): * Unique Particle Attribution, Particle Derivation (Restriction), * Element Declrations Consistent. */ public static void fullSchemaChecking(XSGrammarResolver grammarResolver, SubstitutionGroupHandler SGHandler, CMBuilder cmBuilder, XMLErrorReporter errorReporter) { // get all grammars, and put all substitution group information // in the substitution group handler SchemaGrammar[] grammars = grammarResolver.getGrammars(); for (int i = grammars.length-1; i >= 0; i SGHandler.addSubstitutionGroup(grammars[i].getSubstitutionGroups()); } // for each complex type, check the 3 constraints. // types need to be checked XSComplexTypeDecl[] types; // to hold the errors // REVISIT: do we want to report all errors? or just one? //XMLSchemaError1D errors = new XMLSchemaError1D(); // whether need to check this type again; // whether only do UPA checking boolean further, fullChecked; // if do all checkings, how many need to be checked again. int keepType; // i: grammar; j: type; k: error // for all grammars for (int i = grammars.length-1, j, k; i >= 0; i // get whether only check UPA, and types need to be checked keepType = 0; fullChecked = grammars[i].fFullChecked; types = grammars[i].getUncheckedComplexTypeDecls(); // for each type for (j = types.length-1; j >= 0; j // if only do UPA checking, skip the other two constraints if (!fullChecked) { // 1. Element Decl Consistent } // 2. Particle Derivation if (types[j].fBaseType != null && types[j].fBaseType != SchemaGrammar.fAnyType && types[j].fDerivedBy == SchemaSymbols.RESTRICTION && types[j].fParticle !=null && (types[j].fBaseType instanceof XSComplexTypeDecl) && ((XSComplexTypeDecl)(types[j].fBaseType)).fParticle != null) { try { particleValidRestriction(SGHandler, types[j].fParticle, ((XSComplexTypeDecl)(types[j].fBaseType)).fParticle); } catch (XMLSchemaException e) { errorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, e.getKey(), e.getArgs(), XMLErrorReporter.SEVERITY_ERROR); errorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "derivation-ok-restriction.5.3", new Object[]{types[j].fName}, XMLErrorReporter.SEVERITY_ERROR); } } // 3. UPA // get the content model and check UPA XSCMValidator cm = types[j].getContentModel(cmBuilder); further = false; if (cm != null) { try { further = cm.checkUniqueParticleAttribution(SGHandler); } catch (XMLSchemaException e) { errorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, e.getKey(), e.getArgs(), XMLErrorReporter.SEVERITY_ERROR); } } // now report all errors // REVISIT: do we want to report all errors? or just one? /*for (k = errors.getErrorCodeNum()-1; k >= 0; k--) { errorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, errors.getErrorCode(k), errors.getArgs(k), XMLErrorReporter.SEVERITY_ERROR); }*/ // if we are doing all checkings, and this one needs further // checking, store it in the type array. if (!fullChecked && further) types[keepType++] = types[j]; // clear errors for the next type. // REVISIT: do we want to report all errors? or just one? //errors.clear(); } // we've done with the types in this grammar. if we are checking // all constraints, need to trim type array to a proper size: // only contain those need further checking. // and mark this grammar that it only needs UPA checking. if (!fullChecked) { grammars[i].setUncheckedTypeNum(keepType); grammars[i].fFullChecked = true; } } } /* Check that a given particle is a valid restriction of a base particle. */ public static void particleValidRestriction(SubstitutionGroupHandler sgHandler, XSParticleDecl dParticle, XSParticleDecl bParticle) throws XMLSchemaException { // Invoke particleValidRestriction with a substitution group handler for each // particle. particleValidRestriction(dParticle, sgHandler, bParticle, sgHandler); } private static void particleValidRestriction(XSParticleDecl dParticle, SubstitutionGroupHandler dSGHandler, XSParticleDecl bParticle, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { Vector dChildren = null; Vector bChildren = null; int dMinEffectiveTotalRange=OCCURRENCE_UNKNOWN; int dMaxEffectiveTotalRange=OCCURRENCE_UNKNOWN; // Check for empty particles. If either base or derived particle is empty, // (and the other isn't) it's an error. if (! (dParticle.isEmpty() == bParticle.isEmpty())) { throw new XMLSchemaException("cos-particle-restrict", null); } // Do setup prior to invoking the Particle (Restriction) cases. // This involves: // - removing pointless occurrences for groups, and retrieving a vector of // non-pointless children // - turning top-level elements with substitution groups into CHOICE groups. int dType = dParticle.fType; // Handle pointless groups for the derived particle if (dType == XSParticleDecl.PARTICLE_SEQUENCE || dType == XSParticleDecl.PARTICLE_CHOICE || dType == XSParticleDecl.PARTICLE_ALL) { // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl dtmp = getNonUnaryGroup(dParticle); if (dtmp != dParticle) { // Particle has been replaced. Retrieve new type info. dParticle = dtmp; dType = dParticle.fType; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. dChildren = removePointlessChildren(dParticle); } int dMinOccurs = dParticle.fMinOccurs; int dMaxOccurs = dParticle.fMaxOccurs; // For elements which are the heads of substitution groups, treat as CHOICE if (dSGHandler != null && dType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl dElement = (XSElementDecl)dParticle.fValue; if (dElement.isGlobal()) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] subGroup = dSGHandler.getSubstitutionGroup(dElement); if (subGroup.length >0 ) { // Now, set the type to be CHOICE. The "group" will have the same // occurrence information as the original particle. dType = XSParticleDecl.PARTICLE_CHOICE; dMinOccurs = dParticle.fMinOccurs; dMaxOccurs = dParticle.fMaxOccurs; dMinEffectiveTotalRange = dMinOccurs; dMaxEffectiveTotalRange = dMaxOccurs; // Fill in the vector of children dChildren = new Vector(subGroup.length+1); for (int i = 0; i < subGroup.length; i++) { addElementToParticleVector(dChildren, subGroup[i]); } addElementToParticleVector(dChildren, dElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. dSGHandler = null; } } } int bType = bParticle.fType; // Handle pointless groups for the base particle if (bType == XSParticleDecl.PARTICLE_SEQUENCE || bType == XSParticleDecl.PARTICLE_CHOICE || bType == XSParticleDecl.PARTICLE_ALL) { // Find a group, starting with this particle, with more than 1 child. There // may be none, and the particle of interest trivially becomes an element or // wildcard. XSParticleDecl btmp = getNonUnaryGroup(bParticle); if (btmp != bParticle) { // Particle has been replaced. Retrieve new type info. bParticle = btmp; bType = bParticle.fType; } // Fill in a vector with the children of the particle, removing any // pointless model groups in the process. bChildren = removePointlessChildren(bParticle); } int bMinOccurs = bParticle.fMinOccurs; int bMaxOccurs = bParticle.fMaxOccurs; if (bSGHandler != null && bType == XSParticleDecl.PARTICLE_ELEMENT) { XSElementDecl bElement = (XSElementDecl)bParticle.fValue; if (bElement.isGlobal()) { // Check for subsitution groups. Treat any element that has a // subsitution group as a choice. Fill in the children vector with the // members of the substitution group XSElementDecl[] bsubGroup = bSGHandler.getSubstitutionGroup(bElement); if (bsubGroup.length >0 ) { // Now, set the type to be CHOICE bType = XSParticleDecl.PARTICLE_CHOICE; bMinOccurs = bParticle.fMinOccurs; bMaxOccurs = bParticle.fMaxOccurs; bChildren = new Vector(bsubGroup.length+1); for (int i = 0; i < bsubGroup.length; i++) { addElementToParticleVector(bChildren, bsubGroup[i]); } addElementToParticleVector(bChildren, bElement); // Set the handler to null, to indicate that we've finished handling // substitution groups for this particle. bSGHandler = null; } } } // O.K. - Figure out which particle derivation rule applies and call it switch (dType) { case XSParticleDecl.PARTICLE_ELEMENT: { switch (bType) { // Elt:Elt NameAndTypeOK case XSParticleDecl.PARTICLE_ELEMENT: { checkNameAndTypeOK((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSElementDecl)bParticle.fValue,bMinOccurs,bMaxOccurs); return; } // Elt:Any NSCompat case XSParticleDecl.PARTICLE_WILDCARD: { checkNSCompat((XSElementDecl)dParticle.fValue,dMinOccurs,dMaxOccurs, (XSWildcardDecl)bParticle.fValue,bMinOccurs,bMaxOccurs); return; } // Elt:All RecurseAsIfGroup case XSParticleDecl.PARTICLE_CHOICE: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_SEQUENCE: case XSParticleDecl.PARTICLE_ALL: { // Treat the element as if it were in a group of the same type // as the base Particle dChildren = new Vector(); dChildren.addElement(dParticle); checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSParticleDecl.PARTICLE_WILDCARD: { switch (bType) { // Any:Any NSSubset case XSParticleDecl.PARTICLE_WILDCARD: { checkNSSubset((XSWildcardDecl)dParticle.fValue, dMinOccurs, dMaxOccurs, (XSWildcardDecl)bParticle.fValue, bMinOccurs, bMaxOccurs); return; } case XSParticleDecl.PARTICLE_CHOICE: case XSParticleDecl.PARTICLE_SEQUENCE: case XSParticleDecl.PARTICLE_ALL: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"any:choice,sequence,all,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSParticleDecl.PARTICLE_ALL: { switch (bType) { // All:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs); return; } case XSParticleDecl.PARTICLE_ALL: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_CHOICE: case XSParticleDecl.PARTICLE_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"all:choice,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSParticleDecl.PARTICLE_CHOICE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs); return; } case XSParticleDecl.PARTICLE_CHOICE: { checkRecurseLax(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_ALL: case XSParticleDecl.PARTICLE_SEQUENCE: case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"choice:all,sequence,elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } case XSParticleDecl.PARTICLE_SEQUENCE: { switch (bType) { // Choice:Any NSRecurseCheckCardinality case XSParticleDecl.PARTICLE_WILDCARD: { if (dMinEffectiveTotalRange != OCCURRENCE_UNKNOWN) dMinEffectiveTotalRange = dParticle.minEffectiveTotalRange(); if (dMaxEffectiveTotalRange != OCCURRENCE_UNKNOWN) dMaxEffectiveTotalRange = dParticle.maxEffectiveTotalRange(); checkNSRecurseCheckCardinality(dChildren, dMinEffectiveTotalRange, dMaxEffectiveTotalRange, dSGHandler, bParticle,bMinOccurs,bMaxOccurs); return; } case XSParticleDecl.PARTICLE_ALL: { checkRecurseUnordered(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_SEQUENCE: { checkRecurse(dChildren, dMinOccurs, dMaxOccurs, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_CHOICE: { int min1 = dMinOccurs * dChildren.size(); int max1 = (dMaxOccurs == SchemaSymbols.OCCURRENCE_UNBOUNDED)? dMaxOccurs : dMaxOccurs * dChildren.size(); checkMapAndSum(dChildren, min1, max1, dSGHandler, bChildren, bMinOccurs, bMaxOccurs, bSGHandler); return; } case XSParticleDecl.PARTICLE_ELEMENT: { throw new XMLSchemaException("cos-particle-restrict.2", new Object[]{"seq:elt"}); } default: { throw new XMLSchemaException("Internal-Error", new Object[]{"in particleValidRestriction"}); } } } } } private static void addElementToParticleVector (Vector v, XSElementDecl d) { XSParticleDecl p = new XSParticleDecl(); p.fValue = d; p.fType = XSParticleDecl.PARTICLE_ELEMENT; v.addElement(p); } private static XSParticleDecl getNonUnaryGroup(XSParticleDecl p) { if (p.fType == XSParticleDecl.PARTICLE_ELEMENT || p.fType == XSParticleDecl.PARTICLE_WILDCARD) return p; if (p.fMinOccurs==1 && p.fMaxOccurs==1 && p.fValue!=null && p.fOtherValue==null) return getNonUnaryGroup((XSParticleDecl)p.fValue); else return p; } private static Vector removePointlessChildren(XSParticleDecl p) { if (p.fType == XSParticleDecl.PARTICLE_ELEMENT || p.fType == XSParticleDecl.PARTICLE_WILDCARD || p.fType == XSParticleDecl.PARTICLE_EMPTY) return null; Vector children = new Vector(); gatherChildren(p.fType, (XSParticleDecl)p.fValue, children); if (p.fOtherValue != null) { gatherChildren(p.fType, (XSParticleDecl)p.fOtherValue, children); } return children; } private static void gatherChildren(int parentType, XSParticleDecl p, Vector children) { int min = p.fMinOccurs; int max = p.fMaxOccurs; int type = p.fType; if (type == XSParticleDecl.PARTICLE_EMPTY) return; if (type == XSParticleDecl.PARTICLE_ELEMENT || type== XSParticleDecl.PARTICLE_WILDCARD) { children.addElement(p); return; } XSParticleDecl left = (XSParticleDecl)p.fValue; XSParticleDecl right = (XSParticleDecl)p.fOtherValue; if (! (min==1 && max==1)) { children.addElement(p); } else if (parentType == type) { gatherChildren(type,left,children); if (right != null) { gatherChildren(type,right,children); } } else if (!p.isEmpty()) { children.addElement(p); } } private static void checkNameAndTypeOK(XSElementDecl dElement, int dMin, int dMax, XSElementDecl bElement, int bMin, int bMax) throws XMLSchemaException { // Check that the names are the same if (dElement.fName != bElement.fName || dElement.fTargetNamespace != bElement.fTargetNamespace) { throw new XMLSchemaException( "rcase-NameAndTypeOK.1",new Object[]{dElement.fName, dElement.fTargetNamespace, bElement.fName, bElement.fTargetNamespace}); } // Check nillable if (! (bElement.isNillable() || !dElement.isNillable())) { throw new XMLSchemaException("rcase-NameAndTypeOK.2", new Object[]{dElement.fName}); } // Check occurrence range if (!checkOccurrenceRange(dMin, dMax, bMin, bMax)) { throw new XMLSchemaException("rcase-NameAndTypeOK.3", new Object[]{dElement.fName}); } // Check for consistent fixed values if (bElement.getConstraintType() == XSElementDecl.FIXED_VALUE) { // check the values are the same. NB - this should not be a string // comparison REVISIT when we have new datatype design! String baseFixedValue=(String) bElement.fDefault; String thisFixedValue=(String) dElement.fDefault; if (dElement.getConstraintType() != XSElementDecl.FIXED_VALUE || !baseFixedValue.equals(thisFixedValue)) { throw new XMLSchemaException("rcase-NameAndTypeOK.4", new Object[]{dElement.fName}); } } // Check identity constraints checkIDConstraintRestriction(dElement, bElement); // Check for disallowed substitutions int blockSet1 = dElement.fBlock; int blockSet2 = bElement.fBlock; if (((blockSet1 & blockSet2)!=blockSet2) || (blockSet1==SchemaSymbols.EMPTY_SET && blockSet2!=SchemaSymbols.EMPTY_SET)) throw new XMLSchemaException("rcase-NameAndTypeOK.6", new Object[]{dElement.fName}); // Check that the derived element's type is derived from the base's. if (!checkTypeDerivationOk(dElement.fType, bElement.fType, bElement.fFinal)) { throw new XMLSchemaException("rcase-NameAndTypeOK.7", new Object[]{dElement.fName}); } } private static void checkIDConstraintRestriction(XSElementDecl derivedElemDecl, XSElementDecl baseElemDecl) throws XMLSchemaException { // TODO } // checkIDConstraintRestriction private static boolean checkOccurrenceRange(int min1, int max1, int min2, int max2) { if ((min1 >= min2) && ((max2==SchemaSymbols.OCCURRENCE_UNBOUNDED) || (max1!=SchemaSymbols.OCCURRENCE_UNBOUNDED && max1<=max2))) return true; else return false; } private static void checkNSCompat(XSElementDecl elem, int min1, int max1, XSWildcardDecl wildcard, int min2, int max2) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-NSCompat.2", new Object[]{elem.fName}); } // check wildcard allows namespace of element if (!wildcard.allowNamespace(elem.fTargetNamespace)) { throw new XMLSchemaException("rcase-NSCompat.1", new Object[]{elem.fName,elem.fTargetNamespace}); } } private static void checkNSSubset(XSWildcardDecl dWildcard, int min1, int max1, XSWildcardDecl bWildcard, int min2, int max2) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-NSSubset.2",null); } // check wildcard subset if (!dWildcard.isSubsetOf(bWildcard)) { throw new XMLSchemaException("rcase-NSSubset.1",null); } } private static void checkNSRecurseCheckCardinality(Vector children, int min1, int max1, SubstitutionGroupHandler dSGHandler, XSParticleDecl wildcard, int min2, int max2) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-NSRecurseCheckCardinality.2", null); } // Check that each member of the group is a valid restriction of the wildcard int count = children.size(); try { for (int i = 0; i < count; i++) { XSParticleDecl particle1 = (XSParticleDecl)children.elementAt(i); particleValidRestriction(particle1, dSGHandler, wildcard, null); } } catch (XMLSchemaException e) { throw new XMLSchemaException("rcase-NSRecurseCheckCardinality.1", null); } } private static void checkRecurse(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-Recurse.1", null); } int count1= dChildren.size(); int count2= bChildren.size(); int current = 0; label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = current; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); current +=1; try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); continue label; } catch (XMLSchemaException e) { if (!particle2.emptiable()) throw new XMLSchemaException("rcase-Recurse.2", null); } } throw new XMLSchemaException("rcase-Recurse.2", null); } // Now, see if there are some elements in the base we didn't match up for (int j=current; j < count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); if (!particle2.emptiable()) { throw new XMLSchemaException("rcase-Recurse.2", null); } } } private static void checkRecurseUnordered(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-RecurseUnordered.1", null); } int count1= dChildren.size(); int count2 = bChildren.size(); boolean foundIt[] = new boolean[count2]; label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = 0; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); if (foundIt[j]) throw new XMLSchemaException("rcase-RecurseUnordered.2", null); else foundIt[j]=true; continue label; } catch (XMLSchemaException e) { } } // didn't find a match. Detect an error throw new XMLSchemaException("rcase-RecurseUnordered.2", null); } // Now, see if there are some elements in the base we didn't match up for (int j=0; j < count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); if (!foundIt[j] && !particle2.emptiable()) { throw new XMLSchemaException("rcase-RecurseUnordered.2", null); } } } private static void checkRecurseLax(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-RecurseLax.1", null); } int count1= dChildren.size(); int count2 = bChildren.size(); int current = 0; label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = current; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); current +=1; try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); continue label; } catch (XMLSchemaException e) { } } // didn't find a match. Detect an error throw new XMLSchemaException("rcase-RecurseLax.2", null); } } private static void checkMapAndSum(Vector dChildren, int min1, int max1, SubstitutionGroupHandler dSGHandler, Vector bChildren, int min2, int max2, SubstitutionGroupHandler bSGHandler) throws XMLSchemaException { // See if the sequence group is a valid restriction of the choice // Here is an example of a valid restriction: // <choice minOccurs="2"> // </choice> // <sequence> // </sequence> // check Occurrence ranges if (!checkOccurrenceRange(min1,max1,min2,max2)) { throw new XMLSchemaException("rcase-MapAndSum.2", null); } int count1 = dChildren.size(); int count2 = bChildren.size(); label: for (int i = 0; i<count1; i++) { XSParticleDecl particle1 = (XSParticleDecl)dChildren.elementAt(i); for (int j = 0; j<count2; j++) { XSParticleDecl particle2 = (XSParticleDecl)bChildren.elementAt(j); try { particleValidRestriction(particle1, dSGHandler, particle2, bSGHandler); continue label; } catch (XMLSchemaException e) { } } // didn't find a match. Detect an error throw new XMLSchemaException("rcase-MapAndSum.1", null); } } // to check whether two element overlap, as defined in constraint UPA public static boolean overlapUPA(XSElementDecl element1, XSElementDecl element2, SubstitutionGroupHandler sgHandler) { // if the two element have the same name and namespace, if (element1.fName == element2.fName && element1.fTargetNamespace == element2.fTargetNamespace) { return true; } // or if there is an element decl in element1's substitution group, // who has the same name/namespace with element2 XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(element1); for (int i = subGroup.length-1; i >= 0; i if (subGroup[i].fName == element2.fName && subGroup[i].fTargetNamespace == element2.fTargetNamespace) { return true; } } // or if there is an element decl in element2's substitution group, // who has the same name/namespace with element1 subGroup = sgHandler.getSubstitutionGroup(element2); for (int i = subGroup.length-1; i >= 0; i if (subGroup[i].fName == element1.fName && subGroup[i].fTargetNamespace == element1.fTargetNamespace) { return true; } } return false; } // to check whether an element overlaps with a wildcard, // as defined in constraint UPA public static boolean overlapUPA(XSElementDecl element, XSWildcardDecl wildcard, SubstitutionGroupHandler sgHandler) { // if the wildcard allows the element if (wildcard.allowNamespace(element.fTargetNamespace)) return true; // or if the wildcard allows any element in the substitution group XSElementDecl[] subGroup = sgHandler.getSubstitutionGroup(element); for (int i = subGroup.length-1; i >= 0; i if (wildcard.allowNamespace(subGroup[i].fTargetNamespace)) return true; } return false; } public static boolean overlapUPA(XSWildcardDecl wildcard1, XSWildcardDecl wildcard2) { // if the intersection of the two wildcard is not empty list XSWildcardDecl intersect = wildcard1.performIntersectionWith(wildcard2, wildcard1.fProcessContents); if (intersect == null || intersect.fType != XSWildcardDecl.WILDCARD_LIST || intersect.fNamespaceList.length != 0) { return true; } return false; } // call one of the above methods according to the type of decls public static boolean overlapUPA(Object decl1, Object decl2, SubstitutionGroupHandler sgHandler) { if (decl1 instanceof XSElementDecl) { if (decl2 instanceof XSElementDecl) { return overlapUPA((XSElementDecl)decl1, (XSElementDecl)decl2, sgHandler); } else { return overlapUPA((XSElementDecl)decl1, (XSWildcardDecl)decl2, sgHandler); } } else { if (decl2 instanceof XSElementDecl) { return overlapUPA((XSElementDecl)decl2, (XSWildcardDecl)decl1, sgHandler); } else { return overlapUPA((XSWildcardDecl)decl1, (XSWildcardDecl)decl2); } } } } // class XSContraints
package org.opencms.loader; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.staticexport.CmsLinkManager; import org.opencms.util.CmsResourceTranslator; import com.opencms.core.CmsException; import com.opencms.core.CmsRequestHttpServlet; import com.opencms.core.I_CmsConstants; import com.opencms.core.I_CmsRequest; import com.opencms.core.I_CmsResponse; import com.opencms.file.CmsFile; import com.opencms.file.CmsObject; import com.opencms.file.CmsRequestContext; import com.opencms.file.CmsResource; import com.opencms.template.A_CmsXmlContent; import com.opencms.template.CmsRootTemplate; import com.opencms.template.CmsTemplateCache; import com.opencms.template.CmsTemplateClassManager; import com.opencms.template.CmsXmlControlFile; import com.opencms.template.I_CmsTemplate; import com.opencms.template.I_CmsTemplateCache; import com.opencms.template.I_CmsXmlTemplate; import com.opencms.template.cache.CmsElementCache; import com.opencms.template.cache.CmsElementDefinition; import com.opencms.template.cache.CmsElementDefinitionCollection; import com.opencms.template.cache.CmsElementDescriptor; import com.opencms.template.cache.CmsUri; import com.opencms.template.cache.CmsUriDescriptor; import com.opencms.template.cache.CmsUriLocator; import com.opencms.util.Encoder; import java.io.IOException; import java.io.OutputStream; import java.util.Enumeration; import java.util.Hashtable; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import source.org.apache.java.util.Configurations; /** * Implementation of the {@link I_CmsResourceLoader} for * XMLTemplates.<p> * * @author Alexander Kandzior (a.kandzior@alkacon.com) * * @version $Revision: 1.32 $ */ public class CmsXmlTemplateLoader implements I_CmsResourceLoader { /** Magic elemet replace name */ public static final String C_ELEMENT_REPLACE = "_CMS_ELEMENTREPLACE"; /** The id of this loader */ public static final int C_RESOURCE_LOADER_ID = 3; /** Flag for debugging output. Set to 9 for maximum verbosity. */ private static final int DEBUG = 0; /** The element cache used for the online project */ private static CmsElementCache m_elementCache; /** The template cache that holds all cached templates */ protected static I_CmsTemplateCache m_templateCache = new CmsTemplateCache(); /** The variant dependencies for the element cache */ private static Hashtable m_variantDeps; /** * The constructor of the class is empty and does nothing. */ public CmsXmlTemplateLoader() { // NOOP } /** * Compatibility method to ensure the legacy cache command line parameters * are still supported.<p> * * @param clearFiles if true, A_CmsXmlContent cache is cleared * @param clearTemplates if true, internal template cache is cleared */ private static void clearLoaderCache(boolean clearFiles, boolean clearTemplates) { if (clearFiles) { A_CmsXmlContent.clearFileCache(); } if (clearTemplates) { m_templateCache.clearCache(); } } /** * Returns the element cache that belongs to the given cms context, * or null if the element cache is not initialized.<p> * * @param cms the opencms context * @return the element cache that belongs to the given cms context */ public static final CmsElementCache getElementCache(CmsObject cms) { if (cms.getRequestContext().currentProject().isOnlineProject()) { return m_elementCache; } else { return null; } } /** * Returns the variant dependencies of the online element cache.<p> * * @return the variant dependencies of the online element cache */ public static final CmsElementCache getOnlineElementCache() { return m_elementCache; } /** * Returns the hashtable with the variant dependencies used for the elementcache.<p> * * @return the hashtable with the variant dependencies used for the elementcache */ public static final Hashtable getVariantDependencies() { return m_variantDeps; } /** * Returns true if the element cache is enabled for the given cms context.<p> * * @param cms the opencms context * @return true if the element cache is enabled for the given cms context */ public static final boolean isElementCacheEnabled(CmsObject cms) { return (m_elementCache != null) && cms.getRequestContext().currentProject().isOnlineProject(); } /** * Utility method used by the loader implementation to give control * to the CanonicalRoot.<p> * * The CanonicalRoot will call the master template and return a byte array of the * generated output.<p> * * @param cms the cms context object * @param templateClass to generate the output of the master template * @param masterTemplate masterTemplate for the output * @param parameters contains all parameters for the template class * @return the generated output or null if there were errors * @throws CmsException if something goes wrong */ private byte[] callCanonicalRoot(CmsObject cms, I_CmsTemplate templateClass, CmsFile masterTemplate, Hashtable parameters) throws CmsException { try { CmsRootTemplate root = new CmsRootTemplate(); return root.getMasterTemplate(cms, templateClass, masterTemplate, m_templateCache, parameters); } catch (Exception e) { // no document we could show... handleException(cms, e, "Received error while calling canonical root for requested file " + masterTemplate.getName() + ". "); } return null; } /** * Destroy this ResourceLoder, this is a NOOP so far. */ public void destroy() { // NOOP } /** * @see org.opencms.loader.I_CmsResourceLoader#export(com.opencms.file.CmsObject, com.opencms.file.CmsFile) */ public void export(CmsObject cms, CmsFile file) throws CmsException { processXmlTemplate(cms, file); } /** * @see org.opencms.loader.I_CmsResourceLoader#export(com.opencms.file.CmsObject, com.opencms.file.CmsFile, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public byte[] export(CmsObject cms, CmsFile file, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, CmsException { // TODO: get real file translator CmsRequestHttpServlet cmsReq = new CmsRequestHttpServlet(req, new CmsResourceTranslator(new String[0], true)); byte[] result = generateOutput(cms, file, cmsReq); if (result != null) { return result; } else { return "".getBytes(); } } /** * Starts generating the output. * Calls the canonical root with the appropriate template class. * * @param cms CmsObject Object for accessing system resources * @param file CmsFile Object with the selected resource to be shown * @param req the CmsRequest * @return the generated output for the file * @throws CmsException if something goes wrong */ protected byte[] generateOutput(CmsObject cms, CmsFile file, I_CmsRequest req) throws CmsException { byte[] output = null; // Hashtable for collecting all parameters. Hashtable newParameters = new Hashtable(); String uri = cms.getRequestContext().getUri(); // ladies and gentelman: and now for something completly different String absolutePath = cms.readAbsolutePath(file); String templateProp = cms.readProperty(absolutePath, I_CmsConstants.C_PROPERTY_TEMPLATE); String xmlTemplateContent = null; if (templateProp != null) { // i got a black magic template, StringBuffer buf = new StringBuffer(256); buf.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"); buf.append("<PAGE>\n<class>"); buf.append(I_CmsConstants.C_XML_CONTROL_DEFAULT_CLASS); buf.append("</class>\n<masterTemplate>"); // i got a black magic template, buf.append(templateProp); buf.append("</masterTemplate>\n<ELEMENTDEF name=\"body\">\n<CLASS>"); buf.append(I_CmsConstants.C_XML_CONTROL_DEFAULT_CLASS); buf.append("</CLASS>\n<TEMPLATE>"); // i got a black magic template got me so blind I can't see, buf.append(uri); buf.append("</TEMPLATE>\n</ELEMENTDEF>\n</PAGE>\n"); // i got a black magic template it's try'in to make a devil out of me... xmlTemplateContent = buf.toString(); uri += I_CmsConstants.C_XML_CONTROL_FILE_SUFFIX; } // Parameters used for element cache boolean elementCacheEnabled = CmsXmlTemplateLoader.isElementCacheEnabled(cms); CmsElementCache elementCache = null; CmsUriDescriptor uriDesc = null; CmsUriLocator uriLoc = null; CmsUri cmsUri = null; String templateClass = null; String templateName = null; CmsXmlControlFile doc = null; if (elementCacheEnabled) { // Get the global element cache object elementCache = CmsXmlTemplateLoader.getElementCache(cms); // Prepare URI Locator uriDesc = new CmsUriDescriptor(uri); uriLoc = elementCache.getUriLocator(); cmsUri = uriLoc.get(uriDesc); } // check if printversion is requested String replace = req.getParameter(C_ELEMENT_REPLACE); boolean elementreplace = false; CmsElementDefinition replaceDef = null; if (replace != null) { int index = replace.indexOf(":"); if (index != -1) { elementreplace = true; cmsUri = null; String elementName = replace.substring(0, index); String replaceUri = replace.substring(index+1); replaceDef = new CmsElementDefinition(elementName, I_CmsConstants.C_XML_CONTROL_DEFAULT_CLASS, replaceUri, null, new Hashtable()); newParameters.put(C_ELEMENT_REPLACE + "_VFS_" + elementName, cms.getRequestContext().addSiteRoot(replaceUri)); } } if ((cmsUri == null) || !elementCacheEnabled) { // Entry point to page file analysis. // For performance reasons this should only be done if the element // cache is not activated or if it's activated but no URI object could be found. // Parse the page file try { if (xmlTemplateContent == null) { doc = new CmsXmlControlFile(cms, file); } else { doc = new CmsXmlControlFile(cms, uri, xmlTemplateContent); } } catch (Exception e) { // there was an error while parsing the document. // No chance to go on here. handleException(cms, e, "There was an error while parsing XML page file " + cms.readAbsolutePath(file)); return "".getBytes(); } if (! elementCacheEnabled && (replaceDef != null)) { // Required to enable element replacement if element cache is disabled doc.setElementClass(replaceDef.getName(), replaceDef.getClassName()); doc.setElementTemplate(replaceDef.getName(), replaceDef.getTemplateName()); } // Get the names of the master template and the template class from // the parsed page file. Fall back to default value, if template class // is not defined templateClass = doc.getTemplateClass(); if (templateClass == null || "".equals(templateClass)) { templateClass = this.getClass().getName(); } if (templateClass == null || "".equals(templateClass)) { templateClass = I_CmsConstants.C_XML_CONTROL_DEFAULT_CLASS; } templateName = doc.getMasterTemplate(); if (templateName != null && !"".equals(templateName)) { templateName = CmsLinkManager.getAbsoluteUri(templateName, cms.readAbsolutePath(file)); } // Previously, the template class was loaded here. // We avoid doing this so early, since in element cache mode the template // class is not needed here. // Now look for parameters in the page file... // ... first the params of the master template... Enumeration masterTemplateParams = doc.getParameterNames(); while (masterTemplateParams.hasMoreElements()) { String paramName = (String)masterTemplateParams.nextElement(); String paramValue = doc.getParameter(paramName); newParameters.put(I_CmsConstants.C_ROOT_TEMPLATE_NAME + "." + paramName, paramValue); } // ... and now the params of all subtemplates Enumeration elementDefinitions = doc.getElementDefinitions(); while (elementDefinitions.hasMoreElements()) { String elementName = (String)elementDefinitions.nextElement(); if (doc.isElementClassDefined(elementName)) { newParameters.put(elementName + "._CLASS_", doc.getElementClass(elementName)); } if (doc.isElementTemplateDefined(elementName)) { // need to check for the body template here so that non-XMLTemplate templates // like JSPs know where to find the body defined in the XMLTemplate String template = doc.getElementTemplate(elementName); if (xmlTemplateContent == null) { template = doc.validateBodyPath(cms, template, file); } if (I_CmsConstants.C_XML_BODY_ELEMENT.equalsIgnoreCase(elementName)) { // found body element if (template != null) { cms.getRequestContext().setAttribute(I_CmsConstants.C_XML_BODY_ELEMENT, template); } } newParameters.put(elementName + "._TEMPLATE_", template); } if (doc.isElementTemplSelectorDefined(elementName)) { newParameters.put(elementName + "._TEMPLATESELECTOR_", doc.getElementTemplSelector(elementName)); } Enumeration parameters = doc.getElementParameterNames(elementName); while (parameters.hasMoreElements()) { String paramName = (String)parameters.nextElement(); String paramValue = doc.getElementParameter(elementName, paramName); if (paramValue != null) { newParameters.put(elementName + "." + paramName, paramValue); } else { if (OpenCms.getLog(this).isInfoEnabled()) { OpenCms.getLog(this).info("Empty parameter \"" + paramName + "\" found."); } } } } } // URL parameters ary really dynamic. // We cannot store them in an element cache. // Therefore these parameters must be collected in ANY case! String datafor = req.getParameter("datafor"); if (datafor == null) { datafor = ""; } else { if (!"".equals(datafor)) { datafor = datafor + "."; } } Enumeration urlParameterNames = req.getParameterNames(); while (urlParameterNames.hasMoreElements()) { String pname = (String)urlParameterNames.nextElement(); String paramValue = req.getParameter(pname); if (paramValue != null) { if ((!"datafor".equals(pname)) && (!"_clearcache".equals(pname))) { newParameters.put(datafor + pname, paramValue); } } else { if (OpenCms.getLog(this).isInfoEnabled()) { OpenCms.getLog(this).info("Empty URL parameter \"" + pname + "\" found."); } } } if (elementCacheEnabled && (cmsUri == null)) { // No URI could be found in cache. // So create a new URI object with a start element and store it using the UriLocator CmsElementDescriptor elemDesc = new CmsElementDescriptor(templateClass, templateName); CmsElementDefinitionCollection eldefs = doc.getElementDefinitionCollection(); if (elementreplace) { // we cant cach this eldefs.add(replaceDef); cmsUri = new CmsUri(elemDesc, eldefs); } else { cmsUri = new CmsUri(elemDesc, eldefs); elementCache.getUriLocator().put(uriDesc, cmsUri); } } if (elementCacheEnabled) { // now lets get the output if (elementreplace) { output = cmsUri.callCanonicalRoot(elementCache, cms, newParameters); } else { output = elementCache.callCanonicalRoot(cms, newParameters, uri); } } else { // Element cache is deactivated. So let's go on as usual. try { CmsFile masterTemplate = loadMasterTemplateFile(cms, templateName, doc); I_CmsTemplate tmpl = getTemplateClass(templateClass); if (!(tmpl instanceof I_CmsXmlTemplate)) { String errorMessage = "Error in " + cms.readAbsolutePath(file) + ": " + templateClass + " is not a XML template class."; if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(errorMessage); } throw new CmsException(errorMessage, CmsException.C_XML_WRONG_TEMPLATE_CLASS); } // TODO: Make cache more efficient clearLoaderCache(true, true); output = callCanonicalRoot(cms, tmpl, masterTemplate, newParameters); } catch (CmsException e) { if (OpenCms.getLog(this).isWarnEnabled()) { OpenCms.getLog(this); } doc.removeFromFileCache(); throw e; } } return output; } /** * @see org.opencms.loader.I_CmsResourceLoader#getLoaderId() */ public int getLoaderId() { return C_RESOURCE_LOADER_ID; } /** * Return a String describing the ResourceLoader, * which is <code>"The OpenCms default resource loader for XMLTemplates"</code>.<p> * * @return a describing String for the ResourceLoader */ public String getResourceLoaderInfo() { return "The OpenCms default resource loader for XMLTemplates"; } /** * Calls the CmsClassManager to get an instance of the given template class.<p> * * The returned object is checked to be an implementing class of the interface * I_CmsTemplate. * If the template cache of the template class is not yet set up, * this will be done, too.<p> * * @param classname name of the requested template class * @return instance of the template class * @throws CmsException if something goes wrong */ private I_CmsTemplate getTemplateClass(String classname) throws CmsException { if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Getting start template class: " + classname); } Object o = CmsTemplateClassManager.getClassInstance(classname); // Check, if the loaded class really is a OpenCms template class. // This is done be checking the implemented interface. if (!(o instanceof I_CmsTemplate)) { String errorMessage = "Class " + classname + " is not an OpenCms template class."; if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(errorMessage); } throw new CmsException(errorMessage, CmsException.C_XML_NO_TEMPLATE_CLASS); } I_CmsTemplate cmsTemplate = (I_CmsTemplate)o; if (!cmsTemplate.isTemplateCacheSet()) { cmsTemplate.setTemplateCache(m_templateCache); } return cmsTemplate; } /** * Utility method to handle any occurence of an execption.<p> * * If the Exception is NO CmsException (i.e. it was not detected previously) * it will be written to the logfile.<p> * * If the current user is the anonymous user, no further exception will * be thrown, but a server error will be sent * (we want to prevent the user from seeing any exeptions). * Otherwise a new Exception will be thrown. * This will trigger the OpenCms error message box.<p> * * @param cms the cms context object * @param e Exception that should be handled * @param errorText error message that should be shown * @throws CmsException if */ private void handleException(CmsObject cms, Exception e, String errorText) throws CmsException { // log the error if it is no CmsException if (! (e instanceof CmsException)) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(errorText, e); } } // if the user is a guest (and it's not a login exception) we send an servlet error, // otherwise we try to throw an exception. CmsRequestContext reqContext = cms.getRequestContext(); if ((DEBUG == 0) && reqContext.currentUser().isGuestUser() && (!(e instanceof CmsException && ((CmsException)e).getType() == CmsException.C_NO_USER))) { throw new CmsException(errorText, CmsException.C_SERVICE_UNAVAILABLE, e); } else { if (e instanceof CmsException) { throw (CmsException)e; } else { throw new CmsException(errorText, CmsException.C_LOADER_ERROR, e); } } } /** * Initialize the ResourceLoader.<p> * * @param conf the OpenCms configuration */ public void init(Configurations conf) { // Check, if the element cache should be enabled boolean enableElementCache = conf.getBoolean("elementcache.enabled", false); if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Element cache : " + (enableElementCache ? "enabled" : "disabled")); if (enableElementCache) { try { m_elementCache = new CmsElementCache(conf.getInteger("elementcache.uri", 10000), conf.getInteger("elementcache.elements", 50000), conf.getInteger("elementcache.variants", 100)); } catch (Exception e) { if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isWarnEnabled()) OpenCms.getLog(CmsLog.CHANNEL_INIT).warn(". Element cache : non-critical error " + e.toString()); } m_variantDeps = new Hashtable(); m_elementCache.getElementLocator().setExternDependencies(m_variantDeps); } else { m_elementCache = null; } if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) { OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Loader init : " + this.getClass().getName() + " initialized"); } } /** * @see org.opencms.loader.I_CmsResourceLoader#load(com.opencms.file.CmsObject, com.opencms.file.CmsFile, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void load(CmsObject cms, CmsFile file, HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { processXmlTemplate(cms, file); } catch (CmsException e) { throw new ServletException(e.getMessage(), e); } } /** * Internal utility method for checking and loading a given template file. * @param cms CmsObject for accessing system resources. * @param templateName Name of the requestet template file. * @param doc CmsXmlControlFile object containig the parsed body file. * @return CmsFile object of the requested template file. * @throws CmsException if something goes wrong */ private CmsFile loadMasterTemplateFile(CmsObject cms, String templateName, com.opencms.template.CmsXmlControlFile doc) throws CmsException { CmsFile masterTemplate = null; try { masterTemplate = cms.readFile(templateName); } catch (Exception e) { handleException(cms, e, "Cannot load master template " + templateName + ". "); doc.removeFromFileCache(); } return masterTemplate; } /** * Processes the XmlTemplates and writes the result to * the apropriate output stream, which is obtained from the request * context of the cms object.<p> * * @param cms the cms context object * @param file the selected resource to be shown * @throws CmsException if something goes wrong */ private void processXmlTemplate(CmsObject cms, CmsFile file) throws CmsException { // first some debugging output. if ((DEBUG > 0) && OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("Loader started for " + file.getName()); } // check all values to be valid String errorMessage = null; if (file == null) { errorMessage = "CmsFile missing"; } if (cms == null) { errorMessage = "CmsObject missing"; } if (errorMessage != null) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(errorMessage); } throw new CmsException(errorMessage, CmsException.C_LOADER_ERROR); } // Check the clearcache parameter String clearcache = cms.getRequestContext().getRequest().getParameter("_clearcache"); // Clear loader caches if this is required clearLoaderCache(((clearcache != null) && ("all".equals(clearcache) || "file".equals(clearcache))), ((clearcache != null) && ("all".equals(clearcache) || "template".equals(clearcache)))); // get the CmsRequest I_CmsRequest req = cms.getRequestContext().getRequest(); byte[] result = generateOutput(cms, file, req); if (result != null) { writeBytesToResponse(cms, result); } } /** * Does the job of including an XMLTemplate * as a sub-element of a JSP or other resource loaders.<p> * * @param cms used to access the OpenCms VFS * @param file the reqested JSP file resource in the VFS * @param req the current request * @param res the current response * * @throws ServletException might be thrown in the process of including the JSP * @throws IOException might be thrown in the process of including the JSP * * @see com.opencms.flex.cache.CmsFlexRequestDispatcher */ public void service(CmsObject cms, CmsResource file, ServletRequest req, ServletResponse res) throws ServletException, IOException { long timer1; if (DEBUG > 0) { timer1 = System.currentTimeMillis(); System.err.println("============ CmsXmlTemplateLoader loading: " + cms.readAbsolutePath(file)); System.err.println("CmsXmlTemplateLoader.service() cms uri is: " + cms.getRequestContext().getUri()); } // save the original context settings String rnc = cms.getRequestContext().getEncoding().trim(); // String oldUri = cms.getRequestContext().getUri(); I_CmsRequest cms_req = cms.getRequestContext().getRequest(); HttpServletRequest originalreq = (HttpServletRequest)cms_req.getOriginalRequest(); try { // get the CmsRequest byte[] result = null; com.opencms.file.CmsFile fx = cms.readFile(cms.readAbsolutePath(file)); // care about encoding issues String dnc = OpenCms.getDefaultEncoding().trim(); String enc = cms.readProperty(cms.readAbsolutePath(fx), I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, true, dnc).trim(); // fake the called URI (otherwise XMLTemplate / ElementCache would not work) // cms.getRequestContext().setUri(cms.readAbsolutePath(fx)); cms_req.setOriginalRequest(req); cms.getRequestContext().setEncoding(enc); if (DEBUG > 1) { System.err.println("CmsXmlTemplateLoader.service(): Encodig set to " + cms.getRequestContext().getEncoding()); System.err.println("CmsXmlTemplateLoader.service(): Uri set to " + cms.getRequestContext().getUri()); } // process the included XMLTemplate result = generateOutput(cms, fx, cms_req); // append the result to the output stream if (result != null) { // Encoding project: // The byte array must internally be encoded in the OpenCms // default encoding. It will be converted to the requested encoding // on the most top-level JSP element result = Encoder.changeEncoding(result, enc, dnc); if (DEBUG > 1) System.err.println("CmsXmlTemplateLoader.service(): encoding=" + enc + " requestEncoding=" + rnc + " defaultEncoding=" + dnc); res.getOutputStream().write(result); } } catch (Exception e) { if (DEBUG > 0) e.printStackTrace(System.err); throw new ServletException("Error in CmsXmlTemplateLoader while processing " + cms.readAbsolutePath(file), e); } finally { // restore the context settings cms_req.setOriginalRequest(originalreq); cms.getRequestContext().setEncoding(rnc); // cms.getRequestContext().setUri(oldUri); if (DEBUG > 1) { System.err.println("CmsXmlTemplateLoader.service(): Encodig reset to " + cms.getRequestContext().getEncoding()); System.err.println("CmsXmlTemplateLoader.service(): Uri reset to " + cms.getRequestContext().getUri()); } } if (DEBUG > 0) { long timer2 = System.currentTimeMillis() - timer1; System.err.println("============ CmsXmlTemplateLoader time delivering XmlTemplate for " + cms.readAbsolutePath(file) + ": " + timer2 + "ms"); } } /** * Writes a given byte array to the HttpServletRespose output stream.<p> * * @param cms an initialized CmsObject * @param result byte array that should be written. * @throws CmsException if something goes wrong */ private void writeBytesToResponse(CmsObject cms, byte[] result) throws CmsException { try { I_CmsResponse resp = cms.getRequestContext().getResponse(); if ((result != null) && !resp.isRedirected()) { // Only write any output to the response output stream if // the current request is neither redirected nor streamed. OutputStream out = resp.getOutputStream(); resp.setContentLength(result.length); resp.setHeader("Connection", "keep-alive"); out.write(result); out.close(); } } catch (IOException ioe) { if (OpenCms.getLog(this).isDebugEnabled()) { OpenCms.getLog(this).debug("IO error while writing to response stream for " + cms.getRequestContext().getFileUri(), ioe); } } catch (Exception e) { String errorMessage = "Cannot write output to HTTP response stream"; handleException(cms, e, errorMessage); } } }
package org.openid4java.util; import java.util.Map; import java.util.HashMap; /** * Container class for the various options associated with HTTP requests. * * @see org.openid4java.util.HttpCache * @author Marius Scurtescu, Johnny Bufu */ public class HttpRequestOptions { /** * Returns an {@link HttpRequestOptions} object suitable to use for * HTTP requests to perform discovery. */ public static HttpRequestOptions getDefaultOptionsForDiscovery() { return new HttpRequestOptions(); } /** * Returns an {@link HttpRequestOptions} object suitable to use for * HTTP requests to OP endpoints for the purpose of creating associations * or verifying signatures. */ public static HttpRequestOptions getDefaultOptionsForOpCalls() { HttpRequestOptions options = new HttpRequestOptions(); options.setConnTimeout(10000); options.setSocketTimeout(10000); options.setMaxRedirects(0); options.setAllowCircularRedirects(false); return options; } /** * HTTP connect timeout, in milliseconds. Default 3000 miliseconds. */ private int _connTimeout = 3000; /** * HTTP socket (read) timeout, in milliseconds. Default 5000 miliseconds. */ private int _socketTimeout = 5000; /** * Maximum number of redirects to be followed for the HTTP calls. * Defalut 10. */ private int _maxRedirects = 10; /** * Maximum size in bytes to be retrieved for the response body. * Default 100,000 bytes. */ private int _maxBodySize = 100000; /** * Map with HTTP request headers to be used when placing the HTTP request. */ private Map _requestHeaders = new HashMap(); /** * If set to false, a new HTTP request will be placed even if a cached copy * exists. This applies to the internal HttpCache, not the HTTP protocol * cache-control mechanisms. * * @see org.openid4java.util.HttpCache */ private boolean _useCache = true; private boolean _allowCircularRedirects = true; /** * If HttpRequestOptions' content type matches a cached HttpResponse's * content type, the cache copy is returned; otherwise a new HTTP request * is placed. */ private String _contentType = null; /** * If set to a positive value, then new HTTP request will be placed if * the cache is older than that positive value (in seconds) * This applies to the internal HttpCache, not the HTTP protocol * cache-control mechanisms. * * @see org.openid4java.util.HttpCache */ private long _cacheTTLSeconds = 60; /** * Constructs a set of HTTP request options with the default values. */ public HttpRequestOptions() { } /** * Creates a new HttpRequestOptions object as a clone of the provided * parameter. * * @param other HttpRequestOptions instance to be cloned. */ public HttpRequestOptions(HttpRequestOptions other) { this._connTimeout = other._connTimeout; this._socketTimeout = other._socketTimeout; this._maxRedirects = other._maxRedirects; this._maxBodySize = other._maxBodySize; if (other._requestHeaders != null) this._requestHeaders = new HashMap(other._requestHeaders); this._useCache = other._useCache; this._contentType = other._contentType; this._allowCircularRedirects = other._allowCircularRedirects; this._cacheTTLSeconds = other._cacheTTLSeconds; } /** * Gets the HTTP connect timeout, in milliseconds. */ public int getConnTimeout() { return _connTimeout; } /** * Sets the HTTP connect timeout, in milliseconds. */ public void setConnTimeout(int connTimeout) { this._connTimeout = connTimeout; } /** * Gets the HTTP socket (read) timeout, in milliseconds. */ public int getSocketTimeout() { return _socketTimeout; } /** * Sets HTTP socket (read) timeout, in milliseconds. */ public void setSocketTimeout(int socketTimeout) { this._socketTimeout = socketTimeout; } /** * Gets the internal limit configured for the maximum number of redirects * to be followed for the HTTP calls. */ public int getMaxRedirects() { return _maxRedirects; } /** * Sets the maximum number of redirects to be followed for the HTTP calls. */ public void setMaxRedirects(int maxRedirects) { this._maxRedirects = maxRedirects; } /** * Gets configuration parameter for the maximum HTTP body size * that will be downloaded. */ public int getMaxBodySize() { return _maxBodySize; } /** * Sets the maximum HTTP body size that will be downloaded. */ public void setMaxBodySize(int maxBodySize) { this._maxBodySize = maxBodySize; } /** * Gets the HTTP request headers that will be used when placing * HTTP requests using the options in this object. */ public Map getRequestHeaders() { return _requestHeaders; } /** * Sets the HTTP request headers that will be used when placing * HTTP requests using the options in this object. */ public void setRequestHeaders(Map requestHeaders) { this._requestHeaders = requestHeaders; } /** * Adds a new HTTP request header. */ public void addRequestHeader(String headerName, String headerValue) { _requestHeaders.put(headerName, headerValue); } /** * Returns true if a cached copy can be used when placing HTTP requests * using the options in this object. This applies to the internally * implemented HTTP cache, NOT to the HTTP protocol cache-control. */ public boolean isUseCache() { return _useCache; } /** * Sets the flag for allowing cached copy to be used when placing * HTTP requests using the options in this object. This applies * to the internally implemented HTTP cache, NOT to the HTTP protocol * cache-control. */ public void setUseCache(boolean useCache) { this._useCache = useCache; } /** * Gets the required content-type for the HTTP response. If this option * matches the content-type of a cached response, the cached copy is used; * otherwise a new HTTP request is made. */ public String getContentType() { return _contentType; } /** * Sets the required content-type for the HTTP response. If this option * matches the content-type of a cached response, the cached copy is used; * otherwise a new HTTP request is made. */ public void setContentType(String contentType) { this._contentType = contentType; } public boolean getAllowCircularRedirects() { return _allowCircularRedirects; } public void setAllowCircularRedirects(boolean allow) { _allowCircularRedirects = allow; } /** * * Gets the TTL for the cached response in seconds */ public long getCacheTTLSeconds() { return _cacheTTLSeconds; } /** * * Sets the TTL for the cached response in seconds */ public void setCacheTTLSeconds(long ttl) { _cacheTTLSeconds = ttl; } }
package burlap.behavior.policy; import burlap.behavior.singleagent.MDPSolverInterface; import burlap.behavior.valuefunction.QFunction; import burlap.behavior.valuefunction.QValue; import burlap.datastructures.BoltzmannDistribution; import burlap.oomdp.core.AbstractGroundedAction; import burlap.oomdp.core.AbstractObjectParameterizedGroundedAction; import burlap.oomdp.core.states.State; import javax.management.RuntimeErrorException; import java.util.ArrayList; import java.util.List; /** * This class implements a Boltzmann policy where the the Q-values represent * the components of the Boltzmann distribution. This policy requires a QComputable * valueFunction to be passed to it. * @author James MacGlashan * */ public class BoltzmannQPolicy extends Policy implements SolverDerivedPolicy { protected QFunction qplanner; double temperature; /** * Initializes with a temperature value. The temperature value controls how greedy the Boltzmann distribution is. * The temperature should be positive with values near zero causing the distribution to be more greedy. A high temperature * causes the distribution to be more uniform. * @param temperature the positive temperature value to use */ public BoltzmannQPolicy(double temperature){ this.qplanner = null; this.temperature = temperature; } /** * Initializes with a temperature value and the QComputable valueFunction to use. The temperature value controls how greedy the Boltzmann distribution is. * The temperature should be positive with values near zero causing the distribution to be more greedy. A high temperature * causes the distribution to be more uniform. * @param planner the q-computable valueFunction to use. * @param temperature the positive temperature value to use */ public BoltzmannQPolicy(QFunction planner, double temperature){ this.qplanner = planner; this.temperature = temperature; } @Override public AbstractGroundedAction getAction(State s) { return this.sampleFromActionDistribution(s); } @Override public List<ActionProb> getActionDistributionForState(State s) { List<QValue> qValues = this.qplanner.getQs(s); return this.getActionDistributionForQValues(s, qValues); } private List<ActionProb> getActionDistributionForQValues(State queryState, List <QValue> qValues){ List <ActionProb> res = new ArrayList<Policy.ActionProb>(); double [] rawQs = new double[qValues.size()]; for(int i = 0; i < qValues.size(); i++){ rawQs[i] = qValues.get(i).q; } BoltzmannDistribution bd = new BoltzmannDistribution(rawQs, this.temperature); double [] probs = bd.getProbabilities(); for(int i = 0; i < qValues.size(); i++){ QValue q = qValues.get(i); AbstractGroundedAction translated = AbstractObjectParameterizedGroundedAction.Helper.translateParameters(q.a, q.s, queryState); ActionProb ap = new ActionProb(translated, probs[i]); res.add(ap); } return res; } @Override public boolean isStochastic() { return true; } @Override public void setSolver(MDPSolverInterface solver) { if(!(solver instanceof QFunction)){ throw new RuntimeErrorException(new Error("Planner is not a QComputablePlanner")); } this.qplanner = (QFunction) solver; } @Override public boolean isDefinedFor(State s) { return true; //can always find q-values with default value } }
package ch.hsr.ifs.pystructure.playground; import java.util.LinkedList; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Expr; import ch.hsr.ifs.pystructure.typeinference.basetype.IEvaluatedType; import ch.hsr.ifs.pystructure.typeinference.contexts.PythonContext; import ch.hsr.ifs.pystructure.typeinference.goals.types.ExpressionTypeGoal; import ch.hsr.ifs.pystructure.typeinference.inferencer.PythonTypeInferencer; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.visitors.ExpressionAtLineVisitor; import ch.hsr.ifs.pystructure.typeinference.visitors.Workspace; public class Swush { public static void main(String[] args) { LinkedList<String> sysPath = new LinkedList<String>(); PythonTypeInferencer inferencer = new PythonTypeInferencer(); String path = "s101g/examples/pydoku/"; Workspace workspace = new Workspace(path, sysPath); Module module = workspace.getModule("pydoku"); int[] lines = {7, 14}; for (int line : lines) { Expr expression = getExpressionAtLine(module, line); PythonContext context = new PythonContext(workspace, module); ExpressionTypeGoal goal = new ExpressionTypeGoal(context, expression.value); IEvaluatedType type = inferencer.evaluateType(goal, -1); System.out.println("Type is: " + type); } // for (Definition<?> x : module.getDefinitions()) { // if (x instanceof AssignDefinition) { // AssignDefinition assign = (AssignDefinition) x; // exprType node = assign.getNode().targets[0]; // ExpressionTypeGoal goal = new ExpressionTypeGoal(context, node); // IEvaluatedType type = inferencer.evaluateType(goal, -1); // if (type == null) { // System.out.println("Type inferencer returned null for " + x + " / " + x.getNode()); // } else { // System.out.println(" type " + type.getTypeName()) ; } private static Expr getExpressionAtLine(Module module, int line) { SimpleNode rootNode = module.getNode(); ExpressionAtLineVisitor visitor = new ExpressionAtLineVisitor(line); try { visitor.traverse(rootNode); } catch (Exception e) { throw new RuntimeException(e); } Expr expression = visitor.getExpression(); if (expression == null) { throw new RuntimeException("Unable to find expression on line " + line); } return expression; } }
package polytheque.view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import org.omg.CORBA.Object; import java.sql.Date; import com.toedter.calendar.JDateChooser; @SuppressWarnings("serial") public class AppliReserverJeu extends JPanel implements ActionListener { private TacheDAffichage tacheDAffichageDeLApplication; private JButton boutonRetourAccueil; private JButton boutonValider; private JTextField searchContent; private JTextField ExtensionContent; private JDateChooser dateChooser; public AppliReserverJeu(TacheDAffichage afficheAppli) { this.tacheDAffichageDeLApplication = afficheAppli; creerPanneauRecherche(); //creerPanneauExtension(); creerPanneauDate(); this.boutonRetourAccueil = new JButton(); this.boutonRetourAccueil.setBounds(400, 700, 100, 30); this.boutonRetourAccueil.addActionListener(this); this.add(boutonRetourAccueil); } /*private void creerPanneauExtension() { JPanel ExtensionPanel = new JPanel(); ExtensionPanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50)); JLabel labelSearch = new JLabel("Recherche par nom :"); labelSearch.setBounds(300, 400, 100, 30); ExtensionPanel.add(labelSearch); this.ExtensionContent = new JTextField(); this.ExtensionContent.setBounds(450,400, 100, 30); this.ExtensionContent.setColumns(10); ExtensionPanel.add(this.searchContent, BorderLayout.NORTH); this.add(ExtensionPanel); } */ private void creerPanneauRecherche() { JPanel searchPanel = new JPanel(); searchPanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50)); JLabel labelSearch = new JLabel("Recherche par nom :"); labelSearch.setBounds(400, 0, 100, 30); searchPanel.add(labelSearch); this.searchContent = new JTextField(); this.searchContent.setBounds(450, 0, 100, 30); this.searchContent.setColumns(10); searchPanel.add(this.searchContent, BorderLayout.NORTH); this.add(searchPanel); } private void creerPanneauDate() { JPanel DatePanel = new JPanel(); DatePanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50)); JLabel labelDate = new JLabel("Cliquez sur la date a laquelle vous voudriez emprunter le jeux :"); labelDate.setBounds(400, 150, 100, 30); DatePanel.add(labelDate); this.dateChooser = new JDateChooser(); this.dateChooser.setBounds(450, 150, 100, 30); DatePanel.add(this.dateChooser); this.add(DatePanel); this.boutonValider = new JButton("Valider"); this.boutonValider.setBounds(400, 500, 100, 30); this.boutonValider.addActionListener(this); this.add(boutonValider); } public void actionPerformed(ActionEvent e) { JButton boutonSelectionne = (JButton) e.getSource(); if (boutonSelectionne == this.boutonValider && this.dateChooser.getDate() != null && this.searchContent.getText() != null) { this.tacheDAffichageDeLApplication.createReservation(this.tacheDAffichageDeLApplication.getAdherentByNothing().getIdAdherent(),this.tacheDAffichageDeLApplication.getJeu(this.searchContent.getText()).getIdJeu(),20,(Date) this.dateChooser.getDate()); this.tacheDAffichageDeLApplication.afficherMessage("Reservation confirmee"," Confirmation", JOptionPane.INFORMATION_MESSAGE); this.tacheDAffichageDeLApplication.afficherAccueil(); } else if (boutonSelectionne == this.boutonRetourAccueil) { this.tacheDAffichageDeLApplication.afficherAccueil();; } } }
package edu.cmu.sv.ws.ssnoc.test; import static com.eclipsesource.restfuse.Assert.assertBadRequest; import static com.eclipsesource.restfuse.Assert.assertCreated; import static com.eclipsesource.restfuse.Assert.assertOk; import java.sql.Timestamp; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.runner.RunWith; import com.eclipsesource.restfuse.Destination; import com.eclipsesource.restfuse.HttpJUnitRunner; import com.eclipsesource.restfuse.MediaType; import com.eclipsesource.restfuse.Method; import com.eclipsesource.restfuse.Response; import com.eclipsesource.restfuse.annotation.Context; import com.eclipsesource.restfuse.annotation.HttpTest; import edu.cmu.sv.ws.ssnoc.common.logging.Log; import edu.cmu.sv.ws.ssnoc.data.util.ConnectionPoolFactory; import edu.cmu.sv.ws.ssnoc.data.util.DBUtils; import edu.cmu.sv.ws.ssnoc.data.util.IConnectionPool; import edu.cmu.sv.ws.ssnoc.dto.Message; import edu.cmu.sv.ws.ssnoc.dto.User; import edu.cmu.sv.ws.ssnoc.rest.MessageService; import edu.cmu.sv.ws.ssnoc.rest.UserService; @RunWith(HttpJUnitRunner.class) public class MessageServiceIT { @Rule public Destination destination = new Destination(this, "http://localhost:4321/ssnoc"); @Context public Response response; @BeforeClass public static void initialSetUp() throws Exception { try { IConnectionPool cp = ConnectionPoolFactory.getInstance() .getH2ConnectionPool(); cp.switchConnectionToTest(); DBUtils.reinitializeDatabase(); UserService userService = new UserService(); User testuser = new User(); testuser.setUserName("testuser"); testuser.setPassword("testuser"); userService.addUser(testuser); System.out.println(">>>>>>>Created testuser<<<<<<"); Message msg = new Message(); MessageService msgService = new MessageService(); msg.setAuthor("SSNAdmin"); Timestamp postedAt = new Timestamp(1234); msg.setPostedAt(postedAt); msg.setContent("testSendPrivateMessageToAnotherUser"); msgService.postPrivateChatMessage("SSNAdmin", "testuser", msg); System.out.println(">>>>>>>Sent private message from SSNAdmin to testuser<<<<<<"); } catch (Exception e) { Log.error(e); } finally { Log.exit(); } } @AfterClass public static void finalTearDown() throws Exception { try { IConnectionPool cp = ConnectionPoolFactory.getInstance() .getH2ConnectionPool(); cp.switchConnectionToLive(); } catch (Exception e) { Log.error(e); } finally { Log.exit(); } } @HttpTest(method = Method.POST, path = "/user/signup", type = MediaType.APPLICATION_JSON, content = "{\"userName\":\"testuser\",\"password\":\"testuser\"}") public void createTestUser() { assertCreated(response); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test wall message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testPostingAMessage() { assertCreated(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test wall message")); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin/testuser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test chat message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testChatMessage() { assertCreated(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test chat message")); } @HttpTest(method = Method.POST, path = "/message/SSNAdmin/invaliduser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testChattingWithNonExistantUsers() { assertBadRequest(response); } @HttpTest(method = Method.POST, path = "/message/invaliduser", type = MediaType.APPLICATION_JSON, content = "{\"content\":\"This is a test wall message\",\"postedAt\":\"Nov 11, 2014 10:10:15 AM\"}") public void testPostingMessageAsANonExistantUser() { assertBadRequest(response); } // /get// @HttpTest(method = Method.GET, path = "/messages/wall") public void checkWallMessage() { assertOk(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test wall message")); } @HttpTest(method = Method.GET, path = "/messages/SSNAdmin/testuser") public void checkChatMessage() { assertOk(response); String msg = response.getBody(); Assert.assertTrue(msg.contains("This is a test chat message")); } @HttpTest(method = Method.GET, path = "/message/1") public void checkMessageID() { assertOk(response); } @HttpTest(method = Method.GET, path = "/users/SSNAdmin/chatbuddies") public void checkChatBuddies() { assertOk(response); String buddies = response.getBody(); Assert.assertTrue(buddies.contains("testuser")); } }
package com.bellaire.aerbot.systems; import com.bellaire.aerbot.Environment; import com.bellaire.aerbot.custom.RobotDrive3; import com.bellaire.aerbot.input.InputMethod; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.PIDSubsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class WheelSystem implements RobotSystem, Runnable { public static final double SHIFT_DELAY = 0.5; public static double Kp = -.08; public static double Ki = 0; public static double Kd = 0.0; public static final double SHIFTING_SPEED = 1.8; public static final double RAMPING = 0.5; private StraightDrivePID straightDrivePID; private RobotDrive3 wheels; private InputMethod inputMethod; private Relay gearbox; private int gear = 0; // off private boolean gearPress = false, dirToggle = false; private int dir = 1; private double currentLeftY = 0; private double currentRampY = 0; private GyroSystem gyro; private boolean straightDriving; private double heading; private double correctRotate; private AccelerometerSystem accelerometer; private Timer timer; private boolean automatic = true; private boolean disableStraightDrive = false; private boolean disableStraightDrivePressed; /** * Nothing is done in this constructor */ public WheelSystem() { } /* (non-Javadoc) * @see com.bellaire.aerbot.systems.RobotSystem#init(com.bellaire.aerbot.Environment) */ public void init(Environment environment) { wheels = new RobotDrive3(1, 2); gearbox = new Relay(2); this.gearsOff(); wheels.setSafetyEnabled(false); // this.motion = e.getMotionTracker(); gyro = environment.getGyroSystem(); accelerometer = environment.getAccelerometerSystem(); inputMethod = environment.getInput(); timer = new Timer(); timer.start(); straightDrivePID = new StraightDrivePID(); } /** * PIDSubsystem subclass for straight driving with gyro */ public class StraightDrivePID extends PIDSubsystem{ /** * passes Kp, Ki and Kd to super */ public StraightDrivePID(){ super(Kp, Ki, Kd); } /* (non-Javadoc) * @see edu.wpi.first.wpilibj.command.PIDSubsystem#returnPIDInput() */ protected double returnPIDInput() { return gyro.getAngle(); } /* (non-Javadoc) * @see edu.wpi.first.wpilibj.command.PIDSubsystem#usePIDOutput(double) */ protected void usePIDOutput(double value) { //SmartDashboard.putNumber("Straight drive PID: ", value); correctRotate = value; } /* (non-Javadoc) * @see edu.wpi.first.wpilibj.command.Subsystem#initDefaultCommand() */ protected void initDefaultCommand() { } } /** * resets straightDrivePID's PIDController */ public void resetStraightDrivePID(){ straightDrivePID.getPIDController().reset(); } /** * @return if straightDrivePID's PIDController is enabled */ public boolean straightDriveControllerEnabled(){ return straightDrivePID.getPIDController().isEnable(); } /** * @param setpoint the target value */ public void setStraightDrivePIDSetpoint(double setpoint){ straightDrivePID.setSetpoint(setpoint); } /** * calls enable() */ public void enableStraightDrivePID(){ straightDrivePID.enable(); } /** * calls disable() */ public void disableStraightDrivePID(){ straightDrivePID.disable(); } /** * @return the gyro */ protected GyroSystem getGyro() { return gyro; } /** * @param gyro the gyro to set */ protected void setGyro(GyroSystem gyro) { this.gyro = gyro; } /** * @return the accelerometer */ protected AccelerometerSystem getAccelerometer() { return accelerometer; } /** * @param accelerometer the accelerometer to set */ protected void setAccelerometer(AccelerometerSystem accelerometer) { this.accelerometer = accelerometer; } /** * @return the correctRotate */ protected double getCorrectRotate() { return correctRotate; } /** * @param correctRotate the correctRotate to set */ protected void setCorrectRotate(double correctRotate) { this.correctRotate = correctRotate; } /** * @return the straightDriving */ protected boolean isStraightDriving() { return straightDriving; } /** * @param straightDriving the straightDriving to set */ protected void setStraightDriving(boolean straightDriving) { this.straightDriving = straightDriving; } /** * @return the gear */ public int getGear() { return gear; } /** * @param gear the gear to set */ protected void setGear(int gear) { this.gear = gear; } /** * @return the currentLeftY */ protected double getCurrentLeftY() { return currentLeftY; } /** * @return the currentRampY */ protected double getCurrentRampY() { return currentRampY; } /** * @param currentRampY the currentRampY to set */ protected void setCurrentRampY(double currentRampY) { this.currentRampY = currentRampY; } /** * @param currentLeftY the currentLeftY to set */ protected void setCurrentLeftY(double currentLeftY) { this.currentLeftY = currentLeftY; } /** * @return the timer */ protected Timer getTimer() { return timer; } /** * @param timer the timer to set */ protected void setTimer(Timer timer) { this.timer = timer; } /** * Shifts to low gear */ public void gearsOff() { gear = 0; gearbox.set(Relay.Value.kOff); } /** * Shifts to high gear */ public void gearsReverse() { gear = 1; gearbox.set(Relay.Value.kReverse); } /* (non-Javadoc) * @see com.bellaire.aerbot.systems.RobotSystem#destroy() */ public void destroy() { gearbox.free(); wheels.free(); } /** * @param moveValue current movement value * @return equivilent of signnum */ public int actualMovementDirection(double moveValue){ if(moveValue == 0) return 0; else if(moveValue > 0) return 1; else return -1; } /** * @param outputMaginitude magnitude value * @param curve curve value */ public void drive(double outputMaginitude, double curve) { wheels.drive(outputMaginitude, curve); } /** * @param moveValue movement value from -1 to 1 * @param rotateValue rotation value from -1 to 1 */ public void arcadeDrive(double moveValue, double rotateValue) { wheels.arcadeDrive(moveValue, rotateValue); } /** * Uses PID and gyro to drive straight * @param moveValue movement value * @throws NullPointerException if gyro is null */ public void straightDrive(double moveValue) throws NullPointerException{ // set correct heading if (!straightDriving) { heading = gyro.getAngle(); resetStraightDrivePID(); } straightDriving = true; // correct error in heading if error more than 2 degrees if (Math.abs(heading - gyro.getAngle()) > 2 && !straightDriveControllerEnabled()) { setStraightDrivePIDSetpoint(heading); enableStraightDrivePID(); } else if (Math.abs(heading - gyro.getAngle()) <= 2 && straightDriveControllerEnabled()) { disableStraightDrivePID(); correctRotate = 0; } arcadeDrive(moveValue, correctRotate); } /** * Shift gears automatically if necessary */ public void automaticGearShift() { //only autoshift once every half second if(timer.get() > SHIFT_DELAY){ //shift based on speed from accelerometer and only when on the wrong gear if (Math.abs(accelerometer.getSpeed()) > SHIFTING_SPEED && gear == 0 && Math.abs(currentLeftY) > .75) { // also only shift into high gear if throttle is high gearsReverse(); timer.reset(); } else if (Math.abs(accelerometer.getSpeed()) <= SHIFTING_SPEED && gear == 1) { gearsOff(); timer.reset(); } } } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run(){ move(inputMethod); } /** * move according to input * @param input input from driver */ public void move(InputMethod input) { currentLeftY = -input.getLeftY(); currentRampY += (currentLeftY - currentRampY) * RAMPING; if (!disableStraightDrive && Math.abs(input.getLeftY()) > .15 && Math.abs(input.getRightX()) < .15) straightDrive(currentRampY * dir); else{ arcadeDrive(currentRampY * dir, input.getRightX()); straightDriving = false; } updateSmartDashboard(input); boolean shift = input.shift(); if (!shift) { gearPress = false; } if (gearPress == false) { if (shift) { gearPress = true; automatic = false; if (gear == 0) { this.gearsReverse(); } else if (gear == 1) { this.gearsOff(); } } } //don't autoshift while turning if (automatic && Math.abs(input.getRightX()) < 0.15) automaticGearShift(); if (!dirToggle) { if (input.directionToggle()) { dirToggle = true; dir *= -1; } } dirToggle = input.directionToggle(); // toggle straight driving if (!disableStraightDrivePressed && input.straightDrive()) disableStraightDrive = !disableStraightDrive; disableStraightDrivePressed = input.straightDrive(); } /** * @param input */ public void updateSmartDashboard(InputMethod input) { try { SmartDashboard.putBoolean("Low gear: ", gear == 0); SmartDashboard.putBoolean("Switched front: ", dir == -1); SmartDashboard.putBoolean("Automatic shifting: ", automatic); SmartDashboard.putBoolean("Straight driving: ", straightDriving); SmartDashboard.putNumber("Angle: ", gyro.getHeading()); SmartDashboard.putNumber("Ramped Movement: ", currentRampY); SmartDashboard.putNumber("Rotation Input: " , input.getRightX()); SmartDashboard.putBoolean("Straight driving disabled: ", disableStraightDrive); } catch (NullPointerException ex) { } try { SmartDashboard.putNumber("AccelerationX: ", accelerometer.getAccelerationX()); SmartDashboard.putNumber("AccelerationY: ", accelerometer.getAccelerationY()); SmartDashboard.putNumber("AccelerationZ: ", accelerometer.getAccelerationZ()); } catch (NullPointerException ex) { } try { SmartDashboard.putNumber("Speed: ", accelerometer.getSpeed()); } catch (NullPointerException ex) { } } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.io.Serializable; import java.sql.Connection; import java.sql.SQLException; import com.samskivert.io.PersistenceException; import com.samskivert.util.StringUtil; import com.samskivert.jdbc.ConnectionProvider; import com.samskivert.jdbc.DatabaseLiaison; import com.samskivert.jdbc.DuplicateKeyException; import com.samskivert.jdbc.LiaisonRegistry; import com.samskivert.jdbc.MySQLLiaison; import com.samskivert.jdbc.PostgreSQLLiaison; import com.samskivert.jdbc.depot.annotation.TableGenerator; import static com.samskivert.jdbc.depot.Log.log; /** * Defines a scope in which global annotations are shared. */ public class PersistenceContext { /** Map {@link TableGenerator} instances by name. */ public HashMap<String, TableGenerator> tableGenerators = new HashMap<String, TableGenerator>(); /** * A cache listener is notified when cache entries change. Its purpose is typically to do * further invalidation of dependent entries in other caches. */ public static interface CacheListener<T> { /** * The given entry (which is never null) has just been evicted from the cache slot * indicated by the given key. * * This method is most commonly used to trigger custom cache invalidation of records that * depend on the one that was just invalidated. */ public void entryInvalidated (CacheKey key, T oldEntry); /** * The given entry, which may be an explicit null, has just been placed into the cache * under the given key. The previous cache entry, if any, is also supplied. * * This method is most likely used by repositories to index entries by attribute for quick * cache invalidation when brute force is unrealistically time consuming. */ public void entryCached (CacheKey key, T newEntry, T oldEntry); } /** * The callback for {@link #cacheTraverse}; this is called for each entry in a given cache. */ public static interface CacheTraverser<T extends Serializable> { /** * Performs whatever cache-related tasks need doing for this cache entry. This method * is called for each cache entry in a full-cache enumeration. */ public void visitCacheEntry ( PersistenceContext ctx, String cacheId, Serializable key, T record); } /** * A simple implementation of {@link CacheTraverser} that selectively deletes entries in * a cache depending on the return value of {@link #testCacheEntry}. */ public static abstract class CacheEvictionFilter<T extends Serializable> implements CacheTraverser<T> { // from CacheTraverser public void visitCacheEntry ( PersistenceContext ctx, String cacheId, Serializable key, T record) { if (testForEviction(key, record)) { ctx.cacheInvalidate(cacheId, key); } } /** * Decides whether or not this entry should be evicted and returns true if yes, false if * no. */ protected abstract boolean testForEviction (Serializable key, T record); } /** * Creates a persistence context that will use the supplied provider to obtain JDBC * connections. * * @param ident the identifier to provide to the connection provider when requesting a * connection. */ public PersistenceContext (String ident, ConnectionProvider conprov) { this(ident, conprov, null); } /** * Creates a persistence context that will use the supplied provider to obtain JDBC * connections. * * @param ident the identifier to provide to the connection provider when requesting a * connection. */ public PersistenceContext (String ident, ConnectionProvider conprov, CacheAdapter adapter) { _ident = ident; _conprov = conprov; _liaison = LiaisonRegistry.getLiaison(conprov.getURL(ident)); _cache = adapter; } /** * Returns the cache adapter used by this context or null if caching is disabled. */ public CacheAdapter getCacheAdapter () { return _cache; } /** * Shuts this persistence context down, shutting down any caching system in use and shutting * down the JDBC connection pool. */ public void shutdown () { try { if (_cache != null) { _cache.shutdown(); } } catch (Throwable t) { log.log(Level.WARNING, "Failure shutting down Depot cache.", t); } _conprov.shutdown(); } /** * Create and return a new {@link SQLBuilder} for the appropriate dialect. * * TODO: At some point perhaps use a more elegant way of discerning our dialect. */ public SQLBuilder getSQLBuilder (DepotTypes types) { if (_liaison instanceof PostgreSQLLiaison) { return new PostgreSQLBuilder(types); } if (_liaison instanceof MySQLLiaison) { return new MySQLBuilder(types); } throw new IllegalArgumentException("Unknown liaison type: " + _liaison.getClass()); } /** * Registers a migration for the specified entity class. * * <p> This method must be called <b>before</b> an Entity is used by any repository. Thus you * should register all migrations immediately after creating your persistence context or if you * are careful to ensure that your Entities are only used by a single repository, you can * register your migrations in the constructor for that repository. * * <p> Note that the migration process is as follows: * * <ul><li> Note the difference between the entity's declared version and the version recorded * in the database. * <li> Run all registered pre-migrations * <li> Perform all default migrations (column additions and removals) * <li> Run all registered post-migrations </ul> * * Thus you must either be prepared for the entity to be at <b>any</b> version prior to your * migration target version because we may start up, find the schema at version 1 and the * Entity class at version 8 and do all "standard" migrations in one fell swoop. So if a column * got added in version 2 and renamed in version 6 and your migration was registered for * version 6 to do that migration, it must be prepared for the column not to exist at all. * * <p> If you want a completely predictable migration process, never use the default migrations * and register a pre-migration for every single schema migration and they will then be * guaranteed to be run in registration order and with predictable pre- and post-conditions. */ public <T extends PersistentRecord> void registerMigration ( Class<T> type, EntityMigration migration) { getRawMarshaller(type).registerMigration(migration); } /** * Returns the marshaller for the specified persistent object class, creating and initializing * it if necessary. */ public <T extends PersistentRecord> DepotMarshaller<T> getMarshaller (Class<T> type) throws PersistenceException { DepotMarshaller<T> marshaller = getRawMarshaller(type); try { if (!marshaller.isInitialized()) { // initialize the marshaller which may create or migrate the table for its // underlying persistent object marshaller.init(this); if (marshaller.getTableName() != null && _warnOnLazyInit) { log.warning("Record initialized lazily [type=" + type.getName() + "]."); } } } catch (PersistenceException pe) { throw (PersistenceException)new PersistenceException( "Failed to initialize marshaller [type=" + type + "].").initCause(pe); } return marshaller; } /** * Invokes a non-modifying query and returns its result. */ public <T> T invoke (Query<T> query) throws PersistenceException { CacheKey key = query.getCacheKey(); // if there is a cache key, check the cache if (key != null && _cache != null) { CacheAdapter.CachedValue<T> cacheHit = cacheLookup(key); if (cacheHit != null) { log.fine("cache hit [key=" + key + ", hit=" + cacheHit + "]"); T value = cacheHit.getValue(); value = query.transformCacheHit(key, value); if (value != null) { return value; } log.fine("transformCacheHit returned null; rejecting cached value."); } log.fine("cache miss [key=" + key + "]"); } // otherwise, perform the query @SuppressWarnings("unchecked") T result = (T) invoke(query, null, true); // and let the caller figure out if it wants to cache itself somehow query.updateCache(this, result); return result; } /** * Invokes a modifying query and returns the number of rows modified. */ public int invoke (Modifier modifier) throws PersistenceException { modifier.cacheInvalidation(this); int rows = (Integer) invoke(null, modifier, true); if (rows > 0) { modifier.cacheUpdate(this); } return rows; } /** * Returns true if there is a {@link CacheAdapter} configured, false otherwise. */ public boolean isUsingCache () { return _cache != null; } /** * Looks up an entry in the cache by the given key. */ public <T> CacheAdapter.CachedValue<T> cacheLookup (CacheKey key) { if (_cache == null) { return null; } CacheAdapter.CacheBin<T> bin = _cache.getCache(key.getCacheId()); return bin.lookup(key.getCacheKey()); } /** * Stores a new entry indexed by the given key. */ public <T> void cacheStore (CacheKey key, T entry) { if (_cache == null) { return; } if (key == null) { log.warning("Cache key must not be null [entry=" + entry + "]"); Thread.dumpStack(); return; } log.fine("storing [key=" + key + ", value=" + entry + "]"); CacheAdapter.CacheBin<T> bin = _cache.getCache(key.getCacheId()); CacheAdapter.CachedValue element = bin.lookup(key.getCacheKey()); @SuppressWarnings("unchecked") T oldEntry = (element != null ? (T) element.getValue() : null); // update the cache bin.store(key.getCacheKey(), entry); // then do cache invalidations Set<CacheListener<?>> listeners = _listenerSets.get(key.getCacheId()); if (listeners != null && listeners.size() > 0) { for (CacheListener<?> listener : listeners) { log.fine("cascading [listener=" + listener + "]"); @SuppressWarnings("unchecked") CacheListener<T> casted = (CacheListener<T>)listener; casted.entryCached(key, entry, oldEntry); } } } /** * Evicts the cache entry indexed under the given key, if there is one. The eviction may * trigger further cache invalidations. */ public void cacheInvalidate (CacheKey key) { if (key == null) { log.warning("Cache key to invalidate must not be null."); Thread.dumpStack(); } else { cacheInvalidate(key.getCacheId(), key.getCacheKey()); } } /** * Evicts the cache entry indexed under the given class and cache key, if there is one. The * eviction may trigger further cache invalidations. */ public void cacheInvalidate (Class pClass, Serializable cacheKey) { cacheInvalidate(pClass.getName(), cacheKey); } /** * Evicts the cache entry indexed under the given cache id and cache key, if there is one. The * eviction may trigger further cache invalidations. */ public <T extends Serializable> void cacheInvalidate (String cacheId, Serializable cacheKey) { if (_cache == null) { return; } log.fine("invalidating [cacheId=" + cacheId + ", cacheKey=" + cacheKey + "]"); CacheAdapter.CacheBin<T> bin = _cache.getCache(cacheId); CacheAdapter.CachedValue<T> element = bin.lookup(cacheKey); if (element == null) { return; } // find the old entry, if any T oldEntry = element.getValue(); if (oldEntry != null) { // if there was one, do (possibly cascading) cache invalidations Set<CacheListener<?>> listeners = _listenerSets.get(cacheId); if (listeners != null && listeners.size() > 0) { CacheKey key = new SimpleCacheKey(cacheId, cacheKey); for (CacheListener<?> listener : listeners) { log.fine("cascading [listener=" + listener + "]"); @SuppressWarnings("unchecked") CacheListener<T> casted = (CacheListener<T>)listener; casted.entryInvalidated(key, oldEntry); } } } // then evict the keyed entry, if needed log.fine("evicting [cacheKey=" + cacheKey + "]"); bin.remove(cacheKey); } /** * Brutally iterates over the entire contents of the cache associated with the given class, * invoking the callback for each cache entry. */ public <T extends Serializable> void cacheTraverse (Class pClass, CacheTraverser<T> filter) { cacheTraverse(pClass.getName(), filter); } /** * Brutally iterates over the entire contents of the cache identified by the given cache id, * invoking the callback for each cache entry. */ public <T extends Serializable> void cacheTraverse (String cacheId, CacheTraverser<T> filter) { if (_cache == null) { return; } CacheAdapter.CacheBin<T> bin = _cache.getCache(cacheId); if (bin != null) { for (Object key : bin.enumerateKeys()) { CacheAdapter.CachedValue<T> element = bin.lookup((Serializable) key); if (element != null) { filter.visitCacheEntry(this, cacheId, (Serializable) key, element.getValue()); } } } } /** * Registers a new cache listener with the cache associated with the given class. */ public <T extends Serializable> void addCacheListener ( Class<T> pClass, CacheListener<T> listener) { addCacheListener(pClass.getName(), listener); } /** * Registers a new cache listener with the identified cache. */ public <T extends Serializable> void addCacheListener ( String cacheId, CacheListener<T> listener) { Set<CacheListener<?>> listenerSet = _listenerSets.get(cacheId); if (listenerSet == null) { listenerSet = new HashSet<CacheListener<?>>(); _listenerSets.put(cacheId, listenerSet); } listenerSet.add(listener); } /** * Iterates over all {@link PersistentRecord} classes managed by this context and initializes * their {@link DepotMarshaller}. This forces migrations to run and the database schema to be * created. * * @param warnOnLazyInit if true, any persistent records that are resolved after this method is * called will result in a warning so that the application developer can restructure their code * to ensure that those records are properly registered prior to this call. */ public void initializeManagedRecords (boolean warnOnLazyInit) throws PersistenceException { for (Class<? extends PersistentRecord> rclass : _managedRecords) { getMarshaller(rclass); } // now issue a warning if we lazily initialize any other persistent record _warnOnLazyInit = true; } /** * Called when a depot repository is created. We register all persistent record classes used by * the repository so that systems that desire it can force the resolution of all database * tables rather than allowing resolution to happen on demand. */ protected void repositoryCreated (DepotRepository repo) { repo.getManagedRecords(_managedRecords); } /** * Looks up and creates, but does not initialize, the marshaller for the specified Entity * type. */ protected <T extends PersistentRecord> DepotMarshaller<T> getRawMarshaller (Class<T> type) { @SuppressWarnings("unchecked") DepotMarshaller<T> marshaller = (DepotMarshaller<T>)_marshallers.get(type); if (marshaller == null) { _marshallers.put(type, marshaller = new DepotMarshaller<T>(type, this)); } return marshaller; } /** * Internal invoke method that takes care of transient retries * for both queries and modifiers. */ protected <T> Object invoke ( Query<T> query, Modifier modifier, boolean retryOnTransientFailure) throws PersistenceException { boolean isReadOnlyQuery = (query != null); Connection conn = _conprov.getConnection(_ident, isReadOnlyQuery); // TEMP: we synchronize on the connection to cooperate with SimpleRepository when used in // conjunction with a StaticConnectionProvider; at some point we'll switch to standard JDBC // connection pooling which will block in getConnection() instead of returning a connection // that someone else may be using synchronized (conn) { try { if (isReadOnlyQuery) { // if this becomes more complex than this single statement, then this should // turn into a method call that contains the complexity return query.invoke(conn, _liaison); } else { // if this becomes more complex than this single statement, then this should // turn into a method call that contains the complexity return modifier.invoke(conn, _liaison); } } catch (SQLException sqe) { if (!isReadOnlyQuery) { // convert this exception to a DuplicateKeyException if appropriate if (_liaison.isDuplicateRowException(sqe)) { throw new DuplicateKeyException(sqe.getMessage()); } } // let the provider know that the connection failed _conprov.connectionFailed(_ident, isReadOnlyQuery, conn, sqe); conn = null; if (retryOnTransientFailure && _liaison.isTransientException(sqe)) { // the MySQL JDBC driver has the annoying habit of including the embedded // exception stack trace in the message of their outer exception; if I want a // fucking stack trace, I'll call printStackTrace() thanksverymuch String msg = StringUtil.split(String.valueOf(sqe), "\n")[0]; log.info("Transient failure executing op, retrying [error=" + msg + "]."); } else { String msg = isReadOnlyQuery ? "Query failure " + query : "Modifier failure " + modifier; throw new PersistenceException(msg, sqe); } } finally { _conprov.releaseConnection(_ident, isReadOnlyQuery, conn); } } // if we got here, we want to retry a transient failure return invoke(query, modifier, false); } protected String _ident; protected ConnectionProvider _conprov; protected DatabaseLiaison _liaison; protected boolean _warnOnLazyInit; /** The object through which all our caching is relayed, or null, for no caching. */ protected CacheAdapter _cache; protected Map<String, Set<CacheListener<?>>> _listenerSets = new HashMap<String, Set<CacheListener<?>>>(); protected Map<Class<?>, DepotMarshaller<?>> _marshallers = new HashMap<Class<?>, DepotMarshaller<?>>(); /** * The set of persistent records for which this context is responsible. This data is used by * {@link #initializeManagedRecords} to force migration/schema initialization. */ protected Set<Class<? extends PersistentRecord>> _managedRecords = new HashSet<Class<? extends PersistentRecord>>(); }
package org.jsmpp.session; import org.jsmpp.bean.DeliverSm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClientResponseHandler { private static final Logger logger = LoggerFactory.getLogger(ClientResponseHandler.class); public void processDeliverSm(ClientSession session, DeliverSm deliverSm) { if (session.getMessageReceiverListener() != null) { session.getMessageReceiverListener().onAcceptDeliverSm(deliverSm); session.getPDUSender().sendDeliverSmResp(deliverSm); } else { logger.info("Message received to ClientResponseHandler, but MessageReceiverListener is not set"); } } }
package com.darwinsys.todo.model; import java.util.List; public class ExportToodleDo extends Export { public static String FIELDS = "'TASK','FOLDER','CONTEXT','GOAL','LOCATION','STARTDATE','STARTTIME','DUEDATE','DUETIME','REPEAT','LENGTH','TIMER','PRIORITY','TAG','STATUS','STAR','NOTE'"; private static final String COMMA = ",", DQ = "\""; @Override public List<String> export(List<Task> tasks) { List<String> ret = super.export(tasks); ret.add(0, FIELDS); return ret; } @Override public String export(Task t) { StringBuilder sb = new StringBuilder(); sb.append(t.name).append(COMMA) .append(COMMA) // folder .append(notNull(t.context)).append(COMMA) .append(notNull(t.project)).append(COMMA) // == goal .append(COMMA) // location .append(quote(t.creationDate.toString())).append(COMMA) // = startdate .append(quote(notNull(t.dueDate).toString())).append(COMMA) .append(COMMA) // duetime .append(COMMA) // repeat .append(COMMA) // length .append(COMMA) // timer .append(quote(mapPriority(t.priority))) .append(COMMA) // tag .append(COMMA) // status - not used!! .append(COMMA) // star .append(COMMA) // note ; return sb.toString(); } private String quote(String s) { return '"' + s + '"'; } private final Object notNull(Object s) { return s == null ? "" : s; } private String mapPriority(Character priority) { switch(priority) { case 'A': return "3"; case 'B': return "2"; case 'C': return "1"; default: return "0"; } } }
package com.dmdirc.addons.logging; import com.dmdirc.Channel; import com.dmdirc.Main; import com.dmdirc.Query; import com.dmdirc.Server; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.CoreActionType; import com.dmdirc.actions.interfaces.ActionType; import com.dmdirc.commandparser.CommandManager; import com.dmdirc.config.Identity; import com.dmdirc.config.IdentityManager; import com.dmdirc.config.prefs.PreferencesCategory; import com.dmdirc.config.prefs.PreferencesManager; import com.dmdirc.config.prefs.PreferencesSetting; import com.dmdirc.config.prefs.PreferencesType; import com.dmdirc.interfaces.ActionListener; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.parser.ChannelClientInfo; import com.dmdirc.parser.ChannelInfo; import com.dmdirc.parser.ClientInfo; import com.dmdirc.parser.IRCParser; import com.dmdirc.plugins.Plugin; import com.dmdirc.ui.interfaces.InputWindow; import com.dmdirc.ui.interfaces.Window; import com.dmdirc.ui.messages.Styliser; import java.awt.Color; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; import java.util.Map; import java.util.Stack; import java.util.Timer; import java.util.TimerTask; /** * Adds logging facility to client. * * @author Shane 'Dataforce' McCormack * @version $Id: LoggingPlugin.java 969 2007-04-30 18:38:20Z ShaneMcC $ */ public class LoggingPlugin extends Plugin implements ActionListener { /** What domain do we store all settings in the global config under. */ private static final String MY_DOMAIN = "plugin-Logging"; /** The command we registered. */ private LoggingCommand command; /** Open File */ protected class OpenFile { public long lastUsedTime = System.currentTimeMillis(); public BufferedWriter writer = null; public OpenFile(final BufferedWriter writer) { this.writer = writer; } } /** Timer used to close idle files */ protected Timer idleFileTimer; /** Hashtable of open files. */ protected final Map<String, OpenFile> openFiles = new Hashtable<String, OpenFile>(); /** Date format used for "File Opened At" log. */ final DateFormat openedAtFormat = new SimpleDateFormat("EEEE MMMM dd, yyyy - HH:mm:ss"); /** * Creates a new instance of the Logging Plugin. */ public LoggingPlugin() { super(); } /** * Called when the plugin is loaded. */ @Override public void onLoad() { // Set defaults final Identity defaults = IdentityManager.getAddonIdentity(); defaults.setOption(MY_DOMAIN, "general.directory", Main.getConfigDir() + "logs" + System.getProperty("file.separator")); defaults.setOption(MY_DOMAIN, "general.networkfolders", "true"); defaults.setOption(MY_DOMAIN, "advanced.filenamehash", "false"); defaults.setOption(MY_DOMAIN, "general.addtime", "true"); defaults.setOption(MY_DOMAIN, "general.timestamp", "[dd/MM/yyyy HH:mm:ss]"); defaults.setOption(MY_DOMAIN, "general.stripcodes", "true"); defaults.setOption(MY_DOMAIN, "general.channelmodeprefix", "true"); defaults.setOption(MY_DOMAIN, "backbuffer.autobackbuffer", "true"); defaults.setOption(MY_DOMAIN, "backbuffer.lines", "10"); defaults.setOption(MY_DOMAIN, "backbuffer.colour", "14"); defaults.setOption(MY_DOMAIN, "backbuffer.timestamp", "false"); defaults.setOption(MY_DOMAIN, "history.lines", "50000"); defaults.setOption(MY_DOMAIN, "advanced.usedate", "false"); defaults.setOption(MY_DOMAIN, "advanced.usedateformat", "yyyy/MMMM"); final File dir = new File(IdentityManager.getGlobalConfig().getOption(MY_DOMAIN, "general.directory")); if (dir.exists()) { if (!dir.isDirectory()) { Logger.userError(ErrorLevel.LOW, "Unable to create logging dir (file exists instead)"); } } else { if (!dir.mkdirs()) { Logger.userError(ErrorLevel.LOW, "Unable to create logging dir"); } } command = new LoggingCommand(); ActionManager.addListener(this, CoreActionType.CHANNEL_OPENED, CoreActionType.CHANNEL_CLOSED, CoreActionType.CHANNEL_MESSAGE, CoreActionType.CHANNEL_SELF_MESSAGE, CoreActionType.CHANNEL_ACTION, CoreActionType.CHANNEL_SELF_ACTION, CoreActionType.CHANNEL_GOTTOPIC, CoreActionType.CHANNEL_TOPICCHANGE, CoreActionType.CHANNEL_JOIN, CoreActionType.CHANNEL_PART, CoreActionType.CHANNEL_QUIT, CoreActionType.CHANNEL_KICK, CoreActionType.CHANNEL_NICKCHANGE, CoreActionType.CHANNEL_MODECHANGE, CoreActionType.QUERY_OPENED, CoreActionType.QUERY_CLOSED, CoreActionType.QUERY_MESSAGE, CoreActionType.QUERY_SELF_MESSAGE, CoreActionType.QUERY_ACTION, CoreActionType.QUERY_SELF_ACTION); // Close idle files every hour. idleFileTimer = new Timer("LoggingPlugin Timer"); idleFileTimer.schedule(new TimerTask(){ /** {@inheritDoc} */ @Override public void run() { timerTask(); } }, 3600000); } /** * What to do every hour when the timer fires. */ protected void timerTask() { // Oldest time to allow final long oldestTime = System.currentTimeMillis() - 3480000; synchronized (openFiles) { for (String filename : (new Hashtable<String, OpenFile>(openFiles)).keySet()) { OpenFile file = openFiles.get(filename); if (file.lastUsedTime < oldestTime) { try { file.writer.close(); openFiles.remove(filename); } catch (IOException e) { Logger.userError(ErrorLevel.LOW, "Unable to close idle file (File: "+filename+")"); } } } } } /** * Called when this plugin is unloaded. */ @Override public void onUnload() { idleFileTimer.cancel(); idleFileTimer.purge(); CommandManager.unregisterCommand(command); ActionManager.removeListener(this); synchronized (openFiles) { for (String filename : openFiles.keySet()) { OpenFile file = openFiles.get(filename); try { file.writer.close(); } catch (IOException e) { Logger.userError(ErrorLevel.LOW, "Unable to close file (File: "+filename+")"); } } openFiles.clear(); } } /** {@inheritDoc} */ @Override public void showConfig(final PreferencesManager manager) { final PreferencesCategory general = new PreferencesCategory("Logging", "General configuration for Logging plugin."); final PreferencesCategory backbuffer = new PreferencesCategory("Back Buffer", "Options related to the automatic backbuffer"); final PreferencesCategory advanced = new PreferencesCategory("Advanced", "Advanced configuration for Logging plugin. You shouldn't need to edit this unless you know what you are doing."); general.addSetting(new PreferencesSetting(PreferencesType.TEXT, MY_DOMAIN, "general.directory", "false", "Directory", "Directory for log files")); general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "general.networkfolders", "", "Separate logs by network", "Should the files be stored in a sub-dir with the networks name?")); general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "general.addtime", "false", "Timestamp logs", "Should a timestamp be added to the log files?")); general.addSetting(new PreferencesSetting(PreferencesType.TEXT, MY_DOMAIN, "general.timestamp", "", "Timestamp format", "The String to pass to 'SimpleDateFormat' to format the timestamp")); general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "general.stripcodes", "false", "Strip Control Codes", "Remove known irc control codes from lines before saving?")); general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "general.channelmodeprefix", "", "Show channel mode prefix", "Show the @,+ etc next to nicknames")); backbuffer.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "backbuffer.autobackbuffer", "", "Automatically display", "Automatically display the backbuffer when a channel is joined")); backbuffer.addSetting(new PreferencesSetting(PreferencesType.COLOUR, MY_DOMAIN, "backbuffer.colour", "0", "Colour to use for display", "Colour used when displaying the backbuffer")); backbuffer.addSetting(new PreferencesSetting(PreferencesType.INTEGER, MY_DOMAIN, "backbuffer.lines", "0", "Number of lines to show", "Number of lines used when displaying backbuffer")); backbuffer.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "backbuffer.timestamp", "false", "Show Formatter-Timestamp", "Should the line be added to the frame with the timestamp from the formatter aswell as the file contents")); advanced.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "advanced.filenamehash", "false", "Add Filename hash", "Add the MD5 hash of the channel/client name to the filename. (This is used to allow channels with similar names (ie a _ not a -) to be logged separately)")); advanced.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, MY_DOMAIN, "advanced.usedate", "false", "Use Date directories", "Should the log files be in separate directories based on the date?")); advanced.addSetting(new PreferencesSetting(PreferencesType.TEXT, MY_DOMAIN, "advanced.usedateformat", "yyyy/MMMM", "Archive format", "The String to pass to 'SimpleDateFormat' to format the directory name(s) for archiving")); general.addSubCategory(backbuffer.setInline()); general.addSubCategory(advanced.setInline()); manager.getCategory("Plugins").addSubCategory(general.setInlineAfter()); } /** * Get the name of the domain we store all settings in the global config under. * * @return the plugins domain */ protected static String getDomain() { return MY_DOMAIN; } /** * Log a query-related event * * @param type The type of the event to process * @param format Format of messages that are about to be sent. (May be null) * @param arguments The arguments for the event */ protected void handleQueryEvent(final CoreActionType type, final StringBuffer format, final Object... arguments) { final Query query = (Query)arguments[0]; if (query.getServer() == null) { Logger.appError(ErrorLevel.MEDIUM, "Query object has no server ("+type.toString()+")", new Exception("Query object has no server ("+type.toString()+")")); return; } final IRCParser parser = query.getServer().getParser(); ClientInfo client; if (parser == null) { // Without a parser object, we might not be able to find the file to log this to. if (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "general.networkfolders")) { // We *wont* be able to, so rather than logging to an incorrect file we just won't log. return; } client = null; } else { client = parser.getClientInfo(query.getHost()); if (client == null) { client = new ClientInfo(parser, query.getHost()).setFake(true); } } final String filename = getLogFile(client); switch (type) { case QUERY_OPENED: if (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "backbuffer.autobackbuffer")) { showBackBuffer(query.getFrame(), filename); } appendLine(filename, "*** Query opened at: %s", openedAtFormat.format(new Date())); appendLine(filename, "*** Query with User: %s", query.getHost()); appendLine(filename, ""); break; case QUERY_CLOSED: appendLine(filename, "*** Query closed at: %s", openedAtFormat.format(new Date())); final BufferedWriter file = openFiles.get(filename).writer; try { file.close(); } catch (IOException e) { Logger.userError(ErrorLevel.LOW, "Unable to close file (Filename: "+filename+")"); } openFiles.remove(filename); break; case QUERY_MESSAGE: case QUERY_SELF_MESSAGE: case QUERY_ACTION: case QUERY_SELF_ACTION: final boolean isME = (type == CoreActionType.QUERY_SELF_MESSAGE || type == CoreActionType.QUERY_SELF_ACTION); final String overrideNick = (isME) ? getDisplayName(parser.getMyself()) : ""; if (type == CoreActionType.QUERY_MESSAGE || type == CoreActionType.QUERY_SELF_MESSAGE) { appendLine(filename, "<%s> %s", getDisplayName(client, overrideNick), (String)arguments[1]); } else { appendLine(filename, "* %s %s", getDisplayName(client, overrideNick), (String)arguments[1]); } break; } } /** * Log a channel-related event * * @param type The type of the event to process * @param format Format of messages that are about to be sent. (May be null) * @param arguments The arguments for the event */ protected void handleChannelEvent(final CoreActionType type, final StringBuffer format, final Object... arguments) { final Channel chan = ((Channel)arguments[0]); final ChannelInfo channel = chan.getChannelInfo(); final String filename = getLogFile(channel); final ChannelClientInfo channelClient = (arguments.length > 1 && arguments[1] instanceof ChannelClientInfo) ? (ChannelClientInfo)arguments[1] : null; final ClientInfo client = (channelClient != null) ? channelClient.getClient() : null; final String message = (arguments.length > 2 && arguments[2] instanceof String) ? (String)arguments[2] : null; switch (type) { case CHANNEL_OPENED: if (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "backbuffer.autobackbuffer")) { showBackBuffer(chan.getFrame(), filename); } appendLine(filename, "*** Channel opened at: %s", openedAtFormat.format(new Date())); appendLine(filename, ""); break; case CHANNEL_CLOSED: appendLine(filename, "*** Channel closed at: %s", openedAtFormat.format(new Date())); final BufferedWriter file = openFiles.get(filename).writer; try { file.close(); } catch (IOException e) { Logger.userError(ErrorLevel.LOW, "Unable to close file (Filename: "+filename+")"); } openFiles.remove(filename); break; case CHANNEL_MESSAGE: case CHANNEL_SELF_MESSAGE: case CHANNEL_ACTION: case CHANNEL_SELF_ACTION: if (type == CoreActionType.CHANNEL_MESSAGE || type == CoreActionType.CHANNEL_SELF_MESSAGE) { appendLine(filename, "<%s> %s", getDisplayName(client), message); } else { appendLine(filename, "* %s %s", getDisplayName(client), message); } break; case CHANNEL_GOTTOPIC: // ActionManager.processEvent(CoreActionType.CHANNEL_GOTTOPIC, this); final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); appendLine(filename, "*** Topic is: %s", channel.getTopic()); appendLine(filename, "*** Set at: %s on %s by %s", timeFormat.format(1000 * channel.getTopicTime()), dateFormat.format(1000 * channel.getTopicTime()), channel.getTopicUser()); break; case CHANNEL_TOPICCHANGE: appendLine(filename, "*** %s Changed the topic to: %s", getDisplayName(channelClient), message); break; case CHANNEL_JOIN: appendLine(filename, "*** %s (%s) joined the channel", getDisplayName(channelClient), client.toString()); break; case CHANNEL_PART: if (message.isEmpty()) { appendLine(filename, "*** %s (%s) left the channel", getDisplayName(channelClient), client.toString()); } else { appendLine(filename, "*** %s (%s) left the channel (%s)", getDisplayName(channelClient), client.toString(), message); } break; case CHANNEL_QUIT: if (message.isEmpty()) { appendLine(filename, "*** %s (%s) Quit IRC", getDisplayName(channelClient), client.toString()); } else { appendLine(filename, "*** %s (%s) Quit IRC (%s)", getDisplayName(channelClient), client.toString(), message); } break; case CHANNEL_KICK: final String kickReason = (String)arguments[3]; final ChannelClientInfo kickedClient = (ChannelClientInfo)arguments[2]; if (kickReason.isEmpty()) { appendLine(filename, "*** %s was kicked by %s", getDisplayName(kickedClient), getDisplayName(channelClient)); } else { appendLine(filename, "*** %s was kicked by %s (%s)", getDisplayName(kickedClient), getDisplayName(channelClient), kickReason); } break; case CHANNEL_NICKCHANGE: appendLine(filename, "*** %s is now %s", getDisplayName(channelClient, message), getDisplayName(channelClient)); break; case CHANNEL_MODECHANGE: if (channelClient.getNickname().isEmpty()) { appendLine(filename, "*** Channel modes are: %s", message); } else { appendLine(filename, "*** %s set modes: %s", getDisplayName(channelClient), message); } break; } } /** * Process an event of the specified type. * * @param type The type of the event to process * @param format Format of messages that are about to be sent. (May be null) * @param arguments The arguments for the event */ @Override public void processEvent(final ActionType type, final StringBuffer format, final Object ... arguments) { if (type instanceof CoreActionType) { final CoreActionType thisType = (CoreActionType) type; switch (thisType) { case CHANNEL_OPENED: case CHANNEL_CLOSED: case CHANNEL_MESSAGE: case CHANNEL_SELF_MESSAGE: case CHANNEL_ACTION: case CHANNEL_SELF_ACTION: case CHANNEL_GOTTOPIC: case CHANNEL_TOPICCHANGE: case CHANNEL_JOIN: case CHANNEL_PART: case CHANNEL_QUIT: case CHANNEL_KICK: case CHANNEL_NICKCHANGE: case CHANNEL_MODECHANGE: handleChannelEvent(thisType, format, arguments); break; case QUERY_OPENED: case QUERY_CLOSED: case QUERY_MESSAGE: case QUERY_SELF_MESSAGE: case QUERY_ACTION: case QUERY_SELF_ACTION: handleQueryEvent(thisType, format, arguments); break; default: break; } } } /** * Add a backbuffer to a frame. * * @param frame The frame to add the backbuffer lines to * @param filename File to get backbuffer from */ protected static void showBackBuffer(final Window frame, final String filename) { final int numLines = IdentityManager.getGlobalConfig().getOptionInt(MY_DOMAIN, "backbuffer.lines", 0); final String colour = IdentityManager.getGlobalConfig().getOption(MY_DOMAIN, "backbuffer.colour"); final boolean showTimestamp = IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "backbuffer.timestamp"); if (frame == null) { Logger.userError(ErrorLevel.LOW, "Given a null frame"); return; } final File testFile = new File(filename); if (testFile.exists()) { try { final ReverseFileReader file = new ReverseFileReader(testFile); // Because the file includes a newline char at the end, an empty line // is returned by getLines. To counter this, we call getLines(1) and do // nothing with the output. file.getLines(1); final Stack<String> lines = file.getLines(numLines); while (!lines.empty()) { frame.addLine(getColouredString(colour,lines.pop()), showTimestamp); } file.close(); frame.addLine(getColouredString(colour,"--- End of backbuffer\n"), showTimestamp); } catch (FileNotFoundException e) { Logger.userError(ErrorLevel.LOW, "Unable to show backbuffer (Filename: "+filename+"): " + e.getMessage()); } catch (IOException e) { Logger.userError(ErrorLevel.LOW, "Unable to show backbuffer (Filename: "+filename+"): " + e.getMessage()); } catch (SecurityException e) { Logger.userError(ErrorLevel.LOW, "Unable to show backbuffer (Filename: "+filename+"): " + e.getMessage()); } } } /** * Get a coloured String. * If colour is invalid, IRC Colour 14 will be used. * * @param colour The colour the string should be (IRC Colour or 6-digit hex colour) * @param line the line to colour * @return The given line with the appropriate irc codes appended/prepended to colour it. */ protected static String getColouredString(final String colour, final String line) { String res = null; if (colour.length() < 3) { int num; try { num = Integer.parseInt(colour); } catch (NumberFormatException ex) { num = -1; } if (num >= 0 && num <= 15) { res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, num, line); } } else if (colour.length() == 6) { try { Color.decode("#" + colour); res = String.format("%c%s%s%1$c", Styliser.CODE_HEXCOLOUR, colour, line); } catch (NumberFormatException ex) { /* Do Nothing */ } } if (res == null) { res = String.format("%c%02d%s%1$c", Styliser.CODE_COLOUR, 14, line); } return res; } /** * Add a line to a file. * * @param filename Name of file to write to * @param format Format of line to add. (NewLine will be added Automatically) * @param args Arguments for format * @return true on success, else false. */ protected boolean appendLine(final String filename, final String format, final Object... args) { return appendLine(filename, String.format(format, args)); } /** * Add a line to a file. * * @param filename Name of file to write to * @param line Line to add. (NewLine will be added Automatically) * @return true on success, else false. */ protected boolean appendLine(final String filename, final String line) { final StringBuffer finalLine = new StringBuffer(); if (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "general.addtime")) { final DateFormat dateFormat = new SimpleDateFormat(IdentityManager.getGlobalConfig().getOption(MY_DOMAIN, "general.timestamp")); finalLine.append(dateFormat.format(new Date())); } if (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "general.stripcodes")) { finalLine.append(Styliser.stipControlCodes(line)); } else { finalLine.append(line); } //System.out.println("[Adding] "+filename+" => "+finalLine); BufferedWriter out = null; try { if (openFiles.containsKey(filename)) { OpenFile of = openFiles.get(filename); of.lastUsedTime = System.currentTimeMillis(); out = of.writer; } else { out = new BufferedWriter(new FileWriter(filename, true)); openFiles.put(filename, new OpenFile(out)); } out.write(finalLine.toString()); out.newLine(); out.flush(); return true; } catch (IOException e) { /* * Do Nothing * * Makes no sense to keep adding errors to the logger when we can't * write to the file, as chances are it will happen on every incomming * line. */ } return false; } /** * Get the name of the log file for a specific object. * * @param obj Object to get name for * @return the name of the log file to use for this object. */ protected String getLogFile(final Object obj) { final StringBuffer directory = new StringBuffer(); final StringBuffer file = new StringBuffer(); String md5String = ""; directory.append(IdentityManager.getGlobalConfig().getOption(MY_DOMAIN, "general.directory")); if (directory.charAt(directory.length()-1) != File.separatorChar) { directory.append(File.separatorChar); } if (obj == null) { file.append("null.log"); } else if (obj instanceof ChannelInfo) { final ChannelInfo channel = (ChannelInfo) obj; if (channel.getParser() != null) { addNetworkDir(directory, file, channel.getParser().getNetworkName()); } file.append(sanitise(channel.getName().toLowerCase())); md5String = channel.getName(); } else if (obj instanceof ClientInfo) { final ClientInfo client = (ClientInfo) obj; if (client.getParser() != null) { addNetworkDir(directory, file, client.getParser().getNetworkName()); } file.append(sanitise(client.getNickname().toLowerCase())); md5String = client.getNickname(); } else { file.append(sanitise(obj.toString().toLowerCase())); md5String = obj.toString(); } if (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "advanced.usedate")) { final String dateFormat = IdentityManager.getGlobalConfig().getOption(MY_DOMAIN, "advanced.usedateformat"); final String dateDir = (new SimpleDateFormat(dateFormat)).format(new Date()); directory.append(dateDir); if (directory.charAt(directory.length()-1) != File.separatorChar) { directory.append(File.separatorChar); } if (!new File(directory.toString()).exists() && !(new File(directory.toString())).mkdirs()) { Logger.userError(ErrorLevel.LOW, "Unable to create date dirs"); } } if (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "advanced.filenamehash")) { file.append('.'); file.append(md5(md5String)); } file.append(".log"); return directory.toString() + file.toString(); } /** * This function adds the networkName to the log file. * It first tries to create a directory for each network, if that fails * it will prepend the networkName to the filename instead. * * @param directory Current directory name * @param file Current file name * @param networkName Name of network */ protected void addNetworkDir(final StringBuffer directory, final StringBuffer file, final String networkName) { if (!IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "general.networkfolders")) { return; } final String network = sanitise(networkName.toLowerCase()); boolean prependNetwork = false; // Check dir exists final File dir = new File(directory.toString()+network+System.getProperty("file.separator")); if (dir.exists() && !dir.isDirectory()) { Logger.userError(ErrorLevel.LOW, "Unable to create networkfolders dir (file exists instead)"); // Prepend network name to file instead. prependNetwork = true; } else if (!dir.exists() && !dir.mkdirs()) { Logger.userError(ErrorLevel.LOW, "Unable to create networkfolders dir"); prependNetwork = true; } if (prependNetwork) { file.insert(0, " file.insert(0, network); } else { directory.append(network); directory.append(System.getProperty("file.separator")); } } /** * Sanitise a string to be used as a filename. * * @param name String to sanitise * @return Sanitised version of name that can be used as a filename. */ protected static String sanitise(final String name) { return name.replaceAll("[^\\w\\.\\s\\-\\ } /** * Get the md5 hash of a string. * * @param string String to hash * @return md5 hash of given string */ protected static String md5(final String string) { try { final MessageDigest m = MessageDigest.getInstance("MD5"); m.update(string.getBytes(), 0, string.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return ""; } } /** * Get name to display for client. * * @param client The client to get the display name for * @return name to display */ protected String getDisplayName(final ClientInfo client) { return getDisplayName(client, ""); } /** * Get name to display for client. * * @param client The client to get the display name for * @param overrideNick Nickname to display instead of real nickname * @return name to display */ protected String getDisplayName(final ClientInfo client, final String overrideNick) { if (overrideNick.isEmpty()) { return (client == null) ? "Unknown Client" : client.getNickname() ; } else { return overrideNick; } } /** * Get name to display for channelClient (Taking into account the channelmodeprefix setting). * * @param channelClient The client to get the display name for * @return name to display */ protected String getDisplayName(final ChannelClientInfo channelClient) { return getDisplayName(channelClient, ""); } /** * Get name to display for channelClient (Taking into account the channelmodeprefix setting). * * @param channelClient The client to get the display name for * @param overrideNick Nickname to display instead of real nickname * @return name to display */ protected String getDisplayName(final ChannelClientInfo channelClient, final String overrideNick) { final boolean addModePrefix = (IdentityManager.getGlobalConfig().getOptionBool(MY_DOMAIN, "general.channelmodeprefix")); if (channelClient == null) { return (overrideNick.isEmpty()) ? "Unknown Client" : overrideNick; } else if (overrideNick.isEmpty()) { return (addModePrefix) ? channelClient.toString() : channelClient.getNickname(); } else { return (addModePrefix) ? channelClient.getImportantModePrefix() + overrideNick : overrideNick; } } /** * Shows the history window for the specified target, if available. * * @param target The window whose history we're trying to open * @return True if the history is available, false otherwise */ protected boolean showHistory(final InputWindow target) { Object component; if (target.getContainer() instanceof Channel) { component = ((Channel) target.getContainer()).getChannelInfo(); } else if (target.getContainer() instanceof Query) { final IRCParser parser = ((Query) target.getContainer()).getServer().getParser(); component = parser.getClientInfo(((Query) target.getContainer()).getHost()); if (component == null) { component = new ClientInfo(parser, ((Query) target.getContainer()).getHost()).setFake(true); } } else if (target.getContainer() instanceof Server) { component = target.getContainer().getServer().getParser(); } else { // Unknown component return false; } final String log = getLogFile(component); if (!new File(log).exists()) { // File doesn't exist return false; } ReverseFileReader reader; try { reader = new ReverseFileReader(log); } catch (FileNotFoundException ex) { return false; } catch (IOException ex) { return false; } catch (SecurityException ex) { return false; } new HistoryWindow("History", reader, target); return true; } }
package org.jdesktop.swingx.painter; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Paint; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.awt.geom.RectangularShape; import java.awt.geom.RoundRectangle2D; import org.jdesktop.swingx.graphics.GraphicsUtilities; import org.jdesktop.swingx.painter.effects.AreaEffect; /** * A painter which paints square and rounded rectangles * * @author joshua.marinacci@sun.com */ public class RectanglePainter extends AbstractAreaPainter<Object> { private boolean rounded = false; //private Insets insets = new Insets(0,0,0,0); private int roundWidth = 20; private int roundHeight = 20; private int width = -1; private int height = -1; //private double strokeWidth = 1; /** Creates a new instance of RectanglePainter */ public RectanglePainter() { this(0,0,0,0, 0,0, false, Color.RED, 1f, Color.BLACK); } public RectanglePainter(Color fillPaint, Color borderPaint) { this(0,0,0,0,0,0,false,fillPaint,1f,borderPaint); } public RectanglePainter(Paint fillPaint, Paint borderPaint, float borderWidth, RectanglePainter.Style style) { this(); setFillPaint(fillPaint); setBorderPaint(borderPaint); setBorderWidth(borderWidth); setStyle(style); } public RectanglePainter(int top, int left, int bottom, int right) { this(top, left, bottom, right, 0, 0, false, Color.RED, 1f, Color.BLACK); } public RectanglePainter(int top, int left, int bottom, int right, int roundWidth, int roundHeight) { this(top,left,bottom,right,roundWidth, roundHeight, true, Color.RED, 1f, Color.BLACK); } public RectanglePainter(int width, int height, int cornerRadius, Paint fillPaint) { this(new Insets(0,0,0,0), width,height, cornerRadius, cornerRadius, true, fillPaint, 1f, Color.BLACK); } public RectanglePainter(Insets insets, int width, int height, int roundWidth, int roundHeight, boolean rounded, Paint fillPaint, float strokeWidth, Paint borderPaint) { this.width = width; this.height = height; setFillHorizontal(false); setFillVertical(false); setInsets(insets); this.roundWidth = roundWidth; this.roundHeight = roundHeight; this.rounded = rounded; this.setFillPaint(fillPaint); this.setBorderWidth(strokeWidth); this.setBorderPaint(borderPaint); } public RectanglePainter(int top, int left, int bottom, int right, int roundWidth, int roundHeight, boolean rounded, Paint fillPaint, float strokeWidth, Paint borderPaint) { this.setInsets(new Insets(top,left,bottom,right)); setFillVertical(true); setFillHorizontal(true); this.roundWidth = roundWidth; this.roundHeight = roundHeight; this.rounded = rounded; this.setFillPaint(fillPaint); this.setBorderWidth(strokeWidth); this.setBorderPaint(borderPaint); } /** * Indicates if the rectangle is rounded * @return if the rectangle is rounded */ public boolean isRounded() { return rounded; } /** * sets if the rectangle should be rounded * @param rounded if the rectangle should be rounded */ public void setRounded(boolean rounded) { boolean oldRounded = isRounded(); this.rounded = rounded; setDirty(true); firePropertyChange("rounded",oldRounded,rounded); } /** * gets the round width of the rectangle * @return the current round width */ public int getRoundWidth() { return roundWidth; } /** * sets the round width of the rectangle * @param roundWidth a new round width */ public void setRoundWidth(int roundWidth) { int oldRoundWidth = getRoundWidth(); this.roundWidth = roundWidth; setDirty(true); firePropertyChange("roundWidth",oldRoundWidth,roundWidth); } /** * gets the round height of the rectangle * @return the current round height */ public int getRoundHeight() { return roundHeight; } /** * sets the round height of the rectangle * @param roundHeight a new round height */ public void setRoundHeight(int roundHeight) { int oldRoundHeight = getRoundHeight(); this.roundHeight = roundHeight; setDirty(true); firePropertyChange("roundHeight",oldRoundHeight,roundHeight); } protected RectangularShape calculateShape(int width, int height) { Insets insets = getInsets(); int x = insets.left; int y = insets.top; // use the position calcs from the super class Rectangle bounds = calculateLayout(this.width, this.height, width, height); if(this.width != -1 && !isFillHorizontal()) { width = this.width; x = bounds.x; } if(this.height != -1 && !isFillVertical()) { height = this.height; y = bounds.y; } if(isFillHorizontal()) { width = width - insets.left - insets.right; } if(isFillVertical()) { height = height - insets.top - insets.bottom; } RectangularShape shape = new Rectangle2D.Double(x, y, width, height); if(rounded) { shape = new RoundRectangle2D.Double(x, y, width, height, roundWidth, roundHeight); } return shape; } @Override protected void doPaint(Graphics2D g, Object component, int width, int height) { Shape shape = provideShape(g, component, width, height); switch (getStyle()) { case BOTH: drawBackground(g,shape,width,height); drawBorder(g,shape,width,height); break; case FILLED: drawBackground(g,shape,width,height); break; case OUTLINE: drawBorder(g,shape,width,height); break; case NONE: break; } // background // border // leave the clip to support masking other painters GraphicsUtilities.mergeClip(g,shape); /* Area area = new Area(g.getClip()); area.intersect(new Area(shape));//new Rectangle(0,0,width,height))); g.setClip(area);*/ //g.setClip(shape); } private void drawBorder(Graphics2D g, Shape shape, int width, int height) { Paint p = getBorderPaint(); if(isPaintStretched()) { p = calculateSnappedPaint(p, width, height); } g.setPaint(p); g.setStroke(new BasicStroke(getBorderWidth())); // shrink the border by 1 px if(shape instanceof Rectangle2D) { Rectangle2D rect = (Rectangle2D) shape; g.draw(new Rectangle2D.Double(rect.getX(), rect.getY(), rect.getWidth()-1, rect.getHeight()-1)); } else if(shape instanceof RoundRectangle2D) { RoundRectangle2D rect = (RoundRectangle2D) shape; g.draw(new RoundRectangle2D.Double(rect.getX(), rect.getY(), rect.getWidth()-1, rect.getHeight()-1, rect.getArcWidth(), rect.getArcHeight())); } else { g.draw(shape); } } private void drawBackground(Graphics2D g, Shape shape, int width, int height) { Paint p = getFillPaint(); if(isPaintStretched()) { p = calculateSnappedPaint(p, width, height); } g.setPaint(p); g.fill(shape); if(getAreaEffects() != null) { for(AreaEffect ef : getAreaEffects()) { ef.apply(g, shape, width, height); } } } @Override protected Shape provideShape(Graphics2D g, Object comp, int width, int height) { return calculateShape(width,height); } }
package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.plaf.basic.BasicGraphicsUtils; import javax.swing.tree.TreePath; /** * Tree specific cellContext. * <ul> * <li>PENDING: setters for icons? * <li>PENDING: use focus border as returned from list or table instead of * rolling its own? The missing ui-border probably is a consequence of the * border hacking as implemented in core default renderer. SwingX has a * composite default which should use the "normal" border. * </ul> */ public class TreeCellContext extends CellContext<JTree> { /** the icon to use for a leaf node. */ protected Icon leafIcon; /** the default icon to use for a closed folder. */ protected Icon closedIcon; /** the default icon to use for a open folder. */ protected Icon openIcon; /** the border around a focused node. */ private Border treeFocusBorder; /** * Returns the treePath for the row or null if invalid. * */ public TreePath getTreePath() { if (getComponent() == null) return null; if ((row < 0) || (row >= getComponent().getRowCount())) return null; return getComponent().getPathForRow(row); } /** * {@inheritDoc} * <p> * PENDING: implement to return the tree cell editability! */ @Override public boolean isEditable() { return false; // return getComponent() != null ? getComponent().isCellEditable( // getRow(), getColumn()) : false; } /** * {@inheritDoc} */ @Override protected Color getSelectionBackground() { return UIManager.getColor("Tree.selectionBackground"); } /** * {@inheritDoc} */ @Override protected Color getSelectionForeground() { return UIManager.getColor("Tree.selectionForeground"); } /** * {@inheritDoc} */ @Override protected String getUIPrefix() { return "Tree."; } /** * Returns the default icon to use for leaf cell. * * @return the icon to use for leaf cell. */ protected Icon getLeafIcon() { return leafIcon != null ? leafIcon : UIManager .getIcon(getUIKey("leafIcon")); } /** * Returns the default icon to use for open cell. * * @return the icon to use for open cell. */ protected Icon getOpenIcon() { return openIcon != null ? openIcon : UIManager .getIcon(getUIKey("openIcon")); } /** * Returns the default icon to use for closed cell. * * @return the icon to use for closed cell. */ protected Icon getClosedIcon() { return closedIcon != null ? closedIcon : UIManager .getIcon(getUIKey("closedIcon")); } /** * {@inheritDoc} * <p> * * Overridden to return a default depending for the leaf/open cell state. */ @Override public Icon getIcon() { if (isLeaf()) { return getLeafIcon(); } if (isExpanded()) { return getOpenIcon(); } return getClosedIcon(); } @Override protected Border getFocusBorder() { if (treeFocusBorder == null) { treeFocusBorder = new TreeFocusBorder(); } return treeFocusBorder; } /** * Border used to draw around the content of the node. <p> * PENDING: isn't that the same as around a list or table cell, but * without a tree-specific key/value pair in UIManager? */ public class TreeFocusBorder extends LineBorder { private Color treeBackground; private Color focusColor; public TreeFocusBorder() { super(Color.BLACK); treeBackground = getBackground(); if (treeBackground != null) { focusColor = new Color(~treeBackground.getRGB()); } } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color color = UIManager.getColor("Tree.selectionBorderColor"); if (color != null) { lineColor = color; } if (isDashed()) { if (treeBackground != c.getBackground()) { treeBackground = c.getBackground(); focusColor = new Color(~treeBackground.getRGB()); } Color old = g.getColor(); g.setColor(focusColor); BasicGraphicsUtils.drawDashedRect(g, x, y, width, height); g.setColor(old); } else { super.paintBorder(c, g, x, y, width, height); } } /** * @return a boolean indicating whether the focus border * should be painted dashed style. */ private boolean isDashed() { return Boolean.TRUE.equals(UIManager .get("Tree.drawDashedFocusIndicator")); } /** * {@inheritDoc} */ @Override public boolean isBorderOpaque() { return false; } } }
package org.smoothbuild.db.taskresults; import static com.google.common.collect.Lists.newArrayList; import static org.smoothbuild.lang.base.STypes.STRING; import java.util.List; import javax.inject.Inject; import org.smoothbuild.db.hashed.HashedDb; import org.smoothbuild.db.hashed.Marshaller; import org.smoothbuild.db.hashed.Unmarshaller; import org.smoothbuild.db.objects.ObjectsDb; import org.smoothbuild.lang.base.SString; import org.smoothbuild.lang.base.SType; import org.smoothbuild.lang.base.SValue; import org.smoothbuild.message.base.Message; import org.smoothbuild.message.base.MessageType; import org.smoothbuild.message.base.Messages; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashCode; public class TaskResultsDb { private final HashedDb hashedDb; private final ObjectsDb objectsDb; @Inject public TaskResultsDb(@TaskResults HashedDb hashedDb, ObjectsDb objectsDb) { this.hashedDb = hashedDb; this.objectsDb = objectsDb; } public void store(HashCode taskHash, TaskResult<? extends SValue> taskResult) { Marshaller marshaller = new Marshaller(); SValue value = taskResult.value(); ImmutableList<Message> messages = taskResult.messages(); marshaller.write(messages.size()); for (Message message : messages) { SString messageString = objectsDb.string(message.message()); marshaller.write(AllMessageTypes.INSTANCE.valueToByte(message.type())); marshaller.write(messageString.hash()); } if (!Messages.containsProblems(messages)) { marshaller.write(value.hash()); } hashedDb.store(taskHash, marshaller.getBytes()); } public boolean contains(HashCode taskHash) { return hashedDb.contains(taskHash); } public <T extends SValue> TaskResult<T> read(HashCode taskHash, SType<T> type) { try (Unmarshaller unmarshaller = new Unmarshaller(hashedDb, taskHash);) { int size = unmarshaller.readInt(); List<Message> messages = newArrayList(); for (int i = 0; i < size; i++) { MessageType messageType = unmarshaller.readEnum(AllMessageTypes.INSTANCE); HashCode messageStringHash = unmarshaller.readHash(); String messageString = objectsDb.read(STRING, messageStringHash).value(); messages.add(new Message(messageType, messageString)); } if (Messages.containsProblems(messages)) { return new TaskResult<>(null, messages); } else { HashCode resultObjectHash = unmarshaller.readHash(); T value = objectsDb.read(type, resultObjectHash); return new TaskResult<>(value, messages); } } } }
package com.maddyhome.idea.vim.group; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.common.Register; import java.util.List; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; /** * Used to handle playback of macros */ public class MacroGroup extends AbstractActionGroup { public MacroGroup() { } /** * This method is used to play the macro of keystrokes stored in the specified registers. * @param editor The editor to play the macro in * @param context The data context * @param reg The register to get the macro from * @param count The number of times to execute the macro * @return true if able to play the macro, false if invalid or empty register */ public boolean playbackRegister(Editor editor, DataContext context, char reg, int count) { Register register = CommandGroups.getInstance().getRegister().getPlaybackRegister(reg); if (register == null) { return false; } List keys = register.getKeys(); for (int i = 0; i < count; i++) { playbackKeys(editor, context, keys, 0); } lastRegister = reg; return true; } /** * This plays back the last register that was executed, if any. * @param editor The editr to play the macro in * @param context The data context * @param count The number of times to execute the macro * @return true if able to play the macro, false in no previous playback */ public boolean playbackLastRegister(Editor editor, DataContext context, int count) { if (lastRegister != 0) { return playbackRegister(editor, context, lastRegister, count); } return false; } /** * This puts a single keystroke at the end of the event queue for playback * @param editor The editor to play the key in * @param context The data cotnext * @param keys The list of keys to playback * @param pos The position within the list for the specific key to queue */ private void playbackKeys(final Editor editor, final DataContext context, final List keys, final int pos) { if (pos >= keys.size()) { return; } // This took a while to get just right. The original approach has a loop that made a runnable for each // character. It worked except for one case - if the macro had a complete ex command, the editor did not // end up with the focus and I couldn't find anyway to get it to have focus. This approach was the only // solution. This makes the most sense now (of course it took hours of trial and error to come up with // this one). Each key gets added, one at a time, to the event queue. If a given key results in other // events getting queued, they get queued before the next key, just what would happen if the user was typing // the keys one at a time. With the old loop approach, all the keys got queued, then any events they caused // were queued - after the keys. This is what caused the problem. final KeyStroke stroke = (KeyStroke)keys.get(pos); Runnable run = new Runnable() { public void run() { // Handle one keystroke then queue up the next key KeyHandler.getInstance().handleKey(editor, stroke, context); if (pos < keys.size()) { playbackKeys(editor, context, keys, pos + 1); } } }; SwingUtilities.invokeLater(run); } private char lastRegister = 0; }
package com.madphysicist.tools.swing; import com.madphysicist.tools.util.Credentials; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dialog.ModalityType; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Insets; import java.awt.TextComponent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.border.TitledBorder; import javax.swing.text.JTextComponent; /** * A panel in which the user can enter their user name and password. The user * name can optionally be selected from an editable dropdown combo box. If the * panel is not initialized with any user names, the user name input is a text * field. If a list of domains is specified, a domain may also be selected from * a dropdown combo box. This combo box is not visible if there are no domains * to choose from. This class also has a method for displaying a modal dialog * for logging in. * <p> * This class is basically a configurable GUI editor for the {@link * com.madphysicist.tools.util.Credentials} class. * * @author Joseph Fox-Rabinovitz * @version 1.0.0 17 Nov 2013 - J. Fox-Rabinovitz - Created * @since 1.0.0 */ public class LoginPanel extends JPanel { /** * The version ID for serialization. * * @serial Increment the least significant three digits when compatibility * is not compromised by a structural change (e.g. adding a new field with * a sensible default value), and the upper digits when the change makes * serialized versions of of the class incompatible with previous releases. * @since 1.0.0 */ private static final long serialVersionUID = 1000L; /** * The default text of {@link #userNameLabel}. * * @since 1.0.0 */ private static final String USER_NAME_STRING = "User Name:"; /** * The default text of {@link #passwordLabel}. * * @since 1.0.0 */ private static final String PASSWORD_STRING = "Password:"; /** * The default text of {@link #domainLabel}. * * @since 1.0.0 */ private static final String DOMAIN_STRING = "Domain:"; /** * The editable combo-box used to display and edit user names. The model of * this combo box is always set to a {@link SetListModel}, and used to store * the preconfigured user names. If there are no preconfigured user names, * this reference is {@code null}, and the user name is entered through * {@link #userNameField} instead. * * @see #userNameModel * @serial * @since 1.0.0 */ private JComboBox<String> userNameCombo = null; /** * A reference to the model of {@link #userNameCombo}. This field is {@code * null} if {@code userNameCombo} is {@code null}. This reference is * maintained to avoid constant casting whenever access to the model is * required. * * @serial * @since 1.0.0 */ private SetListModel<String> userNameModel = null; /** * The text field used to display and edit user names. If there are * preconfigured user names, they are displayed and edited by {@link * #userNameCombo} and this reference is set to {@code null}. * * @serial * @since 1.0.0 */ private JTextField userNameField = null; /** * The text field used to display and edit the password. The password is * never displayed as plain text. This reference is never {@code null} past * the constructor. * * @serial * @since 1.0.0 */ private JPasswordField passwordField = null; /** * The combo box used to display and select the domain. The model of this * combo box is always set to a {@link SetListModel}, and used to store the * preconfigured domains. If there are no preconfigured domains, this * reference is set to {@code null}. * * @see #domainModel * @serial * @since 1.0.0 */ private JComboBox<String> domainCombo = null; /** * A reference to the model of {@link #domainCombo}. This field is {@code * null} if {@code domainCombo} is {@code null}. This reference is * maintained to avoid constant casting whenever access to the model is * required. * * @serial * @since 1.0.0 */ private SetListModel<String> domainModel = null; /** * The label for the user name editor. The text of the label is configurable * via the {@link #setUserNameLabelText(String)}. If additional * configuration is required, the label itself may be retrieved using the * {@link #getUserNameLabel()} method. This reference is never {@code null} * past the constructor, although the component that it is a label for may * change. * * @serial * @since 1.0.0 */ private JLabel userNameLabel = null; /** * The label for the password text field. The text of the label is * configurable via the {@link #setPasswordLabelText(String)}. If additional * configuration is required, the label itself may be retrieved using the * {@link #getPasswordLabel()} method. This reference is never {@code null} * past the constructor. * * @serial * @since 1.0.0 */ private JLabel passwordLabel = null; /** * The label for the domain editor. The text of the label is configurable * via the {@link #setDomainLabelText(String)}. If additional configuration * is required, the label itself may be retrieved using the {@link * #getDomainLabel()} method. This reference is never {@code null} past the * constuctor, even if {@link #domainCombo} is set to {@code null}. * * @serial * @since 1.0.0 */ private JLabel domainLabel = null; /** * Constructs a panel with no preconfigured user names or domain names. This * will display a simple text field for the user name and a password field. * There will be no way to edit the domain name. * * @since 1.0.0 */ public LoginPanel() { this(null); } /** * Constructs a panel with no preconfigured domain names. This will display * an editable combo box to select user names if there are preconfigured * values. The password will be entered through a password field. There will * be no way to edit the domain name. * * @param userNames the preconfigured user names. The user names will be * displayed in a sorted editable combo box. If the collection is {@code * null} or empty, the user name input will revert to a text field. * @since 1.0.0 */ public LoginPanel(Collection<String> userNames) { this(userNames, null); } /** * Constructs a panel with preconfigured user names and domain names. This * will display an editable combo box to select user names if there are * preconfigured values. The password will be entered through a password * field. There will be a non-editable combo box to select the domain name, * if there are preconfigured values. * * @param userNames the preconfigured user names. The user names will be * displayed in a sorted editable combo box. If the collection is {@code * null} or empty, the user name input will revert to a text field. * @param domains the preconfigured domain names. The domain names will be * displayed in a sorted, non-editable combo box. If the collection is * {@code null} or empty, the domain name input will not be displayed at * all. * @since 1.0.0 */ public LoginPanel(Collection<String> userNames, Collection<String> domains) { super(new GridBagLayout()); initComponents(userNames, domains); } /** * Initializes the sub-components of this panel. The user name is editor is * either a text field or a combo box. The password is manipulated through a * password field. The domain name is optionally selected from a * non-editable combo box. * * @param userNames the user names to configure this panel with. If this * collection contains values, the user name will be displayed and edited * through an editable combo box. Otherwise it will be in a text field. * @param domains the domain names to configure this panel with. If this * collection contains values, the domain name will be displayed and * selected through a non-editable combo box. Otherwise, the combo box will * not be displayed at all. * @since 1.0.0 */ private void initComponents(Collection<String> userNames, Collection<String> domains) { userNameLabel = new JLabel(USER_NAME_STRING); passwordLabel = new JLabel(PASSWORD_STRING); domainLabel = new JLabel(DOMAIN_STRING); passwordField = new JPasswordField(20); passwordLabel.setLabelFor(passwordField); if(userNames == null || userNames.isEmpty()) { setUserNameField(); } else { setUserNameCombo(userNames); Component editor = userNameCombo.getEditor().getEditorComponent(); if(editor instanceof TextComponent) { ((TextComponent)editor).setCaretPosition(Integer.MAX_VALUE); } else if(editor instanceof JTextComponent) { ((JTextComponent)editor).setCaretPosition(((JTextComponent)editor).getText().length()); } } add(userNameLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, GridBagConstants.NORTHWEST, 0, 0)); if(domains == null || domains.isEmpty()) { destroyDomainCombo(false); } else { createDomainCombo(domains, false); } } /** * Checks if the configured list of user names contains the specified value. * * @param userName the user name to check for. * @return {@code false} if there are no configured user names or if the * list does not contain the specified value, {@code true} otherwise. * @since 1.0.0 */ public boolean containsUserName(String userName) { return (userNameModel != null) && userNameModel.contains(userName); } /** * Checks if the configured list of domains contains the specified value. * * @param domain the domain to check for. * @return {@code false} if there are no configured domains or if the list * does not contain the specified value, {@code true} otherwise. * @since 1.0.0 */ public boolean containsDomain(String domain) { return (domainModel != null) && domainModel.contains(domain); } /** * Adds the specified user name to the configured list. If this is the first * user name to be configured, the text box editor will be converted to an * editable combo box to display the configured user name. Otherwise the * name will be added to the dropdown list of the existing combo box in * alphabetical order. Duplicate user names are ignored. * * @param userName the user name to add to the list of configured names. * @return {@code true} if the name was added to the list of preconfigured * user names, {@code false} if it was already in the list. * @since 1.0.0 */ public boolean addUserName(String userName) { if(userNameCombo == null) { setUserNameCombo(Arrays.asList(new String[] {userName})); return true; } return userNameModel.putElement(userName); } /** * Adds the specified domain to the configured list. If this is the first * domain to be configured, a non-editable combo box will be added to * display the configured domain. Otherwise the domain will be added to the * dropdown list of the existing combo box in alphabetical order. Duplicate * domains are ignored. * * @param domain the domain to add to the list of configured domains. * @return {@code true} if the domain was added to the list of preconfigured * domains, {@code false} if it was already in the list. * @since 1.0.0 */ public boolean addDomain(String domain) { if(domainCombo == null) { createDomainCombo(Arrays.asList(new String[] {domain}), true); return true; } return domainModel.putElement(domain); } /** * Removes the specified user name from the list of preconfigured list. If * the last user name in the list is removed, the editor is converted from a * combo box into a text field. * * @param userName the user name to remove. * @return {@code true} if the specified user name was removed from the * list, {@code false} if the list is empty or the user name was not found * in it. * @since 1.0.0 */ public boolean removeUserName(String userName) { if(userNameModel != null) { int size = userNameModel.getSize(); userNameModel.removeElement(userName); if(userNameModel.isEmpty()) { setUserNameField(); return true; } return (size != userNameModel.getSize()); } return false; } /** * Removes the specified domain from the list of preconfigured list. If the * last domain in the list is removed, the combo box displaying the list is * removed entirely from the panel. * * @param domain the domain to remove. * @return {@code true} if the specified domain was removed from the list, * {@code false} if the list is empty or the domain was not found in it. * @since 1.0.0 */ public boolean removeDomain(String domain) { if(domainModel != null) { int size = domainModel.getSize(); domainModel.removeElement(domain); if(domainModel.isEmpty()) { destroyDomainCombo(true); return true; } return (size != domainModel.getSize()); } return false; } /** * Removes all preconfigured user names. The user name editor is converted * from a combo box to a text field. * * @since 1.0.0 */ public void clearUserNames() { if(userNameModel != null) { userNameModel.removeAllElements(); setUserNameField(); } } /** * Removes all preconfigured domains. The domain combo box is removed * entirely from this panel. * * @since 1.0.0 */ public void clearDomains() { if(domainModel != null) { domainModel.removeAllElements(); destroyDomainCombo(true); } } /** * Retrieves the user name currently entered in the text field or combo box * of this panel. * * @return the current user name. May be an empty string. * @since 1.0.0 */ public String getUserName() { if(userNameField != null) { return userNameField.getText(); } else if(userNameCombo != null) { return userNameCombo.getEditor().getItem().toString(); } else { throw new IllegalStateException("UserName editor not initialized"); } } /** * Returns the password currently entered int eh password field. This value * should be zeroed out once it is no longer needed. * * @return the current password. May be an empty array. * @since 1.0.0 */ public char[] getPassword() { if(passwordField != null) { return passwordField.getPassword(); } else { throw new IllegalStateException("Password editor not initialized"); } } /** * Returns the domain currently selected from the combo box on this panel. * Returns {@code null} if there are no preconfigured domains to display. * * @return the current domain. If the domain combo box is not displayed, * the return value is always {@code null}. * @since 1.0.0 */ public String getDomain() { if(domainCombo != null) { return domainCombo.getSelectedItem().toString(); } else { return null; } } /** * Returns the user name, domain and password currently entered into the * form. The user name and password may be empty and the domain name may be * {@code null}. * * @return the current credentials. * @since 1.0.0 */ public Credentials getCredentials() { return new Credentials(getUserName(), getDomain(), getPassword()); } /** * Sets the label text of the user name selector or text field. * * @param newLabel the new label text to set. * @since 1.0.0 */ public void setUserNameLabelText(String newLabel) { userNameLabel.setText(newLabel); } /** * Sets the label text of the password field. * * @param newLabel the new label text to set. * @since 1.0.0 */ public void setPasswordLabelText(String newLabel) { passwordLabel.setText(newLabel); } /** * Sets the label text of the domain selector. If the domain selector is not * shown, this method records the new text for future use. The specified * label will show up later if domains are added to the selector. * * @param newLabel the new label text to set. * @since 1.0.0 */ public void setDomainLabelText(String newLabel) { domainLabel.setText(newLabel); } /** * Retrieves the label of the user name editor in case additional * customization is required. * * @return the label for the user name editor. * @since 1.0.0 */ public JLabel getUserNameLabel() { return userNameLabel; } /** * Retrieves the label of the password field in case additional * customization is required. * * @return the label for the password field. * @since 1.0.0 */ public JLabel getPasswordLabel() { return passwordLabel; } /** * Retrieves the label of the domain selector in case additional * customization is required. Note that this reference will exist even if * the domain selector is not displayed. * * @return the label for the domain combo box. * @since 1.0.0 */ public JLabel getDomainLabel() { return domainLabel; } /** * Shows this panel on an appliation modal dialog and blocks until the * dialog closes. The dialog will have "OK" and "Cancel" buttons. If the * user clicks "OK", the entered credentials are returned. If the user * clicks "Cancel", the return value is {@code null}. * * @return either the entered credentials if the user clicks "OK", or {@code * null} if the user clicks "Cancel". * @since 1.0.0 */ public Credentials displayDialog() { return displayDialog(null); } /** * Shows this panel on an appliation modal dialog and blocks until the * dialog closes. The dialog will have "OK" and "Cancel" buttons. If the * user clicks "OK", the entered credentials are returned. If the user * clicks "Cancel", the return value is {@code null}. * * @param icons an icon set to use for the displayed dialog; * @return either the entered credentials if the user clicks "OK", or {@code * null} if the user clicks "Cancel". * @since 1.0.0 */ public Credentials displayDialog(List<? extends Image> icons) { LoginDialog dialog = new LoginDialog(icons); dialog.setVisible(true); return dialog.getCredentials(); } /** * A convenience method for showing a dialog without explicitly * instantiating this class. This method is an alias for * <pre>showDialog(userNames, null, null)</pre> * The panel in the dialog will not display a domain selector. * * @param userNames the user names to show in the editable combo box where * the user enters their user name. If this reference is {@code null} or * empty, the user name will be entered through a simple text field. * @return the credentials set by the user in the dialog if the user clicks * "OK", or {@code null} if the user clicks "Cancel". * @see #showDialog(Collection, Collection, List) * @since 1.0.0 */ public static Credentials showDialog(Collection<String> userNames) { return showDialog(userNames, null, null); } /** * A convenience method for showing a dialog without explicitly * instantiating this class. This method is an alias for * <pre>new LoginPanel(userNames, domains).displayDialog()</pre> * * @param userNames the user names to show in the editable combo box where * the user enters their user name. If this reference is {@code null} or * empty, the user name will be entered through a simple text field. * @param domains the domains to show in the non-editable combo box from * which the user selects their domain. If this reference is {@code null} or * empty, the domain combo box will not be shown at all. * @return the credentials set by the user in the dialog if the user clicks * "OK", or {@code null} if the user clicks "Cancel". * @see #displayDialog() * @since 1.0.0 */ public static Credentials showDialog(Collection<String> userNames, Collection<String> domains) { return new LoginPanel(userNames, domains).displayDialog(); } /** * A convenience method for showing a dialog without explicitly * instantiating this class. This method is an alias for * <pre>new LoginPanel(userNames, domains).displayDialog(icons)</pre> * * @param userNames the user names to show in the editable combo box where * the user enters their user name. If this reference is {@code null} or * empty, the user name will be entered through a simple text field. * @param domains the domains to show in the non-editable combo box from * which the user selects their domain. If this reference is {@code null} or * empty, the domain combo box will not be shown at all. * @param icons the icon that will be displayed on the dialog. This may be * {@code null}. * @return the credentials set by the user in the dialog if the user clicks * "OK", or {@code null} if the user clicks "Cancel". * @see #displayDialog(List) * @since 1.0.0 */ public static Credentials showDialog(Collection<String> userNames, Collection<String> domains, List<? extends Image> icons) { return new LoginPanel(userNames, domains).displayDialog(icons); } /** * Sets the user name editor to a combo box containing the specified values. * The values are assumed to be a non-empty collection. The model of {@link * #userNameCombo} is set to a {@link SetListModel}, referenced by {@link * #userNameModel}. {@link #userNameField} is set to {@code null} after * being removed from the pabel. The combo box is added in its place. {@link * #userNameLabel} is set as the label for the combo box. * <p> * The panel will be validated and repainted if the previous editor was a * text field. If the previous editor was {@code null}, we are still in the * constructor and should not validate yet. * * @param userNames the user names to add to the new combo box. * @see #addUserNameEditor(JComponent, JComponent) * @since 1.0.0 */ private void setUserNameCombo(Collection<String> userNames) { userNameModel = new SetListModel<>(userNames); userNameCombo = new JComboBox<>(userNameModel); userNameCombo.setEditable(true); userNameCombo.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); addUserNameEditor(userNameCombo, userNameField); userNameField = null; } /** * Sets the user name editor to a text field. {@link #userNameCombo} and * {@link #userNameModel} are set to {@code null}, after being removed from * the panel. {@link #userNameField} is created and added in as the new * editor. {@link #userNameLabel} is set as the label for the text field. * <p> * The panel will be validated and repainted if the previous editor was a * combo box . If the previous editor was {@code null}, we are still in the * constructor and should not validate yet. * * @see #addUserNameEditor(JComponent, JComponent) * @since 1.0.0 */ private void setUserNameField() { userNameField = new JTextField(); addUserNameEditor(userNameField, userNameCombo); userNameCombo = null; userNameModel = null; } /** * Adds the newly created component as an editor for user names in place of * the previous comonent. The new component may be a text field or editable * combo box, depending on whether there are preconfigured user names or * not. If the previous editor is {@code null}, the panel is not validated * or repainted because we are still in the constructor. The new editor is * added to the layout with the proper {@code GridBagConstraints} to * maintain the layout from {@link #initComponents(Collection, Collection)}. * * @param userNameEditor the new editor. * @param previousEditor either the previous editor component or {@code * null} if this method is invoked from the constructor. If it is not {@code * null}, the previous component is explicitly removed from this panel * before the new one is added, and the panel is validated and repainted * afterwards. * @see #valipaint() * @since 1.0.0 */ private void addUserNameEditor(JComponent userNameEditor, JComponent previousEditor) { boolean validateNeeded = (previousEditor != null); if(validateNeeded) { remove(previousEditor); } userNameLabel.setLabelFor(userNameEditor); add(userNameEditor, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, GridBagConstants.NORTHEAST, 0, 0)); if(validateNeeded) { valipaint(); } } /** * Creates and adds the domain name combo box when the first domain name is * configured. The domain is specified as a collection so that the * constructor can add many domains simultaneously. The new combo box is * added to the layout with the proper {@code GridBagConstraints} to * maintain the layout from {@link #initComponents(Collection, Collection)}. * The insets of the components above it, the password field and label, are * also adjusted. * * @param domains the domains to show in the combo box. This collection is * assumed to be non-empty. * @param validate {@code true} if this panel needs to be validated and * repainted, {@code false} otherwise. The only time a validation is not * required is when this method is called from the constructor. * @see #replacePasswordInsets(Insets, Insets, boolean) * @since 1.0.0 */ private void createDomainCombo(Collection<String> domains, boolean validate) { domainModel = new SetListModel<>(domains); domainCombo = new JComboBox<>(domainModel); domainLabel.setLabelFor(domainCombo); add(domainCombo, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, GridBagConstants.SOUTHEAST, 0, 0)); add(domainLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, GridBagConstants.SOUTHWEST, 0, 0)); replacePasswordInsets(GridBagConstants.EAST, GridBagConstants.WEST, validate); } /** * Removes the domain name combo box when the last domain name is removed * from the configured list. To preserve the layout format from {@link * #initComponents(Collection, Collection)}, the insets of the components * above the combo box, the password field and label, are adjusted to * reflect that they are now at the bottom of the panel. * * @param validate {@code true} if this panel needs to be validated and * repainted, {@code false} otherwise. The only time a validation is not * required is when this method is called from the constructor. * @see #replacePasswordInsets(Insets, Insets, boolean) * @since 1.0.0 */ private void destroyDomainCombo(boolean validate) { if(validate) { remove(domainCombo); remove(domainLabel); } domainModel = null; domainCombo = null; replacePasswordInsets(GridBagConstants.SOUTHEAST, GridBagConstants.SOUTHWEST, validate); } /** * Replaces the {@code Inset}s used to display the password label and field * with the specified values. This should be done whenever a component is * added or subtracted from below the fields so that they move towards or * away from the bottom edge. * * @param editorInsets the insets of the editor field, which appears to the * right. * @param labelInsets the insets of the label, which appears to the left. * @param validate {@code true} if the component needs to be validated and * repainted after the insets are changed. The only time the component * should not be validated is when this method is called within the * constructor. If this parameter is {@code true}, the password field and * label will first be removed from the panel before being added back. * Otherwise, this method is being executed in the constructor and there is * nothing to remove. * @see #valipaint() * @since 1.0.0 */ private void replacePasswordInsets(Insets editorInsets, Insets labelInsets, boolean validate) { if(validate) { remove(passwordField); remove(passwordLabel); } add(passwordField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, editorInsets, 0, 0)); add(passwordLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, labelInsets, 0, 0)); if(validate) { valipaint(); } } /** * Calls {@link #validate()} and {@link #repaint()} on this component, in * that order. This method is provided purely for convenience. * * @since 1.0.0 */ private void valipaint() { validate(); repaint(); } /** * The dialog displayed by the {@code displayDialog()} and static {@code * showDialog()} methods of the parent class. This class records the user's * selection when one is made. * * @author Joseph Fox-Rabinovitz * @version 1.0.0 19 Nov 2013 - J. Fox-Rabinovitz - Created * @since 1.0.0 */ private class LoginDialog extends JDialog { /** * The version ID for serialization. * * @serial Increment the least significant three digits when * compatibility is not compromised by a structural change (e.g. adding * a new field with a sensible default value), and the upper digits when * the change makes serialized versions of of the class incompatible * with previous releases. * @since 1.0.0 */ private static final long serialVersionUID = 1000L; /** * The current credentials. This reference is always {@code null} until * the user presses the OK button, when the state of the panel at that * time is retrieved. * * @serial * @since 1.0.0 */ private Credentials credentials; public LoginDialog(List<? extends Image> icons) { super(null, "Login Credentials", ModalityType.APPLICATION_MODAL); this.credentials = null; Action approveAction = new AbstractAction("OK") { private static final long serialVersionUID = 1000L; @Override public void actionPerformed(ActionEvent e) { destroy(LoginPanel.this.getCredentials()); } }; Action rejectAction = new AbstractAction("Cancel") { private static final long serialVersionUID = 1000L; @Override public void actionPerformed(ActionEvent e) { destroy(null); } }; JButton approveButton = new JButton(approveAction); JButton rejectButton = new JButton(rejectAction); JPanel buttonPanel = new JPanel(new GridLayout(1, 2, GridBagConstants.HORIZONTAL_INSET, 0)); buttonPanel.add(rejectButton); buttonPanel.add(approveButton); setLayout(new GridBagLayout()); add(LoginPanel.this, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, GridBagConstants.FILL_HORIZONTAL_NORTH, 0, 0)); add(buttonPanel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LAST_LINE_END, GridBagConstraints.NONE, GridBagConstants.FILL_HORIZONTAL_SOUTH, 0, 0)); getRootPane().setDefaultButton(approveButton); SwingUtilities.setGlobalAccelerator(getRootPane(), KeyStroke.getKeyStroke("ESCAPE"), rejectAction); setIconImages(icons); pack(); setResizable(false); setLocationRelativeTo(null); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { destroy(null); } }); } public Credentials getCredentials() { return credentials; } /** * Makes the dialog visible and requests keyboard focus for the password * field. The password field is focused first because this method * blocks. * * @param b {@inheritDoc} * @since 1.0.0 */ @Override public void setVisible(boolean b) { if(b) { passwordField.requestFocusInWindow(); } super.setVisible(b); } /** * Destroys the dialog GUI. The visibility is set to {@code false} so * that any methods blocking until the dialog disappears can continue. * The {@code LoginPanel} is removed from the dialog and system * resources are freed. This method also sets {@link #credentials}. * * @param credentials the credentials to return. This value should be * {@code null} if this method is called when the "Cancel" button is * clicked. Otherwise, the credentials should come from the panel being * displayed. * @since 1.0.0 */ private void destroy(Credentials credentials) { this.credentials = credentials; setVisible(false); remove(LoginPanel.this); dispose(); } } /** * A panel that displays a {@link JTextField}, a {@link JList}, and two * {@link JButton}s to add and remove entries from either the user or domain * lists on a {@link LoginPanel}. * * @author Joseph Fox-Rabinovitz * @version 1.0.0 18 Nov 2013 - J. Fox-Rabinovitz - Created * @since 1.0.0 */ private class DemoPanel extends JPanel { /** * The version ID for serialization. * * @serial Increment the least significant three digits when * compatibility is not compromised by a structural change (e.g. adding * a new field with a sensible default value), and the upper digits when * the change makes serialized versions of of the class incompatible * with previous releases. * @since 1.0.0 */ private static final long serialVersionUID = 1000L; private final JTextField text; private final JList<String> list; private final SetListModel<String> model; private final JButton add; private final JButton remove; private final String type; public DemoPanel(String type) { super(new GridBagLayout()); setBorder(new TitledBorder(type + " Names")); this.type = type; ActionListener addActionListener = new ActionListener() { @SuppressWarnings({"UseSpecificCatch", "CallToThreadDumpStack", "UseOfSystemOutOrSystemErr"}) @Override public void actionPerformed(ActionEvent e) { String entry = text.getText(); if(entry != null && !entry.isEmpty()) { text.setText(""); model.putElement(entry); try { Method add = LoginPanel.class.getMethod("add" + DemoPanel.this.type, String.class); add.invoke(LoginPanel.this, entry); } catch(Exception ex) { System.err.println("You messed up, clever user! (calling add" + DemoPanel.this.type + ")"); ex.printStackTrace(); } } } }; ActionListener removeActionListener = new ActionListener() { @SuppressWarnings({"UseSpecificCatch", "CallToThreadDumpStack", "UseOfSystemOutOrSystemErr"}) @Override public void actionPerformed(ActionEvent e) { int[] indices = list.getSelectedIndices(); // list is in ascending order for(int i = indices.length - 1; i >= 0; i String entry = model.getElementAt(indices[i]); model.removeElementAt(indices[i]); try { Method remove = LoginPanel.class.getMethod("remove" + DemoPanel.this.type, String.class); remove.invoke(LoginPanel.this, entry); } catch(Exception ex) { System.err.println("You messed up, clever user! (calling remove" + DemoPanel.this.type + ")"); ex.printStackTrace(); } } } }; text = new JTextField(10); text.addActionListener(addActionListener); add(text, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, GridBagConstants.NORTHWEST, 0, 0)); model = new SetListModel<>(); list = new JList<>(model); add(new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), new GridBagConstraints(0, 1, 1, 2, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, GridBagConstants.SOUTHWEST, 0, 0)); add = new JButton("Add"); add.addActionListener(addActionListener); add(add, new GridBagConstraints(1, 0, 1, 2, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, GridBagConstants.NORTHEAST, 0, 0)); remove = new JButton("Remove"); remove.addActionListener(removeActionListener); add(remove, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, GridBagConstants.EAST, 0, 0)); } } /** * Runs a demo of {@code LoginPanel}. The user is presented with a login * panel, a side panel that allows the editing of the login panel's * properties, and a look-and-feel selector that allows the components to be * viewed with any of the installed LAFs. * * @param args the command line arguments are always ignored. * @since 1.0.0 */ public static void main(String[] args) { if(args.length > 0 && args[0].equalsIgnoreCase("Dialog")) { Credentials credentials = showDialog( Arrays.asList("user", "admin", "guest"), Arrays.asList("WORKGROUP", "NET_DOMAIN")); if(credentials != null) { JOptionPane.showMessageDialog(null, "<html>" + "UserName: " + credentials.getUserName() + "<br/>" + "Password: " + new String(credentials.getPassword()) + "<br/>" + "Domain: " + credentials.getDomain() + "</html>", "Credentials Approved", JOptionPane.INFORMATION_MESSAGE); credentials.clearPassword(); } else { JOptionPane.showMessageDialog(null, "You chose to cancel your selection.", "Credentials Rejected", JOptionPane.WARNING_MESSAGE); } } else { LoginPanel loginPanel = new LoginPanel(); loginPanel.setBorder(new TitledBorder("Login Panel")); JPanel sidePanel = new JPanel(new GridLayout(2, 1)); sidePanel.setBorder(new TitledBorder("Edit Properties")); sidePanel.add(loginPanel.new DemoPanel("User")); sidePanel.add(loginPanel.new DemoPanel("Domain")); JFrame frame = new JFrame("LoginPanel Demo v1.0.0"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(loginPanel, BorderLayout.CENTER); frame.add(sidePanel, BorderLayout.EAST); frame.add(SwingUtilities.lookAndFeelSelector(frame), BorderLayout.SOUTH); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } }
package com.moltendorf.bukkit.intellidoors; /** * Door list. * * @author moltendorf */ class List { // Variable data. private Door first = null, last = null, pointer = null; protected synchronized void push(final Door door) { if (first == null) { first = door; } else { door.previous = last; last.next = door; } last = door; } protected synchronized void splice(final Door door) { if (door.previous == null) { first = door.next; } else { door.previous.next = door.next; } if (door.next == null) { last = door.previous; } else { door.next.previous = door.previous; } door.next = null; door.previous = null; } protected synchronized void splice(final Door door, final Door[] list) { if (door.previous == null) { first = list[0]; } else { list[0].previous = door.previous; door.previous.next = list[0]; } if (door.next == null) { last = list[list.length-1]; } else { list[list.length-1].next = door.next; door.next.previous = list[list.length-1]; } door.next = null; door.previous = null; pointer = list[0]; for (int i = 1; i < list.length; ++i) { list[i-1].next = list[i]; list[i].previous = list[i-1]; } } protected synchronized void destruct() { for (Door current = first; current != null; current = pointer) { pointer = current.next; current.cancel(); current.run(this); } pointer = null; } private Door scan(final Set_Door_Double set) { for (Door current = first; current != null; current = pointer) { pointer = current.next; if (current.equals(set, this)) { return current; } } return null; } protected synchronized Door get(final Set_Door_Double set) { final Door door = scan(set); pointer = null; return door; } private Door scan(final Set_Door_Single set) { for (Door current = first; current != null; current = pointer) { pointer = current.next; if (current.equals(set, this)) { return current; } } return null; } protected synchronized Door get(final Set_Door_Single set) { final Door door = scan(set); pointer = null; return door; } protected synchronized Door get(final Set_Trap set) { for (Door current = first; current != null; current = current.next) { if (current.equals(set)) { return current; } } return null; } }
package com.squeed.microgramcaster; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.MediaRouteActionProvider; import android.support.v7.media.MediaRouteSelector; import android.support.v7.media.MediaRouter; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.cast.ApplicationMetadata; import com.google.android.gms.cast.Cast; import com.google.android.gms.cast.Cast.ApplicationConnectionResult; import com.google.android.gms.cast.CastDevice; import com.google.android.gms.cast.CastMediaControlIntent; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.squeed.microgramcaster.channel.Command; import com.squeed.microgramcaster.channel.CommandFactory; import com.squeed.microgramcaster.channel.MicrogramCasterChannel; import com.squeed.microgramcaster.media.IsoFileUtil; import com.squeed.microgramcaster.media.MediaItem; import com.squeed.microgramcaster.media.MediaStoreAdapter; import com.squeed.microgramcaster.server.MyHTTPD; import com.squeed.microgramcaster.server.WebServerService; import com.squeed.microgramcaster.util.TimeFormatter; import com.squeed.microgramcaster.util.WifiHelper; /** * Start Activity for the MicrogramCaster Android app. * * Lists castable files, starts the HTTP server through a Service Intent and * provides the Google Cast plumbing. * * Derived from Google's android-helloworld examples at github.com (TODO add * full URL) * * @author Erik * */ public class MainActivity extends ActionBarActivity { private static final String TAG = "MainActivity"; private static final String APP_NAME = "4E4599F7"; private CastDevice mSelectedDevice; private MediaRouter mMediaRouter; private MediaRouteSelector mMediaRouteSelector; private MediaRouter.Callback mMediaRouterCallback; private GoogleApiClient mApiClient; private Cast.Listener mCastListener; private ConnectionCallbacks mConnectionCallbacks; private ConnectionFailedListener mConnectionFailedListener; private MicrogramCasterChannel mMicrogramCasterChannel; private boolean mApplicationStarted; private boolean mWaitingForReconnect; private MenuItem rotateIcon; private MenuItem playIcon; private MenuItem pauseIcon; private SeekBar seekBar; private ArrayAdapterItem adapter; private TextView currentPosition; private TextView totalDuration; private ProgressDialog loadingDialog; private AlertDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.squeed.microgramcaster.R.layout.activity_main); //ActionBar actionBar = getSupportActionBar(); // actionBar.setBackgroundDrawable(new ColorDrawable( // android.R.color.transparent)); startWebServer(); initMediaRouter(); listVideoFiles(); initSeekBar(); initDialogs(); } private void initDialogs() { this.loadingDialog = new ProgressDialog(this); this.loadingDialog.setTitle("Loading"); this.dialog = new AlertDialog.Builder(this).create(); this.dialog.setTitle("Information"); this.dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); } private void startWebServer() { Intent webServerService = new Intent(this, WebServerService.class); this.startService(webServerService); } private void initSeekBar() { currentPosition = (TextView) findViewById(R.id.currentPosition); totalDuration = (TextView) findViewById(R.id.totalDuration); seekBar = (SeekBar) findViewById(R.id.seekBar1); seekBar.setEnabled(false); // seekBar.setVisibility(SeekBar.INVISIBLE); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { currentPosition.setText(TimeFormatter.formatTime(progress)); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { seekBarHandler.removeCallbacksAndMessages(null); sendMessage(CommandFactory.buildSeekPositionCommand(seekBar.getProgress())); } }); } private void showSeekbar() { seekBar.setEnabled(true); seekBar.setProgress(currentSeekbarPosition); // seekBar.setVisibility(SeekBar.VISIBLE); totalDuration.setVisibility(TextView.VISIBLE); currentPosition.setVisibility(TextView.VISIBLE); } private void hideSeekbar() { adapter.setSelectedPosition(-1); adapter.notifyDataSetChanged(); seekBar.setProgress(0); seekBar.setEnabled(false); seekBarHandler.removeCallbacksAndMessages(null); // seekBar.setVisibility(SeekBar.INVISIBLE); totalDuration.setVisibility(TextView.INVISIBLE); currentPosition.setVisibility(TextView.INVISIBLE); } @Override protected void onResume() { super.onResume(); // Start media router discovery mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN); } @Override protected void onPause() { if (isFinishing()) { // End media router discovery mMediaRouter.removeCallback(mMediaRouterCallback); } super.onPause(); } @Override public void onDestroy() { teardown(); super.onDestroy(); } private void initMediaRouter() { mMediaRouter = MediaRouter.getInstance(getApplicationContext()); mMediaRouteSelector = new MediaRouteSelector.Builder().addControlCategory( CastMediaControlIntent.categoryForCast(APP_NAME)).build(); mMediaRouterCallback = new MediaRouterCallback(); } int currentSeekbarPosition = 0; Handler seekBarHandler = new Handler(); Runnable run = new Runnable() { @Override public void run() { updateSeekBar(); } }; private ListView listView; protected boolean landscape = true; public void updateSeekBar() { currentPosition.setVisibility(TextView.VISIBLE); seekBar.setProgress(currentSeekbarPosition++); seekBarHandler.postDelayed(run, 1000); } public void onEventPlaying(int positionSeconds) { currentSeekbarPosition = positionSeconds; seekBarHandler.removeCallbacksAndMessages(null); playIcon.setVisible(false); pauseIcon.setVisible(true); loadingDialog.hide(); // Send a position request directly as the sync between what the html5 player callbacks says and the actual // time when this callback is invoked differ by a few seconds for some reason. It's a bit like 'playing' // fires 2-3 seconds before the playback actually starts. sendMessage(CommandFactory.buildRequestPositionCommand()); } public void onEventPaused(int positionSeconds) { currentSeekbarPosition = positionSeconds; seekBarHandler.removeCallbacksAndMessages(null); playIcon.setVisible(true); pauseIcon.setVisible(false); } public void onEventFinished() { resetToLandscape(); adapter.setSelectedPosition(-1); adapter.notifyDataSetChanged(); currentSeekbarPosition = 0; seekBar.setProgress(0); loadingDialog.hide(); seekBarHandler.removeCallbacksAndMessages(null); hideMediaControlIcons(); } private void resetToLandscape() { landscape = true; rotateIcon.setIcon(R.drawable.ic_menu_always_landscape_portrait); } public void onRequestedPosition(int positionSeconds) { currentSeekbarPosition = positionSeconds; seekBarHandler.removeCallbacksAndMessages(null); updateSeekBar(); } private void listVideoFiles() { final MediaStoreAdapter mediaStoreAdapter = new MediaStoreAdapter(); ArrayList<MediaItem> mediaFiles = (ArrayList<MediaItem>) mediaStoreAdapter.findFiles(this); listView = (ListView) findViewById(com.squeed.microgramcaster.R.id.videoFiles); adapter = new ArrayAdapterItem(this, R.layout.listview_item, mediaFiles); listView.setAdapter(adapter); OnItemClickListener listener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View listItemView, int position, long arg3) { playSelectedMedia(mediaStoreAdapter, adapter, listItemView, position); } }; listView.setOnItemClickListener(listener); OnItemLongClickListener lcListener = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { return itemLongClicked(mediaStoreAdapter, arg1, arg2); } }; listView.setOnItemLongClickListener(lcListener); } private void playSelectedMedia(final MediaStoreAdapter mediaStoreAdapter, final ArrayAdapterItem adapter, View arg1, int arg2) { if (mSelectedDevice == null || !mApiClient.isConnected()) { Toast.makeText(MainActivity.this, "No cast device selected", Toast.LENGTH_SHORT).show(); adapter.setSelectedPosition(-1); adapter.notifyDataSetChanged(); mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN); return; } adapter.setSelectedPosition(arg2); adapter.notifyDataSetChanged(); String fileName = (String) arg1.getTag(); MediaItem mi = mediaStoreAdapter.findFile(MainActivity.this, fileName); Long durationMillis = mi.getDuration(); seekBar.setMax((int) (durationMillis / 1000L)); currentPosition.setText(TimeFormatter.formatTime(0)); totalDuration.setText(TimeFormatter.formatTime((int) (durationMillis / 1000L))); currentSeekbarPosition = 0; showSeekbar(); if (mApiClient.isConnected()) { resetToLandscape(); loadingDialog.setMessage("Loading '"+fileName+"'"); loadingDialog.show(); sendMessage(CommandFactory.buildPlayUrlCommand(buildMediaItemURL(fileName))); } } private boolean itemLongClicked(final MediaStoreAdapter mediaStoreAdapter, View arg1, int arg2) { String fileName = (String) arg1.getTag(); adapter.setSelectedPosition(arg2); adapter.notifyDataSetChanged(); FileChannel fileChannel = mediaStoreAdapter.getFileChannel(MainActivity.this, fileName); String txt = IsoFileUtil.getInfo(fileChannel); Log.i(TAG, txt); dialog.setMessage(txt); dialog.show(); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(com.squeed.microgramcaster.R.menu.menu, menu); MenuItem mediaRouteMenuItem = menu.findItem(com.squeed.microgramcaster.R.id.media_route_menu_item); MediaRouteActionProvider mediaRouteActionProvider = (MediaRouteActionProvider) MenuItemCompat .getActionProvider(mediaRouteMenuItem); // Set the MediaRouteActionProvider selector for device discovery. if (mediaRouteActionProvider != null) mediaRouteActionProvider.setRouteSelector(mMediaRouteSelector); MenuItem refreshIcon = menu.findItem(com.squeed.microgramcaster.R.id.action_refresh); refreshIcon.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { listVideoFiles(); return false; } }); rotateIcon = menu.findItem(com.squeed.microgramcaster.R.id.action_rotate); rotateIcon.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { sendMessage(CommandFactory.buildToggleRotateCommand()); landscape = !landscape; if(landscape ) { rotateIcon.setIcon(R.drawable.ic_menu_always_landscape_portrait); } else { rotateIcon.setIcon(R.drawable.ic_menu_always_landscape_portrait_blue); } return false; } }); playIcon = menu.findItem(com.squeed.microgramcaster.R.id.action_play); playIcon.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { sendMessage(CommandFactory.buildPlayCommand()); return false; } }); pauseIcon = menu.findItem(com.squeed.microgramcaster.R.id.action_pause); pauseIcon.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { sendMessage(CommandFactory.buildPauseCommand()); playIcon.setVisible(true); pauseIcon.setVisible(false); return false; } }); hideMediaControlIcons(); return true; } /** * An extension of the MediaRoute.Callback so we can invoke our own onRoute * selected/unselected */ private class MediaRouterCallback extends MediaRouter.Callback { @Override public void onRouteSelected(MediaRouter router, android.support.v7.media.MediaRouter.RouteInfo route) { Log.i(TAG, "onRouteSelected: " + route); mSelectedDevice = CastDevice.getFromBundle(route.getExtras()); launchReceiver(); } @Override public void onRouteUnselected(MediaRouter router, android.support.v7.media.MediaRouter.RouteInfo route) { Log.i(TAG, "onRouteUnselected: " + route); teardown(); mSelectedDevice = null; hideMediaControlIcons(); hideSeekbar(); } } private void hideMediaControlIcons() { playIcon.setVisible(false); pauseIcon.setVisible(false); } /** * Start the receiver app */ private void launchReceiver() { try { mCastListener = new Cast.Listener() { @Override public void onApplicationDisconnected(int errorCode) { Log.d(TAG, "application has stopped"); teardown(); } }; // Connect to Google Play services mConnectionCallbacks = new ConnectionCallbacks(); mConnectionFailedListener = new ConnectionFailedListener(); Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(mSelectedDevice, mCastListener); mApiClient = new GoogleApiClient.Builder(this).addApi(Cast.API, apiOptionsBuilder.build()) .addConnectionCallbacks(mConnectionCallbacks) .addOnConnectionFailedListener(mConnectionFailedListener).build(); mApiClient.connect(); } catch (Exception e) { Log.e(TAG, "Failed launchReceiver", e); } } /** * Tear down the connection to the receiver */ private void teardown() { if (mApiClient != null) { if (mApplicationStarted) { try { Cast.CastApi.stopApplication(mApiClient); if (mMicrogramCasterChannel != null) { Cast.CastApi.removeMessageReceivedCallbacks(mApiClient, mMicrogramCasterChannel.getNamespace()); mMicrogramCasterChannel = null; } } catch (IOException e) { Log.e(TAG, "Exception while removing channel", e); } mApplicationStarted = false; } if (mApiClient.isConnected()) { mApiClient.disconnect(); } mApiClient = null; } mSelectedDevice = null; mWaitingForReconnect = false; hideMediaControlIcons(); } /** * Google Play services callbacks */ private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks { @Override public void onConnected(Bundle connectionHint) { Log.d(TAG, "onConnected"); if (mApiClient == null) { // We got disconnected while this runnable was pending // execution. return; } try { if (mWaitingForReconnect) { mWaitingForReconnect = false; // Check if the receiver app is still running if ((connectionHint != null) && connectionHint.getBoolean(Cast.EXTRA_APP_NO_LONGER_RUNNING)) { Log.d(TAG, "App is no longer running"); teardown(); } else { // Re-create the custom message channel try { Cast.CastApi.setMessageReceivedCallbacks(mApiClient, mMicrogramCasterChannel.getNamespace(), mMicrogramCasterChannel); } catch (IOException e) { Log.e(TAG, "Exception while creating channel", e); } } } else { // Launch the receiver app Cast.CastApi.launchApplication(mApiClient, APP_NAME, false).setResultCallback( new ResultCallback<Cast.ApplicationConnectionResult>() { @Override public void onResult(ApplicationConnectionResult result) { Status status = result.getStatus(); Log.d(TAG, "ApplicationConnectionResultCallback.onResult: statusCode" + status.getStatusCode()); if (status.isSuccess()) { ApplicationMetadata applicationMetadata = result.getApplicationMetadata(); String sessionId = result.getSessionId(); String applicationStatus = result.getApplicationStatus(); boolean wasLaunched = result.getWasLaunched(); Log.d(TAG, "application name: " + applicationMetadata.getName() + ", status: " + applicationStatus + ", sessionId: " + sessionId + ", wasLaunched: " + wasLaunched); mApplicationStarted = true; // Create the custom message // channel mMicrogramCasterChannel = new MicrogramCasterChannel(MainActivity.this); try { Cast.CastApi.setMessageReceivedCallbacks(mApiClient, mMicrogramCasterChannel.getNamespace(), mMicrogramCasterChannel); } catch (IOException e) { Log.e(TAG, "Exception while creating channel", e); } // set the initial instructions // on the receiver // sendMessage(getString(R.string.app_name)); } else { Log.e(TAG, "application could not launch"); teardown(); } } }); } } catch (Exception e) { Log.e(TAG, "Failed to launch application", e); } } @Override public void onConnectionSuspended(int cause) { Log.d(TAG, "onConnectionSuspended"); mWaitingForReconnect = true; hideMediaControlIcons(); hideSeekbar(); } } private void sendMessage(Command cmd) { if (mSelectedDevice == null || mApiClient == null || (mApiClient != null && !mApiClient.isConnected())) { if (mApiClient != null && mApiClient.isConnecting()) { Toast.makeText(MainActivity.this, "Currently connecting to Cast Device, please try again in a moment...", Toast.LENGTH_LONG) .show(); } else { Toast.makeText(MainActivity.this, "Cast Device not connected, please try to disconnect and connect again", Toast.LENGTH_LONG) .show(); } return; } try { JSONObject obj = new JSONObject(); obj.put("id", cmd.getId()); obj.put("params", new JSONObject(cmd.getParams())); if (mApiClient != null && mMicrogramCasterChannel != null) { try { Cast.CastApi.sendMessage(mApiClient, mMicrogramCasterChannel.getNamespace(), obj.toString()); } catch (Exception e) { Log.e(TAG, "Exception while sending message", e); } } else { Toast.makeText(MainActivity.this, "Unable to send CMD to receiver, no connection", Toast.LENGTH_SHORT) .show(); launchReceiver(); } } catch (JSONException e) { Toast.makeText(MainActivity.this, "Unable to serialize CMD into JSON: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } } private String buildMediaItemURL(String fileName) { return MyHTTPD.WEB_SERVER_PROTOCOL + "://" + WifiHelper.getLanIP(MainActivity.this) + ":" + MyHTTPD.WEB_SERVER_PORT + "/" + fileName; } /** * Google Play services callbacks */ private class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener { @Override public void onConnectionFailed(ConnectionResult result) { Log.e(TAG, "onConnectionFailed "); teardown(); } } /** * Listen for volume upp/down presses and propagate them to the receiver. */ @Override public boolean dispatchKeyEvent(KeyEvent event) { try { if (event.getAction() == KeyEvent.ACTION_DOWN) { double volume = Cast.CastApi.getVolume(mApiClient); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: try { if (volume < 1.0) Cast.CastApi.setVolume(mApiClient, volume + 0.05d); } catch (IOException e) { } return true; case KeyEvent.KEYCODE_VOLUME_DOWN: try { if (volume > 0.0) Cast.CastApi.setVolume(mApiClient, volume - 0.05d); } catch (IOException e) { } return true; } } } catch (Throwable t) { } return super.dispatchKeyEvent(event); } }
package com.xruby.runtime.javasupport; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.xruby.runtime.lang.RubyAPI; import com.xruby.runtime.lang.RubyBlock; import com.xruby.runtime.lang.RubyClass; import com.xruby.runtime.lang.RubyException; import com.xruby.runtime.lang.RubyID; import com.xruby.runtime.lang.RubyMethod; import com.xruby.runtime.lang.RubyRuntime; import com.xruby.runtime.lang.RubySingletonClass; import com.xruby.runtime.lang.RubyValue; import com.xruby.runtime.lang.RubyVarArgMethod; import com.xruby.runtime.value.RubyArray; /** * Wrapper for Java Class * * @author Yu Su (beanworms@gmail.com), Ye Zheng(dreamhead.cn@gmail.com), * Yu Zhang(zhangyu8374@gmail.com) */ public class JavaClass extends RubyClass { // Const fields private static final String NEW_METHOD = "new"; // Cache of methods (and constructors) private Map<String, List<Method>> methodMap = new HashMap<String, List<Method>>(); private Map<Integer, List<Constructor>> initMap = new HashMap<Integer, List<Constructor>>(); private Map<Method, JavaMethod> javaMethods = new HashMap<Method, JavaMethod>(); private Map<Constructor, JavaMethod> initMethods = new HashMap<Constructor, JavaMethod>(); private Map<String, Field> fieldNames = new HashMap<String, Field>(); private static List<String> packageNames = new ArrayList<String>(); private Class orginJavaClass; private JavaClass(Class clazz,RubyClass superclass){ super(clazz.getName(),superclass,null); this.orginJavaClass = clazz; if(!clazz.isInterface()){ //Initialize public constructors and methods initConstructors(clazz); initMethods(clazz); initFields(clazz); } } private static JavaClass newJavaClass(Class clazz,RubyClass parent){ JavaClass jClass = new JavaClass(clazz,parent); if(clazz.isInterface()){ jClass.setRubyClass(RubyRuntime.ClassClass); new RubySingletonClass(jClass, parent.getRubyClass()); } String fullName = clazz.getName(); //Replace new Java class name prefixed 'J' with orginal class name //if the class name collision occurs RubyAPI.setTopLevelConstant(jClass, fullName); String name = fullName.substring(fullName.lastIndexOf('.')+1); //Check that the class named <code>name</code> exists or not RubyValue value = RubyRuntime.ObjectClass.getConstant(name); if(value == null) RubyAPI.setTopLevelConstant(jClass, name); RubyAPI.setTopLevelConstant(jClass, "J"+name); return jClass; } //Import Java class,the parent class,etc. recursively public static JavaClass createJavaClass(Class clazz){ Class superClass = clazz.getSuperclass(); if(superClass != null){ JavaClass parentClass = createJavaClass(superClass); return newJavaClass(clazz,parentClass); }else{ return newJavaClass(clazz,RubyRuntime.ObjectClass); } } // Collect public methods of given class private void initMethods(Class clazz) { Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { int modifiers = method.getModifiers(); if (Modifier.isPublic(modifiers)) { categoryByName(method); } } } // Collect public constructors of given class private void initConstructors(Class clazz) { Constructor[] constructors = clazz.getConstructors(); for (Constructor constructor : constructors) { int modifiers = constructor.getModifiers(); if (Modifier.isPublic(modifiers)) { categoryByParams(constructor); } } } private void initFields(Class clazz){ Field[] fields = clazz.getDeclaredFields(); for(Field f : fields){ String name = f.getName(); int modifiers = f.getModifiers(); //Unlike the constructor and method,it's impossible //to have two or more fields with the same name fieldNames.put(name, f); if(!Modifier.isFinal(modifiers)){ String setterName = name+"="; fieldNames.put(setterName,f); } if(Modifier.isStatic(modifiers)&&Modifier.isPublic(modifiers)){ if(Modifier.isFinal(modifiers)){ try { //Java class's constant fields. setConstant(name,JavaUtil.convertToRubyValue(f.get(null))); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } // Helper class, catalogue the method private void categoryByName(Method method) { String name = method.getName(); List<Method> list = methodMap.get(name); if (null == list) { list = new ArrayList<Method>(); list.add(method); methodMap.put(name, list); } else { list.add(method); } } private void categoryByParams(Constructor constructor) { Class[] types = constructor.getParameterTypes(); int size = types.length; List<Constructor> list = initMap.get(size); if (null == list) { list = new ArrayList<Constructor>(); list.add(constructor); initMap.put(size, list); } else { list.add(constructor); } } /** * Find method according to given method, if it's "new" * return an "init" fake method * * @param mid method's RubyID * @return wrapper of the method, otherwise null */ @Override public RubyMethod findPublicMethod(RubyID mid) { String methodName = mid.toString(); if(methodName == null) { return null; } if (methodName.equals(NEW_METHOD)) { return new FakeInitMethod(); } RubyClass klass = this; while(klass != null){ if(klass instanceof JavaClass){ if(((JavaClass)klass).methodMap.containsKey(methodName)){ return new FakeMethod(methodName); } if(((JavaClass)klass).fieldNames.keySet().contains(methodName)){ return new FakeInstanceVarMethod(methodName); } }else{ //Caution:not invoke findPublicMethod return klass.findOwnMethod(mid); } klass = klass.getSuperClass(); } return null; } /** * In JavaClass, it's just an alias for findPublicMethod * * @param mid method's RubyID * @return Method instance */ @Override public RubyMethod findMethod(RubyID mid) { return findPublicMethod(mid); } /** * This is the actual method which will be invoked * * @param mid method's RubyID * @return method instance */ @Override public RubyMethod findOwnPublicMethod(RubyID mid) { return findPublicMethod(mid); } JavaMethod getJavaMethod(Method method) { JavaMethod jMethod = javaMethods.get(method); if (null == jMethod) { jMethod = new JavaMethod(method); javaMethods.put(method, jMethod); } return jMethod; } // TODO: InComplete, method cache is required(indexed by params' number) JavaMethod findJavaMethod(String methodName, RubyArray args) { int size = args == null ? 0 : args.size(); List<Method> list = null; RubyClass klass = this; while(klass != null){ list = ((JavaClass)klass).methodMap.get(methodName); if (null != list) { break; }else{ klass = klass.getSuperClass(); } } if (null == list) { return null; } if (list.size() == 1) { Method method = list.get(0); Class[] params = method.getParameterTypes(); if (size != params.length) { throw new RubyException("Illegal arguments"); } return getJavaMethod(method); } else { List<Method> tmpList = new ArrayList<Method>(); for (Method method : list) { if (method.getParameterTypes().length == size) { tmpList.add(method); } } if (tmpList.size() == 1) { return getJavaMethod(tmpList.get(0)); } else { //Analyzing args return getJavaMethod(JavaUtil.matchMethod(tmpList, args)); } } } JavaMethod getJavaConstructor(Constructor constructor) { JavaMethod jMethod = initMethods.get(constructor); if (null == jMethod) { jMethod = new JavaMethod(constructor); initMethods.put(constructor, jMethod); } return jMethod; } JavaMethod findInitMethod(RubyArray args) { int size = args == null ? 0 : args.size(); List<Constructor> list = initMap.get(size); if (null == list) { return null; } if (list.size() == 1) { Constructor constructor = list.get(0); return getJavaConstructor(constructor); } else { return getJavaConstructor(JavaUtil.matchInitMethod(list, args)); } } private class FakeMethod extends RubyVarArgMethod { private String methodName; public FakeMethod(String methodName) { this.methodName = methodName; } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { JavaClass clazz = null; //This is a trick.Because no creating the metaclass for every Java //class,deal with the static methods as follows: if(receiver instanceof JavaClass){ clazz = (JavaClass)receiver; }else{ clazz = (JavaClass) receiver.getRubyClass(); } JavaMethod method = clazz.findJavaMethod(methodName, args); if (null == method) { throw new RubyException("Signature of method " + methodName + " is illegal"); } return method.run(receiver, args, block); } } private class FakeInitMethod extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { JavaClass clazz = (JavaClass) receiver; JavaMethod method = clazz.findInitMethod(args); if (null == method) { throw new RubyException("Signature is illegal"); } return method.run(receiver, args, block); } } private class FakeInstanceVarMethod extends RubyVarArgMethod { private String instanceVarName; public FakeInstanceVarMethod(String name) { this.instanceVarName = name; } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { JavaClass clazz = null; //This is a trick.Because no creating the metaclass for every Java //class,deal with the static fields as follows: if(receiver instanceof JavaClass){ clazz = (JavaClass)receiver; }else{ clazz = (JavaClass) receiver.getRubyClass(); } JavaMethod method = null; boolean flag = false; do{ if(clazz.fieldNames.keySet().contains(instanceVarName)){ Method m = null; boolean isGetter = true; try { if(instanceVarName.endsWith("=")){ isGetter = false; m = JavaClass.class.getDeclaredMethod("setter", new Class[]{Field.class,Object.class,Object.class}); }else{ m = JavaClass.class.getDeclaredMethod("getter", new Class[]{Field.class,Object.class}); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } method = new JavaMethod(m,clazz.fieldNames.get(instanceVarName),isGetter); break; } clazz = (JavaClass)clazz.getSuperClass(); flag = clazz.getName().equals("Object"); }while(!flag); if(flag) throw new RubyException("The Instance variable "+instanceVarName+"doesn't exists or can't be accessed!"); return method.run(receiver, args, block); } } public static Object getter(Field f,Object obj){ try { return f.get(obj); } catch (IllegalArgumentException e) { //ignore it } catch (IllegalAccessException e2) { //If the Java class define a getter method by itself,... String name = f.getName(); StringBuffer sb = new StringBuffer(); sb.append("get"); sb.append(Character.toUpperCase(name.charAt(0))); sb.append(name.substring(1)); String methodName = sb.toString(); try { //Suppose that getter method is not overload! Method[] ms = obj.getClass().getMethods(); for(Method m : ms){ if(m.getName().equals(methodName)){ return m.invoke(obj, new Object[]{}); } } } catch (Exception e1) { //ignore it } } throw new RubyException("The Instance variable "+f.getName()+"doesn't exists or can't be accessed!"); } public static void setter(Field f,Object obj,Object val){ try { f.set(obj, val); return; } catch (IllegalArgumentException e) { //ignore it } catch (IllegalAccessException e) { //If the Java class define a setter method by itself,... String name = f.getName(); StringBuffer sb = new StringBuffer(); sb.append("set"); sb.append(Character.toUpperCase(name.charAt(0))); sb.append(name.substring(1)); String methodName = sb.toString(); try { //Suppose that setter method is not overload! Method[] ms = obj.getClass().getMethods(); for(Method m : ms){ if(m.getName().equals(methodName)){ m.invoke(obj, new Object[]{val}); return; } } } catch (Exception e1) { //ignore it } } throw new RubyException("The Instance variable "+f.getName()+"doesn't exists or can't be accessed!"); } public static void addPackage(String name){ packageNames.add(name); } public static String[] getPackeageList(){ String[] tmp = new String[packageNames.size()]; Iterator<String> iter = packageNames.iterator(); int count = 0; while(iter.hasNext()){ tmp[count] = iter.next(); count++; } return tmp; } public Class getOriginJavaClass(){ return this.orginJavaClass; } }
package am.batchMode; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import am.Utility; public class TrackDispatcher { public final static String BENCHMARK = "benchmarks"; public final static String ANATOMY = "anatomy"; public final static String CONFERENCE = "conference"; //decides which track has to be launched public static void dispatchTrack(String track, String subTrack){ try{ if(subTrack.equals("")){ System.out.println("Running in batchMode on track = "+track); } else System.out.println("Running in batchMode on track = "+track+" and subTrack = "+subTrack); if(track.equalsIgnoreCase(BENCHMARK)){ BenchmarkTrack bt = new BenchmarkTrack(subTrack); bt.launch(); } else if(track.equalsIgnoreCase(ANATOMY)){ AnatomyTrack at = new AnatomyTrack(subTrack); at.launch(); } else if(track.equalsIgnoreCase(CONFERENCE)){ //TODO ConferenceTrack ct = new ConferenceTrack(subTrack); ct.launch(); } else{ System.out.println("The selected track doesn't exist.\nTo run the UI remove the string argument from the running parameters."); } } catch(Exception ex){ ex.printStackTrace(); } } public static void printExecutionTime(long time, String fileName) throws Exception{ System.out.println("Total execution time in h:m:s:ms: "+Utility.getFormattedTime(time)); File timeFile = new File(fileName); PrintWriter ptime = new PrintWriter(timeFile); ptime.println("Total execution time in ms: "+time); ptime.println("Total execution time in h:m:s:ms: "+Utility.getFormattedTime(time)); ptime.close(); } }
package com.simperium; import com.simperium.client.Bucket; import com.simperium.client.BucketObject; import com.simperium.client.BucketSchema; import com.simperium.client.Syncable; import com.simperium.client.User; import com.simperium.client.User.AuthResponseHandler; import com.simperium.client.SyncService; import com.simperium.client.ClientFactory; import com.simperium.client.ClientFactory.*; import com.simperium.client.GhostStorageProvider; import com.simperium.client.ObjectCacheProvider; import com.simperium.client.AuthProvider; import com.simperium.client.ChannelProvider; import com.simperium.client.Channel; import com.simperium.storage.StorageProvider; import com.simperium.storage.StorageProvider.BucketStore; import com.simperium.util.Logger; import org.json.JSONObject; import android.content.Context; public class Simperium implements User.StatusChangeListener { // builds and Android client public static Simperium newClient(String appId, String appSecret, Context context){ return newClient(appId, appSecret, new com.simperium.android.AndroidClient(context)); } public static Simperium newClient(String appId, String appSecret, ClientFactory factory){ simperiumClient = new Simperium(appId, appSecret, factory); return simperiumClient; } public interface OnUserCreatedListener { void onUserCreated(User user); } public static final String VERSION = "1.0"; public static final String CLIENT_ID = String.format("android-%s", VERSION); public static final int SIGNUP_SIGNIN_REQUEST = 1000; // The request code private String appId; private String appSecret; private User user; private User.StatusChangeListener userListener; private static Simperium simperiumClient = null; private OnUserCreatedListener onUserCreatedListener; protected AuthProvider mAuthProvider; protected ChannelProvider mChannelProvider; protected StorageProvider mStorageProvider; protected GhostStorageProvider mGhostStorageProvider; protected ObjectCacheProvider mObjectCacheProvider; protected SyncService mSyncService; public Simperium(String appId, String appSecret, ClientFactory factory){ this.appId = appId; this.appSecret = appSecret; mAuthProvider = factory.buildAuthProvider(appId, appSecret); mChannelProvider = factory.buildChannelProvider(appId); mStorageProvider = factory.buildStorageProvider(); mGhostStorageProvider = factory.buildGhostStorageProvider(); mObjectCacheProvider = factory.buildObjectCacheProvider(); mSyncService = factory.buildSyncService(); Logger.log(String.format("Initializing Simperium %s", CLIENT_ID)); loadUser(); } public static Simperium getInstance() throws SimperiumNotInitializedException{ if(null == simperiumClient) throw new SimperiumNotInitializedException("You must create an instance of Simperium before call this method."); return simperiumClient; } private void loadUser(){ user = new User(this); mAuthProvider.restoreUser(user); if (user.needsAuthorization()) { user.setStatus(User.Status.NOT_AUTHORIZED); } } public String getAppId(){ return appId; } public User getUser(){ return user; } public boolean needsAuthorization(){ // we don't have an access token yet return user.needsAuthorization(); } /** * Creates a bucket and starts syncing data and uses the provided * Class to instantiate data. * * Should only allow one instance of bucketName and the schema should * match the existing bucket? * * @param bucketName the namespace to store the data in simperium */ public <T extends Syncable> Bucket<T> bucket(String bucketName, BucketSchema<T> schema){ return bucket(bucketName, schema, mStorageProvider.createStore(bucketName, schema)); } /** * Allow alternate storage mechanisms */ public <T extends Syncable> Bucket<T> bucket(String bucketName, BucketSchema<T> schema, BucketStore<T> storage){ // initialize the bucket ObjectCacheProvider.ObjectCache<T> cache = mObjectCacheProvider.buildCache(); Bucket<T> bucket = new Bucket<T>(mSyncService, bucketName, schema, user, storage, mGhostStorageProvider, cache); // initialize the communication method for the bucket Bucket.Channel<T> channel = mChannelProvider.buildChannel(bucket); // tell the bucket about the channel bucket.setChannel(channel); storage.prepare(bucket); return bucket; } /** * Creates a bucket and starts syncing data. Users the generic BucketObject for * serializing and deserializing data * * @param bucketName namespace to store the data in simperium */ public Bucket<BucketObject> bucket(String bucketName){ return bucket(bucketName, new BucketObject.Schema(bucketName)); } /** * Creates a bucket and uses the Schema remote name as the bucket name. */ public <T extends Syncable> Bucket<T> bucket(BucketSchema<T> schema){ return bucket(schema.getRemoteName(), schema); } public void setAuthProvider(String providerString){ mAuthProvider.setAuthProvider(providerString); } public void setOnUserCreatedListener(OnUserCreatedListener listener){ onUserCreatedListener = listener; } protected void notifyOnUserCreatedListener(User user){ if (onUserCreatedListener != null){ onUserCreatedListener.onUserCreated(user); } } public User createUser(String email, String password, final AuthResponseHandler handler){ user.setCredentials(email, password); AuthResponseHandler wrapper = new AuthResponseHandlerWrapper(handler){ @Override public void onSuccess(User user){ super.onSuccess(user); notifyOnUserCreatedListener(user); } }; mAuthProvider.createUser(user, wrapper); return user; } public User authorizeUser(String email, String password, AuthResponseHandler handler){ user.setCredentials(email, password); mAuthProvider.authorizeUser(user, handler); return user; } public void deauthorizeUser(){ user.setAccessToken(null); user.setEmail(null); mAuthProvider.deauthorizeUser(user); user.setStatus(User.Status.NOT_AUTHORIZED); } public void onUserStatusChange(User.Status status){ if (userListener != null) { userListener.onUserStatusChange(status); } } public User.StatusChangeListener getUserStatusChangeListener() { return userListener; } public void setUserStatusChangeListener(User.StatusChangeListener listener){ userListener = listener; } private class AuthResponseHandlerWrapper implements AuthResponseHandler { final private AuthResponseHandler handler; public AuthResponseHandlerWrapper(final AuthResponseHandler handler){ this.handler = handler; } @Override public void onSuccess(User user) { handler.onSuccess(user); } @Override public void onInvalid(User user, Throwable error, JSONObject validationErrors) { handler.onInvalid(user, error, validationErrors); } @Override public void onFailure(User user, Throwable error, String message) { handler.onFailure(user, error, message); } } }
// Use package zuulframework package TWoT_test; import static TWoT_test.EquippableItem.EItem.CHEST_SLOT; import static TWoT_test.EquippableItem.EItem.WEAPON_SLOT; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class TWoT{ // Init variabels private Room currentRoom; private Player player; // Deffine rooms private Room roomCellar, roomVillage, roomHouse1, roomHouse2, roomHouse3, roomForest, roomWizardHouse, roomCave, roomCaveGruul, roomClearing, roomDungeon, roomLibrary, roomEvilWizardsLair; // Create the constructor for TWoT class public TWoT(){ // Create the different rooms used createRooms(); player = new Player("StartName", 1.0, 1.0, 100, new Inventory()); } public void testMatch(){ player = new Player("Test player1", 2.0, 1.0, 100, new Inventory()); Monster monster = new Monster("Test monster1", 1.0, 1.0, 100, 100); Combat c = new Combat(player, monster); List<Fight> fight = c.AFight(); for(Fight f: fight){ System.out.println("Who won: " + f.winner()); System.out.println("Player rolled: " + f.getPlayerRoll()); System.out.println("Monster rolled: " + f.getMonsterRoll()); System.out.println(f.winner() + " took " + f.getDamage() + " damage."); if(f.isDone()){ if(f.getMonster().getHealth() <= 0){ System.out.println("\nPlayer won!"); System.out.println("Monster dropped: " + f.getMonster().getGoldDrop() + " gold."); }else{ System.out.println("Monster won!"); } } System.out.println(); } } /** * Creates all the rooms in the game. */ private void createRooms(){ roomCellar = new Room("Cellar", "***Cellar*** \nYou wake up in a dull cellar. Light is emitting from a torch on the wall " + "and you barely get on your feet.\nYou’ve been laying on a haystack for God knows how long and " + "your feet are extremely sore.\nTo your right you see a table with multiple drawers and right in " + "front of you an old door with a lock.\nYou can choose to inspect the door, the table or the haystack behind you."); roomVillage = new Room("Village of Treldan", "\n\n***Village of Treldan*** \nIt’s dark outside. You seem to be familiar with this part of the village. " + "\nYou still wonder why you were locked up in that cell, but your thoughts are quickly interrupted " + "by a sobbing by the gate.\nA guard seems to be crying, and something doesn’t seem right in the " + "village. All houses seem to be empty and the doors are wide open.\nYou gasp as you see several " + "people lying dead in the side of the road.\nYou enter the town of Treldan; you can choose to " + "inspect the guard at the gate, house one, house two or house three.\""); roomHouse1 = new Room("House of the Reborn", "\n\n***House of the Reborn*** \nThe house you venture into is dark – very dark. It seems like " + "there is a man in a corner of the room close you and a woman in the other end of the room." + "\nYou enter the house, you can choose to inspect the woman, the man or leave through the door " + "behind you."); roomHouse2 = new Room("House of Riches", "\n\n***House of Riches*** \n You use your bloody key to get in. This house is lit up by a " + "candle on the table.\nThere’s a blood-stained bed in the corner of the room. A bunch of sacks " + "are placed up against a poorly build wardrobe.\nThe other corner is not lit up by the candle and " + "you can’t see what is there.\nYou enter the house, you can choose to inspect the wardrobe, the " + "bed, the dark corner or leave through the door behind you."); roomHouse3 = new Room("House of the Guard", "\n\n***House of the Guard*** \nThe door is barred from the inside, you jump through an open " + "window in the house, cutting yourself on a sharp piece of glass. You lose 5 HP.\nThe house is neatly " + "decorated, and the infected clearly havent been in here, in the left corner of the room there is " + "a dusty set of armor and lying in an open chest at the end of a double-bed.\nAdditionally, there " + "is also a small kitchen area with knives, pots, pans, and the like.\nYou enter the house, you " + "can chose to inspect the kitchen, the bed, the chest or go back through the door behind you."); roomForest = new Room("The Forest of Treldan", "\n\n***The Forest of Treldan*** \nAs you ride through the forest you are ambushed by a pack " + "of goblins who try to murder you and take your valuables.\nYou almost fall prey to the savages, " + "as you are saved by a wizard who zaps! the goblins with magic and scare them away.\nHe heals your " + "wounds and helps you back on your feet.\nYou thank the wizard and ask him if there is anything " + "you can do to repay him. Come meet me in my house when you're ready, its the Large Tree-house " + "over there.\nI have need of help in order to save Treldan! You enter the Forest of Treldan, you " + "scout around and look for anything, and spot a dead goblin and a couple of suspicious looking " + "mushrooms.\nYou can go to the wizards house, look at the mushrooms, and search the dead " + "goblin. Alternatively, you can also go back to the village."); roomWizardHouse = new Room ("The Nice Wizard's House","\n\n***The Wizard's House*** \nThe wizard's house is better described as a hollow tree with doors " + "and windows, you can see a number of magical artifacts, a staircase to a upstairs part of the " + "house, there is also what looks to be an alchemy lab.\nThe wizard sits quietly in a comfy chair " + "with his legs up, snoring.\nYou can chose to interact with the " + "wizard, the alchemy lab, the magical items, or go upstairs."); roomCave = new Room("Troll Cave", "\n\n***Troll Cave*** \nYou enter the troll cave, and immediately get sorrounded by 3 trolls," + " one directly in fron of you, one to the left, and one to your right.\nIn the back " + "you can see a larger shadowy figure in the back of the cave, but you need to " + "get rid of the trolls to get to him first.\nYou can interact with the 3 trolls in front of " + "you but you need to kill all of them in order to get further into the cave"); roomCaveGruul = new Room("Gruul's Lair","\n\n***Gruul's Lair*** \n You approach the shadowy figure and as you come closer, the giant troll rises" + " up, easily towering 2 meters above you, opens its mouth and roars fiercely at you."); roomClearing = new Room("Clearing of Unicorns", "***Clearing of Unicorns*** \nYou enter the clearing of unicorns and are immediately" + " blinded by a bright light.\nAs you regain your sight you lay eyes upon the most magnificent " + "create you have ever seen.\nThe unicorn looks at you curiously and goes back to eating grass. " + "\nYou scout the surrounding area for anything else, and spot an old tree. "); roomDungeon = new Room("Dungeon of Suffering", "\n\n***Dungeon of Suffering*** \nA loud whoosh and you find yourself in some kind of dungeon " + "– probably the one belonging to the evil wizard of Treldan.\nYou realise you must be in his Tower." + "\nYou get up on your feet and sees that the room your in is barely lit by torches, the walls are " + "slimy and there are no windows. To no surprise you find three heavely armored skeletons.\nYou " + "sigh. You can choose to inspect either skeleton one, skeleton two or skeleton three."); roomLibrary = new Room("The Neverending Library", "\n\n***The Neverending Library*** \nYou find yourself in the biggest room you’ve ever been " + "in. Books upon books is all you see, and bookcases fill up the gigantic room.\nIt would take ages " + "to go through every single book, you think to yourself."); roomEvilWizardsLair = new Room("The Evil Wizard's Lair", "\n\n***The Evil Wizard's Lair*** \nAs you ascend the stairs your legs feel heavier and " + "heavier.\nYou can barely walk as you make it up to the final step – the pain is then suddenly " + "relieved.\nYou open a large door and you see the Evil Wizard of Treldan standing in the room with " + "a giant dragon."); // roomCellar Interior roomCellarExit = new Exit(roomVillage); Interior roomCellarStick = new QuestItem("A needle", 1, "It was found in the haystack", 99901, "It must have been super uncomfortable laying on the haystack.\nYou search around the haystack and end up finding a strong needle. The needle has been added to your inventory."); Interior roomCellarCheeseSandwich = new UseableItem("Cheese sandwhich", 20, "Do you dare eat it?", "The table has several books and journals that are of no interest to you. In the drawer you find a cheese sandwich for eating.", 55501); roomCellar.addMapInterior("door", roomCellarExit); roomCellar.addMapInterior("haystack", roomCellarStick); roomCellar.addMapInterior("table", roomCellarCheeseSandwich); //roomVillage Interior roomVillageExit1 = new Exit(roomHouse1); Interior roomVillageExit2 = new Exit(roomHouse2); Interior roomVillageExit3 = new Exit(roomHouse3); Npc mogens = new Npc("Mogens", true, 22201); mogens.addConversation("g"); Interior roomVillageNPC = mogens; roomVillage.addMapInterior("house1", roomVillageExit1); roomVillage.addMapInterior("house2", roomVillageExit2); roomVillage.addMapInterior("house3", roomVillageExit3); roomVillage.addMapInterior("guard", roomVillageNPC); //roomHouse1 Interior roomHouse1Exit = new Exit(roomVillage); Monster woman = new Monster("Woman", 1.0, 1.0, 50, 0); Interior roomHouse1Woman = woman; Interior roomHouse1Man = new UseableItem("Cheese sandwhich", 20, "Nom nom nom", "A dead man is half-sitting in a chair. In his pockets you find a cheese sandwhich.", 55501); roomHouse1.addMapInterior("woman", roomHouse1Woman); roomHouse1.addMapInterior("man", roomHouse1Man); roomHouse1.addMapInterior("door", roomHouse1Exit); //roomHouse2 Interior roomHouse2Exit = new Exit(roomVillage); Interior roomHouse2Wardrobe = new EquippableItem("Dull Sword", 842,"Dull and a sword.",1.3,1.0, WEAPON_SLOT, "You find nothing of interest in the wardrobe. You tear open the sacks with your bare hands and cut your fingers on something. You lift up a dull but usable sword.", 33301); //Tag 10 skade Interior roomHouse2Bed = new QuestItem("Kids", 2, "Small and crying", 99902, "As you approach the bed, you hear muffled sniffling and crying, you quickly duck down and lift the duvey covers - you find two children around the age of 10 and 7 huddled up tears on their cheecks.\n\"Please mister, don’t hurt us\" - you reassure the children that you are not going to hurt them, but taking them back to their father, the guard. "); Interior roomHouse2DarkCorner = new UseableItem("Cinnamon Roll",5,"Cinnamon roll with cinnamon", "As you approach the dark corner you fear the worst, but to your surprise you find a cinnamon roll on a shelf.", 55502); roomHouse2.addMapInterior("door", roomHouse2Exit); roomHouse2.addMapInterior("wardrobe", roomHouse2Wardrobe); roomHouse2.addMapInterior("bed", roomHouse2Bed); roomHouse2.addMapInterior("corner", roomHouse2DarkCorner); //roomHouse3 Interior roomHouse3Exit = new Exit(roomVillage); Interior roomHouse3Kitchen = new UseableItem("Old rusty coin", 366, "It's old and rusty.", "The knives are all rusty and dull, you cant use them for anything, but you find a rusty coin stashed away in a secret compartment of the oven.", 55503); //Interior roomHouse3Bed = new PlayerHealth; Interior roomHouse3Chest = new EquippableItem("Old leather armor", 32819, "Quite fabulous", 1.0, 1.3, CHEST_SLOT, "There is a set of leather armor in the chest, it's old and rusty but durable, you put it on and it suits you surprisingly well.", 33302); roomHouse3.addMapInterior("door", roomHouse3Exit); roomHouse3.addMapInterior("kitchen", roomHouse3Kitchen); //roomHouse3.addMapInterior("Bed", roomHouse3Bed); roomHouse3.addMapInterior("chest", roomHouse3Chest); //roomForrest Interior roomForrestExit1 = new Exit(roomWizardHouse); Interior roomForrestExit2 = new Exit(roomCave); Interior roomForrestExit3 = new Exit(roomClearing); Interior roomForrestMushroom = new UseableItem("Mushroom", 286, "It stinks, but it might come in handy scaring off weaker foes.", "You go pick up a mushroom, it stinks, but it might come in handy scaring off weaker foes.", 55504); Interior roomForrestDeadGoblin = new EquippableItem("Handaxe", 293811, "Sturdy, and propably packs a punch.", 1.0, 0.0, WEAPON_SLOT, "You search the dead goblin. Its skin is charred from the wizards light magic and its black blood is slowly seeping out its mouth. You find 25 gold and a well kept short handaxe, its sturdy and probably packs quite a punch.", 55504); roomForest.addMapInterior("mushroom", roomForrestMushroom); roomForest.addMapInterior("dead goblin", roomForrestDeadGoblin); roomForest.addMapInterior("wizard's house", roomForrestExit1); roomForest.addMapInterior("troll cave", roomForrestExit2); roomForest.addMapInterior("clearing of unicorns", roomForrestExit3); //roomWizardHouse Interior roomWizardHouseExit = new Exit(roomForest); Interior roomWizardHouseUpstairs = new UseableItem("Smooth ruby", 200, "A valueable stone.", "You check the wizards room for any valuables, find a piece of jewelry, and go downstairs again.", 55505); Interior roomWizardHouseBox = new UseableItem("Mysterious Ring",150,"Odd looking ring with a curiously intricate design, you decide to hold onto it.", "You rummage through the box of magical artifacts, and find a odd looking ring with a curiously intricate design, you decide to hold onto it.", 55506); Interior roomWizardHouseLab = new UseableItem("Health Potion",20,"Regenerates health points", "You search the alchemy lab and find a health potion.", 55507); Npc wizard = new Npc("Wizard", true, 22202); wizard.addConversation("g"); Interior roomWizardHouseNPC = wizard; roomWizardHouse.addMapInterior("upstairs", roomWizardHouseUpstairs); roomWizardHouse.addMapInterior("box of items", roomWizardHouseBox); roomWizardHouse.addMapInterior("alchemy lab", roomWizardHouseLab); roomWizardHouse.addMapInterior("wizard", roomWizardHouseNPC); roomWizardHouse.addMapInterior("forest", roomWizardHouseExit); //roomCave Interior roomCaveExit1 = new Exit(roomForest); Interior roomCaveExit2 = new Exit(roomCaveGruul); Monster troll = new Monster("Troll", 1.0, 1.0, 50, 3000); Interior roomWizardHouseMonster1 = troll; Interior roomWizardHouseMonster2 = troll; Interior roomWizardHouseMonster3 = troll; roomCave.addMapInterior("troll1",roomWizardHouseMonster1); roomCave.addMapInterior("troll2",roomWizardHouseMonster2); roomCave.addMapInterior("troll3",roomWizardHouseMonster3); roomCave.addMapInterior("forest",roomCaveExit1); roomCave.addMapInterior("gruuls lair",roomCaveExit2); //roomCaveGrull Interior roomCaveGruulExit1 = new Exit(roomCave); Monster gruul = new Monster("Gruul", 1.8, 2.0, 100, 5); Interior roomCaveGruulMonster = gruul; roomCave.addMapInterior("gruul", roomCaveGruulMonster); roomCave.addMapInterior("cave", roomCaveGruulExit1); //roomClearing Interior roomClearingExit1 = new Exit(roomForest); Monster giant_troll_boss = new Monster("Humongous troll", 2.1, 1.5, 200, 100); Monster unicorn = new Monster("Unicorn", 1.6, 1.5, 400, 2000000000); Interior roomClearingMonster1 = unicorn; Interior roomClearingTree = new UseableItem("Doorknob", 0, "You don't have a door", "", 55508); Interior roomClearingBoss = giant_troll_boss; roomClearing.addMapInterior("giant troll", roomClearingBoss); roomClearing.addMapInterior("forest", roomClearingExit1); roomClearing.addMapInterior("unicorn", roomClearingMonster1); roomClearing.addMapInterior("old tree", roomClearingTree); //roomDungeon Interior roomDungeonExit = new Exit(roomLibrary); Interior roomDungeonSkeleton1 = new UseableItem("",0,"", "", 0); Interior roomDungeonSkeleton2 = new UseableItem("",0,"", "", 0); Interior roomDungeonSkeleton3 = new QuestItem("Broken handle",50,"Couldn't handle it", 99903, ""); roomDungeon.addMapInterior("skeleton1", roomDungeonSkeleton1); roomDungeon.addMapInterior("skeleton2", roomDungeonSkeleton2); roomDungeon.addMapInterior("skeleton3", roomDungeonSkeleton3); roomDungeon.addMapInterior("hidden pathway", roomDungeonExit); //roomLibrary Interior roomLibraryExit = new Exit(roomEvilWizardsLair); roomLibrary.addMapInterior("book on da shelf", roomLibraryExit); //roomEvilWizardsLair /* Interior roomEvilWizardsLairDevice = new OuchItem(TBA); Interior roomEvilWizardsLairDevice2 = new OuchItem(TBA); Monster evil_wizard_f_boss = new Monster("Evil wizard!!1!", 3.0, 3.0, 1, 900); roomEvilWizardsLair.addMapInterior("It looks like a pot, but it's a landmine, ouch.",roomEvilWizardsLairDevice); roomEvilWizardsLair.addMapInterior("It looks like a glass, but it's a samsung note7, ouch.",roomEvilWizardsLairDevice2); roomEvilWizardsLair.addMapInterior("It looks like a pot, but it's really the evil wizard.",evil_wizard_f_boss); */ //set which room you start in. currentRoom = roomCellar; } /** * Return the WelcomeMessage hashmap which contains the welcome messages. * The keys are: * welcomeMessage1 * welcomeMessage2 * needHelp * getRooms * @return */ public HashMap<String, String> getWelcomeMessages(){ HashMap<String, String> welcomeList = new HashMap(); welcomeList.put("welcomeMessage1", "Welcome to the World of Zuul!"); welcomeList.put("welcomeMessage2", "World of Zuul is a new, incredibly boring adventure game."); welcomeList.put("needHelp", "Type '" + CommandWord.HELP + "' if you need help."); welcomeList.put("getRooms", currentRoom.getDescription()); return welcomeList; } /** * Return the HelpMessage hashmap which contains the help messages. * The keys are: * helpMessage1 : "You are lost. You are alone. You wander" * helpMessage2 : "around at the university." * helpMessage3 : "Your command words are:" * commands : display all the commands possible * @return */ public HashMap<String, String> getHelpMessages(){ //init a new object of type hashmap HashMap<String, String> helpList = new HashMap(); helpList.put("helpMessage1", "You are at " + currentRoom.getName()); helpList.put("helpMessage2", "Here is where you can go: " + currentRoom.getFullDescription()); helpList.put("helpMessage3", "Your command words are:"); //return the helplist when done. return helpList; } /** * Go to the desired room defined from the command param. * @param command * @return String */ public List<String> goTo(Command command){ List<String> description = new ArrayList<>(); if(!command.hasSecondWord()) { description.add("\"Go where?\""); return description; } // Create an object of klass Room and return if the exit is correct. Interior interior = currentRoom.getMapInterior(command.getSecondWord()); // If the nextroom is null it means that there was no next room in that direction. if(interior == null) { description.add("Place doesn't exist."); return description; }else if(interior instanceof Exit){ if(currentRoom == roomCellar){ for(Item i: getInventoryItems()){ if(i instanceof QuestItem){ if(((QuestItem)i).getItemId() == 99901){ currentRoom = ((Exit)interior).getNewRoom(); description.add("You manage to pick the lock with the needle, but sadly the needle breaks and cannot be used later."); player.removeInventoryItem(i); description.add(currentRoom.getDescription()); return description; } } } description.add("A giant lock is on the door and it seems indestructible."); description.add("Some sort of lockpick would come in handy."); return description; } currentRoom = ((Exit)interior).getNewRoom(); description.add(currentRoom.getDescription()); return description; }else{ description.add("Nothing here."); return description; } } public List<String> inspectThing(Command command){ List<String> inspectActions = new ArrayList(); if(!command.hasSecondWord()){ inspectActions.add("Inspect what?"); return inspectActions; } Interior interior = currentRoom.getMapInterior(command.getSecondWord()); if(interior == null){ inspectActions.add("This interior doesn't exist"); return inspectActions; } else if(interior instanceof Item){ if(interior instanceof EquippableItem){ currentRoom.removeInterior(command.getSecondWord()); player.addItemToInventory((Item)interior); inspectActions.add(((EquippableItem) interior).getRoomDescription()); player.addHighscore(((EquippableItem) interior).getItemValue()); return inspectActions; } else if(interior instanceof QuestItem){ currentRoom.removeInterior(command.getSecondWord()); player.addItemToInventory((Item)interior); inspectActions.add(((QuestItem) interior).getRoomDescription()); player.addHighscore(((QuestItem) interior).getItemValue()); return inspectActions; } else if(interior instanceof UseableItem){ currentRoom.removeInterior(command.getSecondWord()); player.addItemToInventory((Item)interior); inspectActions.add(((UseableItem) interior).getRoomDescription()); player.addHighscore(((UseableItem) interior).getItemValue()); return inspectActions; } else{ inspectActions.add("mystery Item nothing happend"); return inspectActions; } } else if(interior instanceof Npc){ inspectActions.add("This is an Npc"); switch(((Npc) interior).getNpcID()){ case 22201: for(Item i: getInventoryItems()){ if(i instanceof QuestItem){ if(((QuestItem)i).getItemId() == 99902){ inspectActions.add("You found my kids!?"); player.removeInventoryItem(i); inspectActions.add("As a reword i let you pass to the forrest."); Interior roomVillageExit4 = new Exit(roomForest); roomVillage.addMapInterior("forrest", roomVillageExit4); return inspectActions; } } } inspectActions.add("Hello my name is " + ((Npc) interior).getName()); inspectActions.add("I cant find my kids anywhere, can you?"); break; } return inspectActions; } else if(interior instanceof Monster){ Combat combat = new Combat(player, (Monster)interior); inspectActions.add("You found a monster! It's a " + ((Monster) interior).getMonsterName() + "."); for(Fight f : combat.AFight()){ if(!f.isDone()){ inspectActions.add(f.toString()); } else { inspectActions.add(f.toString()); inspectActions.add("The winner of the fight is " + f.winner()); } } if(player.getHealth() < 1){ inspectActions.add("YOU DIED! You lost highscore points."); player.removeHighscore(69); player.setHealth(100); } else { inspectActions.add("Your remaining hp: " + player.getHealth()); currentRoom.removeInterior(command.getSecondWord()); } return inspectActions; } else{ inspectActions.add("Use \"Go to\" to go to an exit"); return inspectActions; } } /** * * @return */ public List<Item> getInventoryItems(){ return player.getInventoryItems(); } /** * * @return */ public List<EquippableItem> getEquippableItems(){ return player.getEquippableItems(); } /** * Returns false if the user entered more then "quit" and return true otherwise * @param command * @return Boolean */ public boolean quit(Command command){ //if the command is quit and has a second word do nothing. Else quit. if(command.hasSecondWord()) { return false; } else { return true; } } /** * * @return */ public static List<String> getMenuSelections(){ List<String> menu = new ArrayList(); menu.add("NEW GAME "); menu.add("LOAD GAME"); menu.add("EXIT GAME"); return menu; } /** * * @param playerName */ public void setPlayerName(String playerName){ player.setPlayerName(playerName); } /** * * @return */ public String getPlayerName(){ return player.getPlayerName(); } }
package algorithms.graphs; import algorithms.matrix.MatrixUtil; import algorithms.util.PairInt; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TObjectIntMap; import gnu.trove.set.TIntSet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import thirdparty.graphMatchingToolkit.algorithms.VolgenantJonker; public class ApproxGraphSearchZeng { public List<Graph> approxFullSearch(Graph q, List<Graph> db, int w) { List<Graph> results = new ArrayList<Graph>(); Graph dbi; StarStructure[] sQ = StarStructure.createStarStructureMultiset(q); StarStructure[] sg1, sg2; int[][] a1, a2; StarStructure s; Graph g; int i, k, rIdx; for (int ii = 0; ii < db.size(); ++ii) { dbi = db.get(ii); sg1 = StarStructure.copy(sQ); sg2 = StarStructure.createStarStructureMultiset(dbi); a1 = createAdjacencyMatrix(sg1); a2 = createAdjacencyMatrix(sg2); // normalize sq1 and sg2 to have same cardinality for bipartite vertex assignments // order so that sg1.length >= sg2.length if (sg1.length < sg2.length) { StarStructure[] tmp = sg1; sg1 = sg2; sg2 = tmp; } if (sg1.length > sg2.length) { k = sg1.length - sg2.length; //insert k vertices to sg2 and set their labels to eps StarStructure[] _sg2 = new StarStructure[sg1.length]; System.arraycopy(sg2, 0, _sg2, 0, sg2.length); for (i = 0; i < k; ++i) { rIdx = sg1.length + i; s = new StarStructure(rIdx, StarStructure.eps, new int[0], new int[0], new int[0]); _sg2[sg2.length + i] = s; } sg2 = _sg2; } assert (sg1.length == sg2.length); // create cost matrix for bipartite assignments of vertexes in sg1 to sg2 double[][] distM = StarStructure.createDistanceMatrix(sg1, sg2); VolgenantJonker vj = new VolgenantJonker(); double cost = vj.computeAssignment(distM); int[] assign = vj.getAssignment(); int mappingDist = mappingDistance(sg1, sg2, assign); double lM = lowerBoundEditDistance(sg1, sg2, mappingDist); if (lM > w) { continue; } double tau = suboptimalEditDistance(sg1, sg2, a1, a2, assign); if (tau <= w) { results.add(dbi); continue; } int[] refinedAssign = Arrays.copyOf(assign, assign.length); double rho = refinedSuboptimalEditDistance(sg1, sg2, a1, a2, refinedAssign, tau, distM); if (rho <= w) { results.add(dbi); continue; } } // end loop over db graphs throw new UnsupportedOperationException("not yet implemented"); } public List<Graph> approxSubSearch(Graph q, List<Graph> db, int w) { throw new UnsupportedOperationException("not yet implemented"); } protected double suboptimalEditDistance(StarStructure[] sg1, StarStructure[] sg2, int[][] a1, int[][] a2, int[] assignments) { int[][] p = createP(assignments); int[][] c = createLabelMatrix(sg1, sg2, assignments); assert(c.length == p.length); assert(c[0].length == p[0].length); /* C(g, h, P') = sum_(i|0:n-1) sum_(j|0:n-1) ( c[i][j]*p[i][j] + (1/2) || a1 - P*a2*P^T ||_1 Assuming that the L1-norm here is the same convention as MatLab: For p-norm = 1, the L1-norm is the maximum absolute column sum of the matrix. ||X||_1 = max sum for an arg j where (0<=j<=n-1) sum_(i=0 to n-1) ( |a[i][j] ) */ int[][] pA2PT = MatrixUtil.multiply(p, MatrixUtil.multiply(a2, MatrixUtil.transpose(p))); double term2 = 0.5*MatrixUtil.lp1Norm( MatrixUtil.elementwiseSubtract(a1, pA2PT)); double term1 = 0; int i, j; for (i = 0; i < c.length; ++i) { for (j = 0; j < c[i].length; ++j) { term1 += c[i][j] * p[i][j]; } } return term1 + term2; } protected double lowerBoundEditDistance(StarStructure[] sg1, StarStructure[] sg2, int mappingDist) { int maxDeg1 = maxDegree(sg1); int maxDeg2 = maxDegree(sg2); double denom = Math.max(maxDeg1, maxDeg2) + 1; double lM = mappingDist/denom; return lM; } protected int mappingDistance(StarStructure[] sg1, StarStructure[] sg2, int[] assignments) { // usign the assignments, sum the edit distances. int sum = 0, i; StarStructure s1, s2; for (i = 0; i < assignments.length; ++i) { s1 = sg1[i]; s2 = sg2[assignments[i]]; sum += StarStructure.calculateEditDistance(s1, s2); } return sum; } /** * find the maximum degree of a vertex for the graph g. * @param sg * @return */ private int maxDegree(StarStructure[] sg) { int max = 0, deg; for (int i = 0; i < sg.length; ++i) { deg = sg[i].vLabels.length; if (deg > max) { max = deg; } } return max; } private int[][] createAdjacencyMatrix(StarStructure[] s) { int nV = s.length; int[][] a = new int[nV][]; StarStructure si; int uIdx, vIdx, j; for (int i = 0; i < nV; ++i) { a[i] = new int[nV]; si = s[i]; uIdx = si.rootIdx; for (j = 0; j < si.vLabels.length; ++j) { vIdx = si.origVIndexes[j]; a[uIdx][vIdx] = 1; } } return a; } private int[][] createP(int[] assignments) { int n = assignments.length; int[][] p = new int[n][]; int i; for (i = 0; i < n; ++i) { p[i] = new int[n]; } for (i = 0; i < n; ++i) { p[i][assignments[i]] = 1; } assert(MatrixUtil.isAPermutationMatrix(p)); return p; } private int[][] createLabelMatrix(StarStructure[] sg1, StarStructure[] sg2, int[] assignments) { int[][] c = new int[sg1.length][]; int i, j; for (i = 0; i < sg1.length; ++i) { c[i] = new int[sg2.length]; } for (i = 0; i < assignments.length; ++i) { j = assignments[i]; if (sg1[i].rootLabel == sg2[j].rootLabel) { c[i][j] = 1; } } return c; } /** * calculates the refined suboptimal edit distance by swapping the * vertex assignments and calculating the * suboptimal distance, keeping the permuted assignments that result in * the smallest edit distance. * @param sg1 star structures for graph g1 * @param sg2 star structures for graph g2 * @param a1 adjacency matrix for graph g1 * @param a2 adjacency matrix for graph g2 * @param refinedAssign input initial vertex assignments and output * refined vertex assignments. * @param tau the sub-optimal edit distance the given sub-optimal edit distance C(g,h,P) where * P is formed from the given assignments in refinedAssign. * @param distM cost matrix for bipartite assignments of vertexes in sg1 to sg2 * @return */ protected double refinedSuboptimalEditDistance(StarStructure[] sg1, StarStructure[] sg2, int[][] a1, int[][] a2, int[] refinedAssign, double tau, double[][] distM) { /* int[] assign = Arrays.copyOf(refinedAssign, refinedAssign.length); double dist; double min = tau; do { dist = tau; change assign calc tau if (min > tau) { min = tau; System.arraycopy(assign, 0, refinedAssign, 0, assign.length); } } while (min < dist); return min; */ throw new UnsupportedOperationException("not yet implemented"); } /** * an undirected attributed graph */ public static class Graph { public final TIntIntMap vLabels; public final TObjectIntMap<PairInt> eLabels; public final TIntObjectMap<TIntSet> adjMap; /** * construct a graph instance using given data structures. Note that this * method copies by reference and does not copy by value into new * data structures (can use MatrixUtil.copy() methods). * @param adjMap * @param vLabels * @param eLabels */ public Graph(TIntObjectMap<TIntSet> adjMap, TIntIntMap vLabels, TObjectIntMap<PairInt> eLabels) { this.vLabels = vLabels; this.eLabels = eLabels; this.adjMap = adjMap; } } }
package bdv.img.catmaid; import java.io.File; import org.jdom2.Element; import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription; import mpicbg.spim.data.generic.sequence.ImgLoaderIo; import mpicbg.spim.data.generic.sequence.XmlIoBasicImgLoader; @ImgLoaderIo( format = "catmaid", type = CatmaidImageLoader.class ) public class XmlIoCatmaidImageLoader implements XmlIoBasicImgLoader< CatmaidImageLoader > { @Override public Element toXml( final CatmaidImageLoader imgLoader, final File basePath ) { throw new UnsupportedOperationException( "not implemented" ); } @Override public CatmaidImageLoader fromXml( final Element elem, final File basePath, final AbstractSequenceDescription< ?, ?, ? > sequenceDescription ) { final long width = Long.parseLong( elem.getChildText( "width" ) ); final long height = Long.parseLong( elem.getChildText( "height" ) ); final long depth = Long.parseLong( elem.getChildText( "depth" ) ); final double resXY = Double.parseDouble( elem.getChildText( "resXY" ) ); final double resZ = Double.parseDouble( elem.getChildText( "resZ" ) ); final String urlFormat = elem.getChildText( "urlFormat" ); final int tileWidth = Integer.parseInt( elem.getChildText( "tileWidth" ) ); final int tileHeight = Integer.parseInt( elem.getChildText( "tileHeight" ) ); final String blockWidthString = elem.getChildText( "blockWidth" ); final String blockHeightString = elem.getChildText( "blockHeight" ); final String blockDepthString = elem.getChildText( "blockDepth" ); final int blockWidth = blockWidthString == null ? tileWidth : Integer.parseInt( blockWidthString ); final int blockHeight = blockHeightString == null ? tileHeight : Integer.parseInt( blockHeightString ); final int blockDepth = blockDepthString == null ? 1 : Integer.parseInt( blockDepthString ); System.out.println( String.format( "Block size = (%d, %d, %d)", blockWidth, blockHeight, blockDepth ) ); final String numScalesString = elem.getChildText( "numScales" ); int numScales; if ( numScalesString == null ) numScales = CatmaidImageLoader.getNumScales( width, height, tileWidth, tileHeight ); else numScales = Integer.parseInt( numScalesString ); final int[][] blockSize = new int[ numScales ][]; for ( int i = 0; i < numScales; ++i ) blockSize[ i ] = new int[]{ blockWidth, blockHeight, blockDepth }; return new CatmaidImageLoader( width, height, depth, resZ / resXY, urlFormat, tileWidth, tileHeight, blockSize ); } }
package br.gov.mj.sislegis.app.model; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlRootElement; import br.gov.mj.sislegis.app.enumerated.Origem; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class Proposicao implements AbstractEntity { private static final long serialVersionUID = 7949894944142814382L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(nullable = false, unique = true) private Integer idProposicao; @Column private String tipo; @Column private String ano; @Column private String numero; @Column private String autor; @Enumerated(EnumType.STRING) @Column private Origem origem; @Column(length=2000) private String resultadoASPAR; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "proposicao") private Set<ReuniaoProposicao> listaReuniaoProposicoes; @Transient private String comissao; @Transient private Integer seqOrdemPauta; @Transient private String sigla; @Column(length=2000) private String ementa; @Column private String linkProposicao; @Transient private String linkPauta; @Column private Posicionamento posicionamento; @ManyToOne(fetch = FetchType.EAGER) private Usuario responsavel; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "proposicao") private Set<TagProposicao> tags; @Transient private Set<Comentario> listaComentario = new HashSet<Comentario>(); @Transient private Set<EncaminhamentoProposicao> listaEncaminhamentoProposicao = new HashSet<EncaminhamentoProposicao>(); @Transient private Reuniao reuniao; @Column(nullable = false) private boolean isFavorita; //@OneToMany(fetch = FetchType.EAGER, mappedBy = "pai") @ManyToMany(fetch = FetchType.EAGER, mappedBy = "proposicoesFilha") private Set<Proposicao> proposicoesPai; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "proposicao_proposicao", joinColumns = { @JoinColumn(name = "proposicao_id")}, inverseJoinColumns={@JoinColumn(name="proposicao_id_filha")}) private Set<Proposicao> proposicoesFilha; public String getSigla() { if (Objects.isNull(sigla)) sigla = getTipo() + " " + getNumero() + "/" + getAno(); return sigla; } public void setSigla(String sigla) { this.sigla = sigla; } public Long getId() { return this.id; } public void setId(final Long id) { this.id = id; } public Integer getIdProposicao() { return idProposicao; } public void setIdProposicao(Integer idProposicao) { this.idProposicao = idProposicao; } public String getTipo() { if (tipo != null && !tipo.isEmpty()) { tipo = tipo.trim(); } return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public String getAno() { return ano; } public void setAno(String ano) { this.ano = ano; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getEmenta() { return ementa; } public void setEmenta(String ementa) { this.ementa = ementa; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public String getComissao() { return comissao; } public void setComissao(String comissao) { this.comissao = comissao; } public Integer getSeqOrdemPauta() { return seqOrdemPauta; } public void setSeqOrdemPauta(Integer seqOrdemPauta) { this.seqOrdemPauta = seqOrdemPauta; } public Origem getOrigem() { return origem; } public void setOrigem(Origem origem) { this.origem = origem; } public String getLinkProposicao() { return linkProposicao; } public void setLinkProposicao(String linkProposicao) { this.linkProposicao = linkProposicao; } public String getLinkPauta() { return linkPauta; } public void setLinkPauta(String linkPauta) { this.linkPauta = linkPauta; } public Posicionamento getPosicionamento() { return posicionamento; } public void setPosicionamento(Posicionamento posicionamento) { this.posicionamento = posicionamento; } public Set<ReuniaoProposicao> getListaReuniaoProposicoes() { return listaReuniaoProposicoes; } public void setListaReuniaoProposicoes(Set<ReuniaoProposicao> listaReuniaoProposicoes) { this.listaReuniaoProposicoes = listaReuniaoProposicoes; } public Set<Comentario> getListaComentario() { return this.listaComentario; } public void setListaComentario(final Set<Comentario> listaComentario) { this.listaComentario = listaComentario; } public Set<EncaminhamentoProposicao> getListaEncaminhamentoProposicao() { return listaEncaminhamentoProposicao; } public void setListaEncaminhamentoProposicao( Set<EncaminhamentoProposicao> listaEncaminhamentoProposicao) { this.listaEncaminhamentoProposicao = listaEncaminhamentoProposicao; } public Set<TagProposicao> getTags() { return tags; } public void setTags(Set<TagProposicao> tags) { this.tags = tags; } public Usuario getResponsavel() { return responsavel; } public void setResponsavel(Usuario responsavel) { this.responsavel = responsavel; } public Reuniao getReuniao() { return reuniao; } public void setReuniao(Reuniao reuniao) { this.reuniao = reuniao; } public String getResultadoASPAR() { return resultadoASPAR; } public void setResultadoASPAR(String resultadoASPAR) { this.resultadoASPAR = resultadoASPAR; } public boolean isFavorita() { return isFavorita; } public void setFavorita(boolean isFavorita) { this.isFavorita = isFavorita; } public Set<Proposicao> getProposicoesPai() { return proposicoesPai; } public Set<Proposicao> getProposicoesFilha() { return proposicoesFilha; } public void setProposicoesPai(Set<Proposicao> proposicoesPai) { this.proposicoesPai = proposicoesPai; } public void setProposicoesFilha(Set<Proposicao> proposicoesFilha) { this.proposicoesFilha = proposicoesFilha; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Proposicao)) { return false; } Proposicao other = (Proposicao) obj; if (id != null) { if (!id.equals(other.id)) { return false; } } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public String toString() { String result = getClass().getSimpleName() + " "; if (idProposicao != null) result += "idProposicao: " + idProposicao; if (tipo != null && !tipo.trim().isEmpty()) result += ", tipo: " + tipo; if (ano != null && !ano.trim().isEmpty()) result += ", ano: " + ano; if (numero != null && !numero.trim().isEmpty()) result += ", numero: " + numero; if (autor != null && !autor.trim().isEmpty()) result += ", autor: " + autor; if (comissao != null && !comissao.trim().isEmpty()) result += ", comissao: " + comissao; if (seqOrdemPauta != null) result += ", seqOrdemPauta: " + seqOrdemPauta; return result; } }
package org.apache.jmeter.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import junit.framework.TestCase; import org.apache.jmeter.gui.JMeterGUIComponent; import org.apache.jmeter.gui.UnsharedComponent; import org.apache.jmeter.gui.tree.JMeterTreeNode; import org.apache.jmeter.save.SaveService; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jmeter.testelement.property.PropertyIterator; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.reflect.ClassFinder; import org.apache.log.Logger; /** * @author Michael Stover * @version $Revision$ */ public class JMeterTest extends TestCase { private static Logger log = LoggingManager.getLoggerForClass(); public JMeterTest(String name) { super(name); } public void testGUIComponents() throws Exception { Iterator iter = getObjects(JMeterGUIComponent.class).iterator(); while (iter.hasNext()) { JMeterGUIComponent item = (JMeterGUIComponent) iter.next(); if (item instanceof JMeterTreeNode) { continue; } assertEquals( "Failed on " + item.getClass().getName(), item.getStaticLabel(), item.getName()); TestElement el = item.createTestElement(); assertNotNull( "createTestElement failed on " + item.getClass().getName(), el); assertEquals( "GUI-CLASS: Failed on " + item.getClass().getName(), item.getClass().getName(), el.getPropertyAsString(TestElement.GUI_CLASS)); assertEquals( "NAME: Failed on " + item.getClass().getName(), item.getName(), el.getPropertyAsString(TestElement.NAME)); assertEquals( "TEST-CLASS: Failed on " + item.getClass().getName(), el.getClass().getName(), el.getPropertyAsString(TestElement.TEST_CLASS)); TestElement el2 = item.createTestElement(); el.setProperty(TestElement.NAME, "hey, new name!:"); el.setProperty("NOT", "Shouldn't be here"); if (!(item instanceof UnsharedComponent)) { assertEquals( "GUI-CLASS: Failed on " + item.getClass().getName(), "", el2.getPropertyAsString("NOT")); } log.debug("Saving element: " + el.getClass()); el = SaveService.createTestElement( SaveService.getConfigForTestElement(null, el)); log.debug("Successfully saved"); item.configure(el); assertEquals( "CONFIGURE-TEST: Failed on " + item.getClass().getName(), el.getPropertyAsString(TestElement.NAME), item.getName()); item.modifyTestElement(el2); assertEquals( "Modify Test: Failed on " + item.getClass().getName(), "hey, new name!:", el2.getPropertyAsString(TestElement.NAME)); } } public void testSerializableElements() throws Exception { Iterator iter = getObjects(Serializable.class).iterator(); while (iter.hasNext()) { Serializable serObj = (Serializable) iter.next(); if (serObj.getClass().getName().endsWith("_Stub")) { continue; } try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(serObj); out.close(); ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bytes.toByteArray())); Object readObject = in.readObject(); in.close(); assertEquals( "deserializing class: " + serObj.getClass().getName(), serObj.getClass(), readObject.getClass()); } catch (Exception e) { log.error( "Trying to serialize object: " + serObj.getClass().getName(), e); throw e; } } } public void testTestElements() throws Exception { Iterator iter = getObjects(TestElement.class).iterator(); while (iter.hasNext()) { TestElement item = (TestElement) iter.next(); checkElementCloning(item); assertTrue( item.getClass().getName() + " must implement Serializable", item instanceof Serializable); } } private Collection getObjects(Class extendsClass) throws Exception { Iterator classes = ClassFinder .findClassesThatExtend( JMeterUtils.getSearchPaths(), new Class[] { extendsClass }) .iterator(); List objects = new LinkedList(); String n=""; try { while (classes.hasNext()) { n = (String) classes.next(); //TODO - improve this check if (n.endsWith("RemoteJMeterEngineImpl")) { continue; // Don't try to instantiate remote server } Class c = Class.forName(n); try { try { // Try with a parameter-less constructor first objects.add(c.newInstance()); } catch (InstantiationException e) { try { // Events often have this constructor objects.add( c.getConstructor( new Class[] { Object.class }).newInstance( new Object[] { this })); } catch (NoSuchMethodException f) { // no luck. Ignore this class } } } catch (IllegalAccessException e) { // We won't test serialization of restricted-access // classes. } catch (java.awt.HeadlessException e) { System.out.println("\nError creating "+n+" "+e.toString()); } catch (Exception e) { if (e instanceof RemoteException) { System.out.println("\nError creating "+n+" "+e.toString()); } else { throw new Exception("Error creating "+n,e); } } } } finally { System.out.println("\nLast class="+n); System.out.println("objects.size="+objects.size()); } return objects; } private void cloneTesting(TestElement item, TestElement clonedItem) { assertTrue(item != clonedItem); assertEquals( "CLONE-SAME-CLASS: testing " + item.getClass().getName(), item.getClass().getName(), clonedItem.getClass().getName()); } private void checkElementCloning(TestElement item) { TestElement clonedItem = (TestElement) item.clone(); cloneTesting(item, clonedItem); PropertyIterator iter2 = item.propertyIterator(); while (iter2.hasNext()) { JMeterProperty item2 = iter2.next(); assertEquals(item2, clonedItem.getProperty(item2.getName())); assertTrue(item2 != clonedItem.getProperty(item2.getName())); } } }
package ch.tkuhn.nanopub.server; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import net.trustyuri.TrustyUriUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.commons.lang3.tuple.Pair; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.nanopub.MultiNanopubRdfHandler; import org.nanopub.MultiNanopubRdfHandler.NanopubHandler; import org.nanopub.Nanopub; import org.nanopub.NanopubImpl; import org.nanopub.extra.server.NanopubServerUtils; import org.openrdf.rio.RDFFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CollectNanopubs { private static final int processPagesPerRun = 10; private static NanopubDb db = NanopubDb.get(); private Logger logger = LoggerFactory.getLogger(this.getClass()); private ServerInfo peerInfo; private int peerPageSize; private boolean isFinished = false; private int loaded; private StopWatch watch; public CollectNanopubs(ServerInfo peerInfo) { this.peerInfo = peerInfo; } public void run() { try { logger.info("Checking if there are new nanopubs at " + peerInfo.getPublicUrl()); int startFromPage = 1; long startFromNp = 0; long newNanopubsCount; peerPageSize = peerInfo.getPageSize(); long peerNanopubNo = peerInfo.getNextNanopubNo(); long peerJid = peerInfo.getJournalId(); Pair<Long,Long> lastSeenPeerState = db.getLastSeenPeerState(peerInfo.getPublicUrl()); if (lastSeenPeerState != null) { startFromNp = lastSeenPeerState.getRight(); newNanopubsCount = peerNanopubNo - startFromNp; if (lastSeenPeerState.getLeft() == peerJid) { if (startFromNp == peerNanopubNo) { logger.info("Already up-to-date"); isFinished = true; return; } startFromPage = (int) (startFromNp/peerPageSize) + 1; logger.info(newNanopubsCount + " new nanopubs"); } else { logger.info(newNanopubsCount + " nanopubs in total (unknown journal)"); } } else { newNanopubsCount = peerNanopubNo; logger.info(newNanopubsCount + " nanopubs in total (unknown peer state)"); } int lastPage = (int) (peerNanopubNo/peerPageSize + 1); long ignoreBeforePos = startFromNp; logger.info("Starting from page " + startFromPage + " of " + lastPage); int pageCountThisRun = 0; boolean interrupted = false; for (int p = startFromPage ; p <= lastPage ; p++) { pageCountThisRun++; if (pageCountThisRun > processPagesPerRun) { interrupted = true; break; } processPage(p, p == lastPage, ignoreBeforePos); ignoreBeforePos = 0; } if (interrupted) { logger.info("To be continued (see if other peers have new nanopubs)"); } else { logger.info("Done"); isFinished = true; } } catch (Exception ex) { logger.error(ex.getMessage(), ex); isFinished = true; ScanPeers.lastTimeMeasureMap.put(peerInfo.getPublicUrl(), Float.MAX_VALUE); } } public boolean isFinished() { return isFinished; } private void processPage(int page, boolean isLastPage, long ignoreBeforePos) throws Exception { logger.info("Process page " + page + " from " + peerInfo.getPublicUrl()); loaded = 0; long processNp = (page-1) * peerPageSize; List<String> toLoad = new ArrayList<>(); boolean downloadAsPackage = false; for (String nanopubUri : NanopubServerUtils.loadNanopubUriList(peerInfo, page)) { if (processNp >= ignoreBeforePos) { String ac = TrustyUriUtils.getArtifactCode(nanopubUri); if (ac != null && !db.hasNanopub(ac)) { toLoad.add(ac); if (!isLastPage && toLoad.size() > 5) { // Download entire package if more than 5 nanopubs are new downloadAsPackage = true; processNp++; break; } } } processNp++; } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build(); HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); watch = new StopWatch(); watch.start(); if (downloadAsPackage) { logger.info("Download page " + page + " as compressed package..."); HttpGet get = new HttpGet(peerInfo.getPublicUrl() + "package.gz?page=" + page); get.setHeader("Accept", "application/x-gzip"); HttpResponse resp = c.execute(get); InputStream in; if (wasSuccessful(resp)) { in = new GZIPInputStream(resp.getEntity().getContent()); } else { logger.info("Failed. Trying uncompressed package..."); // This is for compability with older versions; to be removed at some point... get = new HttpGet(peerInfo.getPublicUrl() + "package?page=" + page); get.setHeader("Accept", "application/trig"); resp = c.execute(get); if (!wasSuccessful(resp)) { logger.error("HTTP request failed: " + resp.getStatusLine().getReasonPhrase()); recordTime(); throw new RuntimeException(resp.getStatusLine().getReasonPhrase()); } in = resp.getEntity().getContent(); } MultiNanopubRdfHandler.process(RDFFormat.TRIG, in, new NanopubHandler() { @Override public void handleNanopub(Nanopub np) { if (watch.getTime() > 5 * 60 * 1000) { // Downloading the whole package should never take more than 5 minutes. logger.error("Downloading package took too long; interrupting"); recordTime(); throw new RuntimeException("Downloading package took too long; interrupting"); } try { loadNanopub(np); } catch (Exception ex) { throw new RuntimeException(ex); } } }); } else { logger.info("Download " + toLoad.size() + " nanopubs individually..."); for (String ac : toLoad) { HttpGet get = new HttpGet(peerInfo.getPublicUrl() + ac); get.setHeader("Accept", "application/trig"); HttpResponse resp = c.execute(get); if (!wasSuccessful(resp)) { logger.error("HTTP request failed: " + resp.getStatusLine().getReasonPhrase()); recordTime(); throw new RuntimeException(resp.getStatusLine().getReasonPhrase()); } InputStream in = resp.getEntity().getContent(); loadNanopub(new NanopubImpl(in, RDFFormat.TRIG)); } } recordTime(); db.updatePeerState(peerInfo, processNp); } private void recordTime() { try { watch.stop(); Float avg = null; if (loaded > 0) { avg = (float) watch.getTime() / loaded; ScanPeers.lastTimeMeasureMap.put(peerInfo.getPublicUrl(), avg); } logger.info("Time measurement: " + watch.getTime() + " for " + loaded + " nanopubs (average: " + avg + ")"); } catch (Exception ex) { // ignore } } private boolean wasSuccessful(HttpResponse resp) { int c = resp.getStatusLine().getStatusCode(); return c >= 200 && c < 300; } private void loadNanopub(Nanopub np) throws Exception { db.loadNanopub(np); loaded++; } }
package club.magicfun.aquila.job; import java.io.File; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import club.magicfun.aquila.util.HtmlUtility; import club.magicfun.aquila.util.StringUtility; public class TestWebDriver3 { private static final Logger logger = LoggerFactory.getLogger(TestWebDriver3.class); private static final String PRODUCT_CATEGORY_URL_TEMPLATE = "http://item.taobao.com/item.htm?id={PRODUCTID}"; private static final String SHOP_TYPE_TMALL = "tmall"; private static final String SHOP_TYPE_TAOBAO = "taobao"; public static void main(String[] args) { String dir = System.getProperty("user.dir"); String osName = System.getProperty("os.name"); // load the appropriate chrome drivers according to the OS type if (osName.toLowerCase().indexOf("windows") > -1) { System.setProperty("webdriver.chrome.driver", dir + File.separator + "drivers" + File.separator + "win" + File.separator + "chromedriver.exe"); } else if (osName.toLowerCase().indexOf("mac") > -1) { System.setProperty("webdriver.chrome.driver", dir + File.separator + "drivers" + File.separator + "mac" + File.separator + "chromedriver"); } WebDriver webDriver = new ChromeDriver(); List<Long> productIds = new ArrayList<Long>(); productIds.add(44057413538l); productIds.add(42453456250l); productIds.add(41129702139l); productIds.add(1771185060l); productIds.add(37833049213l); productIds.add(38403988528l); for (Long productId : productIds) { String shopType = null; boolean containsCategoryFlag = false; boolean isPromotedFlag = false; String productName = null; String monthSaleAmount = null; String favouriteCount = null; String shopName = null; logger.info("Dealing with Product Id: " + productId); String url = PRODUCT_CATEGORY_URL_TEMPLATE.replaceFirst("\\{PRODUCTID\\}", productId.toString()); webDriver.get(url); System.out.println("Current URL: " + webDriver.getCurrentUrl()); if (StringUtility.containsAny(webDriver.getCurrentUrl(), "detail.tmall.com")) { shopType = SHOP_TYPE_TMALL; } else if (StringUtility.containsAny(webDriver.getCurrentUrl(), "item.taobao.com")) { shopType = SHOP_TYPE_TAOBAO; } logger.info("shop type = " + shopType); if (SHOP_TYPE_TAOBAO.equalsIgnoreCase(shopType)) { try{ if (webDriver.findElement(By.xpath("//div[@class='tb-skin']/dl/dt")).getText().equals("")) { containsCategoryFlag = true; } } catch (NoSuchElementException ex) { // do nothing here } try{
package com.akiban.sql.optimizer.rule; import com.akiban.sql.optimizer.plan.*; import com.akiban.sql.optimizer.plan.JoinNode.JoinType; import com.akiban.server.error.UnsupportedSQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** Take a map join node and push enough into the inner loop that the * bindings can be evaluated properly. * Or, looked at another way, what is before expressed through * data-flow is after expressed as control-flow. */ public class MapFolder extends BaseRule { private static final Logger logger = LoggerFactory.getLogger(MapFolder.class); @Override protected Logger getLogger() { return logger; } static class MapJoinsFinder implements PlanVisitor, ExpressionVisitor { List<MapJoin> result = new ArrayList<MapJoin>(); public List<MapJoin> find(PlanNode root) { root.accept(this); return result; } @Override public boolean visitEnter(PlanNode n) { return visit(n); } @Override public boolean visitLeave(PlanNode n) { return true; } @Override public boolean visit(PlanNode n) { if (n instanceof MapJoin) { result.add((MapJoin)n); } return true; } @Override public boolean visitEnter(ExpressionNode n) { return visit(n); } @Override public boolean visitLeave(ExpressionNode n) { return true; } @Override public boolean visit(ExpressionNode n) { return true; } } @Override public void apply(PlanContext planContext) { BaseQuery query = (BaseQuery)planContext.getPlan(); List<MapJoin> maps = new MapJoinsFinder().find(query); for (MapJoin map : maps) handleJoinType(map); for (MapJoin map : maps) foldOuterMap(map); for (MapJoin map : maps) fold(map); } // First pass: account for the join type by adding something at // the tip of the inner (fast) side of the loop. protected void handleJoinType(MapJoin map) { switch (map.getJoinType()) { case INNER: break; case LEFT: map.setInner(new NullIfEmpty(map.getInner())); break; case SEMI: map.setInner(new Limit(map.getInner(), 1)); break; default: throw new UnsupportedSQLException("complex join type " + map, null); } map.setJoinType(null); // No longer special. } // Second pass: if one map has another on the outer (slow) side, // turn them inside out. Nesting must all be on the inner side to // be like regular loops. Conceptually, the two trace places, but // actually doing that would mess up the depth nesting for the // next pass. protected void foldOuterMap(MapJoin map) { if (map.getOuter() instanceof MapJoin) { MapJoin otherMap = (MapJoin)map.getOuter(); foldOuterMap(otherMap); PlanNode inner = map.getInner(); PlanNode outer = otherMap.getInner(); map.setOuter(otherMap.getOuter()); map.setInner(otherMap); otherMap.setOuter(outer); otherMap.setInner(inner); } } // Final pass: move things upstream of the map down into the inner (fast) side. protected void fold(MapJoin map) { PlanWithInput parent = map; PlanNode child; do { child = parent; parent = child.getOutput(); } while (!((parent instanceof MapJoin) || // These need to be outside. (parent instanceof Subquery) || (parent instanceof ResultSet) || (parent instanceof AggregateSource) || (parent instanceof Sort) || // Captures enough at the edge of the inside. (child instanceof Project))); if (child != map) { map.getOutput().replaceInput(map, map.getInner()); parent.replaceInput(child, map); map.setInner(child); } } }
package com.bitdecay.game.screen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.Align; import com.bitdecay.game.Launcher; import com.bitdecay.game.MyGame; import com.bitdecay.game.util.InputHelper; import com.bitdecay.game.util.SoundLibrary; import java.util.ArrayList; import java.util.List; /** * This is the menu screen. It should be fairly easy to add new options by using the previous options as templates. A lot of the parts of the menu are constructed using the conf values in the /resources/conf/application.conf file. If you make any changes, consider making them such that you can use the conf files to change them in the future. */ public class MainMenuScreen implements Screen { private MyGame game; private Stage stage = new Stage(); private Table menu; private List<MenuOption> menuOptions = new ArrayList<>(); private Image background; private Skin skin; private int menuSelection; public MainMenuScreen(MyGame game) { this.game = game; menuSelection = 0; skin = new Skin(Gdx.files.classpath(Launcher.conf.getString("menu.skin"))); background = new Image(new Texture(Gdx.files.classpath(Launcher.conf.getString("menu.titleBackground")))); background.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); menu = new Table(); menu.setFillParent(true); // Here is where you add more menu options menu.add(buildNewMenuOption("Start", this::gotoGame)).height(60).padBottom(20).padTop(150).row(); menu.add(buildNewMenuOption("Credits", this::gotoCredits)).height(60).padBottom(20).row(); menu.add(buildNewMenuOption("Quit", this::exitGame)).height(60).padBottom(20).row(); menu.align(Align.center); menu.padLeft(-475); menu.padBottom(0); stage.addActor(background); stage.addActor(menu); Gdx.input.setInputProcessor(stage); updateMenuSelection(0); } private Label buildNewMenuOption(String itemText, Runnable runnable){ Label l = new Label(itemText, skin); l.setFontScale(8); l.setColor(Color.BLACK); l.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { runnable.run(); } }); menuOptions.add(new MenuOption(itemText, runnable, l)); return l; } @Override public void show() { // TODO: maybe play music here if the music from the intro is not still playing SoundLibrary.loopMusic(Launcher.conf.getString("splash.music")); // animate the main menu when entering Action fadeIn = Actions.sequence(Actions.alpha(0), Actions.delay(0.25f), Actions.fadeIn(2.5f)); background.addAction(fadeIn); menu.addAction(fadeIn); } @Override public void render(float delta) { Gdx.gl.glClearColor(0f, 0f, 0f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(); stage.draw(); update(); } public void update(){ if (InputHelper.isKeyJustPressed(Input.Keys.UP, Input.Keys.LEFT, Input.Keys.W, Input.Keys.A)) updateMenuSelection(-1); else if (InputHelper.isKeyJustPressed(Input.Keys.DOWN, Input.Keys.RIGHT, Input.Keys.S, Input.Keys.D)) updateMenuSelection(1); else if (InputHelper.isKeyJustPressed(Input.Keys.ENTER, Input.Keys.SPACE)) makeSelection(); } private void gotoGame() { game.setScreen(new GameScreen(game)); } private void gotoCredits() { game.setScreen(new CreditsScreen(game)); } private void exitGame() { Gdx.app.exit(); } private void makeSelection(){ SoundLibrary.playSound(Launcher.conf.getString("menu.selectSoundFx")); menuOptions.get(menuSelection).runnable.run(); } private void updateMenuSelection(int change) { menuSelection += change; if (menuSelection >= menuOptions.size()) menuSelection = 0; else if (menuSelection < 0) menuSelection = menuOptions.size() - 1; for (int i = 0; i < menuOptions.size(); i++){ if (menuSelection == i) menuOptions.get(i).label.setColor(Color.GREEN); else menuOptions.get(i).label.setColor(Color.BLACK); } } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { dispose(); } @Override public void dispose() { stage.dispose(); } private class MenuOption{ public String text; public Runnable runnable; public Label label; public MenuOption(String text, Runnable runnable, Label label){ this.text = text; this.runnable = runnable; this.label = label; } } }
package com.cloudbees.jenkins; import hudson.Extension; import hudson.Util; import hudson.console.AnnotatedLargeText; import hudson.model.Action; import hudson.model.Hudson; import hudson.model.Hudson.MasterComputer; import hudson.model.Item; import hudson.model.AbstractProject; import hudson.model.Project; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.SequentialExecutionQueue; import hudson.util.StreamTaskListener; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.json.JSONObject; import org.apache.commons.jelly.XMLOutput; import org.kohsuke.github.GHException; import org.kohsuke.github.GHRepository; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; /** * Triggers a build when we receive a GitHub post-commit webhook. * * @author Kohsuke Kawaguchi */ public class GitHubPushTrigger extends Trigger<AbstractProject<?,?>> implements GitHubTrigger { @DataBoundConstructor public GitHubPushTrigger() { } /** * Called when a POST is made. */ @Deprecated public void onPost() { onPost(""); } /** * Called when a POST is made. */ public void onPost(String triggeredByUser) { final String pushBy = triggeredByUser; getDescriptor().queue.execute(new Runnable() { private boolean runPolling() { try { StreamTaskListener listener = new StreamTaskListener(getLogFile()); try { PrintStream logger = listener.getLogger(); long start = System.currentTimeMillis(); logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date())); boolean result = job.poll(listener).hasChanges(); logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start)); if(result) logger.println("Changes found"); else logger.println("No changes"); return result; } catch (Error e) { e.printStackTrace(listener.error("Failed to record SCM polling")); LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e); throw e; } catch (RuntimeException e) { e.printStackTrace(listener.error("Failed to record SCM polling")); LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e); throw e; } finally { listener.close(); } } catch (IOException e) { LOGGER.log(Level.SEVERE,"Failed to record SCM polling",e); } return false; } public void run() { if (runPolling()) { String name = " #"+job.getNextBuildNumber(); GitHubPushCause cause; try { cause = new GitHubPushCause(getLogFile(), pushBy); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to parse the polling log",e); cause = new GitHubPushCause(pushBy); } if (job.scheduleBuild(cause)) { LOGGER.info("SCM changes detected in "+ job.getName()+". Triggering "+name); } else { LOGGER.info("SCM changes detected in "+ job.getName()+". Job is already in the queue"); } } } }); } /** * Returns the file that records the last/current polling activity. */ public File getLogFile() { return new File(job.getRootDir(),"github-polling.log"); } /** * @deprecated * Use {@link GitHubRepositoryNameContributor#parseAssociatedNames(AbstractProject)} */ public Set<GitHubRepositoryName> getGitHubRepositories() { return Collections.emptySet(); } @Override public void start(AbstractProject<?,?> project, boolean newInstance) { super.start(project, newInstance); if (newInstance && getDescriptor().isManageHook()) { // make sure we have hooks installed. do this lazily to avoid blocking the UI thread. final Collection<GitHubRepositoryName> names = GitHubRepositoryNameContributor.parseAssociatedNames(job); getDescriptor().queue.execute(new Runnable() { public void run() { LOGGER.log(Level.INFO, "Adding GitHub webhooks for {0}", names); OUTER: for (GitHubRepositoryName name : names) { for (GHRepository repo : name.resolve()) { try { if(createJenkinsHook(repo, getDescriptor().getHookUrl())) { continue OUTER; } } catch (Throwable e) { LOGGER.log(Level.WARNING, "Failed to add GitHub webhook for "+name, e); } } } } }); } } private boolean createJenkinsHook(GHRepository repo, URL url) { try { repo.createHook("jenkins", Collections.singletonMap("jenkins_hook_url", url.toExternalForm()), null, true); return true; } catch (IOException e) { throw new GHException("Failed to update jenkins hooks", e); } } @Override public void stop() { if (getDescriptor().isManageHook()) { Cleaner cleaner = Cleaner.get(); if (cleaner != null) { cleaner.onStop(job); } } } @Override public Collection<? extends Action> getProjectActions() { return Collections.singleton(new GitHubWebHookPollingAction()); } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } /** * Action object for {@link Project}. Used to display the polling log. */ public final class GitHubWebHookPollingAction implements Action { public AbstractProject<?,?> getOwner() { return job; } public String getIconFileName() { return "clipboard.png"; } public String getDisplayName() { return "GitHub Hook Log"; } public String getUrlName() { return "GitHubPollLog"; } public String getLog() throws IOException { return Util.loadFile(getLogFile()); } /** * Writes the annotated log to the given output. * @since 1.350 */ public void writeLogTo(XMLOutput out) throws IOException { new AnnotatedLargeText<GitHubWebHookPollingAction>(getLogFile(), Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter()); } } @Extension public static class DescriptorImpl extends TriggerDescriptor { private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(MasterComputer.threadPoolForRemoting); private boolean manageHook; private String hookUrl; private volatile List<Credential> credentials = new ArrayList<Credential>(); public DescriptorImpl() { load(); } @Override public boolean isApplicable(Item item) { return item instanceof AbstractProject; } @Override public String getDisplayName() { return "Build when a change is pushed to GitHub"; } /** * True if Jenkins should auto-manage hooks. */ public boolean isManageHook() { return manageHook; } public void setManageHook(boolean v) { manageHook = v; save(); } /** * Returns the URL that GitHub should post. */ public URL getHookUrl() throws MalformedURLException { return hookUrl!=null ? new URL(hookUrl) : new URL(Hudson.getInstance().getRootUrl()+GitHubWebHook.get().getUrlName()+'/'); } public boolean hasOverrideURL() { return hookUrl!=null; } public List<Credential> getCredentials() { return credentials; } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { JSONObject hookMode = json.getJSONObject("hookMode"); manageHook = "auto".equals(hookMode.getString("value")); JSONObject o = hookMode.getJSONObject("hookUrl"); if (o!=null && !o.isNullObject()) { hookUrl = o.getString("url"); } else { hookUrl = null; } credentials = req.bindJSONToList(Credential.class,hookMode.get("credentials")); save(); return true; } public static DescriptorImpl get() { return Trigger.all().get(DescriptorImpl.class); } public static boolean allowsHookUrlOverride() { return ALLOW_HOOKURL_OVERRIDE; } } /** * Set to false to prevent the user from overriding the hook URL. */ public static boolean ALLOW_HOOKURL_OVERRIDE = !Boolean.getBoolean(GitHubPushTrigger.class.getName()+".disableOverride"); private static final Logger LOGGER = Logger.getLogger(GitHubPushTrigger.class.getName()); }
package com.conveyal.taui.models; import java.util.BitSet; import java.util.List; import com.conveyal.geojson.GeometryDeserializer; import com.conveyal.geojson.GeometrySerializer; import com.conveyal.r5.model.json_serialization.BitSetDeserializer; import com.conveyal.r5.model.json_serialization.BitSetSerializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.vividsolutions.jts.geom.LineString; /** * Add a trip pattern. */ public class AddTripPattern extends Modification { public String name; @JsonDeserialize(using= GeometryDeserializer.class) @JsonSerialize(using= GeometrySerializer.class) public LineString geometry; // in theory these would be more efficient as bitsets but they'd get turned into // boolean[] when sent to mongo public boolean[] stops; public boolean[] controlPoints; /** stop IDs that particular points have been snapped to. will be mostly null, as most stops are generally not snapped */ public String[] stopIds; public boolean bidirectional; public List<Timetable> timetables; public String getType() { return "add-trip-pattern"; } public static class Timetable { /** Days of the week on which this service is active */ public boolean monday, tuesday, wednesday, thursday, friday, saturday, sunday; /** Speed, kilometers per hour */ public int speed; /** hop times in seconds */ public int[] hopTimes; /** dwell times in seconds */ public int[] dwellTimes; /** start time (seconds since GTFS midnight) */ public int startTime; /** end time for frequency-based trips (seconds since GTFS midnight) */ public int endTime; /** Dwell time at each stop, seconds */ public int dwellTime; /** headway for frequency-based patterns */ public int headwaySecs; } }
package de.dominikmuench.twintowns; import java.util.ArrayList; import java.util.List; import processing.core.PApplet; import processing.core.PFont; import processing.data.TableRow; import controlP5.CheckBox; import controlP5.ControlFont; import controlP5.ControlP5; import controlP5.Range; import de.dominikmuench.twintowns.markers.PartnershipMarker; import de.dominikmuench.twintowns.model.GermanMunicipality; import de.dominikmuench.twintowns.model.Municipality; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.events.MapEvent; import de.fhpotsdam.unfolding.events.MapEventListener; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.marker.Marker; import de.fhpotsdam.unfolding.providers.EsriProvider; @SuppressWarnings("serial") public class TwinTownsApp extends PApplet implements MapEventListener { private TwinTownTable table; private UnfoldingMap map; private ControlP5 cp5; private Range numOfPartnersRange; private CheckBox averageDirectionCheckBox; /* * (non-Javadoc) * * @see processing.core.PApplet#setup() */ @Override public void setup() { // General size(800, 600, P2D); // size(displayWidth, displayHeight, P2D); smooth(); // Map map = new UnfoldingMap(this, new EsriProvider.WorldGrayCanvas()); MapState.getInstance().setMap(map); map.setTweening(true); map.zoomAndPanTo(6, new Location(51.164181f, 10.454150f)); map.setZoomRange(3, 9); // Font PFont pFont = createFont("OpenSans", 12, true); ControlFont font = new ControlFont(pFont, 12); cp5 = new ControlP5(this); MapState.getInstance().setCp5(cp5); cp5.addTextfield("municipalityFilter") .setText("München") .setPosition(10, 10) .setSize(200, 20) .setCaptionLabel("City") .setFont(font) .setColorCaptionLabel(0); cp5.addTextfield("stateFilter") .setText("Bavaria") .setPosition(10, 50) .setSize(200, 20) .setCaptionLabel("State") .setFont(font) .setColorCaptionLabel(0); cp5.addCheckBox("numOfPartners") .setPosition(10, 90) .setColorLabel(0) .setSize(20, 20) .setItemsPerRow(1) .setSpacingRow(20) .addItem("Number of partnerships", 0); numOfPartnersRange = cp5.addRange("numOfPartnersRange") .setBroadcast(false) .setPosition(10, 120) .setSize(200, 10) .setHandleSize(10) .setRange(1, 100) .setDecimalPrecision(0) .setRangeValues(1, 80) .setBroadcast(true) .setCaptionLabel("Filter") .setColorCaptionLabel(0) .hide(); averageDirectionCheckBox = cp5.addCheckBox("averageDirection") .setPosition(10, 120) .setColorLabel(0) .setSize(20, 20) .setItemsPerRow(1) .setSpacingRow(20) .addItem("Average direction", 0); new RestrictedEventDispatcher(this, map, new Rectangle(0, 0, 210, 140)); // Data & Markers table = new TwinTownTable(this); List<PartnershipMarker> markers = new ArrayList<>(); PartnershipMarker lastMarker = null; for (TableRow row : table.rows()) { if (table.getMunicipality(row).contains("Kreis") || table.getMunicipality(row).contains("Bezirk")) { continue; } GermanMunicipality germanMunicipality = new GermanMunicipality( table.getMunicipality(row), new Location( table.getLatitude(row), table.getLongitude(row)), table.getState(row)); Municipality partnerMunicipality = new Municipality( table.getPartnerMunicipality(row), new Location( table.getPartnerLatitude(row), table.getPartnerLongitude(row)), table.getPartnerCountry(row), table.getPartnerContinent(row)); if (lastMarker == null || !lastMarker.getGermanMunicipality().getName() .equals(table.getMunicipality(row))) { PartnershipMarker connMarker = new PartnershipMarker( germanMunicipality, partnerMunicipality); markers.add(connMarker); lastMarker = connMarker; } else { lastMarker.addPartnerMunicipality(partnerMunicipality); } } for (PartnershipMarker marker : markers) { map.addMarker(marker); } } /* * (non-Javadoc) * * @see processing.core.PApplet#draw() */ @Override public void draw() { map.draw(); } // @Override // public boolean sketchFullScreen() { // return true; @Override public void mouseMoved() { for (Marker marker : map.getMarkers()) { if (!marker.equals(MapState.getInstance().getClickedMarker())) { marker.setSelected(false); } } Marker hitMarker = map.getFirstHitMarker(mouseX, mouseY); if (hitMarker != null) { map.getMarkers().remove(hitMarker); map.getMarkers().add(hitMarker); hitMarker.setSelected(true); MapState.getInstance().setSelectedMarker((PartnershipMarker) hitMarker); } } @Override public void mouseClicked() { for (Marker marker : map.getMarkers()) { marker.setSelected(false); } PartnershipMarker hitMarker = MapState.getInstance().getSelectedMarker(); if (hitMarker != null) { hitMarker.setSelected(true); MapState.getInstance().setClickedMarker(hitMarker); } else { MapState.getInstance().setClickedMarker(null); } } @Override public String getId() { // TODO Auto-generated method stub return null; } @Override public void onManipulation(MapEvent event) { // TODO Auto-generated method stub System.err.println(event.toString()); } public void numOfPartners(float[] a) { if (a[0] == 1.0) { numOfPartnersRange.show(); averageDirectionCheckBox.setPosition(10, averageDirectionCheckBox.getPosition().y + 25); } else { numOfPartnersRange.hide(); averageDirectionCheckBox.setPosition(10, averageDirectionCheckBox.getPosition().y - 25); } } public static void main(String[] args) { PApplet.main(new String[] { "de.dominikmuench.twintowns.TwinTownsApp" }); } }
package com.foundationdb.server.error; import org.slf4j.Logger; import java.util.ResourceBundle; /** * The error codes that are part of the public API. * * From the SQL Standard, the SQLSTATE (ErrorCodes) are a 2 character class value * followed by a 3 character sub-class value. These characters are either digits or * upper-case latin characters. (0-9 or A-Z). * * Class values that begin with 0 through 4 or A through H are defined by the standard. * Class values that begin with 5 through 9 or I through Z are implementation defined. * * The subclass '000' means no subclass to the given SQLSTATE class * * Sub-class values that begin with 0-4 or A-H are defined by either the SQL standard, or * another standard. Sub-class values beginning with 5-9 or I-Z are implementation defined * subclasses. * * The SQLCODE encompasses more than errors, though most of the SQLCODES do indicate errors or * exceptions. The ErrorCode implements the errors and exceptions, but not any of the non-error * SQLCODES. * * The specific division between a class and a subclass is not made clear by the standard. */ public enum ErrorCode { // Class 00 - successful completion SUCCESSFUL_COMPLETION ("00", "000", Importance.TRACE, null), // Class 01 - warning // No Warnings defined // Class 02 - No data found // Class 07 - dynamic SQL error // SubClass 001 - using clause does not match dynamic parameter specifications // SubClass 002 - using clause does not match target specifications // SubClass 003 - cursor specification cannot be executed // SubClass 004 - using clause required for dynamic parameters // SubClass 005 - prepared statement not a cursor specification // SubClass 006 - restricted data type attribute violation // SubClass 007 - using clause required for result fields // SubClass 008 - invalid descriptor count // SubClass 009 - invalid descriptor index // SubClass 00B - data type transform function violation // SubClass 00C - undefined DATA value // SubClass 00D - invalid DATA target // SubClass 00E - invalid LEVEL value // SubClass 00F - invalid DATETIME_INTERVAL_CODE // Class 08 - connection exception // SubClass 001 - SQL-client unable to establish SQL-connection // SubClass 002 - connection name in use // SubClass 003 - connection does not exist // SubClass 004 - SQL-server rejected establishment of SQL-connection // SubClass 006 - connection failure // SubClass 007 - transaction resolution unknown CONNECTION_TERMINATED ("08", "500", Importance.ERROR, ConnectionTerminatedException.class), // Class 09 - triggered action exception // Class 0A - feature not supported UNSUPPORTED_SQL ("0A", "500", Importance.ERROR, UnsupportedSQLException.class), UNSUPPORTED_PARAMETERS ("0A", "501", Importance.ERROR, UnsupportedParametersException.class), UNSUPPORTED_EXPLAIN ("0A", "502", Importance.ERROR, UnsupportedExplainException.class), UNSUPPORTED_CREATE_SELECT ("0A", "503", Importance.ERROR, UnsupportedCreateSelectException.class), UNSUPPORTED_FK_INDEX ("0A", "504", Importance.ERROR, UnsupportedFKIndexException.class), UNSUPPORTED_CHECK ("0A", "505", Importance.ERROR, UnsupportedCheckConstraintException.class), UNSUPPORTED_GROUP_UNIQUE("0A", "506", Importance.DEBUG, UnsupportedUniqueGroupIndexException.class), UNSUPPORTED_INDEX_PREFIX("0A", "507", Importance.ERROR, UnsupportedIndexPrefixException.class), SELECT_EXISTS_ERROR ("0A", "508", Importance.DEBUG, SelectExistsErrorException.class), UNSUPPORTED_GROUP_INDEX_JOIN("0A", "509", Importance.DEBUG, UnsupportedGroupIndexJoinTypeException.class), STALE_STATEMENT ("0A", "50A", Importance.ERROR, StaleStatementException.class), // Class 0D - invalid target type specification // Class 0E - invalid schema name list specification // Class 0F - locator exception // Class 0L - invalid grantor // Class 0M - invalid SQL-invoked procedure reference // Class 0P - invalid role specification // Class 0S - invalid transform group name specification // Class 0T - target table disagrees with cursor definition // Class 0U - attempt to assign to non-updatable column // Class 0V - attempt to assign to ordering column // Class 0W - prohibited statement encountered during trigger execution // Class 0Z - diagnostics exceptions // Class 21 - cardinality violation SUBQUERY_TOO_MANY_ROWS ("21", "000", Importance.DEBUG, SubqueryTooManyRowsException.class), // Class 22 - data exception // SubClass 001 - string data, right truncation STRING_TRUNCATION ("22", "001", Importance.DEBUG, StringTruncationException.class), // SubClass 002 - null value, no indicator parameter // SubClass 003 - numeric value out of range VALUE_OUT_OF_RANGE ("22", "003", Importance.DEBUG, OutOfRangeException.class), // SubClass 004 - null value not allowed // SubClass 005 - error in assignment // SubClass 006 - invalid interval format INVALID_INTERVAL_FORMAT ("22", "006", Importance.DEBUG, InvalidIntervalFormatException.class), // SubClass 007 - invalid datetime format INVALID_DATE_FORMAT ("22", "007", Importance.DEBUG, InvalidDateFormatException.class), // SubClass 008 - datetime field overflow // SubClass 009 - invalid time zone displacement value // SubClass 00B - escape character conflict // SubClass 00C - invalid use of escape character // SubClass 00D - invalid escape octet // SubClass 00E - null value in array target // SubClass 00F - zero-length character string // SubClass 00G - most specific type mismatch // SubClass 00H - sequence generator limit exceeded SEQUENCE_LIMIT_EXCEEDED ("22", "00H", Importance.DEBUG, SequenceLimitExceededException.class), // SubClass 00P - interval value out of range // SubClass 00Q - multiset value overflow // SubClass 010 - invalid indicator parameter value // SubClass 011 - substring error // SubClass 012 - division by zero DIVIDE_BY_ZERO ("22", "012", Importance.DEBUG, DivisionByZeroException.class), // SubClass 013 - invalid preceding or following size in window function // SubClass 014 - invalid argument for NTILE function // SubClass 015 - interval field overflow // SubClass 016 - invalid argument for NTH_VALUE function // SubClass 018 - invalid character value for cast INVALID_CHAR_TO_NUM ("22", "018", Importance.DEBUG, InvalidCharToNumException.class), // SubClass 019 - invalid escape character // SubClass 01B - invalid regular expression // SubClass 01C - null row not permitted in table // SubClass 01E - invalid argument for natural logarithm // SubClass 01F - invalid argument for power function // SubClass 01G - invalid argument for width bucket function // SubClass 01H - invalid row version // SubClass 01U - attempt to replace a zero-length string // SubClass 01W - invalid row count in fetch first clause // SubClass 01X - invalid row count in result offset clause // SubClass 021 - character not in repertoire // SubClass 022 - indicator overflow // SubClass 023 - invalid parameter value INVALID_PARAMETER_VALUE ("22", "023", Importance.DEBUG, InvalidParameterValueException.class), // SubClass 024 - unterminated C string // SubClass 025 - invalid escape sequence // SubClass 026 - string data, length mismatch // SubClass 027 - trim error // SubClass 029 - noncharacter in UCS string // SubClass 02D - null value substituted for mutator subject parameter // SubClass 02E - array element error // SubClass 02F - array data, right truncation // SubClass 02G - invalid repeat argument in a sample clause // SubClass 02H - invalid sample size 02H TABLE_DEFINITION_CHANGED("22", "501", Importance.DEBUG, TableDefinitionChangedException.class), NEGATIVE_LIMIT ("22", "502", Importance.DEBUG, NegativeLimitException.class), INVALID_ARGUMENT_TYPE ("22", "503", Importance.DEBUG, InvalidArgumentTypeException.class), ZERO_DATE_TIME ("22", "504", Importance.DEBUG, ZeroDateTimeException.class), EXTERNAL_ROW_READER_EXCEPTION ("22", "505", Importance.DEBUG, ExternalRowReaderException.class), SECURITY ("22", "506", Importance.ERROR, SecurityException.class), // Class 23 - integrity constraint violation DUPLICATE_KEY ("23", "501", Importance.DEBUG, DuplicateKeyException.class), NOT_NULL_VIOLATION ("23", "502", Importance.ERROR, NotNullViolationException.class), FK_CONSTRAINT_VIOLATION ("23", "503", Importance.DEBUG, ForeignKeyConstraintDMLException.class), // Class 24 - invalid cursor state CURSOR_IS_FINISHED ("24", "501", Importance.ERROR, CursorIsFinishedException.class), CURSOR_IS_UNKNOWN ("24", "502", Importance.ERROR, CursorIsUnknownException.class), NO_ACTIVE_CURSOR ("24", "503", Importance.ERROR, NoActiveCursorException.class), CURSOR_CLOSE_BAD ("24", "504", Importance.ERROR, CursorCloseBadException.class), // Class 25 - invalid transaction state // SubClass 001 - active SQL-transaction // SubClass 002 - branch transaction already active TRANSACTION_IN_PROGRESS ("25", "002", Importance.DEBUG, TransactionInProgressException.class), // SubClass 003 - inappropriate access mode for branch transaction TRANSACTION_READ_ONLY ("25", "003", Importance.DEBUG, TransactionReadOnlyException.class), // SubClass 004 - inappropriate isolation level for branch transaction // SubClass 005 - no active SQL-transaction for branch transaction NO_TRANSACTION ("25", "005", Importance.DEBUG, NoTransactionInProgressException.class), // SubClass 006 - read-only SQL-transaction // SubClass 007 - schema and data statement mixing not supported // SubClass 008 - held cursor requires same isolation level TRANSACTION_ABORTED ("25", "P02", Importance.DEBUG, TransactionAbortedException.class), // No standard, Postgres uses P02 // Class 26 - invalid SQL statement name // Class 27 - triggered data change violation // Class 28 - invalid authorization specification AUTHENTICATION_FAILED ("28", "000", Importance.DEBUG, AuthenticationFailedException.class), // Class 2B - dependent privilege descriptors still exist VIEW_REFERENCES_EXIST ("2B", "000", Importance.DEBUG, ViewReferencesExist.class), // Class 2C - invalid character set name UNSUPPORTED_CHARSET ("2C", "000", Importance.DEBUG, UnsupportedCharsetException.class), // Class 2D - invalid transaction termination // Class 2E - invalid connection name // Class 2F - SQL routine exception // Class 2H - invalid collation name UNSUPPORTED_COLLATION ("2H", "000", Importance.DEBUG, UnsupportedCollationException.class), // Class 30 - invalid SQL statement identifier // Class 33 - invalid SQL descriptor name // Class 34 - invalid cursor name // Class 35 - invalid condition number // Class 36 - cursor sensitivity exception // Class 38 - external routine exception // Class 39 - external routine invocation EXTERNAL_ROUTINE_INVOCATION ("39", "000", Importance.DEBUG, ExternalRoutineInvocationException.class), // Class 3B - savepoint exception // Class 3C - ambiguous cursor name // Class 3D - invalid catalog name // Class 3F - invalid schema name NO_SUCH_SCHEMA ("3F", "000", Importance.DEBUG, NoSuchSchemaException.class), // Class 40 - transaction rollback QUERY_TIMEOUT ("40", "000", Importance.ERROR, QueryTimedOutException.class), PERSISTIT_ROLLBACK ("40", "001", Importance.ERROR, PersistitRollbackException.class), // Class 42 - syntax error or access rule violation // These exceptions are re-thrown errors from the parser and from the // AISBinder, ASTStatementLoader, BasicDDLFunctions, or BasicDMLFunctions SQL_PARSE_EXCEPTION ("42", "000", Importance.DEBUG, SQLParseException.class), NO_SUCH_TABLE ("42", "501", Importance.DEBUG, NoSuchTableException.class), NO_INDEX ("42", "502", Importance.DEBUG, NoSuchIndexException.class), NO_SUCH_GROUP ("42", "503", Importance.DEBUG, NoSuchGroupException.class), NO_SUCH_TABLEDEF ("42", "504", Importance.DEBUG, RowDefNotFoundException.class), NO_SUCH_TABLEID ("42", "505", Importance.DEBUG, NoSuchTableIdException.class), AMBIGUOUS_COLUMN_NAME ("42", "506", Importance.DEBUG, AmbiguousColumNameException.class), SUBQUERY_RESULT_FAIL ("42", "507", Importance.DEBUG, SubqueryResultsSetupException.class), JOIN_NODE_ERROR ("42", "508", Importance.DEBUG, JoinNodeAdditionException.class), CORRELATION_NAME_ALREADY_USED ("42", "509", Importance.DEBUG, CorrelationNameAlreadyUsedException.class), VIEW_BAD_SUBQUERY ("42", "50A", Importance.DEBUG, ViewHasBadSubqueryException.class), TABLE_BAD_SUBQUERY ("42", "50B", Importance.DEBUG, TableIsBadSubqueryException.class), WRONG_FUNCTION_ARITY ("42", "50C", Importance.DEBUG, WrongExpressionArityException.class), NO_SUCH_FUNCTION ("42", "50D", Importance.DEBUG, NoSuchFunctionException.class), ORDER_GROUP_BY_NON_INTEGER_CONSTANT("42", "50E", Importance.DEBUG, OrderGroupByNonIntegerConstant.class), ORDER_GROUP_BY_INTEGER_OUT_OF_RANGE("42", "50F", Importance.DEBUG, OrderGroupByIntegerOutOfRange.class), MISSING_GROUP_INDEX_JOIN("42", "510", Importance.DEBUG, MissingGroupIndexJoinTypeException.class), TABLE_INDEX_JOIN ("42", "511", Importance.DEBUG, TableIndexJoinTypeException.class), INSERT_WRONG_COUNT ("42", "512", Importance.DEBUG, InsertWrongCountException.class), UNSUPPORTED_CONFIGURATION ("42", "513", Importance.DEBUG, UnsupportedConfigurationException.class), SCHEMA_DEF_PARSE_EXCEPTION ("42", "514", Importance.DEBUG, SchemaDefParseException.class), SQL_PARSER_INTERNAL_EXCEPTION ("42", "515", Importance.DEBUG, SQLParserInternalException.class), NO_SUCH_SEQUENCE ("42", "516", Importance.DEBUG, NoSuchSequenceException.class), NO_SUCH_UNIQUE ("42", "517", Importance.DEBUG, NoSuchUniqueException.class), NO_SUCH_GROUPING_FK ("42", "518", Importance.DEBUG, NoSuchGroupingFKException.class), NO_SUCH_ROUTINE ("42", "519", Importance.DEBUG, NoSuchRoutineException.class), NO_SUCH_CAST ("42", "51A", Importance.DEBUG, NoSuchCastException.class), PROCEDURE_CALLED_AS_FUNCTION ("42", "51B", Importance.DEBUG, ProcedureCalledAsFunctionException.class), NO_SUCH_CURSOR ("42", "51C", Importance.DEBUG, NoSuchCursorException.class), NO_SUCH_PREPARED_STATEMENT ("42", "51D", Importance.DEBUG, NoSuchPreparedStatementException.class), // Class 42/600 - JSON interface errors KEY_COLUMN_MISMATCH ("42", "600", Importance.DEBUG, KeyColumnMismatchException.class), KEY_COLUMN_MISSING ("42", "601", Importance.DEBUG, KeyColumnMissingException.class), INVALID_CHILD_COLLECTION("42", "602", Importance.DEBUG, InvalidChildCollectionException.class), // Class 42/700 - full text errors FULL_TEXT_QUERY_PARSE ("42", "700", Importance.DEBUG, FullTextQueryParseException.class), // Class 42/800 - Akiba Direct errors CANT_CALL_SCRIPT_LIBRARY ("42", "800", Importance.DEBUG, CantCallScriptLibraryException.class), SCRIPT_REGISTRATION_EXCEPTION ("42", "801", Importance.DEBUG, ScriptLibraryRegistrationException.class), DIRECT_ENDPOINT_NOT_FOUND ("42", "802", Importance.DEBUG, DirectEndpointNotFoundException.class), DIRECT_TRANSACTION_FAILED ("42", "803", Importance.ERROR, DirectTransactionFailedException.class), // Class 44 - with check option violation // Class 46 - SQL/J INVALID_SQLJ_JAR_URL ("46", "001", Importance.DEBUG, InvalidSQLJJarURLException.class), DUPLICATE_SQLJ_JAR ("46", "002", Importance.DEBUG, DuplicateSQLJJarNameException.class), REFERENCED_SQLJ_JAR ("46", "003", Importance.DEBUG, ReferencedSQLJJarException.class), NO_SUCH_SQLJ_JAR ("46", "00B", Importance.DEBUG, NoSuchSQLJJarException.class), SQLJ_INSTANCE_EXCEPTION ("46", "103", Importance.DEBUG, SQLJInstanceException.class), INVALID_SQLJ_DEPLOYMENT_DESCRIPTOR ("46", "200", Importance.DEBUG, InvalidSQLJDeploymentDescriptorException.class), // Class 50 - DDL definition failure PROTECTED_TABLE ("50", "002", Importance.DEBUG, ProtectedTableDDLException.class), JOIN_TO_PROTECTED_TABLE ("50", "003", Importance.DEBUG, JoinToProtectedTableException.class), JOIN_TO_UNKNOWN_TABLE ("50", "004", Importance.DEBUG, JoinToUnknownTableException.class), JOIN_TO_WRONG_COLUMNS ("50", "005", Importance.DEBUG, JoinToWrongColumnsException.class), DUPLICATE_TABLE ("50", "006", Importance.DEBUG, DuplicateTableNameException.class), UNSUPPORTED_DROP ("50", "007", Importance.DEBUG, UnsupportedDropException.class), UNSUPPORTED_DATA_TYPE ("50", "008", Importance.DEBUG, UnsupportedDataTypeException.class), JOIN_TO_MULTIPLE_PARENTS("50", "009", Importance.DEBUG, JoinToMultipleParentsException.class), UNSUPPORTED_INDEX_DATA_TYPE("50", "00A", Importance.DEBUG, UnsupportedIndexDataTypeException.class), UNSUPPORTED_INDEX_SIZE ("50", "00B", Importance.DEBUG, UnsupportedIndexSizeException.class), DUPLICATE_COLUMN ("50", "00C", Importance.DEBUG, DuplicateColumnNameException.class), DUPLICATE_GROUP ("50", "00D", Importance.DEBUG, DuplicateGroupNameException.class), REFERENCED_TABLE ("50", "00E", Importance.DEBUG, ReferencedTableException.class), DROP_INDEX_NOT_ALLOWED ("50", "00F", Importance.DEBUG, DropIndexNotAllowedException.class), FK_DDL_VIOLATION ("50", "00G", Importance.DEBUG, ForeignConstraintDDLException.class), PROTECTED_INDEX ("50", "00H", Importance.DEBUG, ProtectedIndexException.class), BRANCHING_GROUP_INDEX ("50", "00I", Importance.DEBUG, BranchingGroupIndexException.class), WRONG_NAME_FORMAT ("50", "00J", Importance.DEBUG, WrongNameFormatException.class), DUPLICATE_VIEW ("50", "00K", Importance.DEBUG, DuplicateViewException.class), UNDEFINED_VIEW ("50", "00L", Importance.DEBUG, UndefinedViewException.class), SUBQUERY_ONE_COLUMN ("50", "00M", Importance.DEBUG, SubqueryOneColumnException.class), DUPLICATE_SCHEMA ("50", "00N", Importance.DEBUG, DuplicateSchemaException.class), DROP_SCHEMA_NOT_ALLOWED ("50", "00O", Importance.DEBUG, DropSchemaNotAllowedException.class), WRONG_TABLE_FOR_INDEX ("50", "00P", Importance.DEBUG, WrongTableForIndexException.class), MISSING_DDL_PARAMETERS ("50", "00Q", Importance.DEBUG, MissingDDLParametersException.class), INDEX_COL_NOT_IN_GROUP ("50", "00R", Importance.DEBUG, IndexColNotInGroupException.class), INDEX_TABLE_NOT_IN_GROUP("50", "00S", Importance.DEBUG, IndexTableNotInGroupException.class), INDISTINGUISHABLE_INDEX ("50", "00T", Importance.DEBUG, IndistinguishableIndexException.class), DROP_GROUP_NOT_ROOT ("50", "00U", Importance.DEBUG, DropGroupNotRootException.class), BAD_SPATIAL_INDEX ("50", "00V", Importance.DEBUG, BadSpatialIndexException.class), DUPLICATE_ROUTINE ("50", "00W", Importance.DEBUG, DuplicateRoutineNameException.class), DUPLICATE_PARAMETER ("50", "00X", Importance.DEBUG, DuplicateParameterNameException.class), SET_STORAGE_NOT_ROOT ("50", "00Y", Importance.DEBUG, SetStorageNotRootException.class), // AIS Validation errors, Attempts to modify and build an AIS failed // due to missing or invalid information. GROUP_MULTIPLE_ROOTS ("50", "010", Importance.DEBUG, GroupHasMultipleRootsException.class), JOIN_TYPE_MISMATCH ("50", "011", Importance.DEBUG, JoinColumnTypesMismatchException.class), PK_NULL_COLUMN ("50", "012", Importance.DEBUG, PrimaryKeyNullColumnException.class), DUPLICATE_INDEXES ("50", "013", Importance.DEBUG, DuplicateIndexException.class), MISSING_PRIMARY_KEY ("50", "014", Importance.DEBUG, NoPrimaryKeyException.class), DUPLICATE_TABLEID ("50", "015", Importance.DEBUG, DuplicateTableIdException.class), JOIN_COLUMN_MISMATCH ("50", "016", Importance.DEBUG, JoinColumnMismatchException.class), INDEX_LACKS_COLUMNS ("50", "017", Importance.DEBUG, IndexLacksColumnsException.class), NO_SUCH_COLUMN ("50", "018", Importance.DEBUG, NoSuchColumnException.class), DUPLICATE_STORAGE_DESCRIPTION_KEYS("50", "019", Importance.DEBUG, DuplicateStorageDescriptionKeysException.class), TABLE_NOT_IN_GROUP ("50", "01B", Importance.DEBUG, TableNotInGroupException.class), NAME_IS_NULL ("50", "01C", Importance.DEBUG, NameIsNullException.class), DUPLICATE_INDEX_COLUMN ("50", "01D", Importance.DEBUG, DuplicateIndexColumnException.class), COLUMN_POS_ORDERED ("50", "01E", Importance.DEBUG, ColumnPositionNotOrderedException.class), TABLE_COL_IN_GROUP ("50", "01F", Importance.DEBUG, TableColumnNotInGroupException.class), GROUP_MISSING_COL ("50", "01G", Importance.DEBUG, GroupMissingTableColumnException.class), GROUP_MISSING_INDEX ("50", "01H", Importance.DEBUG, GroupMissingIndexException.class), BAD_COLUMN_DEFAULT ("50", "01I", Importance.DEBUG, BadColumnDefaultException.class), NULL_REFERENCE ("50", "01J", Importance.DEBUG, AISNullReferenceException.class), BAD_AIS_REFERENCE ("50", "01L", Importance.DEBUG, BadAISReferenceException.class), BAD_INTERNAL_SETTING ("50", "01M", Importance.DEBUG, BadAISInternalSettingException.class), TYPES_ARE_STATIC ("50", "01N", Importance.DEBUG, TypesAreStaticException.class), GROUP_INDEX_DEPTH ("50", "01O", Importance.DEBUG, GroupIndexDepthException.class), DUPLICATE_INDEXID ("50", "01P", Importance.DEBUG, DuplicateIndexIdException.class), STORAGE_DESCRIPTION_INVALID ("50", "01Q", Importance.DEBUG, StorageDescriptionInvalidException.class), GROUP_MIXED_TABLE_TYPES ("50", "01S", Importance.DEBUG, GroupMixedTableTypes.class), GROUP_MULTIPLE_MEM_TABLES ("50", "01T", Importance.DEBUG, GroupMultipleMemoryTables.class), JOIN_PARENT_NO_PK ("50", "01U", Importance.DEBUG, JoinParentNoExplicitPK.class), DUPLICATE_SEQUENCE ("50", "01V", Importance.DEBUG, DuplicateSequenceNameException.class), INDEX_COLUMN_IS_PARTIAL ("50", "01W", Importance.DEBUG, IndexColumnIsPartialException.class), COLUMN_SIZE_MISMATCH ("50", "01X", Importance.DEBUG, ColumnSizeMismatchException.class), WHOLE_GROUP_QUERY ("50", "01Y", Importance.DEBUG, WholeGroupQueryException.class), SEQUENCE_INTERVAL_ZERO ("50", "01Z", Importance.DEBUG, SequenceIntervalZeroException.class), SEQUENCE_MIN_GE_MAX ("50", "020", Importance.DEBUG, SequenceMinGEMaxException.class), SEQUENCE_START_IN_RANGE ("50", "021", Importance.DEBUG, SequenceStartInRangeException.class), ALTER_MADE_NO_CHANGE ("50", "023", Importance.DEBUG, AlterMadeNoChangeException.class), INVALID_ROUTINE ("50", "024", Importance.DEBUG, InvalidRoutineException.class), INVALID_INDEX_ID ("50", "025", Importance.DEBUG, InvalidIndexIDException.class), // 50026 available COLUMN_NOT_GENERATED ("50", "027", Importance.DEBUG, ColumnNotGeneratedException.class), COLUMN_ALREADY_GENERATED ("50", "028", Importance.DEBUG, ColumnAlreadyGeneratedException.class), DROP_SEQUENCE_NOT_ALLOWED ("50", "029", Importance.DEBUG, DropSequenceNotAllowedException.class), JOIN_TO_SELF ("50", "030", Importance.DEBUG, JoinToSelfException.class), STALE_AIS ("51", "001", Importance.TRACE, OldAISException.class), // Messaging errors MALFORMED_REQUEST ("51", "010", Importance.ERROR, MalformedRequestException.class), // Class 52 - Configuration & startup errors SERVICE_NOT_STARTED ("52", "001", Importance.ERROR, ServiceNotStartedException.class), SERVICE_ALREADY_STARTED ("52", "002", Importance.ERROR, ServiceStartupException.class), SERVICE_CIRC_DEPEND ("52", "003", Importance.ERROR, CircularDependencyException.class), BAD_CONFIG_DIRECTORY ("52", "004", Importance.ERROR, BadConfigDirectoryException.class), //52005 CONFIG_LOAD_FAILED ("52", "006", Importance.ERROR, ConfigurationPropertiesLoadException.class), //52007 //52008 //52009 //5200A TAP_BEAN_FAIL ("52", "00B", Importance.ERROR, TapBeanFailureException.class), //5200C //5200D QUERY_LOG_CLOSE_FAIL ("52", "00E", Importance.ERROR, QueryLogCloseException.class), INVALID_PORT ("52", "00F", Importance.ERROR, InvalidPortException.class), INVALID_VOLUME ("52", "010", Importance.ERROR, InvalidVolumeException.class), INVALID_OPTIMIZER_PROPERTY ("52", "011", Importance.ERROR, InvalidOptimizerPropertyException.class), IS_TABLE_VERSION_MISMATCH ("52", "012", Importance.ERROR, ISTableVersionMismatchException.class), // Class 53 - Internal error INTERNAL_ERROR ("53", "000", Importance.ERROR, null), INTERNAL_CORRUPTION ("53", "001", Importance.ERROR, RowDataCorruptionException.class), //53002 PERSISTIT_ERROR ("53", "003", Importance.ERROR, PersistitAdapterException.class), //53004 *RESERVED* ROW_OUTPUT ("53", "005", Importance.DEBUG, RowOutputException.class), SCAN_RETRY_ABANDONDED ("53", "006", Importance.ERROR, ScanRetryAbandonedException.class), //53007 //53008 TABLEDEF_MISMATCH ("53", "009", Importance.DEBUG, TableDefinitionMismatchException.class), PROTOBUF_READ ("53", "00A", Importance.ERROR, ProtobufReadException.class), PROTOBUF_WRITE ("53", "00B", Importance.ERROR, ProtobufWriteException.class), INVALID_ALTER ("53", "00C", Importance.ERROR, InvalidAlterException.class), MERGE_SORT_IO ("53", "00D", Importance.ERROR, MergeSortIOException.class), AIS_VALIDATION ("53", "00E", Importance.ERROR, AISValidationException.class), // Class 55 - Type conversion errors UNKNOWN_TYPE ("55", "001", Importance.DEBUG, UnknownDataTypeException.class), UNKNOWN_TYPE_SIZE ("55", "002", Importance.DEBUG, UnknownTypeSizeException.class), INCONVERTIBLE_TYPES ("55", "003", Importance.DEBUG, InconvertibleTypesException.class), OVERFLOW ("55", "004", Importance.DEBUG, OverflowException.class), // Class 56 - Explain query errors UNABLE_TO_EXPLAIN ("56", "000", Importance.DEBUG, UnableToExplainException.class), // Class 57 - Insert, Update, Delete processing exceptions NO_SUCH_ROW ("57", "001", Importance.DEBUG, NoSuchRowException.class), CONCURRENT_MODIFICATION ("57", "002", Importance.DEBUG, ConcurrentScanAndUpdateException.class), //57003 //57004 //57005 //57006 //57007 FK_VALUE_MISMATCH ("57", "008", Importance.DEBUG, FKValueMismatchException.class), // Class 58 - Query canceled by user QUERY_CANCELED ("58", "000", Importance.ERROR, QueryCanceledException.class), // Class 70 - Unknown errors UNKNOWN ("70", "000", Importance.ERROR, null), UNEXPECTED_EXCEPTION ("70", "001", Importance.ERROR, null), ; private final String code; private final String subcode; private final Importance importance; private final Class<? extends InvalidOperationException> exceptionClass; private final String formattedValue; private static final String ROLLBACK_CLASS = "40"; static final ResourceBundle resourceBundle = ResourceBundle.getBundle("com.foundationdb.server.error.error_code"); private ErrorCode(String code, String subCode, Importance importance, Class<? extends InvalidOperationException> exception) { this.code = code; this.subcode = subCode; this.importance = importance; this.exceptionClass = exception; this.formattedValue = this.code + this.subcode; } public static ErrorCode valueOfCode(String value) { for (ErrorCode e : values()) { if (e.getFormattedValue().equals(value)) { return e; } } throw new RuntimeException(String.format("Invalid code value: %s", value)); } public Importance getImportance() { return importance; } public String getMessage() { return resourceBundle.getString(name()); } public Class<? extends InvalidOperationException> associatedExceptionClass() { return exceptionClass; } public String getFormattedValue() { return formattedValue; } public String getCode() { return code; } public String getSubCode() { return subcode; } public boolean isRollbackClass() { return ROLLBACK_CLASS.equals(code); } public void logAtImportance(Logger log, String msg, Object... msgArgs) { switch(getImportance()) { case TRACE: log.trace(msg, msgArgs); break; case DEBUG: log.debug(msg, msgArgs); break; case ERROR: log.error(msg, msgArgs); break; default: assert false : "Unknown importance: " + getImportance(); } if(msgArgs.length == 0 || !(msgArgs[msgArgs.length - 1] instanceof Throwable)) { log.warn("Cause unknown. Here is the current stack.", new RuntimeException()); } } public static enum Importance { TRACE, DEBUG, ERROR } }
package com.github.jkschoen.jsma.misc; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.ProcessBuilder.Redirect; import java.nio.file.Files; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JSMAUtils { static final Logger logger = LoggerFactory.getLogger(JSMAUtils.class); private static boolean JHEAD_EXISTS = false; static { ProcessBuilder pb = new ProcessBuilder("jhead","-h"); Map<String, String> env = pb.environment(); Process p; try { p = pb.start(); p.waitFor(); JHEAD_EXISTS = true; } catch (IOException e) { logger.warn("jhead is not on the path: '"+env.get("PATH")+"'"); } catch (InterruptedException e) { logger.warn("jhead is not on the path: '"+env.get("PATH")+"'"); } } private static boolean JPEGTRAN_EXISTS = false; static { ProcessBuilder pb = new ProcessBuilder("jpegtran","-h"); Map<String, String> env = pb.environment(); Process p; try { p = pb.start(); p.waitFor(); JPEGTRAN_EXISTS = true; } catch (IOException e) { logger.warn("jpegtran is not on the path: '"+env.get("PATH")+"'"); } catch (InterruptedException e) { logger.warn("jpegtran is not on the path: '"+env.get("PATH")+"'"); } } public static String uncapitalize(String input){ if (input == null){ return null; } if (input.length()==1){ return input.toLowerCase(); } return input.substring(0, 1).toLowerCase() + input.substring(1); } public static String md5(File file) throws NoSuchAlgorithmException, IOException { if (!file.exists() || !file.isFile()) { return null; } return md5(Files.readAllBytes(file.toPath())); } public static String md5(String md5Me) throws NoSuchAlgorithmException, UnsupportedEncodingException { return md5(md5Me.getBytes("UTF-8")); } public static String md5(byte[] md5Me) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(md5Me); byte byteData[] = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } public static boolean rotateImage(File image) throws IOException, InterruptedException{ if (!JSMAUtils.JHEAD_EXISTS){ logger.warn("jhead is not on the path, image will not checked if it needs to rotate."); return false; } if (!JSMAUtils.JPEGTRAN_EXISTS){ logger.warn("jpegtran is not on the path, image will not checked if it needs to rotate."); return false; } ProcessBuilder pb = new ProcessBuilder("jhead","-autorot", image.getAbsolutePath()); pb.redirectOutput(Redirect.INHERIT); pb.redirectError(Redirect.INHERIT); Process p = pb.start(); p.waitFor(); return true; } }
package com.jaamsim.BasicObjects; import java.util.ArrayList; import java.util.Locale; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.Keyword; import com.jaamsim.input.ValueInput; import com.jaamsim.math.Vec3d; import com.jaamsim.render.HasScreenPoints; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.DistanceUnit; import com.jaamsim.units.TimeUnit; import com.sandwell.JavaSimulation.ColourInput; import com.sandwell.JavaSimulation.Vec3dListInput; import com.sandwell.JavaSimulation3D.DisplayEntity; /** * Moves one or more Entities along a path at a constant speed. */ public class EntityConveyor extends LinkedService implements HasScreenPoints { @Keyword(description = "The travel time for the conveyor.", example = "Conveyor1 TravelTime { 10.0 s }") private final ValueInput travelTimeInput; @Keyword(description = "A list of points in { x, y, z } coordinates defining the line segments that" + "make up the arrow. When two coordinates are given it is assumed that z = 0." , example = "Conveyor1 Points { { 6.7 2.2 m } { 4.9 2.2 m } { 4.9 3.4 m } }") private final Vec3dListInput pointsInput; @Keyword(description = "The width of the Arrow line segments in pixels.", example = "Conveyor1 Width { 1 }") private final ValueInput widthInput; @Keyword(description = "The colour of the arrow, defined using a colour keyword or RGB values.", example = "Conveyor1 Color { red }") private final ColourInput colorInput; private final ArrayList<DisplayEntity> entityList; // List of the entities being conveyed private final ArrayList<Double> startTimeList; // List of times at which the entities entered the conveyor private double totalLength; // Graphical length of the conveyor private final ArrayList<Double> lengthList; // Length of each segment of the conveyor private final ArrayList<Double> cumLengthList; // Total length to the end of each segment private Object screenPointLock = new Object(); private HasScreenPoints.PointsInfo[] cachedPointInfo; { operatingThresholdList.setHidden(true); travelTimeInput = new ValueInput("TravelTime", "Key Inputs", 0.0d); travelTimeInput.setValidRange(0.0, Double.POSITIVE_INFINITY); travelTimeInput.setUnitType(TimeUnit.class); this.addInput(travelTimeInput); ArrayList<Vec3d> defPoints = new ArrayList<Vec3d>(); defPoints.add(new Vec3d(0.0d, 0.0d, 0.0d)); defPoints.add(new Vec3d(1.0d, 0.0d, 0.0d)); pointsInput = new Vec3dListInput("Points", "Key Inputs", defPoints); pointsInput.setValidCountRange(2, Integer.MAX_VALUE ); pointsInput.setUnitType(DistanceUnit.class); this.addInput(pointsInput); widthInput = new ValueInput("Width", "Key Inputs", 1.0d); widthInput.setUnitType(DimensionlessUnit.class); widthInput.setValidRange(1.0d, Double.POSITIVE_INFINITY); this.addInput(widthInput); colorInput = new ColourInput("Color", "Key Inputs", ColourInput.BLACK); this.addInput(colorInput); this.addSynonym(colorInput, "Colour"); } public EntityConveyor() { entityList = new ArrayList<DisplayEntity>(); startTimeList = new ArrayList<Double>(); lengthList = new ArrayList<Double>(); cumLengthList = new ArrayList<Double>(); } @Override public void earlyInit() { super.earlyInit(); entityList.clear(); startTimeList.clear(); this.setPresentState(); // Initialize the segment length data lengthList.clear(); cumLengthList.clear(); totalLength = 0.0; for (int i = 1; i < pointsInput.getValue().size(); i++) { // Get length between points Vec3d vec = new Vec3d(); vec.sub3(pointsInput.getValue().get(i), pointsInput.getValue().get(i-1)); double length = vec.mag3(); lengthList.add(length); totalLength += length; cumLengthList.add(totalLength); } } @Override public void addDisplayEntity(DisplayEntity ent ) { super.addDisplayEntity(ent); // Add the entity to the conveyor entityList.add(ent); startTimeList.add(this.getSimTime()); // If necessary, wake up the conveyor if (!this.isBusy()) { this.setBusy(true); this.setPresentState(); this.startAction(); } } @Override public void startAction() { // Schedule the next entity to reach the end of the conveyor double dt = startTimeList.get(0) + travelTimeInput.getValue() - this.getSimTime(); dt = Math.max(dt, 0); // Round-off to the nearest tick can cause a negative value this.scheduleProcess(dt, 5, endActionTarget); } @Override public void endAction() { // Remove the entity from the conveyor DisplayEntity ent = entityList.remove(0); startTimeList.remove(0); // Send the entity to the next component this.sendToNextComponent(ent); // Stop if the conveyor is empty if (entityList.isEmpty()) { this.setBusy(false); this.setPresentState(); return; } // Schedule the next entity to reach the end of the conveyor this.startAction(); } /** * Return the position coordinates for a given distance along the conveyor. * @param dist = distance along the conveyor. * @return position coordinates */ private Vec3d getPositionForDistance(double dist) { // Find the present segment int seg = 0; for (int i = 0; i < cumLengthList.size(); i++) { if (dist <= cumLengthList.get(i)) { seg = i; break; } } // Interpolate between the start and end of the segment double frac = 0.0; if (seg == 0) { frac = dist / lengthList.get(0); } else { frac = ( dist - cumLengthList.get(seg-1) ) / lengthList.get(seg); } if (frac < 0.0) frac = 0.0; else if (frac > 1.0) frac = 1.0; Vec3d vec = new Vec3d(); vec.interpolate3(pointsInput.getValue().get(seg), pointsInput.getValue().get(seg+1), frac); return vec; } @Override public void updateForInput(Input<?> in) { super.updateForInput(in); // If Points were input, then use them to set the start and end coordinates if (in == pointsInput || in == colorInput || in == widthInput) { synchronized(screenPointLock) { cachedPointInfo = null; } return; } } @Override public void updateGraphics(double simTime) { // Loop through the entities on the conveyor for (int i = 0; i < entityList.size(); i++) { DisplayEntity each = entityList.get(i); // Calculate the distance travelled by this entity double dist = (simTime - startTimeList.get(i)) / travelTimeInput.getValue() * totalLength; // Set the position for the entity each.setPosition(this.getPositionForDistance( dist)); } } @Override public HasScreenPoints.PointsInfo[] getScreenPoints() { synchronized(screenPointLock) { if (cachedPointInfo == null) { cachedPointInfo = new HasScreenPoints.PointsInfo[1]; HasScreenPoints.PointsInfo pi = new HasScreenPoints.PointsInfo(); cachedPointInfo[0] = pi; pi.points = pointsInput.getValue(); pi.color = colorInput.getValue(); pi.width = widthInput.getValue().intValue(); if (pi.width < 1) pi.width = 1; } return cachedPointInfo; } } @Override public boolean selectable() { return true; } /** * Inform simulation and editBox of new positions. */ @Override public void dragged(Vec3d dist) { ArrayList<Vec3d> vec = new ArrayList<Vec3d>(pointsInput.getValue().size()); for (Vec3d v : pointsInput.getValue()) { vec.add(new Vec3d(v.x + dist.x, v.y + dist.y, v.z + dist.z)); } StringBuilder tmp = new StringBuilder(); for (Vec3d v : vec) { tmp.append(String.format((Locale)null, " { %.3f %.3f %.3f m }", v.x, v.y, v.z)); } InputAgent.processEntity_Keyword_Value(this, pointsInput, tmp.toString()); super.dragged(dist); } }
package com.nhn.pinpoint.profiler.context; import com.nhn.pinpoint.common.AnnotationKey; import com.nhn.pinpoint.common.ServiceType; import com.nhn.pinpoint.common.util.ParsingResult; import com.nhn.pinpoint.profiler.interceptor.MethodDescriptor; import java.util.List; public interface Trace { public static final int DEFAULT_STACKID = -1; public static final int ROOT_STACKID = 0; AsyncTrace createAsyncTrace(); void traceBlockBegin(); void markBeforeTime(); long getBeforeTime(); void markAfterTime(); long getAfterTime(); void traceBlockBegin(int stackId); void traceRootBlockEnd(); void traceBlockEnd(); void traceBlockEnd(int stackId); TraceId getTraceId(); boolean canSampled(); void recordException(Object result); void recordApi(MethodDescriptor methodDescriptor); void recordApi(MethodDescriptor methodDescriptor, Object[] args); void recordApi(MethodDescriptor methodDescriptor, Object[] args, int start, int end); void recordApi(int apiId); void recordApi(int apiId, Object[] args); void recordApi(int apiId, Object[] args, int start, int end); void recordAttribute(AnnotationKey key, String value); ParsingResult recordSqlInfo(String sql); void recordSqlParsingResult(ParsingResult parsingResult); void recordAttribute(AnnotationKey key, Object value); void recordServiceType(ServiceType serviceType); void recordRpcName(String rpc); void recordDestinationId(String destinationId); // . endpint . @Deprecated void recordDestinationAddress(List<String> address); void recordDestinationAddressList(List<String> addressList); void recordEndPoint(String endPoint); void recordRemoteAddr(String remoteAddr); void recordNextSpanId(int spanId); void setTraceContext(TraceContext traceContext); void recordParentApplication(String parentApplicationName, short parentApplicationType); void recordAcceptorHost(String host); int getStackFrameId(); }
package dr.app.beauti.options; import dr.app.beauti.enumTypes.FixRateType; import dr.app.beauti.enumTypes.OperatorType; import dr.app.beauti.enumTypes.PriorType; import dr.app.beauti.enumTypes.RelativeRatesType; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.UPGMATree; import dr.evolution.util.Taxa; import dr.math.MathUtils; import dr.stats.DiscreteStatistics; import java.util.List; /** * @author Alexei Drummond * @author Andrew Rambaut * @author Walter Xie * @version $Id$ */ public class ClockModelOptions extends ModelOptions { // Instance variables private final BeautiOptions options; private FixRateType rateOptionClockModel = FixRateType.RElATIVE_TO; private double meanRelativeRate = 1.0; public ClockModelOptions(BeautiOptions options) { this.options = options; initGlobalClockModelParaAndOpers(); fixRateOfFirstClockPartition(); } private void initGlobalClockModelParaAndOpers() { createParameter("allClockRates", "All the relative rates regarding clock models"); createOperator("deltaAllClockRates", RelativeRatesType.CLOCK_RELATIVE_RATES.toString(), "Delta exchange operator for all the relative rates regarding clock models", "allClockRates", OperatorType.DELTA_EXCHANGE, 0.75, rateWeights); // only available for *BEAST and EBSP createUpDownAllOperator("upDownAllRatesHeights", "Up down all rates and heights", "Scales all rates inversely to node heights of the tree", demoTuning, branchWeights); } /** * return a list of parameters that are required * * @param params the parameter list */ public void selectParameters(List<Parameter> params) { } /** * return a list of operators that are required * * @param ops the operator list */ public void selectOperators(List<Operator> ops) { if (rateOptionClockModel == FixRateType.FIX_MEAN) { Operator deltaOperator = getOperator("deltaAllClockRates"); // update delta clock operator weight deltaOperator.weight = options.getPartitionClockModels().size(); ops.add(deltaOperator); } //up down all rates and trees operator only available for *BEAST and EBSP if (rateOptionClockModel == FixRateType.RElATIVE_TO && //TODO what about Calibration? (options.starBEASTOptions.isSpeciesAnalysis() || options.isEBSPSharingSamePrior())) { ops.add(getOperator("upDownAllRatesHeights")); } } public FixRateType getRateOptionClockModel() { return rateOptionClockModel; } // public void setRateOptionClockModel(FixRateType rateOptionClockModel) { // this.rateOptionClockModel = rateOptionClockModel; public void setMeanRelativeRate(double meanRelativeRate) { this.meanRelativeRate = meanRelativeRate; } public double[] calculateInitialRootHeightAndRate(List<PartitionData> partitions) { double avgInitialRootHeight = 1; double avgInitialRate = 1; double avgMeanDistance = 1; if (options.hasData()) { avgMeanDistance = options.getAveWeightedMeanDistance(partitions); } if (options.getPartitionClockModels().size() > 0) { avgInitialRate = options.clockModelOptions.getSelectedRate(options.getPartitionClockModels(partitions)); // all clock models } switch (options.clockModelOptions.getRateOptionClockModel()) { case FIX_MEAN: case RElATIVE_TO: if (options.hasData()) { avgInitialRootHeight = avgMeanDistance / avgInitialRate; } break; case TIP_CALIBRATED: avgInitialRootHeight = options.maximumTipHeight * 10.0;//TODO avgInitialRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case NODE_CALIBRATED: avgInitialRootHeight = getCalibrationEstimateOfRootTime(partitions); avgInitialRate = avgMeanDistance / avgInitialRootHeight;//TODO break; case RATE_CALIBRATED: break; default: throw new IllegalArgumentException("Unknown fix rate type"); } avgInitialRootHeight = MathUtils.round(avgInitialRootHeight, 2); avgInitialRate = MathUtils.round(avgInitialRate, 2); return new double[]{avgInitialRootHeight, avgInitialRate}; } public double getSelectedRate(List<PartitionClockModel> models) { double selectedRate = 1; if (rateOptionClockModel == FixRateType.FIX_MEAN) { selectedRate = meanRelativeRate; } else if (rateOptionClockModel == FixRateType.RElATIVE_TO) { // fix ?th partition if (models.size() == 1) { selectedRate = models.get(0).getRate(); } else { selectedRate = getAverageRate(models); } } else { // calibration: all isEstimatedRate = true //TODO calibration } return selectedRate; } private double getCalibrationEstimateOfRootTime(List<PartitionData> partitions) { // TODO - shouldn't this method be in the PartitionTreeModel?? List<Taxa> taxonSets = options.taxonSets; if (taxonSets != null && taxonSets.size() > 0) { // estimated root times based on each of the taxon sets double[] rootTimes = new double[taxonSets.size()]; for (int i = 0; i < taxonSets.size(); i++) { Taxa taxa = taxonSets.get(i); Parameter tmrcaStatistic = options.priorOptions.getStatistic(taxa); double taxonSetCalibrationTime = tmrcaStatistic.getPriorExpectation(); // the calibration distance is the patristic genetic distance back to the common ancestor of // the set of taxa. double calibrationDistance = 0; // the root distance is the patristic genetic distance back to the root of the tree. double rootDistance = 0; int siteCount = 0; for (PartitionData partition : partitions) { Tree tree = new UPGMATree(partition.distances); NodeRef node = Tree.Utils.getCommonAncestorNode(tree, Taxa.Utils.getTaxonListIdSet(taxa)); calibrationDistance += tree.getNodeHeight(node); rootDistance += tree.getNodeHeight(tree.getRoot()); siteCount += partition.getAlignment().getSiteCount(); } rootDistance /= partitions.size(); calibrationDistance /= partitions.size(); if (calibrationDistance == 0.0) { calibrationDistance = 0.25 / siteCount; } if (rootDistance == 0) { rootDistance = 0.25 / siteCount; } rootTimes[i] += (rootDistance / calibrationDistance) * taxonSetCalibrationTime; } // return the mean estimate of the root time for this set of partitions return DiscreteStatistics.mean(rootTimes); } return 0.0; } // FixRateType.FIX_MEAN public double getMeanRelativeRate() { return meanRelativeRate; } // FixRateType.ESTIMATE public double getAverageRate(List<PartitionClockModel> models) { //TODO average per tree, but how to control the estimate clock => tree? double averageRate = 0; double count = 0; for (PartitionClockModel model : models) { if (!model.isEstimatedRate()) { averageRate = averageRate + model.getRate(); count = count + 1; } } if (count > 0) { averageRate = averageRate / count; } return averageRate; } // Calibration Series Data public double getAverageRateForCalibrationSeriesData() { double averageRate = 0; //TODO return averageRate; } // Calibration TMRCA public double getAverageRateForCalibrationTMRCA() { double averageRate = 0; //TODO return averageRate; } public boolean isTipCalibrated() { return options.maximumTipHeight > 0; } public boolean isNodeCalibrated() { if (options.taxonSets != null && options.taxonSets.size() > 0) { return true; } else { for (PartitionTreeModel model : options.getPartitionTreeModels()) { Parameter rootHeightPara = model.getParameter("treeModel.rootHeight"); if (rootHeightPara.priorType == PriorType.LOGNORMAL_PRIOR || rootHeightPara.priorType == PriorType.NORMAL_PRIOR || rootHeightPara.priorType == PriorType.LAPLACE_PRIOR || rootHeightPara.priorType == PriorType.TRUNC_NORMAL_PRIOR || (rootHeightPara.priorType == PriorType.GAMMA_PRIOR && rootHeightPara.gammaAlpha > 1) || (rootHeightPara.priorType == PriorType.GAMMA_PRIOR && rootHeightPara.gammaOffset > 0) || (rootHeightPara.priorType == PriorType.UNIFORM_PRIOR && rootHeightPara.uniformLower > 0 && rootHeightPara.uniformUpper < Double.POSITIVE_INFINITY) || (rootHeightPara.priorType == PriorType.EXPONENTIAL_PRIOR && rootHeightPara.exponentialOffset > 0)) { return true; } } return false; } } public boolean isRateCalibrated() { return false;//TODO } public int[] getPartitionClockWeights() { int[] weights = new int[options.getPartitionClockModels().size()]; // use List? int k = 0; for (PartitionClockModel model : options.getPartitionClockModels()) { for (PartitionData partition : model.getAllPartitionData()) { int n = partition.getSiteCount(); weights[k] += n; } k += 1; } assert (k == weights.length); return weights; } public void fixRateOfFirstClockPartition() { this.rateOptionClockModel = FixRateType.RElATIVE_TO; // fix rate of 1st partition int i = 0; for (PartitionClockModel model : options.getPartitionClockModels()) { if (i < 1) { model.setEstimatedRate(false); } else { model.setEstimatedRate(true); } i = i + 1; } } public void fixMeanRate() { this.rateOptionClockModel = FixRateType.FIX_MEAN; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); // all set to NOT fixed, because detla exchange } } public void tipTimeCalibration() { this.rateOptionClockModel = FixRateType.TIP_CALIBRATED; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); } } public void nodeCalibration() { this.rateOptionClockModel = FixRateType.NODE_CALIBRATED; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); } } public void rateCalibration() { this.rateOptionClockModel = FixRateType.RATE_CALIBRATED; for (PartitionClockModel model : options.getPartitionClockModels()) { model.setEstimatedRate(true); } } }
package com.profiler.server.handler; import java.net.DatagramPacket; import org.apache.thrift.TBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.profiler.common.ServiceType; import com.profiler.common.dto.thrift.Span; import com.profiler.server.dao.AgentIdApplicationIndex; import com.profiler.server.dao.ApplicationTraceIndex; import com.profiler.server.dao.RootTraceIndexDao; import com.profiler.server.dao.TraceIndex; import com.profiler.server.dao.Traces; public class SpanHandler implements Handler { private final Logger logger = LoggerFactory.getLogger(SpanHandler.class.getName()); @Autowired private TraceIndex traceIndexDao; @Autowired private Traces traceDao; @Autowired private RootTraceIndexDao rootTraceIndexDao; @Autowired private ApplicationTraceIndex applicationTraceIndexDao; @Autowired private AgentIdApplicationIndex agentIdApplicationIndexDao; public void handler(TBase<?, ?> tbase, DatagramPacket datagramPacket) { assert (tbase instanceof Span); try { Span span = (Span) tbase; if (logger.isInfoEnabled()) { logger.info("Received SPAN=" + span); } String applicationName = agentIdApplicationIndexDao.selectApplicationName(span.getAgentId()); if (applicationName == null) { logger.warn("Applicationname '{}' not found. Drop the log.", applicationName); return; } else { logger.info("Applicationname '{}' found. Write the log.", applicationName); } if (logger.isDebugEnabled()) { logger.debug("Found Applicationname={}", applicationName); } traceDao.insert(applicationName, span); if (span.getParentSpanId() == -1) { rootTraceIndexDao.insert(span); } if (ServiceType.parse(span.getServiceType()).isIndexable()) { traceIndexDao.insert(span); applicationTraceIndexDao.insert(applicationName, span); } else { logger.debug("Skip writing index. '{}'", span); } } catch (Exception e) { logger.warn("Span handle error " + e.getMessage(), e); } } }
package dr.inference.trace; import dr.inferencexml.trace.MarginalLikelihoodAnalysisParser; import dr.util.Attribute; import dr.util.FileHelpers; import dr.xml.*; import java.io.File; import java.io.FileNotFoundException; import java.util.*; /** * @author Marc A. Suchard * @author Alexander Alekseyenko */ public class PathSamplingAnalysis { public static final String PATH_SAMPLING_ANALYSIS = "pathSamplingAnalysis"; public static final String LIKELIHOOD_COLUMN = "likelihoodColumn"; public static final String THETA_COLUMN = "thetaColumn"; public static final String FORMAT = "%5.5g"; PathSamplingAnalysis(String logLikelihoodName, List<Double> logLikelihoodSample, List<Double> thetaSample) { this.logLikelihoodSample = logLikelihoodSample; this.logLikelihoodName = logLikelihoodName; this.thetaSample = thetaSample; } public double getLogBayesFactor() { if (!logBayesFactorCalculated) { calculateBF(); } return logBayesFactor; } private void calculateBF() { // R code from Alex Alekseyenko // psMLE = function(likelihood, pathParameter){ // y=tapply(likelihood,pathParameter,mean) // L = length(y) // midpoints = (y[1:(L-1)] + y[2:L])/2 // x = as.double(names(y)) // widths = (x[2:L] - x[1:(L-1)]) // sum(widths*midpoints) Map<Double, List<Double>> map = new HashMap<Double, List<Double>>(); orderedTheta = new ArrayList<Double>(); for (int i = 0; i < logLikelihoodSample.size(); i++) { if (!map.containsKey(thetaSample.get(i))) { map.put(thetaSample.get(i), new ArrayList<Double>()); orderedTheta.add(thetaSample.get(i)); } map.get(thetaSample.get(i)).add(logLikelihoodSample.get(i)); } Collections.sort(orderedTheta); meanLogLikelihood = new ArrayList<Double>(); for (double t : orderedTheta) { double totalMean = 0; int lengthMean = 0; List<Double> values = map.get(t); for (double v : values) { totalMean += v; lengthMean++; } meanLogLikelihood.add(totalMean / lengthMean); } logBayesFactor = 0; innerArea = 0; for (int i = 0; i < meanLogLikelihood.size() - 1; i++) { logBayesFactor += (meanLogLikelihood.get(i + 1) + meanLogLikelihood.get(i)) / 2.0 * (orderedTheta.get(i + 1) - orderedTheta.get(i)); if (i > 0 && i < (meanLogLikelihood.size() - 1)) { innerArea += (meanLogLikelihood.get(i + 1) + meanLogLikelihood.get(i)) / 2.0 * (orderedTheta.get(i + 1) - orderedTheta.get(i)); } } logBayesFactorCalculated = true; } public String toString() { double bf = getLogBayesFactor(); StringBuffer sb = new StringBuffer(); sb.append("PathParameter\tMeanPathLikelihood\n"); for (int i = 0; i < orderedTheta.size(); ++i) { sb.append(String.format(FORMAT, orderedTheta.get(i))); sb.append("\t"); sb.append(String.format(FORMAT, meanLogLikelihood.get(i))); sb.append("\n"); } sb.append("\nlog Bayes factor (using path sampling) from "); sb.append(logLikelihoodName); sb.append(" = "); sb.append(String.format(FORMAT, bf) + " (" + bf + ")"); sb.append("\nInner area for path parameter in (" + String.format(FORMAT, orderedTheta.get(1)) + "," + String.format(FORMAT, orderedTheta.get(orderedTheta.size() - 2)) + ") = " + String.format(FORMAT, innerArea)); sb.append("\n"); return sb.toString(); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return PATH_SAMPLING_ANALYSIS; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME); StringTokenizer tokenFileName = new StringTokenizer(fileName); int numberOfFiles = tokenFileName.countTokens(); System.out.println(numberOfFiles + " file(s) found with marginal likelihood samples"); try { String likelihoodName = ""; List sampleLogLikelihood = null; List sampleTheta = null; for (int j = 0; j < numberOfFiles; j++) { File file = new File(tokenFileName.nextToken()); String name = file.getName(); String parent = file.getParent(); if (!file.isAbsolute()) { parent = System.getProperty("user.dir"); } file = new File(parent, name); fileName = file.getAbsolutePath(); XMLObject cxo = xo.getChild(LIKELIHOOD_COLUMN); likelihoodName = cxo.getStringAttribute(Attribute.NAME); cxo = xo.getChild(THETA_COLUMN); String thetaName = cxo.getStringAttribute(Attribute.NAME); LogFileTraces traces = new LogFileTraces(fileName, file); traces.loadTraces(); int maxState = traces.getMaxState(); // leaving the burnin attribute off will result in 10% being used int burnin = xo.getAttribute(MarginalLikelihoodAnalysisParser.BURN_IN, maxState / 5); if (burnin < 0 || burnin >= maxState) { burnin = maxState / 5; System.out.println("WARNING: Burn-in larger than total number of states - using to 20%"); } burnin = 0; traces.setBurnIn(burnin); int traceIndexLikelihood = -1; int traceIndexTheta = -1; for (int i = 0; i < traces.getTraceCount(); i++) { String traceName = traces.getTraceName(i); if (traceName.trim().equals(likelihoodName)) { traceIndexLikelihood = i; } if (traceName.trim().equals(thetaName)) { traceIndexTheta = i; } } if (traceIndexLikelihood == -1) { throw new XMLParseException("Column '" + likelihoodName + "' can not be found for " + getParserName() + " element."); } if (traceIndexTheta == -1) { throw new XMLParseException("Column '" + thetaName + "' can not be found for " + getParserName() + " element."); } if (sampleLogLikelihood == null && sampleTheta == null) { sampleLogLikelihood = traces.getValues(traceIndexLikelihood); sampleTheta = traces.getValues(traceIndexTheta); } else { sampleLogLikelihood.addAll(traces.getValues(traceIndexLikelihood)); sampleTheta.addAll(traces.getValues(traceIndexTheta)); } } PathSamplingAnalysis analysis = new PathSamplingAnalysis(likelihoodName, sampleLogLikelihood, sampleTheta); System.out.println(analysis.toString()); return analysis; } catch (FileNotFoundException fnfe) { throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element."); } catch (java.io.IOException ioe) { throw new XMLParseException(ioe.getMessage()); } catch (TraceException e) { throw new XMLParseException(e.getMessage()); } }
package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.HashMap; 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.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.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.UnionType; 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 _float; final TypeDeclaration _null; final TypeDeclaration anything; final TypeDeclaration callable; final TypeDeclaration empty; final TypeDeclaration metaClass; TypeUtils(Module languageModule) { com.redhat.ceylon.compiler.typechecker.model.Package pkg = languageModule.getPackage("ceylon.language"); tuple = (TypeDeclaration)pkg.getMember("Tuple", null, false); iterable = (TypeDeclaration)pkg.getMember("Iterable", null, false); sequential = (TypeDeclaration)pkg.getMember("Sequential", null, false); numeric = (TypeDeclaration)pkg.getMember("Numeric", null, false); _integer = (TypeDeclaration)pkg.getMember("Integer", null, false); _float = (TypeDeclaration)pkg.getMember("Float", null, false); _null = (TypeDeclaration)pkg.getMember("Null", null, false); anything = (TypeDeclaration)pkg.getMember("Anything", null, false); callable = (TypeDeclaration)pkg.getMember("Callable", null, false); empty = (TypeDeclaration)pkg.getMember("Empty", null, false); pkg = languageModule.getPackage("ceylon.language.model"); metaClass = (TypeDeclaration)pkg.getMember("Class", null, false); } /** Prints the type arguments, usually for their reification. */ public static void printTypeArguments(Node node, Map<TypeParameter,ProducedType> targs, GenerateJsVisitor gen) { 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(), ":"); final ProducedType pt = e.getValue(); if (pt == null) { gen.out("'", e.getKey().getName(), "'"); continue; } final TypeDeclaration d = pt.getDeclaration(); boolean composite = d instanceof UnionType || d instanceof IntersectionType; boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty(); boolean closeBracket = false; if (composite) { outputTypeList(node, d, gen, true); } else if (d instanceof TypeParameter) { resolveTypeParameter(node, (TypeParameter)d, gen); } else { gen.out("{t:"); outputQualifiedTypename( gen.isImported(node == null ? null : node.getUnit().getPackage(), pt.getDeclaration()), pt, gen); closeBracket = true; } if (hasParams) { gen.out(",a:"); printTypeArguments(node, pt.getTypeArguments(), gen); } if (closeBracket) { gen.out("}"); } } gen.out("}"); } static void outputQualifiedTypename(final boolean imported, ProducedType pt, GenerateJsVisitor gen) { 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 { if (t.isAlias()) { t = t.getExtendedTypeDeclaration(); } boolean qual = false; if (t.getScope() instanceof ClassOrInterface) { List<ClassOrInterface> parents = new ArrayList<>(); ClassOrInterface parent = (ClassOrInterface)t.getScope(); parents.add(0, parent); while (parent.getScope() instanceof ClassOrInterface) { parent = (ClassOrInterface)parent.getScope(); parents.add(0, parent); } qual = true; for (ClassOrInterface p : parents) { gen.out(gen.getNames().name(p), "."); } } else if (imported) { //This wasn't needed but now we seem to get imported decls with no package when compiling ceylon.language.model types final String modAlias = gen.getNames().moduleAlias(t.getUnit().getPackage().getModule()); if (modAlias != null && !modAlias.isEmpty()) { gen.out(modAlias, "."); } qual = true; } String tname = gen.getNames().name(t); if (!qual && isReservedTypename(tname)) { gen.out(tname, "$"); } else { gen.out(tname); } } } /** 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(Node node, ProducedType pt, GenerateJsVisitor gen, boolean typeReferences) { TypeDeclaration type = pt.getDeclaration(); if (type.isAlias()) { type = type.getExtendedTypeDeclaration(); } boolean unionIntersection = type instanceof UnionType || type instanceof IntersectionType; if (unionIntersection) { outputTypeList(node, type, gen, typeReferences); } else if (typeReferences) { if (type instanceof TypeParameter) { resolveTypeParameter(node, (TypeParameter)type, gen); } else { gen.out("{t:"); outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen); if (!pt.getTypeArgumentList().isEmpty()) { gen.out(",a:"); printTypeArguments(node, pt.getTypeArguments(), gen); } gen.out("}"); } } else { gen.out("'", type.getQualifiedNameString(), "'"); } } /** Appends an object with the type's type and list of union/intersection types. */ static void outputTypeList(Node node, TypeDeclaration type, GenerateJsVisitor gen, boolean typeReferences) { gen.out("{ t:'"); final List<ProducedType> subs; if (type instanceof IntersectionType) { gen.out("i"); subs = type.getSatisfiedTypes(); } else { gen.out("u"); subs = type.getCaseTypes(); } gen.out("', l:["); boolean first = true; for (ProducedType t : subs) { if (!first) gen.out(","); typeNameOrList(node, t, gen, typeReferences); first = false; } gen.out("]}"); } /** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */ static void resolveTypeParameter(Node node, TypeParameter tp, GenerateJsVisitor gen) { Scope parent = node.getScope(); while (parent != null && parent != tp.getContainer()) { parent = parent.getScope(); } if (tp.getContainer() instanceof ClassOrInterface) { if (parent == tp.getContainer()) { if (((ClassOrInterface)tp.getContainer()).isAlias()) { //when resolving for aliases we just take the type arguments from the alias call gen.out("$$targs$$.", tp.getName()); } else { gen.self((ClassOrInterface)tp.getContainer()); gen.out(".$$targs$$.", tp.getName()); } } else { //This can happen in expressions such as Singleton(n) when n is dynamic gen.out("{/*NO PARENT*/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()); } 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; } static boolean isReservedTypename(String typeName) { return JsCompiler.compilingLanguageModule && (typeName.equals("Object") || typeName.equals("Number") || typeName.equals("Array")) || typeName.equals("String") || typeName.equals("Boolean"); } /** 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(Tree.Term term, final ProducedType t, final GenerateJsVisitor gen) { String tmp = gen.getNames().createTempVariable(); gen.out("(", tmp, "="); term.visit(gen); gen.out(",", GenerateJsVisitor.getClAlias(), "isOfType(", tmp, ","); TypeUtils.typeNameOrList(term, t, gen, true); gen.out(")?", tmp, ":", GenerateJsVisitor.getClAlias(), "throwexc('dynamic objects cannot be used here'))"); } static void encodeParameterListForRuntime(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.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); gen.out("}"); } gen.out("]"); } /** This method encodes the type parameters of a Tuple (taken from a Callable) in the same way * as a parameter list for runtime. */ void encodeTupleAsParameterListForRuntime(ProducedType _callable, GenerateJsVisitor gen) { if (!_callable.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) { gen.out("[/*WARNING: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]"); return; } List<ProducedType> targs = _callable.getTypeArgumentList(); if (targs == null || targs.size() != 2) { gen.out("[/*WARNING: missing argument types for Callable*/]"); return; } ProducedType _tuple = targs.get(1); gen.out("["); int pos = 1; while (!(empty.equals(_tuple.getDeclaration()) || _tuple.getDeclaration() instanceof TypeParameter)) { if (pos > 1) gen.out(","); gen.out("{", MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos++), "',"); gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',"); gen.out(MetamodelGenerator.KEY_TYPE, ":"); if (tuple.equals(_tuple.getDeclaration())) { metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen); _tuple = _tuple.getTypeArgumentList().get(2); } else if (sequential.equals(_tuple.getDeclaration())) { metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(0), gen); _tuple = _tuple.getTypeArgumentList().get(0); } else { System.out.println("WTF? Tuple is actually " + _tuple.getProducedTypeQualifiedName() + ", " + _tuple.getClass().getName()); if (pos > 100) { System.exit(1); } } gen.out("}"); } gen.out("]"); } static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen) { if (d.getAnnotations() == null || d.getAnnotations().isEmpty()) { encodeForRuntime(d, gen, null); } else { encodeForRuntime(d, gen, new RuntimeMetamodelAnnotationGenerator() { @Override public void generateAnnotations() { gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":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(null, 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 { boolean farg = true; for (String s : a.getPositionalArguments()) { if (farg)farg=false; else gen.out(","); gen.out(s); } } gen.out(")"); } else { gen.out("null/*MISSING DECLARATION FOR ANNOTATION ", a.getName(), "*/"); } } gen.out("];}"); } }); } } /** 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(); encodeForRuntime(d, gen, include ? new RuntimeMetamodelAnnotationGenerator() { @Override public void generateAnnotations() { gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":"); outputAnnotationsFunction(annotations, gen); } } : null); } static void encodeForRuntime(final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) { gen.out("function(){return{mod:$$METAMODEL$$"); List<TypeParameter> tparms = null; List<ProducedType> satisfies = null; if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters(); if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) { gen.out(",'super':"); metamodelTypeNameOrList(d.getUnit().getPackage(), ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen); } satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes(); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters(); satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes(); } 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(((Method)d).getParameterLists().get(0), gen); tparms = ((Method) d).getTypeParameters(); } } if (d.isMember()) { gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer())); } if (tparms != null && !tparms.isEmpty()) { gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{"); boolean first = true; boolean comma = false; for(TypeParameter tp : tparms) { if (!first)gen.out(","); first=false; gen.out(tp.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("}"); } gen.out("}"); } if (satisfies != null) { 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 (annGen != null) { annGen.generateAnnotations(); } gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['"); gen.out(d.getUnit().getPackage().getNameAsString(), "']"); if (d.isToplevel()) { gen.out("['", d.getName(), "']"); } else { ArrayList<String> path = new ArrayList<>(); Declaration p = d; while (p instanceof Declaration) { path.add(0, p.getName()); //Build the path in reverse if (!p.isToplevel()) { if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { path.add(0, p.isAnonymous() ? "$o" : "$c"); } else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { path.add(0, "$i"); } else if (p instanceof Method) { path.add(0, "$m"); } else { path.add(0, "$at"); } } Scope s = p.getContainer(); while (s != null && s instanceof Declaration == false) { s = s.getContainer(); } p = (Declaration)s; } //Output path for (String part : path) { gen.out("['", part, "']"); } } gen.out("};}"); } /** 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( "ceylon.language").getDirectMember("Anything", null, false)).getType(); } TypeDeclaration type = pt.getDeclaration(); if (type.isAlias()) { type = type.getExtendedTypeDeclaration(); } boolean unionIntersection = type instanceof UnionType || type instanceof IntersectionType; if (unionIntersection) { outputMetamodelTypeList(pkg, pt, gen); } else if (type instanceof TypeParameter) { gen.out("'", type.getNameAsString(), "'"); } else { gen.out("{t:"); outputQualifiedTypename(gen.isImported(pkg, type), pt, gen); //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(), ":"); metamodelTypeNameOrList(pkg, e.getValue(), gen); } gen.out("}"); } gen.out("}"); } } /** Appends an object with the type's type and list of union/intersection types. */ static void outputMetamodelTypeList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg, ProducedType pt, GenerateJsVisitor gen) { TypeDeclaration type = pt.getDeclaration(); gen.out("{ t:'"); final List<ProducedType> subs; if (type instanceof IntersectionType) { gen.out("i"); subs = type.getSatisfiedTypes(); } else { gen.out("u"); subs = type.getCaseTypes(); } gen.out("', l:["); boolean first = true; for (ProducedType t : subs) { if (!first) gen.out(","); metamodelTypeNameOrList(pkg, t, gen); first = false; } gen.out("]}"); } 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; } /** Outputs a function that returns the specified annotations, so that they can be loaded lazily. */ static void outputAnnotationsFunction(final Tree.AnnotationList annotations, final GenerateJsVisitor gen) { if (annotations == null || annotations.getAnnotations().isEmpty()) { gen.out("[]"); } else { gen.out("function(){return["); boolean first = true; 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(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.DriverStationLCD.Line; /** * * @author Philip2 */ public class Shooter extends Team3373 { int StageOneMotorPWM = 1; //Declares channel of StageOne PWM int StageTwoMotorPWM = 2; //Declares channel of StageTwo PWM Talon StageOneTalon = new Talon(StageOneMotorPWM); //Creates instance of StageOne PWM Talon StageTwoTalon = new Talon(StageTwoMotorPWM); //Creates instance of StageTwo PWM DriverStationLCD dsLCD; Joystick shootStick = new Joystick(2); boolean shootA = shootStick.getRawButton(1); boolean shootB = shootStick.getRawButton(2); boolean shootX = shootStick.getRawButton(3); boolean shootY = shootStick.getRawButton(4); boolean shootRB = shootStick.getRawButton(5); boolean shootLB = shootStick.getRawButton(6); boolean shootBack = shootStick.getRawButton(7); boolean shootStart = shootStick.getRawButton(8); boolean test; double shootLX = shootStick.getRawAxis(1); double shootLY = shootStick.getRawAxis(2); double shootTriggers = shootStick.getRawAxis(3); double shootRX = shootStick.getRawAxis(4); double shootRY = shootStick.getRawAxis(5); double shootDP = shootStick.getRawAxis(6); double ShooterSpeedStage1 = StageOneTalon.get(); double ShooterSpeedStage2 = StageTwoTalon.get(); double ShooterSpeedMax = 5300; double ShooterSpeedAccel = 250; double stageOneScaler = .5; //What stage one is multiplied by in order to make it a pecentage of stage 2 double PWMMax = 1; //maximum voltage sent to motor double MaxScaler = PWMMax/10000; double ShooterSpeedScale = MaxScaler * ShooterSpeedMax; //Scaler for voltage to RPM. Highly experimental!! double currentRPMT2 = StageTwoTalon.get()*ShooterSpeedScale; double currentRPMT1 = currentRPMT2*stageOneScaler; double target; double RPMIncrease = 250; double idle = 1 * ShooterSpeedScale; double off = 0; public void Shooter() { dsLCD = DriverStationLCD.getInstance(); dsLCD.updateLCD(); if (shootStart){ StageTwoTalon.set(idle); StageOneTalon.set(idle * stageOneScaler); dsLCD.println(Line.kUser1, 7, "On"); } else if (shootBack){ StageTwoTalon.set(off); StageOneTalon.set(off *stageOneScaler); dsLCD.println(Line.kUser1, 7, "Off"); } if (shootA){ StageTwoTalon.set(currentRPMT2 + (RPMIncrease*ShooterSpeedScale)); StageOneTalon.set((currentRPMT2 + RPMIncrease) *stageOneScaler); target = currentRPMT2 + RPMIncrease; dsLCD.println(Line.kUser2, 1, "Adding " + RPMIncrease + "RPM"); } if (shootB){ //This code is used to subtrack the current speed of Stage 2 StageTwoTalon.set(currentRPMT2 - RPMIncrease); StageOneTalon.set((currentRPMT2 - RPMIncrease) *.5); target = currentRPMT2 - RPMIncrease; dsLCD.println(Line.kUser2, 1, "Removing " + RPMIncrease + "RPM."); if (StageTwoTalon.get() < 0){ StageTwoTalon.set(off); //if the speed is less than 0, turn off } } if (shootX){ stageOneScaler += 0.05; //changes stage1 percentage of stage2 adds 5% dsLCD.println(Line.kUser6, 1, "Adding 5% to Stage One Percentile"); } else if (shootY){ stageOneScaler -= 0.05; //changes stage1 percentage of stage2 subtracts 5% dsLCD.println(Line.kUser6, 1, "Subtracting 5% to Stage One Percentile"); } if (target > currentRPMT2) { dsLCD.println(Line.kUser5, 1, "Accelerating"); } else if (target < currentRPMT2) { dsLCD.println(Line.kUser5, 1, "Decelerating"); } dsLCD.println(Line.kUser1, 1, "Motors "); dsLCD.println(Line.kUser3, 1, "Stage One Speed Percentile: " + (currentRPMT1/currentRPMT2)*100 + "%"); dsLCD.println(Line.kUser4, 1, "Target Speed: " + (target) + "RPM"); dsLCD.updateLCD(); } }
package com.rosshambrick.standardlib; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Toast; import butterknife.ButterKnife; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.android.app.AppObservable; import rx.android.lifecycle.LifecycleEvent; import rx.android.lifecycle.LifecycleObservable; import rx.functions.Action0; import rx.subjects.BehaviorSubject; public abstract class RxFragment extends DialogFragment { private BlockingProgressFragment blockingProgressFragment; private Toolbar toolbar; private final BehaviorSubject<LifecycleEvent> lifecycleSubject = BehaviorSubject.create(); private Observable<LifecycleEvent> lifecycle() { return lifecycleSubject.asObservable(); } abstract protected boolean isDebug(); @Override public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(LifecycleEvent.ATTACH); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar); lifecycleSubject.onNext(LifecycleEvent.CREATE); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.inject(this, view); lifecycleSubject.onNext(LifecycleEvent.CREATE_VIEW); } @Override public void onStart() { super.onStart(); lifecycleSubject.onNext(LifecycleEvent.START); } @Override public void onResume() { super.onResume(); lifecycleSubject.onNext(LifecycleEvent.RESUME); } @Override public void onPause() { lifecycleSubject.onNext(LifecycleEvent.PAUSE); super.onPause(); } @Override public void onStop() { lifecycleSubject.onNext(LifecycleEvent.STOP); super.onStop(); } @Override public void onDestroyView() { lifecycleSubject.onNext(LifecycleEvent.DESTROY_VIEW); super.onDestroyView(); } @Override public void onDetach() { lifecycleSubject.onNext(LifecycleEvent.DETACH); super.onDetach(); } @Override public void onDestroy() { super.onDestroy(); lifecycleSubject.onNext(LifecycleEvent.DESTROY); } protected void showBlockingProgress() { showBlockingProgress(null); } protected void showBlockingProgress(Subscription subscription) { blockingProgressFragment = BlockingProgressFragment.newInstance(); blockingProgressFragment.show(getFragmentManager(), BlockingProgressFragment.TAG); blockingProgressFragment.setOnCancelListener(subscription); } public void handleError(Throwable e) { handleError(null, e); } protected void handleError(String message, Throwable e) { Log.e(getClass().getSimpleName(), e.getLocalizedMessage(), e); if (isDebug() || message != null) { Toast.makeText(getActivity(), message == null ? e.getLocalizedMessage() : message, Toast.LENGTH_LONG).show(); } } protected void dismissBlockingProgress() { if (blockingProgressFragment != null) { blockingProgressFragment.dismiss(); blockingProgressFragment = null; } } public Toolbar getToolbar() { return toolbar; } protected <T> Subscription blockingSubscribe(Observable<T> observable, Observer<T> observer) { Subscription subscription = bind(observable) .finallyDo(new Action0() { @Override public void call() { RxFragment.this.dismissBlockingProgress(); } }) .subscribe(observer); showBlockingProgress(subscription); return subscription; } protected <T> Subscription subscribe(Observable<T> observable, Observer<T> observer) { Observable<T> boundObservable = bind(observable); return boundObservable.subscribe(observer); } protected <T> Observable<T> bind(Observable<T> observable) { Observable<T> boundObservable = AppObservable.bindFragment(this, observable); return LifecycleObservable.bindFragmentLifecycle(lifecycle(), boundObservable); } protected void toast(int messageId) { Toast.makeText(getActivity(), messageId, Toast.LENGTH_SHORT).show(); } protected void toast(String message) { Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); } protected int getColor(int colorRes) { return getResources().getColor(colorRes); } protected int getDimensionPixelOffset(int dpResource) { return getResources().getDimensionPixelOffset(dpResource); } protected void debugToast(int messageResId) { if (isDebug()) { Toast.makeText(getActivity(), messageResId, Toast.LENGTH_LONG).show(); } } public void onCompleted() { //nothing by default } public void onError(Throwable e) { handleError(e); } }
package com.salesforce.scmt.service; import static com.salesforce.scmt.rabbitmq.RabbitConfiguration.EXCHANGE_TRACTOR; import static com.salesforce.scmt.rabbitmq.RabbitConfiguration.QUEUE_DESK_DATA_MIGRATION; import static com.salesforce.scmt.rabbitmq.RabbitConfiguration.QUEUE_DESK_ATTACHMENT; import static com.salesforce.scmt.utils.Utils.getPostParamsFromRequest; import static java.lang.System.getenv; import java.io.IOException; import java.security.InvalidParameterException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import com.desk.java.apiclient.DeskClient; import com.desk.java.apiclient.DeskClientBuilder; import com.desk.java.apiclient.model.CustomField; import com.desk.java.apiclient.model.Group; import com.desk.java.apiclient.model.User; import com.salesforce.scmt.model.DeployResponse; import com.salesforce.scmt.utils.*; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.logging.HttpLoggingInterceptor; import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import com.salesforce.scmt.utils.SalesforceConstants.DeskMigrationFields; import spark.Request; import spark.Response; public class DeskService { private static final String DESK_API_LOG_LEVEL = "DESK_API_LOG_LEVEL"; private static final String DESK_API_LOG_LEVEL_NONE = "NONE"; private static final String DESK_API_LOG_LEVEL_BASIC = "BASIC"; private static final String DESK_API_LOG_LEVEL_HEADERS = "HEADERS"; private static final String DESK_API_LOG_LEVEL_BODY = "BODY"; private String _migrationId; private DeskClient _client; private Map<String, String> _clientSettings; private SalesforceService _sfService; // these are used for caching public List<Group> _deskGroups; public List<User> _deskUsers; public Map<Integer, String> _deskGroupId2Name; public DeskService(Map<String, Object> config) { this(config.get("deskUrl").toString(), config.get("consumerKey").toString(), config.get("consumerSecret").toString(), config.get("accessToken").toString(), config.get("accessTokenSecret").toString(), (config.containsKey("desk_migration_id") ? config.get("desk_migration_id").toString() : null), config.get("server_url").toString(), config.get("session_id").toString(), (config.containsKey("auditEnabled") ? Boolean.valueOf(config.get("auditEnabled").toString()) : false)); } public DeskService(String deskUrl, String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret, String migrationId, String serverUrl, String sessionId, Boolean auditEnabled) { System.out.println(serverUrl+" "+ sessionId); // check if a desk migration id was passed if (migrationId != null) { setMigrationId(migrationId); } deskUrl = deskUrl.replaceFirst("(http|https):\\/\\/www\\.|www.|(http|https):\\/\\/", ""); // create a desk client System.out.println("deskUrl" +deskUrl); createDeskClient(deskUrl, consumerKey, consumerSecret, accessToken, accessTokenSecret); // create Salesforce Service instance _sfService = new SalesforceService(serverUrl, sessionId); // check if auditEnabled was passed _sfService.setAuditFieldsEnabled(auditEnabled); } public SalesforceService getSalesforceService() { return _sfService; } public String getMigrationId() { return _migrationId; } public void setMigrationId(String migrationId) { _migrationId = migrationId; } public List<Group> getDeskGroups() { return _deskGroups; } public void setDeskGroups(List<Group> groups) { _deskGroups = groups; } public List<User> getDeskUsers() { return _deskUsers; } public void setDeskUsers(List<User> users) { _deskUsers = users; } public Map<Integer, String> getDeskGroupId2Name() { return _deskGroupId2Name; } public void setDeskGroupId2Name(Map<Integer, String> groupId2Name) { _deskGroupId2Name = groupId2Name; } private DeskClient createDeskClient(String deskUrl, String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) { // check if we need to create a desck client if (_client == null || !_client.getHostname().equalsIgnoreCase(deskUrl)) { // DEBUG if (_client != null) { Utils.log("Static Desk Client Hostname: [" + _client.getHostname() + "], new Desk Hostname: [" + deskUrl + "]"); } // check that required parameters are not empty if (deskUrl.isEmpty() || consumerKey.isEmpty() || consumerSecret.isEmpty() || accessToken.isEmpty() || accessTokenSecret.isEmpty()) { throw new InvalidParameterException("All of the parameters are required!"); } // save the settings so I can re-queue jobs _clientSettings = new HashMap<>(); _clientSettings.put("deskUrl", deskUrl); _clientSettings.put("consumerKey", consumerKey); _clientSettings.put("consumerSecret", consumerSecret); _clientSettings.put("accessToken", accessToken); _clientSettings.put("accessTokenSecret", accessTokenSecret); // create client builder DeskClientBuilder clientBuilder = new DeskClientBuilder(deskUrl, consumerKey, consumerSecret, accessToken, accessTokenSecret); // set logging for desk client HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(Level.NONE); // default to NONE, which still produces a log, but very simple String deskApiLogLevel = getenv(DESK_API_LOG_LEVEL); // if a log level is specified in the environment config var, apply it if (deskApiLogLevel != null && !deskApiLogLevel.equalsIgnoreCase(DESK_API_LOG_LEVEL_NONE)) { Utils.log("Setting logging level of Desk.com API to: [" + deskApiLogLevel + "]"); if (deskApiLogLevel.equalsIgnoreCase(DESK_API_LOG_LEVEL_BASIC)) { logging.setLevel(Level.BASIC); } else if (deskApiLogLevel.equalsIgnoreCase(DESK_API_LOG_LEVEL_HEADERS)) { logging.setLevel(Level.HEADERS); } else if (deskApiLogLevel.equalsIgnoreCase(DESK_API_LOG_LEVEL_BODY)) { logging.setLevel(Level.BODY); } } // add the limit override header Interceptor requestHeader = new Interceptor() { @Override public com.squareup.okhttp.Response intercept(Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Request original = chain.request(); com.squareup.okhttp.Request request = original.newBuilder() .method(original.method(), original.body()) .build(); return chain.proceed(request); } }; // add the interceptors clientBuilder.applicationInterceptors(Arrays.asList(logging, requestHeader)); // create the client and assign to private member variable _client = DeskClient.create(clientBuilder); } return _client; } public DeskClient getClient() { return _client; } public Map<String, Object> getClientSettings() { Map<String, Object> clientSettings = new HashMap<>(_clientSettings); // set Salesforce Service info clientSettings.put("server_url", _sfService.getServerUrl()); clientSettings.put("session_id", _sfService.getSessionId()); clientSettings.put("desk_migration_id", getMigrationId()); /*/ String msg = "Client Settings:"; for (String key : clientSettings.keySet()) { msg += "\n\t" + key + ": " + clientSettings.get(key); } Utils.log(msg); return clientSettings; } public static Object authenticateTokens(Request req, Response res) throws Exception { // get the post parameters in a hash map Map<String, String> postParams = getPostParamsFromRequest(req, new String[] { "deskUrl", "consumerKey", "consumerSecret", "accessToken", "accessTokenSecret" }); // response map Map<String, Object> response = new TreeMap<>(); DeskService deskService; try { // create a DeskService instance based on the data posted (e.g. tokens, url, session id, etc.) deskService = new DeskService(postParams.get("deskUrl"), postParams.get("consumerKey"), postParams.get("consumerSecret"), postParams.get("accessToken"), postParams.get("accessTokenSecret"), (postParams.containsKey("desk_migration_id") ? postParams.get("desk_migration_id") : null), postParams.get("server_url"), postParams.get("session_id"), (postParams.containsKey("auditEnabled") ? Boolean.valueOf(postParams.get("auditEnabled")) : false)); // build a DeskUtil (this has some non-static pieces so we can cache desk groups) DeskUtil deskUtil = new DeskUtil(deskService); // get the languages Map<String, Object> languages = deskUtil.getDeskSiteLanguagesMap(); // get the groups Set<Integer> groupIds = deskUtil.getDeskGroupIds(); // get the custom fields List<CustomField> custom_fields = deskUtil.getDeskCustomFields(); // build response and return it response.put("languages", languages); response.put("groups", groupIds); response.put("custom_fields", custom_fields); } catch(Exception unknownHost) { throw new Exception("Unable to connect to Desk.com API"); } return response; } public static Object migrateMetadata(Request req, Response res) throws Exception { // get the post parameters in a hash map Map<String, String> postParams = getPostParamsFromRequest(req, new String[] { "server_url", "session_id", "deskUrl", "consumerKey", "consumerSecret", "accessToken", "accessTokenSecret"}); // create a DeskService instance based on the data posted (e.g. tokens, url, session id, etc.) DeskService deskService = new DeskService(postParams.get("deskUrl"), postParams.get("consumerKey"), postParams.get("consumerSecret"), postParams.get("accessToken"), postParams.get("accessTokenSecret"), (postParams.containsKey("desk_migration_id") ? postParams.get("desk_migration_id") : null), postParams.get("server_url"), postParams.get("session_id"), (postParams.containsKey("auditEnabled") ? Boolean.valueOf(postParams.get("auditEnabled")) : false)); // build a DeskUtil (this has some non-static pieces so we can cache desk groups) DeskUtil deskUtil = new DeskUtil(deskService); // response map DeployResponse response = new DeployResponse(); // check if custom fields were passed if (postParams.containsKey("custom_fields")) { // create the custom fields that were passed response.addDeployResponse(deskUtil.createCustomFields(postParams.get("custom_fields"))); } // check if groups were passed if (postParams.containsKey("groups")) { // create the groups that were passed response.addDeployResponse(deskUtil.createQueues(postParams.get("groups"))); } return response; } public static Object migrateData(Request req, Response res) throws Exception { // get the post parameters in a hash map Map<String, String> postParams = getPostParamsFromRequest(req, new String[] { "server_url", "session_id", "deskUrl", "consumerKey", "consumerSecret", "accessToken", "accessTokenSecret"}); // create a DeskService instance based on the data posted (e.g. tokens, url, session id, etc.) DeskService deskService = new DeskService(postParams.get("deskUrl"), postParams.get("consumerKey"), postParams.get("consumerSecret"), postParams.get("accessToken"), postParams.get("accessTokenSecret"), (postParams.containsKey("desk_migration_id") ? postParams.get("desk_migration_id") : null), postParams.get("server_url"), postParams.get("session_id"), (postParams.containsKey("auditEnabled") ? Boolean.valueOf(postParams.get("auditEnabled")) : false)); // build a DeskUtil (this has some non-static pieces so we can cache desk groups) DeskUtil deskUtil = new DeskUtil(deskService); deskUtil.updateMigrationStatus(DeskMigrationFields.StatusQueued, "", null); // publish the job to RabbitMQ RabbitUtil.publishToQueue(QUEUE_DESK_DATA_MIGRATION, EXCHANGE_TRACTOR, JsonUtil.toJson(postParams).getBytes()); return "SUBMITTED"; } public static Object migrateAttachments(Request req, Response res) throws Exception { // get the post parameters in a hash map Map<String, String> postParams = getPostParamsFromRequest(req, new String[] { "server_url", "session_id", "deskUrl", "consumerKey", "consumerSecret", "accessToken", "accessTokenSecret"}); // create a DeskService instance based on the data posted (e.g. tokens, url, session id, etc.) DeskService deskService = new DeskService(postParams.get("deskUrl"), postParams.get("consumerKey"), postParams.get("consumerSecret"), postParams.get("accessToken"), postParams.get("accessTokenSecret"), (postParams.containsKey("desk_migration_id") ? postParams.get("desk_migration_id") : null), postParams.get("server_url"), postParams.get("session_id"), (postParams.containsKey("auditEnabled") ? Boolean.valueOf(postParams.get("auditEnabled")) : false)); // build a DeskUtil (this has some non-static pieces so we can cache desk groups) DeskUtil deskUtil = new DeskUtil(deskService); deskUtil.updateMigrationStatus(DeskMigrationFields.StatusQueued, "", null); // publish the job to RabbitMQ RabbitUtil.publishToQueue(QUEUE_DESK_ATTACHMENT, EXCHANGE_TRACTOR, JsonUtil.toJson(postParams).getBytes()); return "SUBMITTED"; } public static Object retrieveMetadata(Request req, Response res) throws Exception { // get the post parameters in a hash map Map<String, String> postParams = getPostParamsFromRequest(req, new String[] { "deskUrl", "consumerKey", "consumerSecret", "accessToken", "accessTokenSecret" }); // response map Map<String, Object> response = new TreeMap<>(); DeskService deskService; try { // create a DeskService instance based on the data posted (e.g. tokens, url, session id, etc.) deskService = new DeskService(postParams.get("deskUrl"), postParams.get("consumerKey"), postParams.get("consumerSecret"), postParams.get("accessToken"), postParams.get("accessTokenSecret"), (postParams.containsKey("desk_migration_id") ? postParams.get("desk_migration_id") : null), postParams.get("server_url"), postParams.get("session_id"), (postParams.containsKey("auditEnabled") ? Boolean.valueOf(postParams.get("auditEnabled")) : false)); // build a DeskUtil (this has some non-static pieces so we can cache desk groups) DeskUtil deskUtil = new DeskUtil(deskService); // get the groups List<Group> groups = deskUtil.getDeskGroups(); // get the users List<User> users = deskUtil.getDeskUsers(); // get the custom fields List<CustomField> custom_fields = deskUtil.getDeskCustomFields(); // build response and return it response.put("groups", groups); response.put("users", users); response.put("custom_fields", custom_fields); } catch(Exception unknownHost) { throw new Exception("Unable to connect to Desk.com API"); } return response; } }
package com.simsilica.ethereal.zone; import com.simsilica.mathd.AaBBox; import com.simsilica.mathd.Quatd; import com.simsilica.mathd.Vec3d; import com.simsilica.mathd.Vec3i; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Manages all of the zones for all of the players. This * is used to update the status of active objects. The zone * manager then makes sure that information gets to where it needs to go. * * <p>Object updates need to be done in the context of a 'frame' so * that the updates can be properly grouped together. To do this, * the game code that is reporting updates needs to call the ZoneManager * methods using a specific life cycle:</p> * * <ul> * <li>beginUpdate(frameTime): starts a new frame. The frame time will * be used to stamp any state updates.</li> * <li>updateEntity(...): record an update event for the specific entity * within the current frame.</li> * <li>remove(entityId): removes an entity from the zone manager. This can * be called between beginUpdate() and endUpdate() but it can also be called * outside of those calls and the removal will be enqueued for the next update. * If this feature is used then make sure to also call add() if the object * needs to come back.</li> * <li>endUpdate(): closes updates to the current frame.</li> * <li>add(entityId): used outside of beginUpdate()/endUpdate() if remove(id) * is also used outside of beingUpdate()/endUpdate(). Calling remove(id) * outside of a begin/end block will enqueue the removal for the next begin/end * block. add() will remove it from this queue in case that removal hasn't been * sent yet. Normally add() is not required as updateEntity() will add the * entity if it hasn't already seen it.</lI> * </ul> * * @author Paul Speed */ public class ZoneManager { static Logger log = LoggerFactory.getLogger(ZoneManager.class); private ZoneGrid grid; private final Map<Long, ZoneRange> index = new HashMap<>(); // Per frame, keep track of the keys we did not get updates for. // Added for no-change support. private Set<Long> noUpdates; private long updateTime = -1; // The active zones private final Map<ZoneKey,Zone> zones = new ConcurrentHashMap<>(16, 0.75f, 2); private final Lock historyLock = new ReentrantLock(); private final Set<Long> pendingRemoval = new HashSet<>(); // Keeps track of the frame times for a certain // block of history. private boolean collectHistory = false; private int historyBacklog; private long[] historyIndex; private int historySize = 0; // For perf tracking private long nextLog = 0; private long updateStartTime = 0; private long totalUpdateTime = 0; // Control which ZoneRange implementation is used... currently // there are only two and we'll default to the older better-tested // one for a while. private boolean dynamicZoneRange = false; // For frame rate limiting private int frameUnderflowLimit = 60; private int frameOverflowLimit = 70; /** * Creates a new ZoneManager with a ZoneGrid sized using zoneSize and * with a history backlog of 12 frames. */ public ZoneManager( int zoneSize ) { this(new ZoneGrid(zoneSize)); } /** * Creates a new ZoneManager with the specified grid representation and * with a history backlog of 12. */ public ZoneManager( ZoneGrid grid ) { this(grid, 12); } /** * Creates a new zone manager with the specified grid representation and * history backlog. * * @param grid The grid settings used for zone partitioning. * @param historyBacklog Designates how many frames of history to keep * in each zone. */ public ZoneManager( ZoneGrid grid, int historyBacklog ) { this.grid = grid; this.historyBacklog = historyBacklog; this.historyIndex = new long[historyBacklog]; } /** * Returns the current zone specification used for partioning space into * zones. */ public ZoneGrid getGrid() { return grid; } /** * Set to true to support objects that are larger than the grid spacing. * This is a new experimental feature that may become the default behavior * someday. In the mean time, applications have to specifically turn it * on because the new code is less tested. * The older internal zone range implementation would not support objects * that spanned more than two zones in any direction (and will log an error * when it encounters this). The thinking was that it could use a fixed size * array and avoid constantly recreating it. The thing is it was always * cloning it internally anyway whenever the range changed. * The new code builds its array dynamically and can essentially support * any zone range. It's probably just as good and just as memory efficient. */ public void setSupportLargeObjects( boolean b ) { this.dynamicZoneRange = b; } public boolean getSupportLargeObjects() { return dynamicZoneRange; } /** * Set to true if history should be collected or false if object updates * should be ignored. This method is used internal to the framework for * managing the lifecycle of dependent components. When a ZoneManager is * not part of an active state collection process then it's important that * it not collect any history because it might overflow its buffers since purge() * is never called. Generally, the StateCollector will turn history collection on * when it is ready to start periodically purging history. * Defaults to false until a state collection process turns it on. */ public void setCollectHistory( boolean b ) { this.collectHistory = b; } /** * Returns true if the ZoneManager is currently collecting history, false otherwise. * When a ZoneManager is not part of an active StateCollector then it's important * that it not track history. */ public boolean getCollectHistory() { return collectHistory; } public void setFrameRateLimits( int frameUnderflowLimit, int frameOverflowLimit ) { if( frameUnderflowLimit < 0 || frameOverflowLimit < 0 ) { throw new IllegalArgumentException("Frame limits must be positive."); } if( frameUnderflowLimit > frameOverflowLimit ) { throw new IllegalArgumentException("Frame underflow limit must be less than the overflow limit."); } this.frameUnderflowLimit = frameUnderflowLimit; this.frameOverflowLimit = frameOverflowLimit; } public void setFrameUnderflowLimit( int frameUnderflowLimit ) { if( frameUnderflowLimit < 0 ) { throw new IllegalArgumentException("Frame underflow limit must be positive."); } if( frameUnderflowLimit > frameOverflowLimit ) { throw new IllegalArgumentException("Frame underflow limit must be less than the overflow limit."); } this.frameUnderflowLimit = frameUnderflowLimit; } public int getFrameUnderflowLimit() { return frameUnderflowLimit; } public void setFrameOverflowLimit( int frameOverflowLimit ) { if( frameOverflowLimit < 0 ) { throw new IllegalArgumentException("Frame overflow limit must be positive."); } if( frameOverflowLimit < frameUnderflowLimit ) { throw new IllegalArgumentException("Frame overflow limit must be larger than the underflow limit."); } this.frameOverflowLimit = frameOverflowLimit; } public int getFrameOverflowLimit() { return frameOverflowLimit; } protected ZoneRange getZoneRange( Long id, boolean create ) { ZoneRange result = index.get(id); if( result == null && create ) { if( dynamicZoneRange ) { result = new DynamicZoneRange(id); } else { result = new OctZoneRange(id); } index.put(id, result); } return result; } long frameCounter = 0; long nextFrameTime = System.nanoTime() + 1000000000L; //long lastTime = 0; /** * Starts history collection for a frame at the specified time. All * updateEntity() and remove() calls after this beginUpdate() will be * collected together and associated with the specified frame time * until endUpdate() is called. */ public void beginUpdate( long time ) { if( log.isTraceEnabled() ) { log.trace("beginUpdate(" + time + ")"); } updateStartTime = System.nanoTime(); updateTime = time; /*if( lastTime > 0 ) { long delta = time - lastTime; System.out.println("zone time delta frame[" + timeCheckCounter + "]:" + ((delta)/1000000.0) + " ms"); } lastTime = time;*/ frameCounter++; if( updateStartTime > nextFrameTime ) { if( frameCounter < frameUnderflowLimit ) { log.warn("zone update underflow FPS:" + frameCounter); } else if( frameCounter > frameOverflowLimit ) { log.warn("zone update overflow FPS:" + frameCounter); } //System.out.println("zone update FPS:" + frameCounter); frameCounter = 0; nextFrameTime = System.nanoTime() + 1000000000L; } // Keep track of the IDs for objects that receive no updates. // (by subtraction) Added for no-update support. // Seed it with all known object IDs. noUpdates = new HashSet<>(index.keySet()); // Remove any of the pending deletes noUpdates.removeAll(pendingRemoval); for( Zone z : zones.values() ) { z.beginUpdate(time); } // Deactivate any pending entities for( Long id : pendingRemoval ) { if( log.isDebugEnabled() ) { log.debug("ZONE: --- delayed deactivation:" + id); } ZoneRange range = index.remove(id); if( log.isDebugEnabled() ) { log.debug("range:" + range); } if( range != null ) { range.leave(id); } } pendingRemoval.clear(); } /** * Updates an entity's position in the zone space. * * @param id The ID of the object that has been moved. * @param active Currently unused. Pass 'true' or the non-sleeping state of your object * if you care to be accurate for future changes. * @param p The position of the object in world space. * @param orientation The orientation of the object in world space. * @param bounds The 3D bounds of the object in WORLD SPACE. This is why it's passed * every update and it allows it to change to be accurate as the object rotates and * so on. But more importantly, it pushes the updating of the bounds to the thing * actually controlling the position which might be able to more efficiently update * it than we could internally. */ public void updateEntity( Long id, boolean active, Vec3d p, Quatd orientation, AaBBox bounds ) { if( log.isTraceEnabled() ) { log.trace("updateEntity(" + id + ", " + active + ", " + p + ")"); } // If one day you are looking in here and wondering why 'id' is a Long instead of // just 'long'... it's because we internally use it as a key for a bunch of things. // By exposing the object version to the caller they can avoid the excessive autoboxing // that would occure if we did it internally. By projecting outward, we can even // encourage the caller to also keep Long IDs and then the autoboxing never happens // but at the very least, we only do it once in here. // Updating a regular entity is an implied removal of the parent ID // if it previously had a parent ID. Otherwise, the parent version of // updateEntity() is the same... so we'll just delegate to it. -pspeed:2020-07-04 updateEntity(null, id, active, p, orientation, bounds); // Temporarily leaving the original code here just for easy reference. It // should be removed once we feel really solid about the other updateEntity() // method. -pspeed:2020-07-24 //Vec3i minZone = grid.worldToZone(bounds.getMin()); //Vec3i maxZone = grid.worldToZone(bounds.getMax()); //ZoneRange range = getZoneRange(id, true); //if( !minZone.equals(range.getMin()) || !maxZone.equals(range.getMax()) ) { // if( !range.setRange(minZone, maxZone) ) { // log.error("Error setting range for object:" + id // + " from bounds:" + bounds // + " grid size:" + grid.getZoneSize() // + " likely too small for object with extents:" + bounds.getExtents()); //// Now we blast an update to the zones for any listeners to handle. //range.sendUpdate(p.clone(), orientation.clone()); //// Mark that we've received an update for this object. Added for no-change support. //noUpdates.remove(id); } public void updateEntity( Long parent, Long child, boolean active, Vec3d p, Quatd orientation, AaBBox bounds ) { ZoneRange range = getZoneRange(child, true); range.setParent(parent); ZoneRange parentRange = parent == null ? null : getZoneRange(parent, false); if( parent != null && parentRange == null ) { log.warn("Child:" + child + " has no active parent:" + parent); } Vec3i minZone; Vec3i maxZone; if( parentRange == null ) { // Treat it like a world parent until we have a real // parent. // Clear the parent since we aren't using it range.setParent(null); minZone = grid.worldToZone(bounds.getMin()); maxZone = grid.worldToZone(bounds.getMax()); } else { // Children always adopt the parent's range. minZone = parentRange.getMin(); maxZone = parentRange.getMax(); } if( !minZone.equals(range.getMin()) || !maxZone.equals(range.getMax()) ) { if( !range.setRange(minZone, maxZone) ) { log.error("Error setting range for object:" + child + " from bounds:" + bounds + " grid size:" + grid.getZoneSize() + " likely too small for object with extents:" + bounds.getExtents()); } } // Now we blast an update to the zones for any listeners to handle. range.sendUpdate(p.clone(), orientation.clone()); // Mark that we've received an update for this object. Added for no-change support. noUpdates.remove(child); } /** * Called to end update collection for the current 'frame'. See: beginUpdate() */ public void endUpdate() { log.trace("endUpdate()"); // If we aren't really collecting history then don't do a commit. // We know how the zones push their history so doing this avoids // history accumulation. if( !collectHistory ) { return; } if( log.isTraceEnabled() ) { log.trace("No-updates for keys:" + noUpdates); } // Go through any of the objects that didn't get updates and send // no-update events. Added for no-change support. if( noUpdates != null && !noUpdates.isEmpty() ) { for( Long id : noUpdates ) { ZoneRange range = getZoneRange(id, false); if( range == null ) { log.warn("No zone range found for no-change key:" + id); continue; } range.sendNoChange(); } } // Obtain the general write lock for history // For all of the other data structures, we know we // are the only reader and so don't need any read locks. log.trace("writing history"); historyLock.lock(); try { // If we're about to overflow history then be a little // more graceful than throwing IndexOutOfBounds if( historySize + 1 >= historyIndex.length ) { log.warn("Pausing history collect. Overflow detected, current history size:" + historySize + " max:" + historyBacklog); return; } historyIndex[historySize++] = updateTime; for( Iterator<Map.Entry<ZoneKey,Zone>> i = zones.entrySet().iterator(); i.hasNext(); ) { Map.Entry<ZoneKey,Zone> e = i.next(); Zone z = e.getValue(); if( !z.commitUpdate() && z.isEmpty() ) { if( log.isDebugEnabled() ) { log.debug("Zone no longer active:" + e.getKey() + " active zones:" + zones.keySet() ); } // Now we can remove the zone i.remove(); } } } finally { log.trace("done writing history"); historyLock.unlock(); } updateTime = -1; long end = System.nanoTime(); totalUpdateTime += (end - updateStartTime); if( end > nextLog ) { nextLog = end + 1000000000L; totalUpdateTime = 0; } } /** * Called by a state collection process to return all of the history that * has been collected since the last call to purgeState(). Generally, this * method is called internal to the framework, usually by the StateCollector. * The return array will contain one StateFrame[] for every beginUpdate()/endUpdate() * block since the last purgeState(). Each StateFrame will contain all of the * state updates for that frame divided into separate StateBlocks, one per active * zone. */ public StateFrame[] purgeState() { // Obtain the general write lock for history since // we will be purging it historyLock.lock(); try { int high = 5; if( historySize > high ) { System.out.println( "Purging >" + high + " history frames:" + historySize ); } StateFrame[] state = new StateFrame[historySize]; // Go through each zone and merge its history into an array // of StateFrames. for( Iterator<Map.Entry<ZoneKey,Zone>> i = zones.entrySet().iterator(); i.hasNext(); ) { Map.Entry<ZoneKey,Zone> e = i.next(); Zone z = e.getValue(); StateBlock[] history = z.purgeHistory(); // Merge this zone's state blocks into the coinciding // StateFrames. int h = 0; for( StateBlock b : history ) { if( b.getTime() < historyIndex[h] ) { throw new RuntimeException( "StateBlock precedes history index. Time:" + b.getTime() + " history index:" + h + " history time:" + historyIndex[h] ); } // A given zone may have gaps in its history as compared to // global state. while( b.getTime() > historyIndex[h] ) { h++; } if( state[h] == null ) { state[h] = new StateFrame(historyIndex[h], zones.size()); } state[h].add(b); } } historySize = 0; return state; } finally { historyLock.unlock(); } } /** * Let's the zone manager know about a particular entity. This is * only required if remove() is used for objects that may come back * later... like for objects that enter/leave the zone manager if they * are awake/asleep. Essentially it just makes sure that the object * isn't pending removal on the next update. */ public void add( Long id ) { if( log.isDebugEnabled() ) { log.debug("ZONE: +++ activated:" + id); } pendingRemoval.remove(id); } /** * Removes the entity from the zone manager. This can also be * used to temporarily deactivate an entity but then add() must be * called if it is active again. */ public void remove( Long id ) { if( log.isDebugEnabled() ) { log.debug("ZONE: --- deactivated:" + id); } ZoneRange range = index.get(id); if( log.isDebugEnabled() ) { log.debug("range:" + range); } if( range == null ) { return; } // See if we are in the middle of a frame update or not if( updateTime < 0 ) { // Outside of a frame update we need to hold onto // the removal until we have proper history setup. // Save it for later if( log.isDebugEnabled() ) { log.debug("ZONE: --- pending:" + id); } pendingRemoval.add(id); } else { if( log.isDebugEnabled() ) { log.debug("ZONE: --- leaving zone:" + id); } // Should really check the thread also index.remove(id); range.leave(id); } } protected Zone getZone( ZoneKey key, boolean create ) { Zone result = zones.get(key); if( result == null && create ) { result = new Zone(key, historyBacklog); if( updateTime >= 0 ) { result.beginUpdate(updateTime); } zones.put(key, result); } return result; } /** * Sends the object update to the specified zone. If parent is null then * 'child' is a child of the world. */ protected void updateZoneObject( Long parent, Long id, Vec3d p, Quatd orientation, ZoneKey key ) { Zone zone = getZone(key, false); if( zone == null ) { log.warn( "Body is updating a zone that does not exist, id:" + id + ", zone:" + key ); return; } zone.update(parent, id, p, orientation); } protected void enterZone( Long id, ZoneKey key ) { if( log.isDebugEnabled() ) { log.debug("ZONE: enter zone:" + id + " " + key); } // Add this entity to the zone's children. // If there is no zone created yet then create one Zone zone = getZone(key, true); zone.addChild(id); } protected void leaveZone( Long id, ZoneKey key ) { if( log.isDebugEnabled() ) { log.debug("ZONE: leave zone:" + id + " " + key); } // Remove this body from the zone's children... // If the zone has no more children then remove it Zone zone = getZone(key, false); if( zone == null ) { log.warn( "Body is leaving zone that does not exist, id:" + id + ", zone:" + key ); return; } zone.removeChild(id); if( zone.isEmpty() ) { // We can't remove the zone until it is both empty // and devoid of state. We do that when we commit // the current block of state. // But we can call any activation listeners to let them // know it has been deactivated, I suppose. } } public static void main( String... args ) { ZoneGrid grid = new ZoneGrid(32); ZoneManager zones = new ZoneManager(grid); zones.beginUpdate(12345); zones.updateEntity(1L, true, new Vec3d(0, 0, 0), new Quatd(), new AaBBox(10)); zones.updateEntity(1L, true, new Vec3d(16, 16, 0), new Quatd(), new AaBBox(10)); zones.updateEntity(1L, true, new Vec3d(32, 16, 0), new Quatd(), new AaBBox(10)); zones.updateEntity(1L, true, new Vec3d(48, 16, 0), new Quatd(), new AaBBox(10)); } private ZoneKey createKey( int x, int y, int z ) { return new ZoneKey(grid, x, y, z); } protected interface ZoneRange { public Vec3i getMin(); public Vec3i getMax(); public boolean setRange( Vec3i newMin, Vec3i newMax ); public void sendUpdate( Vec3d p, Quatd orientation ); public void sendNoChange(); public void leave( Long id ); public void setParent( Long parent ); public Long getParent(); } /** * The original ZoneRange implementation that maxed out * at 8 zones, ie: 2x2x2. It keeps a fixed array of zone keys * and nulls out the ones that aren't being used. * I think the original thinking was that we avoid array creation * churn... but it also limits the size of objects to never be any * bigger than a zone cell. Besides which we are recreating * keys at least as often as we might the array. */ protected final class OctZoneRange implements ZoneRange { Long id; Long parent; Vec3i min; Vec3i max; // Keys go like: // min.y // min.x max.x // min.z 0 1 // max.z 3 2 // max.y // min.x max.x // min.z 4 5 // max.z 7 6 ZoneKey[] keys = new ZoneKey[8]; // For purposes of handling 'no-change' updates, we will keep // the last state we received. Added for no-updated support. Vec3d lastPosition; Quatd lastOrientation; public OctZoneRange( Long id ) { this.id = id; } @Override public Vec3i getMin() { return min; } @Override public Vec3i getMax() { return max; } private boolean contains( int x, int y, int z ) { if( x < min.x || y < min.y || z < min.z ) return false; if( x > max.x || y > max.y || z > max.z ) return false; return true; } @Override public void sendUpdate( Vec3d p, Quatd orientation ) { // They were cloned before giving them to us, safe // to keep them directly. Added for no-updated support. lastPosition = p; lastOrientation = orientation; if( keys[0] != null ) { updateZoneObject(parent, id, p, orientation, keys[0]); } if( keys[1] != null ) { updateZoneObject(parent, id, p, orientation, keys[1]); } if( keys[2] != null ) { updateZoneObject(parent, id, p, orientation, keys[2]); } if( keys[3] != null ) { updateZoneObject(parent, id, p, orientation, keys[3]); } } @Override public void sendNoChange() { // Nothing special here... just resend the last data. // Someday maybe there is something optimized? Don't // know what and doesn't matter today. Added for no-change support. sendUpdate(lastPosition, lastOrientation); } @Override public boolean setRange( Vec3i newMin, Vec3i newMax ) { boolean result = true; // Check the range to see if it's too large... this indicates that // the bounds is too big for the grid spacing. if( newMax.x - newMin.x > 1 || newMax.y - newMin.y > 1 || newMax.z - newMin.z > 1 ) { log.error("OctZoneRange: Range too big:" + newMin + " -> " + newMax); result = false; } ZoneKey[] oldKeys = keys.clone(); // We could avoid recreating keys if they are already // set but the logic is tricky to get right and it's // not called very often anyway. // Create all of the min.y keys first and we will // project them if max.y != min.y keys[0] = createKey(newMin.x, newMin.y, newMin.z); if( newMin.x != newMax.x ) keys[1] = createKey(newMax.x, newMin.y, newMin.z); else keys[1] = null; if( newMin.z != newMax.z ) keys[3] = createKey(newMin.x, newMin.y, newMax.z); else keys[3] = null; if( keys[1] != null && keys[3] != null ) keys[2] = createKey(newMax.x, newMin.y, newMax.z); else keys[2] = null; if( newMin.y != newMax.y ) { // Need to project them up keys[4] = keys[0] == null ? null : createKey(keys[0].x, newMax.y, keys[0].z); keys[5] = keys[1] == null ? null : createKey(keys[1].x, newMax.y, keys[1].z); keys[6] = keys[2] == null ? null : createKey(keys[2].x, newMax.y, keys[2].z); keys[7] = keys[3] == null ? null : createKey(keys[3].x, newMax.y, keys[3].z); } else { // Null them all out keys[4] = null; keys[5] = null; keys[6] = null; keys[7] = null; } if( this.min == null ) { // Then this is the first time and we can be optimized to // just enter all of them. this.min = newMin; this.max = newMax; enter(id); return result; } enterMissing( id, newMin, newMax, keys ); Vec3i oldMin = this.min; Vec3i oldMax = this.max; this.min = newMin; this.max = newMax; leaveMissing( id, oldMin, oldMax, oldKeys ); return result; } private void enter( Long id ) { for( ZoneKey key : keys ) { if( key != null ) { enterZone(id, key); } } } @Override public void leave( Long id ) { if( log.isDebugEnabled() ) { log.debug("OctZoneRange.leave(" + id + ") keys:" + Arrays.asList(keys)); } for( ZoneKey key : keys ) { if( key != null ) { leaveZone(id, key); } } } private void enterMissing( Long id, Vec3i minZone, Vec3i maxZone, ZoneKey[] zoneKeys ) { // See which new zone keys are not in the current range for( ZoneKey key : zoneKeys ) { if( key != null && !contains(key.x, key.y, key.z) ) { enterZone(id, key); } } } private void leaveMissing( Long id, Vec3i minZone, Vec3i maxZone, ZoneKey[] zoneKeys ) { // See which old zone keys are not in the current range for( ZoneKey key : zoneKeys ) { if( key != null && !contains(key.x, key.y, key.z) ) { leaveZone(id, key); } } } public void setParent( Long parent ) { this.parent = parent; } public Long getParent() { return parent; } } protected final class DynamicZoneRange implements ZoneRange { Long id; Long parent; Vec3i min; Vec3i max; ZoneKey[] keys = new ZoneKey[0]; int keyCount; // For purposes of handling 'no-change' updates, we will keep // the last state we received. Added for no-updated support. Vec3d lastPosition; Quatd lastOrientation; public DynamicZoneRange( Long id ) { this.id = id; } @Override public Vec3i getMin() { return min; } @Override public Vec3i getMax() { return max; } private boolean contains( int x, int y, int z ) { if( x < min.x || y < min.y || z < min.z ) return false; if( x > max.x || y > max.y || z > max.z ) return false; return true; } @Override public void sendUpdate( Vec3d p, Quatd orientation ) { // They were cloned before giving them to us, safe // to keep them directly. Added for no-updated support. lastPosition = p; lastOrientation = orientation; for( int i = 0; i < keyCount; i++ ) { updateZoneObject(parent, id, p, orientation, keys[i]); } } @Override public void sendNoChange() { // Nothing special here... just resend the last data. // Someday maybe there is something optimized? Don't // know what and doesn't matter today. Added for no-change support. sendUpdate(lastPosition, lastOrientation); } @Override public boolean setRange( Vec3i newMin, Vec3i newMax ) { ZoneKey[] oldKeys = keys.clone(); int oldKeyCount = keyCount; int xSize = newMax.x - newMin.x + 1; int ySize = newMax.y - newMin.y + 1; int zSize = newMax.z - newMin.z + 1; int size = xSize * ySize * zSize; if( oldKeys.length < size || oldKeys.length > size * 2 ) { // Grow or shrink it. We shrink if our keys are less than // half the old size just to avoid taking up too much RAM. // ...and to avoid potential memory explosions for large objects // that never shrink again. keys = new ZoneKey[size]; } keyCount = size; int index = 0; for( int i = 0; i < xSize; i++ ) { for( int j = 0; j < ySize; j++ ) { for( int k = 0; k < zSize; k++ ) { keys[index] = createKey(newMin.x + i, newMin.y + j, newMin.z + k); index++; } } } if( this.min == null ) { // Then this is the first time and we can be optimized to // just enter all of them. this.min = newMin; this.max = newMax; enter(id); return true; } enterMissing(id, newMin, newMax, keys, keyCount); Vec3i oldMin = this.min; Vec3i oldMax = this.max; this.min = newMin; this.max = newMax; leaveMissing(id, oldMin, oldMax, oldKeys, oldKeyCount); return true; } private void enter( Long id ) { for( int i = 0; i < keyCount; i++ ) { enterZone(id, keys[i]); } } @Override public void leave( Long id ) { if( log.isDebugEnabled() ) { log.debug("DynamicZoneRange.leave(" + id + ") keys:" + Arrays.asList(keys)); } if( (long)id != (long)this.id ) { log.warn("How would this ever happen: id:" + id + " this.id:" + this.id); } for( int i = 0; i < keyCount; i++ ) { leaveZone(id, keys[i]); } } private void enterMissing( Long id, Vec3i minZone, Vec3i maxZone, ZoneKey[] zoneKeys, int count ) { // See which new zone keys are not in the current range for( int i = 0; i < count; i++ ) { ZoneKey key = zoneKeys[i]; if( !contains(key.x, key.y, key.z) ) { enterZone(id, key); } } } private void leaveMissing( Long id, Vec3i minZone, Vec3i maxZone, ZoneKey[] zoneKeys, int count ) { // See which old zone keys are not in the current range for( int i = 0; i < count; i++ ) { ZoneKey key = zoneKeys[i]; if( !contains(key.x, key.y, key.z) ) { leaveZone(id, key); } } } public void setParent( Long parent ) { this.parent = parent; } public Long getParent() { return parent; } @Override public String toString() { return "DynamicZoneRange[" + id + ", " + min + ", " + max + "]"; } } }
package com.sixtyfour.cbmnative; import java.util.ArrayList; import java.util.List; import com.sixtyfour.Logger; import com.sixtyfour.config.CompilerConfig; /** * An optimizer for the native code in pseudo assembly language. * * @author EgonOlsen * */ public class NativeOptimizer { private final static int MAX_AHEAD = 15; private static List<NativePattern> patterns = new ArrayList<NativePattern>(); private static boolean optimizeSimpleForPokeLoops = true; static { patterns.add(new NativePattern(new String[] { "PUSH*", "POP*" }, new String[] { "MOV p1,p0" })); patterns.add(new NativePattern(new String[] { "PUSH X", "MOV C*|*[]*", "POP Y" }, new String[] { "{1}" })); patterns.add(new NativePattern(new String[] { "PUSH Y", "MOV Y,*", "POP X" }, new String[] { "MOV X,Y", "{1}" })); patterns.add(new NativePattern(new String[] { "MOV Y,#*", "MOV X,#-1{INTEGER}", "MUL X,Y" }, new String[] { "{0:MOV Y,#>MOV X,#-}" })); patterns.add(new NativePattern(new String[] { "MOV Y,*", "MOV X,Y" }, new String[] { "{0:MOV Y,>MOV X,}" })); patterns.add(new NativePattern(new String[] { "MOV B,*", "MOV A,B" }, new String[] { "{0:MOV B,>MOV A,}" })); patterns.add(new NativePattern(new String[] { "MOV Y*", "PUSH Y", "JSR COMPACT", "MOV A*", "POP X" }, new String[] { "{2}", "{3}", "{0:MOV Y,>MOV X,}" })); patterns.add(new NativePattern(new String[] { "MOV Y*", "PUSH Y", "MOV A*", "POP X" }, new String[] { "{2}", "{0:MOV Y,>MOV X,}" })); patterns.add(new NativePattern(new String[] { "PUSH X", "JSR COMPACT", "MOV A*", "POP X" }, new String[] { "{1}", "{2}" })); patterns.add(new NativePattern(new String[] { "PUSH X", "MOV A*", "POP X" }, new String[] { "{1}" })); patterns.add(new NativePattern(new String[] { "MOV Y,X", "MOV X*", "ADD X,Y" }, new String[] { "{1:MOV X,>MOV Y,}", "{2}" })); patterns.add(new NativePattern(new String[] { "MOV Y,X", "MOV X*", "MUL X,Y" }, new String[] { "{1:MOV X,>MOV Y,}", "{2}" })); patterns.add(new NativePattern(new String[] { "PUSH C", "CHGCTX #1", "MOV B*", "POP C" }, new String[] { "{1}", "{2}" })); patterns.add(new NativePattern(new String[] { "MOV X,X" }, new String[] {})); patterns.add(new NativePattern(new String[] { "MOV Y,Y" }, new String[] {})); patterns.add(new NativePattern(new String[] { "PUSH X", "MOV X,#*", "POP Y" }, new String[] { "MOV Y,X", "{1}" })); patterns.add(new NativePattern(new String[] { "PUSH Y", "MOV X,#*", "POP Y" }, new String[] { "{1}" })); patterns.add(new NativePattern(new String[] { "MOV X,#*", "MOVB (Y),X" }, new String[] { "{0:MOV X,>MOVB (Y),}" })); patterns.add(new NativePattern(new String[] { "MOV Y,#*", "MOV G,Y" }, new String[] { "{0:MOV Y,>MOV G,}" })); patterns.add(new NativePattern(new String[] { "MOV X,#*", "MOV G,Y" }, new String[] { "{0:MOV X,>MOV G,}" })); patterns.add(new NativePattern(new String[] { "INT X,Y", "INT X,X" }, new String[] { "{0}" })); patterns.add(new NativePattern(new String[] { "POP C", "PUSH C" }, new String[] {})); // The // #-method // introduced // this...we // can // handle // here // more // easily // than // avoid // the // actual // creation. patterns.add(new NativePattern(new String[] { "PUSH C", "MOV C*", "PUSH C", "CHGCTX #1", "MOV B*", "POP D", "POP C" }, new String[] { "{1:MOV C,>MOV D,}", "{3}", "{4}" })); // The fact that NOPs are inserted between expressions now kills the // fastfor-optimizer. This little hack revives it... patterns.add(new NativePattern(new String[] { "MOV Y,#*", "PUSH Y", "NOP", "MOV Y,#*", "PUSH Y", "NOP" }, new String[] { "{0}", "{1}", "{3}", "{4}" })); } public static List<String> optimizeNative(CompilerConfig config, List<String> code, ProgressListener pg) { if (config.isIntermediateLanguageOptimizations()) { Logger.log("Running intermediate code optimizer..."); code = optimizeNativeInternal(config, code, pg); } return code; } static List<String> optimizeNativeInternal(CompilerConfig config, List<String> code, ProgressListener pg) { if (config.isIntermediateLanguageOptimizations()) { int oldCode = 0; if (pg != null) { pg.start(); } do { if (pg != null) { pg.nextStep(); } oldCode = code.size(); code = applyPatterns(config, code); } while (oldCode != code.size()); if (pg != null) { pg.done(); } } return code; } private static List<String> applyPatterns(CompilerConfig config, List<String> code) { List<String> ret = new ArrayList<String>(); String[] lines = new String[MAX_AHEAD]; String[][] splittedLines = new String[MAX_AHEAD][]; if (code.size() > 1) { for (int i = 0; i < code.size() - 1; i++) { boolean cont = false; int p = 0; String line0 = code.get(i); for (; p < MAX_AHEAD && p + i < code.size(); p++) { String line = code.get(p + i); lines[p] = line; splittedLines[p] = lines[p].split(" |,"); } for (; p < MAX_AHEAD; p++) { lines[p] = null; splittedLines[p] = null; } for (NativePattern pattern : patterns) { String[] toReplace = pattern.getToReplace(); String[] replaceWith = pattern.getReplaceWith(); boolean match = true; for (p = 0; p < toReplace.length; p++) { if (lines[p] == null) { match = false; break; } String sf = toReplace[p]; String[] parts = sf.split("\\|"); boolean subMatch = true; for (String sfs : parts) { String sfo = sfs.replace("*", ""); if ((sfs.startsWith("*") && sfs.endsWith("*") && lines[p].contains(sfo)) || (sfs.startsWith("*") && lines[p].endsWith(sfo) || (sfs.endsWith("*") && lines[p].startsWith(sfo)) || sfs.equals(lines[p]))) { subMatch = true; } else { subMatch = false; break; } } match = subMatch; if (!match) { break; } } if (match) { for (p = 0; p < replaceWith.length; p++) { String rw = replaceWith[p]; String rs = null; if (rw != null && !rw.isEmpty()) { if (rw.startsWith("{") && rw.endsWith("}")) { int pos = rw.indexOf(":"); String num = null; if (pos == -1) { num = rw.substring(1, rw.length() - 1); } else { num = rw.substring(1, pos); } rs = lines[Integer.parseInt(num)]; if (pos != -1) { int pos2 = rw.indexOf(">", pos); rs = rs.replace(rw.substring(pos + 1, pos2), rw.substring(pos2 + 1, rw.length() - 1)); } } if (rs == null) { rs = replaceWith[p]; for (int u = 0; u < MAX_AHEAD && splittedLines[u] != null; u++) { if (splittedLines[u].length > 1) { rs = rs.replace("p" + u, splittedLines[u][1]); } } } } ret.add(rs); } cont = true; i += toReplace.length - 1; // System.out.println("Applied: " + // Arrays.toString(pattern.toReplace)); } } if (cont) { continue; } // Special optimizations without a pattern definition... if (config.isIntOptimizations()) { // Not doing these optimizations also disables the // corresponding ones in the native optimizer, because it // will then never encounter a JSR FXXX call... // MOV Y,#1{INTEGER} // MOV X,T%{INTEGER} // ADD X,Y // This is actually not that great in itself, but the native // optimizer can build upon it... if (lines[0].equals("MOV Y,#1{INTEGER}") && lines[1].startsWith("MOV X") && lines[1].endsWith("%{INTEGER}") && lines[2].equals("ADD X,Y")) { ret.add(lines[1]); ret.add("JSR FINX"); i += 2; continue; } // MOV Y,#1{INTEGER} // MOV X,R%{INTEGER} // SUB X,Y // ...this neither... if (lines[0].equals("MOV Y,#1{INTEGER}") && lines[1].startsWith("MOV X") && lines[1].endsWith("%{INTEGER}") && lines[2].equals("SUB X,Y")) { ret.add(lines[1]); ret.add("JSR FDEX"); i += 2; continue; } } // MOV Y,#128{INTEGER} // MOV X,U{REAL} // DIV X,Y if (lines[0].startsWith("MOV Y,#") && lines[0].endsWith("{INTEGER}") && lines[1].startsWith("MOV X,") && lines[2].equals("DIV X,Y")) { String val = lines[0].replace("MOV Y,#", "").replace("{INTEGER}", ""); float vf = Float.parseFloat(val); vf = (float) (Math.log(vf) / Math.log(2)); if (vf == (int) vf && vf >= 1 && vf <= 8) { ret.add("MOV A,#" + (int) vf + "{INTEGER}"); ret.add(lines[1]); ret.add("SHR X,A"); i += 2; continue; } } // MOV Y,#128{INTEGER} // MOV X,U{REAL} // MUL X,Y if (lines[0].startsWith("MOV Y,#") && lines[0].endsWith("{INTEGER}") && lines[1].startsWith("MOV X,") && lines[2].equals("MUL X,Y")) { String val = lines[0].replace("MOV Y,#", "").replace("{INTEGER}", ""); float vf = Float.parseFloat(val); vf = (float) (Math.log(vf) / Math.log(2)); if (vf == (int) vf && vf >= 1 && vf <= 8) { ret.add("MOV A,#" + (int) vf + "{INTEGER}"); ret.add(lines[1]); ret.add("SHL X,A"); i += 2; continue; } } // MOV Y,#128{INTEGER} // DIV X,Y if (lines[0].startsWith("MOV Y,#") && lines[0].endsWith("{INTEGER}") && lines[1].equals("DIV X,Y")) { String val = lines[0].replace("MOV Y,#", "").replace("{INTEGER}", ""); float vf = Float.parseFloat(val); vf = (float) (Math.log(vf) / Math.log(2)); if (vf == (int) vf && vf >= 1 && vf <= 8) { ret.add("MOV A,#" + (int) vf + "{INTEGER}"); ret.add("SHR X,A"); i += 1; continue; } } // MOV Y,#128{INTEGER} // MUL X,Y if (lines[0].startsWith("MOV Y,#") && lines[0].endsWith("{INTEGER}") && lines[1].equals("MUL X,Y")) { String val = lines[0].replace("MOV Y,#", "").replace("{INTEGER}", ""); float vf = Float.parseFloat(val); vf = (float) (Math.log(vf) / Math.log(2)); if (vf == (int) vf && vf >= 1 && vf <= 8) { ret.add("MOV A,#" + (int) vf + "{INTEGER}"); ret.add("SHL X,A"); i += 1; continue; } } // MOV X,#6{INTEGER} // MOVB 53280,X if (lines[0].startsWith("MOV X,#") && lines[1].startsWith("MOVB") && lines[1].endsWith(",X") && !lines[1].contains("(")) { ret.add(lines[1].replace(",X", lines[0].substring(lines[0].indexOf(",")))); i += 1; continue; } if (lines[0].contains("INTEGER") && lines[0].startsWith("MOV Y,#") && (lines[1].equals("MOV X,(Y)") || lines[1].equals("MOVB X,(Y)"))) { try { int addr = Integer.parseInt(lines[0].substring(lines[0].indexOf("#") + 1, lines[0].indexOf("{"))); if (lines[1].equals("MOVB X,(Y)")) { ret.add("MOVB X," + addr); } else { ret.add("MOV X," + addr); } i += 1; continue; } catch (Exception e) { } } if (splittedLines[0].length == 3 && splittedLines[1].length == 3) { if (splittedLines[0][0].equals("MOV") && splittedLines[0][2].equals("X")) { if (splittedLines[1][1].equals("Y") && splittedLines[0][1].equals(splittedLines[1][2]) && splittedLines[0][1].contains("{")) { ret.add(lines[0]); ret.add("MOV Y,X"); i += 1; continue; } } else if (splittedLines[0][0].equals("MOV") && splittedLines[0][2].equals("Y")) { if (splittedLines[1][1].equals("X") && splittedLines[0][1].equals(splittedLines[1][2]) && splittedLines[0][1].contains("{")) { ret.add(lines[0]); ret.add("MOV X,Y"); i += 1; continue; } } } if (splittedLines[2] != null && splittedLines[2].length > 2 && splittedLines[0].length > 2 && lines[3] != null && splittedLines[0][0].equals("MOV") && splittedLines[0][2].equals("X") && splittedLines[2][2].equals(splittedLines[0][1]) && lines[1].startsWith("MOV Y") && (lines[3].equals("ADD X,Y") || lines[3].equals("SUB X,Y") || lines[3].equals("MUL X,Y") || lines[3].equals("DIV X,Y"))) { ret.add(lines[0]); ret.add(lines[1]); ret.add(lines[3]); i += 3; continue; } // Detect and replace simple for-poke-loops if (optimizeSimpleForPokeLoops && lines[14] != null) { if (lines[0].startsWith("MOV Y,") && (lines[0].endsWith("{INTEGER}") || lines[0].endsWith(".0{REAL}")) && lines[1].equals("PUSH Y") && lines[2].startsWith("MOV Y,") && (lines[2].endsWith("{INTEGER}") || lines[2].endsWith(".0{REAL}"))) { if (lines[3].equals("PUSH Y") && lines[4].startsWith("MOV Y,") && (lines[4].endsWith("{INTEGER}") || lines[4].endsWith(".0{REAL}")) && lines[5].startsWith("MOV") && lines[5].endsWith(",Y")) { if (lines[6].startsWith("MOV A,(") && lines[7].equals("JSR INITFOR") && lines[8].startsWith("MOV Y,") && lines[9].equals("PUSH Y") && lines[10].startsWith("MOV X,")) { if (lines[10].endsWith("}") && lines[11].equals("POP Y") && lines[12].equals("MOVB (Y),X") && lines[13].startsWith("MOV A,") && lines[14].equals("JSR NEXT")) { String[] parts = lines[5].split(" |\\{"); String var = parts[1]; if (lines[13].contains(var + "{}") || lines[13].contains(" ret.add(lines[0]); ret.add(lines[1]); ret.add(lines[2]); ret.add(lines[3]); ret.add(lines[4]); ret.add(lines[5]); ret.add(lines[6]); ret.add(lines[10]); ret.add("JSR FASTFOR"); i += 14; continue; } } } } } } // Opti2 boolean rep = false; for (char c : new char[] { 'C', 'D' }) { if (lines[1].startsWith("MOV " + c + ",")) { if (lines[0].startsWith("MOV ")) { int pos = lines[0].indexOf(","); String r0 = lines[0].substring(4, pos).trim(); String r1 = lines[1].substring(6).trim(); if (r0.equals(r1)) { String right = lines[0].substring(pos + 1).trim(); ret.add("MOV " + c + "," + right); rep = true; break; } } } } if (!rep) { ret.add(line0); } else { i++; } } ret.add(code.get(code.size() - 1)); } else { ret.addAll(code); } return ret; } private static class NativePattern { private String[] toReplace; private String[] replaceWith; public NativePattern(String[] toReplace, String[] replaceWith) { this.toReplace = toReplace; this.replaceWith = replaceWith; } public String[] getToReplace() { return toReplace; } public String[] getReplaceWith() { return replaceWith; } } }
package ethanjones.cubes.launcher; import org.apache.commons.net.ftp.*; import javax.swing.*; import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.MessageDigest; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; public class CubesLauncher { public static final String FTP_ADDRESS = "cubes.ethanjones.me"; public static final String FTP_RELEASES_PATH = "maven/releases/ethanjones/cubes/client/"; public static final String FTP_SNAPSHOTS_PATH = "maven/snapshots/ethanjones/cubes/client/"; public static final String JAVA_CLASS = "ethanjones.cubes.core.platform.desktop.ClientLauncher"; public static final HashMap<String, Version> versions = new HashMap<String, Version>(); public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new VersionWindow(); } }); downloadVersions(); System.out.println(versions.toString()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { VersionWindow.INSTANCE.setVersions(); } }); } private static void downloadVersions() { FTPClient ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftp.configure(config); boolean error = false; try { int reply; ftp.connect(FTP_ADDRESS); System.out.println(ftp.getReplyString()); if (!FTPReply.isPositiveCompletion(reply = ftp.getReplyCode())) { ftp.disconnect(); throw new LauncherException("Failed to connect to ftp server " + reply); } ftp.user("ftp"); if (!FTPReply.isPositiveCompletion(reply = ftp.getReplyCode())) { ftp.disconnect(); throw new LauncherException("Failed to set ftp user " + reply); } FTPFile[] releasesDirectories = ftp.listDirectories(FTP_RELEASES_PATH); for (FTPFile ftpDirectory : releasesDirectories) { String v = ftpDirectory.getName(); String path = FTP_RELEASES_PATH + v + "/client-" + v + ".jar"; versions.put(v, new Version(v, true, path)); } FTPFile[] snapshotsDirectories = ftp.listDirectories(FTP_SNAPSHOTS_PATH); for (FTPFile ftpDirectory : snapshotsDirectories) { String v = ftpDirectory.getName(); FTPFile[] ftpFiles = ftp.listFiles(FTP_SNAPSHOTS_PATH + v, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { return file.getName().endsWith(".jar"); } }); Arrays.sort(ftpFiles, new Comparator<FTPFile>() { @Override public int compare(FTPFile o1, FTPFile o2) { return o1.getName().compareTo(o2.getName()); } }); FTPFile file = ftpFiles[ftpFiles.length - 1]; String path = FTP_SNAPSHOTS_PATH + v + "/" + file.getName(); versions.put(v, new Version(v, false, path)); } for (Version version : versions.values()) { InputStream inputStream = null; try { inputStream = ftp.retrieveFileStream(version.downloadPath + ".sha1"); byte[] bytes = new byte[40]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = inputStream.read(bytes, bytesRead, bytes.length - bytesRead); } boolean success = ftp.completePendingCommand(); inputStream.close(); if (success) { String stringHash = new String(bytes, "ASCII"); byte[] hash = hexStringToByteArray(stringHash); version.setSHA1Hash(stringHash, hash); } else { throw new LauncherException("Failed to download hash "); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ignored) { } } } } ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignored) { } } } if (error) throw new LauncherException("Error whilst downloading versions"); } public static void run(Version version) { File baseFolder = getBaseFolder(); File launcherFolder = new File(baseFolder, "launcher"); File versionFolder = new File(launcherFolder, "versions"); versionFolder.mkdirs(); File jarFile = new File(versionFolder, version.name + ".jar"); boolean update = true; if (jarFile.exists()) { byte[] fileHash = sha1HashFile(jarFile); if (Arrays.equals(fileHash, version.getExpectedHash())) { System.out.println(jarFile + " matches hash: " + version.getExpectedHashString()); update = false; } else { System.out.println(jarFile + " does not matches hash: " + version.getExpectedHashString()); jarFile.delete(); } } if (update) { downloadFile(version.downloadPath, jarFile); } try { URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(classLoader, jarFile.toURI().toURL()); method.setAccessible(false); Class c = Class.forName(JAVA_CLASS); final Method main = c.getDeclaredMethod("main", String[].class); new Thread() { @Override public void run() { try { main.invoke(null, (Object) new String[0]); } catch (Exception e) { throw new LauncherException("Failed to start client", e); } } }.run(); } catch (Exception e) { throw new LauncherException("Failed to start client", e); } } private static void downloadFile(String remote, File local) { FTPClient ftp = new FTPClient(); FTPClientConfig config = new FTPClientConfig(); ftp.configure(config); boolean error = false; try { int reply; ftp.connect(FTP_ADDRESS); System.out.println(ftp.getReplyString()); if (!FTPReply.isPositiveCompletion(reply = ftp.getReplyCode())) { ftp.disconnect(); throw new LauncherException("Failed to connect to ftp server"); } ftp.user("ftp"); if (!FTPReply.isPositiveCompletion(reply = ftp.getReplyCode())) { ftp.disconnect(); throw new LauncherException("Failed to set ftp user"); } if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) { ftp.disconnect(); throw new LauncherException("Failed to set ftp file type"); } OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(local)); boolean success = ftp.retrieveFile(remote, outputStream); if (!success) { throw new LauncherException("Failed to download " + remote); } } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException ignored) { } } } ftp.logout(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignored) { } } } if (error) throw new LauncherException("Error whilst downloading file " + remote); } private static byte[] hexStringToByteArray(String s) { if (s.length() % 2 != 0) throw new LauncherException("Invalid length hex string"); int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); } return data; } private static byte[] sha1HashFile(File file) { MessageDigest digest = null; InputStream fis = null; try { digest = MessageDigest.getInstance("SHA-1"); fis = new FileInputStream(file); int n = 0; byte[] buffer = new byte[8192]; while (n != -1) { n = fis.read(buffer); if (n > 0) { digest.update(buffer, 0, n); } } } catch (Exception e) { throw new LauncherException("Failed to sha1 hash file", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignored) { } } } return digest.digest(); } private static File getBaseFolder() { File homeDir = new File(System.getProperty("user.home")); String str = (System.getProperty("os.name")).toUpperCase(); if (str.contains("WIN")) { return new File(System.getenv("APPDATA"), "Cubes"); } else if (str.contains("MAC")) { return new File(new File(new File(homeDir, "Library"), "Application Support"), "Cubes"); } else { return new File(homeDir, ".Cubes"); } } }
package com.techcavern.wavetact.utils; import com.techcavern.wavetact.utils.databaseUtils.PermChannelUtils; import com.techcavern.wavetact.utils.objects.AuthedUser; import org.pircbotx.Channel; import org.pircbotx.PircBotX; import org.pircbotx.User; import org.pircbotx.hooks.events.WhoisEvent; public class PermUtils { public static String getPrivateAccount(PircBotX bot, String userObject, String hostmask){ String authtype = GetUtils.getAuthType(bot); if(authtype.equals("nickserv")) return getAuthedNickServUser(bot, userObject, hostmask); else if(authtype.equals("account")) return getAuthedUser(bot, userObject, hostmask); else{ return userObject; } } public static String getAuthedAccount(PircBotX bot, String userObject){ String hostmask = IRCUtils.getIRCHostmask(bot, userObject); if(hostmask != null) return getPrivateAccount(bot, userObject, hostmask); else return null; } public static String getAuthedNickServUser(PircBotX bot, String userObject, String hostmask){ String userString = getAuthedUser(bot, userObject, hostmask); if(userString == null){ userString = getAccountName(bot, userObject); if(userString != null) GeneralRegistry.AuthedUsers.add(new AuthedUser(bot.getServerInfo().getServerName(),userString, hostmask )); } return userString; } public static String getAuthedUser(PircBotX bot, String userObject, String hostmask){ String userString = null; for(AuthedUser user:GeneralRegistry.AuthedUsers){ if(user.getAuthHostmask().equals(hostmask) && user.getAuthNetwork().equals(bot.getServerInfo().getServerName())){ userString = user.getAuthAccount(); } } if(hostmask == null){ return userObject; }else{ return userString; } } public static AuthedUser getAuthUser(PircBotX bot, String userObject){ String hostmask = IRCUtils.getIRCHostmask(bot, userObject); for(AuthedUser user:GeneralRegistry.AuthedUsers){ if(user.getAuthHostmask().equals(hostmask) && user.getAuthNetwork().equals(bot.getServerInfo().getServerName())){ return user; } } return null; } @SuppressWarnings("unchecked") public static String getAccountName(PircBotX bot, String userObject) { WhoisEvent whois = IRCUtils.WhoisEvent(bot, userObject); String userString; if (whois.getNick() != null) { userString = whois.getRegisteredAs(); if(userString != null){ userString = userString.toLowerCase(); if (userString.isEmpty()){ userString = userObject.toLowerCase(); } }else{ userString = null; } } else { userString = null; } return userString; } private static int getAutomaticPermLevel(User userObject, Channel channelObject) { if (userObject.isIrcop()) { return 20; } else if (channelObject.isOwner(userObject)) { return 15; } else if (channelObject.isSuperOp(userObject)) { return 13; } else if (channelObject.isOp(userObject)) { return 10; } else if (channelObject.isHalfOp(userObject)) { return 7; } else if (channelObject.hasVoice(userObject)) { return 5; } else { return 0; } } private static int getManualPermLevel(PircBotX bot, String userObject, Channel channelObject, String account) { if (account != null) { if (GetUtils.getControllerByNick(account) != null) { return 9001; } if (GetUtils.getGlobalByNick(account, bot.getServerInfo().getServerName()) != null) { return 20; } if (PermChannelUtils.getPermLevelChannel(bot.getServerInfo().getNetwork(), account, channelObject.getName()) != null) { return PermChannelUtils.getPermLevelChannel(bot.getServerInfo().getNetwork(), account, channelObject.getName()).getPermLevel(); } else { return 0; } } else { return 0; } } public static int getPermLevel(PircBotX bot, String userObject, Channel channelObject){ String auth = PermUtils.getAuthedAccount(bot, userObject); if(auth != null){ return getAuthPermLevel(bot, userObject, channelObject, auth); }else{ return getAuthPermLevel(bot, userObject, channelObject, userObject); } } public static int getAuthPermLevel(PircBotX bot, String userObject, Channel channelObject, String account) { if (channelObject != null) { int mpermlevel = getManualPermLevel(bot, userObject, channelObject, account); User user = GetUtils.getUserByNick(bot,userObject); int apermlevel = 0; if(user != null) { apermlevel = getAutomaticPermLevel(user, channelObject); } if (mpermlevel < 0) { return mpermlevel; } else if (apermlevel < mpermlevel) { return mpermlevel; } else { return apermlevel; } } else { if (account != null) { if (GetUtils.getControllerByNick(account) != null) { return 9001; } else if (GetUtils.getGlobalByNick(account, bot.getServerInfo().getServerName()) != null) { return 20; } else { return 3; } } else { return 3; } } } public static boolean checkIfAccountEnabled(PircBotX bot){ if(GetUtils.getAuthType(bot).equalsIgnoreCase("account")){ return true; }else{ return false; } } }
package eu.e43.impeller.fragment; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; import eu.e43.impeller.Constants; import eu.e43.impeller.R; import eu.e43.impeller.Utils; import eu.e43.impeller.activity.ActivityWithAccount; import eu.e43.impeller.uikit.AvatarView; import eu.e43.impeller.uikit.NavigationDrawerAdapter; public class DrawerFragment extends Fragment implements AdapterView.OnItemClickListener { private static final String TAG = "DrawerFragment"; private DrawerActionListener mListener; public DrawerFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_drawer, container, false); ListView modes = (ListView) v.findViewById(R.id.viewList); modes.setAdapter(new NavigationDrawerAdapter(getActivity())); modes.setOnItemClickListener(this); v.findViewById(R.id.changeAccountButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mListener != null) mListener.doChangeAccount(); } }); ActivityWithAccount awa = (ActivityWithAccount) getActivity(); if(awa.getAccount() != null) { updateUI(v, awa.getAccount()); } return v; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (DrawerActionListener) activity; onAccountChanged(((ActivityWithAccount) getActivity()).getAccount()); } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } public void onAccountChanged(Account acct) { if (acct == null || getView() == null) return; updateUI(getView(), acct); } private void updateUI(View rootView, Account acct) { ActivityWithAccount awa = (ActivityWithAccount) getActivity(); AvatarView avatar = (AvatarView) rootView.findViewById(R.id.avatar); TextView acctId = (TextView) rootView.findViewById(R.id.accountId); TextView acctName = (TextView) rootView.findViewById(R.id.accountName); avatar.resetAvatar(); acctId.setText(acct.name); // Temp / in case there isn't a displayName acctName.setText(acct.name); String id = AccountManager.get(awa).getUserData(acct, "id"); Cursor c = getActivity().getContentResolver().query( awa.getContentUris().objectsUri, new String[] { "_json" }, "id=?", new String[] { id }, null); try { if(c.moveToFirst()) { JSONObject obj = new JSONObject(c.getString(0)); String name = obj.optString("displayName"); if(name != null) { acctName.setText(name); } String img = Utils.getImageUrl(awa, obj.optJSONObject("image")); Log.v(TAG, "The user's avatar is at " + img); awa.getImageLoader().setImage(avatar, img); } } catch (JSONException e) { Log.e(TAG, "Bad data in database", e); } finally { c.close(); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Constants.FeedID feed = (Constants.FeedID) parent.getItemAtPosition(position); if(mListener != null) mListener.onSelectFeed(feed); } public interface DrawerActionListener { public void onSelectFeed(Constants.FeedID feed); public void doChangeAccount(); } }
package com.yandex.money.api.net; import com.google.gson.JsonElement; import com.yandex.money.api.net.providers.HostsProvider; import com.yandex.money.api.typeadapters.JsonUtils; import com.yandex.money.api.typeadapters.TypeAdapter; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.io.InputStream; import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import static com.yandex.money.api.utils.Common.checkNotNull; /** * Base API request. It is preferable to extend your requests from this class or its descendants * rather than {@link ApiRequest}. * * @author Slava Yasevich (vyasevich@yamoney.ru) */ public abstract class BaseApiRequest<T> implements ApiRequest<T> { public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat .forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT") .withLocale(Locale.US) .withZoneUTC(); private final TypeAdapter<T> typeAdapter; private final Map<String, String> headers = new HashMap<>(); private final Map<String, String> parameters = new HashMap<>(); private final ParametersBuffer buffer = new ParametersBuffer(); private byte[] body; /** * Constructor. * * @param typeAdapter typeAdapter used to parse a response */ protected BaseApiRequest(TypeAdapter<T> typeAdapter) { this.typeAdapter = checkNotNull(typeAdapter, "typeAdapter"); } @Override public final String requestUrl(HostsProvider hostsProvider) { String url = requestUrlBase(hostsProvider); return getMethod() == Method.GET ? url + buffer.setParams(parameters).prepareGet() : url; } @Override public final Map<String, String> getHeaders() { return Collections.unmodifiableMap(headers); } @Override public final T parseResponse(InputStream inputStream) { return typeAdapter.fromJson(inputStream); } @Override public final byte[] getBody() { prepareBody(); return body == null ? buffer.setParams(parameters).prepareBytes() : body; } protected abstract String requestUrlBase(HostsProvider hostsProvider); /** * Adds {@link String} header to this request. * * @param key key * @param value value */ protected final void addHeader(String key, String value) { headers.put(key, value); } /** * Adds {@link DateTime} header to this request. * * @param key key * @param value value */ protected final void addHeader(String key, DateTime value) { addHeader(key, value == null ? null : DATE_TIME_FORMATTER.print(value)); } /** * Adds collection of headers. * * @param headers headers to add */ protected final void addHeaders(Map<String, String> headers) { this.headers.putAll(headers); } /** * Adds {@link String} parameter to this request. * * @param key key * @param value value */ protected final void addParameter(String key, String value) { parameters.put(key, value); } /** * Adds {@link Integer} parameter to this request. * * @param key key * @param value value */ protected final void addParameter(String key, Integer value) { addParameter(key, value == null ? null : value.toString()); } /** * Adds {@link Long} parameter to this request. * * @param key key * @param value value */ protected final void addParameter(String key, Long value) { addParameter(key, value == null ? null : value.toString()); } /** * Adds {@link Double} parameter to this request. * * @param key key * @param value value */ protected final void addParameter(String key, Double value) { addParameter(key, value == null ? null : value.toString()); } /** * Adds {@link Boolean} parameter to this request. * * @param key key * @param value value */ protected final void addParameter(String key, Boolean value) { addParameter(key, value == null ? null : value.toString()); } /** * Adds {@link BigDecimal} parameter to this request. * * @param key key * @param value value */ protected final void addParameter(String key, BigDecimal value) { addParameter(key, value == null ? null : value.toPlainString()); } /** * Adds {@link DateTime} parameter to this request. * * @param key key * @param dateTime value */ protected final void addParameter(String key, DateTime dateTime) { addParameter(key, dateTime == null ? null : dateTime.toString()); } /** * Adds collection of parameters. * * @param parameters parameters to add */ protected final void addParameters(Map<String, String> parameters) { this.parameters.putAll(parameters); } /** * Sets a body for a request. Will override any added parameters if not {code null}. * * @param body body of a request */ protected final void setBody(byte[] body) { this.body = body; } /** * Sets a JSON body. Will override any added parameters if not {code null}. * * @param json JSON body * @see #setBody(byte[]) */ protected final void setBody(JsonElement json) { setBody(JsonUtils.getBytes(json)); } /** * Allows you to lazily prepare request body before {@link #getBody()} method returns. You can use * {@link #setBody(byte[])} or any of {@code addParameter*} methods here. */ protected void prepareBody() { } }
package experimentalcode.heidi; import java.util.ArrayList; import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.visualization.visualizers.VisualizerContext; import de.lmu.ifi.dbs.elki.visualization.visualizers.events.SelectionChangedEvent; public class SelectionContext { /** * Selected IDs */ private ArrayModifiableDBIDs selection = DBIDUtil.newArray(); /** * Selected minimal and maximal values for each dimension */ private ArrayList<Double> minValues; private ArrayList<Double> maxValues; /** * Mask to show what dimensions are set in minValues and maxValues */ // TODO: BitSet? private ArrayList<Integer> mask; public void init(VisualizerContext<?> context) { int dim = context.getDatabase().dimensionality(); minValues = new ArrayList<Double>(dim); maxValues = new ArrayList<Double>(dim); mask = new ArrayList<Integer>(dim); for(int d = 0; d < dim; d++) { minValues.add(d, 0.); maxValues.add(d, 0.); mask.add(d, 0); } } // Should be moved to VisualizerContext (as constant // VisualizerContext.SELECTION): public static final String SELECTION = "selection"; // Should be moved to VisualizerContext (as context.getSelection()): public static SelectionContext getSelection(VisualizerContext<?> context) { SelectionContext sel = context.getGenerics(SELECTION, SelectionContext.class); // Note: Alternative - but worse semantics. // Note: caller should handle null // if (sel == null) { // sel = new SelectionContext(); // sel.init(context); return sel; } // Should be moved to VisualizerContext (as context.setSelection(selection)) public static void setSelection(VisualizerContext<?> context, SelectionContext selContext) { context.put(SELECTION, selContext); context.fireContextChange(new SelectionChangedEvent(context)); } /** * Getter for the selected IDs * * @return ArrayList<Integer> */ public ArrayModifiableDBIDs getSelection() { return selection; } /** * Clears the selection * * @param selection */ public void clearSelection() { selection.clear(); } /** * Sets the selected DBIDs * * @param selection */ public void setSelection(ArrayModifiableDBIDs sel) { selection = sel; } public ArrayList<Double> getMaxValues() { return minValues; } public ArrayList<Double> getMinValues() { return maxValues; } public void setMinValues(ArrayList<Double> minV) { minValues = minV; } public void setMaxValues(ArrayList<Double> maxV) { maxValues = maxV; } public void resetMask(VisualizerContext<?> context) { mask.clear(); int dim = context.getDatabase().dimensionality(); for(int d = 0; d < dim; d++) { mask.add(d, 0); } } public ArrayList<Integer> getMask() { return mask; } public void setMask(ArrayList<Integer> m) { mask = m; } }
package de.hwrberlin.it2014.sweproject.cbr; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import de.hwrberlin.it2014.sweproject.database.DatabaseConnection; import de.hwrberlin.it2014.sweproject.database.TableResultsSQL; import de.hwrberlin.it2014.sweproject.model.Judgement; import de.hwrberlin.it2014.sweproject.model.Result; /** * * @author Max Bock & Felix Lehmann * */ public class Case { private int id; private ArrayList<String> description; private ArrayList<Result> similiarCases; //private String evaluation; /** * @author Max Bock * @param interne id, um spter die evaluation zur Anfrage zu zu ordnen * @param userInput */ public Case(int id, ArrayList<String> userInput) //constructor for userrequest { description=userInput; this.id=id; } /** * @author Max Bock * @param DatabaseConnection * @return ArrayList of Sets containing all similiar cases from DB * @throws SQLException */ public ArrayList<Result> getSimiliarFromDB(DatabaseConnection dbc) throws SQLException { // String query = QueryBuilder.buildQuery(description); // ResultSet rs = dbc.executeQuery(query); ScoreProcessor<Judgement> scoreProc=new ScoreProcessor<Judgement>(); ArrayList<Judgement> judgList= scoreProc.getBestMatches(description, 15, (long) 100, ""); similiarCases = judgementToResultList(judgList); return similiarCases; //maybe use ScoreProcessor.getBestMatches() instead } /** * * @param Case * @param Evaluation (true = passend; false = unpassend) */ public void saveEvaluation(DatabaseConnection dbc, boolean[] evaluation) //alt. parameter: (ArrayList<Case> evaluatedCases) and add evaluation as attribute to case { //TODO //save the evaluated cases to DB for step: retain //add evaluation evaluation to query ArrayList<String> insertQueries=new ArrayList<>(); for(Result r : similiarCases) { insertQueries.add(TableResultsSQL.getInsertSQLCode(r)); //add the evaluation? } for(String insertQuery : insertQueries) { try { dbc.executeUpdate(insertQuery); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public String getDescription() { String sstream=""; for (String s : description) { sstream+=s+" "; } return sstream; } public int getID() { return id; } /** * @author Max Bock * @param JudgementList from DBQuery * @return a ArrayList containing Result (userInput, Judgement and similiarity) */ private ArrayList<Result> judgementToResultList(ArrayList<Judgement> judgList) { ArrayList<Result> rl=new ArrayList<Result>(); // ScoreProcessor sp=new ScoreProcessor(); for(Judgement j : judgList) { float sim=1.0f; rl.add(new Result(this.getDescription(), j, sim)); } return rl; } }
package de.is24.deadcode4j.analyzer; import de.is24.deadcode4j.Analyzer; import de.is24.deadcode4j.CodeContext; import org.apache.commons.io.IOUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Collection; import java.util.Map; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; /** * Serves as a base class with which to analyze XML files. * * @since 1.2.0 */ public abstract class XmlAnalyzer implements Analyzer { private static final String NO_ATTRIBUTE = "no attribute"; private final SAXParser parser; private final XmlHandler handler; private final String dependerId; private final String endOfFileName; private final Map<String, String> relevantElements = newHashMap(); private final Collection<String> referencedClasses = newArrayList(); /** * The constructor for an <code>XmlAnalyzer</code>. * Be sure to call {@link #registerClassElement(String)} and/or {@link #registerClassAttribute(String, String)} in the subclasses' * constructor. * * @param dependerId a description of the <i>depending entity</i> with which to * call {@link de.is24.deadcode4j.CodeContext#addDependencies(String, java.util.Collection)} * @param endOfFileName the file suffix used to determine if a file should be analyzed; this can be a mere file * extension like <tt>.xml</tt> or a partial path like <tt>WEB-INF/web.xml</tt> * @param rootElement the expected XML root element or <code>null</code> if such an element does not exist; * i.e. there are multiple valid root elements * @since 1.2.0 */ protected XmlAnalyzer(@Nonnull String dependerId, @Nonnull String endOfFileName, @Nullable String rootElement) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/namespaces", true); this.parser = factory.newSAXParser(); } catch (Exception e) { throw new RuntimeException("Failed to set up XML parser!", e); } if (endOfFileName.trim().length() == 0) { throw new IllegalArgumentException("[endOfFileName] must be set!"); } this.handler = new XmlHandler(rootElement); this.dependerId = dependerId; this.endOfFileName = endOfFileName; } @Override public final void doAnalysis(@Nonnull CodeContext codeContext, @Nonnull File file) { if (file.getName().endsWith(endOfFileName)) { analyzeXmlFile(codeContext, file); } } /** * Registers an XML element containing a fully qualified class name. * * @param elementName the name of the XML element to register */ protected void registerClassElement(@Nonnull String elementName) { this.relevantElements.put(elementName, NO_ATTRIBUTE); } /** * Registers an XML element's attribute denoting a fully qualified class name. * * @param elementName the name of the XML element the attribute may occur at * @param attributeName the name of the attribute to register */ protected void registerClassAttribute(@Nonnull String elementName, @Nonnull String attributeName) { this.relevantElements.put(elementName, attributeName); } private void analyzeXmlFile(@Nonnull CodeContext codeContext, @Nonnull File file) { this.referencedClasses.clear(); this.handler.reset(); InputStream in = null; try { in = new FileInputStream(file); parser.parse(in, handler); } catch (StopParsing command) { return; } catch (Exception e) { throw new RuntimeException("Failed to parse [" + file + "]!", e); } finally { IOUtils.closeQuietly(in); } codeContext.addDependencies(dependerId, this.referencedClasses); } /** * Used to indicate that XML parsing can be stopped. * * @since 1.2.0 */ private static class StopParsing extends SAXException { } /** @since 1.2.0 */ private class XmlHandler extends DefaultHandler { private final String rootElement; private boolean firstElement = true; private StringBuilder buffer; public XmlHandler(String rootElement) { this.rootElement = rootElement; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws StopParsing { if (firstElement && rootElement != null && !rootElement.equals(localName)) { throw new StopParsing(); } else { firstElement = false; } String attributeName = relevantElements.get(localName); if (attributeName != null) { if (NO_ATTRIBUTE.equals(attributeName)) { buffer = new StringBuilder(128); } else { String className = attributes.getValue(attributeName); if (className != null) { referencedClasses.add(className.trim()); } } } } @Override public void characters(char[] ch, int start, int length) { if (buffer != null) { buffer.append(new String(ch, start, length).trim()); } } @Override public void endElement(String uri, String localName, String qName) { if (buffer != null) { referencedClasses.add(buffer.toString()); buffer = null; } } public void reset() { this.firstElement = true; this.buffer = null; } } }