answer
stringlengths
17
10.2M
package org.sagebionetworks.bridge.services; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.joda.time.DateTime; import org.sagebionetworks.bridge.dao.TaskDao; import org.sagebionetworks.bridge.dao.UserConsentDao; import org.sagebionetworks.bridge.exceptions.BadRequestException; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolder; import org.sagebionetworks.bridge.models.GuidCreatedOnVersionHolderImpl; import org.sagebionetworks.bridge.models.accounts.User; import org.sagebionetworks.bridge.models.accounts.UserConsent; import org.sagebionetworks.bridge.models.schedules.Activity; import org.sagebionetworks.bridge.models.schedules.ActivityType; import org.sagebionetworks.bridge.models.schedules.Schedule; import org.sagebionetworks.bridge.models.schedules.ScheduleContext; import org.sagebionetworks.bridge.models.schedules.SchedulePlan; import org.sagebionetworks.bridge.models.schedules.SurveyReference; import org.sagebionetworks.bridge.models.schedules.Task; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.studies.StudyIdentifierImpl; import org.sagebionetworks.bridge.models.surveys.SurveyAnswer; import org.sagebionetworks.bridge.models.surveys.SurveyResponseView; import org.sagebionetworks.bridge.validators.ScheduleContextValidator; import org.sagebionetworks.bridge.validators.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; @Component public class TaskService { private static final Logger logger = LoggerFactory.getLogger(TaskService.class); private static final ScheduleContextValidator VALIDATOR = new ScheduleContextValidator(); private static final List<SurveyAnswer> EMPTY_ANSWERS = ImmutableList.of(); private TaskDao taskDao; private TaskEventService taskEventService; private SchedulePlanService schedulePlanService; private UserConsentDao userConsentDao; private SurveyService surveyService; private SurveyResponseService surveyResponseService; @Autowired public void setTaskDao(TaskDao taskDao) { this.taskDao = taskDao; } @Autowired public void setTaskEventService(TaskEventService taskEventService) { this.taskEventService = taskEventService; } @Autowired public void setSchedulePlanService(SchedulePlanService schedulePlanService) { this.schedulePlanService = schedulePlanService; } @Autowired public void setUserConsentDao(UserConsentDao userConsentDao) { this.userConsentDao = userConsentDao; } @Autowired public void setSurveyService(SurveyService surveyService) { this.surveyService = surveyService; } @Autowired public void setSurveyResponseService(SurveyResponseService surveyResponseService) { this.surveyResponseService = surveyResponseService; } public List<Task> getTasks(User user, ScheduleContext context) { checkNotNull(user); checkNotNull(context); Validate.nonEntityThrowingException(VALIDATOR, context); Map<String, DateTime> events = createEventsMap(context); // Get tasks from the scheduler. None of these tasks have been saved, some may be new, // and some may have already been persisted. They are identified by their runKey. ScheduleContext newContext = new ScheduleContext.Builder() .withContext(context) .withEvents(events).build(); Multimap<String,Task> scheduledTasks = scheduleTasksForPlans(user, newContext); List<Task> tasksToSave = Lists.newArrayList(); for (String runKey : scheduledTasks.keySet()) { if (taskDao.taskRunHasNotOccurred(context.getHealthCode(), runKey)) { for (Task task : scheduledTasks.get(runKey)) { // If they have not been persisted yet, get each task one by one, create a survey // response for survey tasks, and add the tasks to the list of tasks to save. Activity activity = createResponseActivityIfNeeded( context.getStudyIdentifier(), context.getHealthCode(), task.getActivity()); task.setActivity(activity); tasksToSave.add(task); } } } // Finally, save these new tasks taskDao.saveTasks(tasksToSave); // Now read back the tasks from the database to pick up persisted startedOn, finishedOn values, // but filter based on the endsOn time from the query. If the client dynamically adjusts the // lookahead window from a large number of days to a small number of days, the client will still // get back all the tasks scheduled into the longer time period. This is counter-intuitive, // so hide them. return taskDao.getTasks(context).stream().filter(task -> { return (task.getScheduledOn().isBefore(context.getEndsOn()) || task.getScheduledOn().isEqual(context.getEndsOn())); }).collect(Collectors.toList()); } public void updateTasks(String healthCode, List<Task> tasks) { checkArgument(isNotBlank(healthCode)); checkNotNull(tasks); for (int i=0; i < tasks.size(); i++) { Task task = tasks.get(i); if (task == null) { throw new BadRequestException("A task in the array is null"); } if (task.getGuid() == null) { throw new BadRequestException(String.format("Task #%s has no GUID", i)); } } taskDao.updateTasks(healthCode, tasks); } public void deleteTasks(String healthCode) { checkArgument(isNotBlank(healthCode)); taskDao.deleteTasks(healthCode); } /** * @param user * @return */ private Map<String, DateTime> createEventsMap(ScheduleContext context) { Map<String,DateTime> events = taskEventService.getTaskEventMap(context.getHealthCode()); if (!events.containsKey("enrollment")) { return createEnrollmentEventFromConsent(context, events); } return events; } /** * No events have been recorded for this participant, so get an enrollment event from the consent records. * We have back-filled this event, so this should no longer be needed, but is left here just in case. * @param user * @param events * @return */ private Map<String, DateTime> createEnrollmentEventFromConsent(ScheduleContext context, Map<String, DateTime> events) { UserConsent consent = userConsentDao.getUserConsent(context.getHealthCode(), context.getStudyIdentifier()); Map<String,DateTime> newEvents = Maps.newHashMap(); newEvents.putAll(events); newEvents.put("enrollment", new DateTime(consent.getSignedOn())); logger.warn("Enrollment missing from task event table, pulling from consent record"); return newEvents; } private Multimap<String,Task> scheduleTasksForPlans(User user, ScheduleContext context) { StudyIdentifier studyId = new StudyIdentifierImpl(user.getStudyKey()); Multimap<String,Task> scheduledTasks = ArrayListMultimap.create(); List<SchedulePlan> plans = schedulePlanService.getSchedulePlans(context.getClientInfo(), studyId); for (SchedulePlan plan : plans) { Schedule schedule = plan.getStrategy().getScheduleForUser(studyId, plan, user); List<Task> tasks = schedule.getScheduler().getTasks(plan, context); for (Task task : tasks) { scheduledTasks.put(task.getRunKey(), task); } } return scheduledTasks; } private Activity createResponseActivityIfNeeded(StudyIdentifier studyIdentifier, String healthCode, Activity activity) { // If this activity is a task activity, or the survey response for this survey has already been determined // and added to the activity, then do not generate a survey response for this activity. if (activity.getActivityType() == ActivityType.TASK || activity.getSurveyResponse() != null) { return activity; } // Get a survey reference and if necessary, resolve the timestamp to use for the survey SurveyReference ref = activity.getSurvey(); GuidCreatedOnVersionHolder keys = new GuidCreatedOnVersionHolderImpl(ref); if (keys.getCreatedOn() == 0L) { keys = surveyService.getSurveyMostRecentlyPublishedVersion(studyIdentifier, ref.getGuid()); } // Now create a response for that specific survey version SurveyResponseView response = surveyResponseService.createSurveyResponse(keys, healthCode, EMPTY_ANSWERS, null); // And reconstruct the activity with that survey instance as well as the new response object. return new Activity.Builder() .withLabel(activity.getLabel()) .withLabelDetail(activity.getLabelDetail()) .withSurvey(response.getSurvey().getIdentifier(), keys.getGuid(), ref.getCreatedOn()) .withSurveyResponse(response.getResponse().getIdentifier()) .build(); } }
package net.bytebuddy.asm; import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.MethodList; import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.method.ParameterList; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeList; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.scaffold.FieldLocator; import net.bytebuddy.implementation.bytecode.StackSize; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.utility.CompoundList; import org.objectweb.asm.*; import java.io.IOException; import java.lang.annotation.*; import java.util.*; import static net.bytebuddy.matcher.ElementMatchers.named; public class Advice implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper { /** * The dispatcher for instrumenting the instrumented method upon entering. */ private final Dispatcher.Resolved.ForMethodEnter methodEnter; /** * The dispatcher for instrumenting the instrumented method upon exiting. */ private final Dispatcher.Resolved.ForMethodExit methodExit; /** * The binary representation of the class containing the advice methods. */ private final byte[] binaryRepresentation; /** * Creates a new advice. * * @param methodEnter The dispatcher for instrumenting the instrumented method upon entering. * @param methodExit The dispatcher for instrumenting the instrumented method upon exiting. * @param binaryRepresentation The binary representation of the class containing the advice methods. */ protected Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation) { this.methodEnter = methodEnter; this.methodExit = methodExit; this.binaryRepresentation = binaryRepresentation; } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advises binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param type The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> type) { return to(type, ClassFileLocator.ForClassLoader.of(type.getClassLoader())); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param type The type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(Class<?> type, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(type), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param typeDescription A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static Advice to(TypeDescription typeDescription, ClassFileLocator classFileLocator) { try { Dispatcher methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE; for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods()) { methodEnter = resolve(OnMethodEnter.class, methodEnter, methodDescription); methodExit = resolve(OnMethodExit.class, methodExit, methodDescription); } if (!methodEnter.isAlive() && !methodExit.isAlive()) { throw new IllegalArgumentException("No advice defined by " + typeDescription); } Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(); return new Advice(methodEnter.asMethodEnter(), methodExit.asMethodExitTo(resolved), classFileLocator.locate(typeDescription.getName()).resolve()); } catch (IOException exception) { throw new IllegalStateException("Error reading class file of " + typeDescription, exception); } } /** * Checks if a given method represents advise and does some basic validation. * * @param annotation The annotation that indicates a given type of advise. * @param dispatcher Any previous dispatcher. * @param methodDescription A description of the method considered as advise. * @return A dispatcher for the given method or the supplied dispatcher if the given method is not intended to be used as advise. */ private static Dispatcher resolve(Class<? extends Annotation> annotation, Dispatcher dispatcher, MethodDescription.InDefinedShape methodDescription) { if (methodDescription.getDeclaredAnnotations().isAnnotationPresent(annotation)) { if (dispatcher.isAlive()) { throw new IllegalStateException("Duplicate advice for " + dispatcher + " and " + methodDescription); } else if (!methodDescription.isStatic()) { throw new IllegalStateException("Advice for " + methodDescription + " is not static"); } return new Dispatcher.Active(methodDescription); } else { return dispatcher; } } /** * Returns an ASM visitor wrapper that matches the given matcher and applies this advice to the matched methods. * * @param matcher The matcher identifying methods to apply the advice to. * @return A suitable ASM visitor wrapper with the <i>compute frames</i> option enabled. */ public AsmVisitorWrapper.ForDeclaredMethods on(ElementMatcher<? super MethodDescription.InDefinedShape> matcher) { return new AsmVisitorWrapper.ForDeclaredMethods().method(matcher, this); } @Override public MethodVisitor wrap(TypeDescription instrumentedType, MethodDescription.InDefinedShape methodDescription, MethodVisitor methodVisitor, int writerFlags, int readerFlags) { if (methodDescription.isAbstract() || methodDescription.isNative()) { throw new IllegalStateException("Cannot advice abstract or native method " + methodDescription); } return methodExit.isSkipThrowable() ? new AdviceVisitor.WithoutExceptionHandling(methodVisitor, methodDescription, methodEnter, methodExit, binaryRepresentation, writerFlags, readerFlags) : new AdviceVisitor.WithExceptionHandling(methodVisitor, methodDescription, methodEnter, methodExit, binaryRepresentation, writerFlags, readerFlags); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Advice advice = (Advice) other; return methodEnter.equals(advice.methodEnter) && methodExit.equals(advice.methodExit) && Arrays.equals(binaryRepresentation, advice.binaryRepresentation); } @Override public int hashCode() { int result = methodEnter.hashCode(); result = 31 * result + methodExit.hashCode(); result = 31 * result + Arrays.hashCode(binaryRepresentation); return result; } @Override public String toString() { return "Advice{" + "methodEnter=" + methodEnter + ", methodExit=" + methodExit + ", binaryRepresentation=<" + binaryRepresentation.length + " bytes>" + '}'; } protected interface MetaDataHandler { void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack); void injectHandlerFrame(MethodVisitor methodVisitor); void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondaryCompletion); interface ForInstrumentedMethod extends MetaDataHandler { int compoundStackSize(int maxStack); int compoundLocalVariableSize(int maxLocals); ForAdvice bindEntry(MethodDescription.InDefinedShape adviseMethod); ForAdvice bindExit(MethodDescription.InDefinedShape adviseMethod, TypeDescription enterType); int getReaderHint(); } interface ForAdvice extends MetaDataHandler { void recordMaxima(int maxStack, int maxLocals); } enum NoOp implements ForInstrumentedMethod, ForAdvice { INSTANCE; @Override public void recordMaxima(int maxStack, int maxLocals) { /* do nothing */ } @Override public int compoundStackSize(int maxStack) { return -1; } @Override public int compoundLocalVariableSize(int maxLocals) { return -1; } @Override public ForAdvice bindEntry(MethodDescription.InDefinedShape adviseMethod) { return this; } @Override public ForAdvice bindExit(MethodDescription.InDefinedShape adviseMethod, TypeDescription enterType) { return this; } @Override public int getReaderHint() { return ClassReader.SKIP_FRAMES; } @Override public void translateFrame(MethodVisitor methodVisitor, int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { /* do nothing */ } @Override public void injectHandlerFrame(MethodVisitor methodVisitor) { /* do nothing */ } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondaryCompletion) { /* do nothing */ } } class Default implements ForInstrumentedMethod { /** * An empty array indicating an empty frame. */ private static final Object[] EMPTY = new Object[0]; /** * The instrumented method. */ private final MethodDescription.InDefinedShape instrumentedMethod; /** * A list of intermediate types to be considered as part of the instrumented method's steady signature. */ private final TypeList intermediateTypes; private final boolean expandFrames; private int currentFrameDivergence; /** * The maximum stack size required by a visited advice method. */ private int stackSize; /** * The maximum length of the local variable array required by a visited advice method. */ private int localVariableLength; /** * Creates a new frame translator. * * @param instrumentedMethod The instrumented method. * @param intermediateTypes A list of intermediate types to be considered as part of the instrumented method's steady signature. */ protected Default(MethodDescription.InDefinedShape instrumentedMethod, TypeList intermediateTypes, boolean expandFrames) { this.instrumentedMethod = instrumentedMethod; this.intermediateTypes = intermediateTypes; this.expandFrames = expandFrames; stackSize = 2; // Minimum for pushing exceptions or default values. Could be more accurate. } protected static ForInstrumentedMethod of(MethodDescription.InDefinedShape instrumentedMethod, TypeList additionalTypes, int writerFlags, int readerFlags) { return (writerFlags & ClassWriter.COMPUTE_FRAMES) != 0 ? NoOp.INSTANCE : new Default(instrumentedMethod, additionalTypes, (readerFlags & ClassReader.EXPAND_FRAMES) != 0); } /** * Translates a type into a representation of its form inside a stack map frame. * * @param typeDescription The type to translate. * @return A stack entry representation of the supplied type. */ protected static Object toFrame(TypeDescription typeDescription) { if (typeDescription.represents(boolean.class) || typeDescription.represents(byte.class) || typeDescription.represents(short.class) || typeDescription.represents(char.class) || typeDescription.represents(int.class)) { return Opcodes.INTEGER; } else if (typeDescription.represents(long.class)) { return Opcodes.LONG; } else if (typeDescription.represents(float.class)) { return Opcodes.FLOAT; } else if (typeDescription.represents(double.class)) { return Opcodes.DOUBLE; } else { return typeDescription.getInternalName(); } } @Override public ForAdvice bindEntry(MethodDescription.InDefinedShape methodDescription) { return new ForAdvice(methodDescription, new TypeList.Empty(), methodDescription.getReturnType().represents(void.class) ? new TypeList.Empty() : new TypeList.Explicit(methodDescription.getReturnType().asErasure()), TranslationMode.ENTRY); } @Override public ForAdvice bindExit(MethodDescription.InDefinedShape methodDescription, TypeDescription enterType) { List<TypeDescription> typeDescriptions = new ArrayList<TypeDescription>(3); if (!enterType.represents(void.class)) { typeDescriptions.add(enterType); } if (!instrumentedMethod.getReturnType().represents(void.class)) { typeDescriptions.add(instrumentedMethod.getReturnType().asErasure()); } typeDescriptions.add(TypeDescription.THROWABLE); return new ForAdvice(methodDescription, new TypeList.Explicit(typeDescriptions), Collections.<TypeDescription>emptyList(), TranslationMode.EXIT); } @Override public int compoundStackSize(int stackSize) { return Math.max(this.stackSize, stackSize); } @Override public int compoundLocalVariableSize(int localVariableLength) { return Math.max(this.localVariableLength, localVariableLength + instrumentedMethod.getReturnType().getStackSize().getSize() + StackSize.SINGLE.getSize() + intermediateTypes.getStackSize()); } @Override public int getReaderHint() { return expandFrames ? ClassReader.EXPAND_FRAMES : AsmVisitorWrapper.NO_FLAGS; } @Override public void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { translateFrame(methodVisitor, instrumentedMethod, TranslationMode.COPY, intermediateTypes, type, localVariableLength, localVariable, stackSize, stack); } protected void translateFrame(MethodVisitor methodVisitor, MethodDescription.InDefinedShape methodDescription, TranslationMode translationMode, TypeList additionalTypes, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { switch (type) { case Opcodes.F_SAME: case Opcodes.F_SAME1: break; case Opcodes.F_APPEND: currentFrameDivergence += localVariableLength; break; case Opcodes.F_CHOP: currentFrameDivergence -= localVariableLength; break; case Opcodes.F_FULL: case Opcodes.F_NEW: Object[] translated = new Object[localVariableLength - methodDescription.getParameters().size() - (methodDescription.isStatic() ? 0 : 1) + instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1) + additionalTypes.size()]; int index = translationMode.copy(instrumentedMethod, methodDescription, localVariable, translated); for (TypeDescription typeDescription : additionalTypes) { translated[index++] = toFrame(typeDescription); } System.arraycopy(localVariable, methodDescription.getParameters().size() + (methodDescription.isStatic() ? 0 : 1), translated, index, translated.length - index); localVariableLength = translated.length; localVariable = translated; currentFrameDivergence = translated.length - index; break; default: throw new IllegalArgumentException("Unexpected frame type: " + type); } methodVisitor.visitFrame(type, localVariableLength, localVariable, stackSize, stack); } @Override public void injectHandlerFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)}); } else { injectFullFrame(methodVisitor, intermediateTypes, true); } } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondaryCompletion) { if (!expandFrames && currentFrameDivergence == 0) { if (secondaryCompletion) { methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY); } else { Object[] local = instrumentedMethod.getReturnType().represents(void.class) ? new Object[]{Type.getInternalName(Throwable.class)} : new Object[]{toFrame(instrumentedMethod.getReturnType().asErasure()), Type.getInternalName(Throwable.class)}; methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY); } } else { injectFullFrame(methodVisitor, CompoundList.of(intermediateTypes, instrumentedMethod.getReturnType().represents(void.class) ? Collections.singletonList(TypeDescription.THROWABLE) : Arrays.asList(instrumentedMethod.getReturnType().asErasure(), TypeDescription.THROWABLE)), false); } } protected void injectFullFrame(MethodVisitor methodVisitor, List<? extends TypeDescription> additionalTypes, boolean exceptionOnStack) { Object[] localVariable = new Object[instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1) + additionalTypes.size()]; int index = 0; if (!instrumentedMethod.isStatic()) { localVariable[index++] = toFrame(instrumentedMethod.getDeclaringType()); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { localVariable[index++] = toFrame(typeDescription); } for (TypeDescription typeDescription : additionalTypes) { localVariable[index++] = toFrame(typeDescription); } Object[] stackType = exceptionOnStack ? new Object[]{Type.getInternalName(Throwable.class)} : EMPTY; methodVisitor.visitFrame(expandFrames ? Opcodes.F_NEW : Opcodes.F_FULL, localVariable.length, localVariable, stackType.length, stackType); currentFrameDivergence = 0; } protected enum TranslationMode { COPY { @Override protected int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated) { int length = instrumentedMethod.getParameters().size() + (instrumentedMethod.isStatic() ? 0 : 1); System.arraycopy(localVariable, 0, translated, 0, length); return length; } }, ENTRY { @Override protected int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated) { int index = 0; if (!instrumentedMethod.isStatic()) { translated[index++] = instrumentedMethod.isConstructor() ? Opcodes.UNINITIALIZED_THIS : toFrame(instrumentedMethod.getDeclaringType()); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { translated[index++] = toFrame(typeDescription); } return index; } }, EXIT { @Override protected int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated) { int index = 0; if (!instrumentedMethod.isStatic()) { translated[index++] = toFrame(instrumentedMethod.getDeclaringType()); } for (TypeDescription typeDescription : instrumentedMethod.getParameters().asTypeList().asErasures()) { translated[index++] = toFrame(typeDescription); } return index; } }; protected abstract int copy(MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape methodDescription, Object[] localVariable, Object[] translated); } /** * A frame translator that is bound to an advice method. */ protected class ForAdvice implements MetaDataHandler.ForAdvice { /** * The method description for which frames are translated. */ private final MethodDescription.InDefinedShape methodDescription; /** * A list of intermediate types to be considered as part of the instrumented method's steady signature. */ private final TypeList intermediateTypes; /** * The types that this method yields as a result. */ private final List<? extends TypeDescription> yieldedTypes; private final TranslationMode translationMode; /** * Creates a new bound frame translator. * * @param methodDescription The method description for which frames are translated. * @param intermediateTypes A list of intermediate types to be considered as part of the instrumented method's steady signature. * @param yieldedTypes The types that this method yields as a result. */ protected ForAdvice(MethodDescription.InDefinedShape methodDescription, TypeList intermediateTypes, List<? extends TypeDescription> yieldedTypes, TranslationMode translationMode) { this.methodDescription = methodDescription; this.intermediateTypes = intermediateTypes; this.yieldedTypes = yieldedTypes; this.translationMode = translationMode; } @Override public void recordMaxima(int stackSize, int localVariableLength) { Default.this.stackSize = Math.max(Default.this.stackSize, stackSize); Default.this.localVariableLength = Math.max(Default.this.localVariableLength, localVariableLength - methodDescription.getStackSize() + instrumentedMethod.getStackSize() + intermediateTypes.getStackSize()); } @Override public void translateFrame(MethodVisitor methodVisitor, int type, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { Default.this.translateFrame(methodVisitor, methodDescription, translationMode, intermediateTypes, type, localVariableLength, localVariable, stackSize, stack); } @Override public void injectHandlerFrame(MethodVisitor methodVisitor) { if (!expandFrames && currentFrameDivergence == 0) { methodVisitor.visitFrame(Opcodes.F_SAME1, 0, EMPTY, 1, new Object[]{Type.getInternalName(Throwable.class)}); } else { injectFullFrame(methodVisitor, intermediateTypes, true); } } @Override public void injectCompletionFrame(MethodVisitor methodVisitor, boolean secondaryCompletion) { if (!expandFrames && currentFrameDivergence == 0 && yieldedTypes.size() < 4) { if (secondaryCompletion || yieldedTypes.isEmpty()) { methodVisitor.visitFrame(Opcodes.F_SAME, 0, EMPTY, 0, EMPTY); } else { Object[] local = new Object[yieldedTypes.size()]; int index = 0; for (TypeDescription typeDescription : yieldedTypes) { local[index++] = toFrame(typeDescription); } methodVisitor.visitFrame(Opcodes.F_APPEND, local.length, local, 0, EMPTY); } } else { injectFullFrame(methodVisitor, CompoundList.of(intermediateTypes, yieldedTypes), false); } } } } } /** * A method visitor that weaves the advise methods' byte codes. */ protected abstract static class AdviceVisitor extends MethodVisitor { /** * Indicates a zero offset. */ private static final int NO_OFFSET = 0; /** * A description of the instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The dispatcher to be used for method entry. */ private final Dispatcher.Resolved.ForMethodEnter methodEnter; /** * The dispatcher to be used for method exit. */ private final Dispatcher.Resolved.ForMethodExit methodExit; /** * A reader for traversing the advise methods' class file. */ private final ClassReader classReader; /** * The frame translator to use. */ protected final MetaDataHandler.ForInstrumentedMethod metaDataHandler; protected final Label endOfMethod; /** * Creates an advise visitor. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param binaryRepresentation The binary representation of the advise methods' class file. */ protected AdviceVisitor(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation, int writerFlags, int readerFlags) { super(Opcodes.ASM5, methodVisitor); this.instrumentedMethod = instrumentedMethod; this.methodEnter = methodEnter; this.methodExit = methodExit; classReader = new ClassReader(binaryRepresentation); metaDataHandler = MetaDataHandler.Default.of(instrumentedMethod, methodEnter.getEnterType().represents(void.class) ? new TypeList.Empty() : new TypeList.Explicit(methodEnter.getEnterType()), writerFlags, readerFlags); endOfMethod = new Label(); } @Override public void visitCode() { super.visitCode(); append(methodEnter); onUserStart(); } /** * Writes the advise for entering the instrumented method. */ protected abstract void onUserStart(); @Override public void visitVarInsn(int opcode, int offset) { super.visitVarInsn(opcode, offset < instrumentedMethod.getStackSize() ? offset : offset + methodEnter.getEnterType().getStackSize().getSize()); } @Override public void visitIincInsn(int offset, int increment) { super.visitIincInsn(offset < instrumentedMethod.getStackSize() ? offset : offset + methodEnter.getEnterType().getStackSize().getSize(), increment); } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: mv.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE); mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); return; case Opcodes.IRETURN: onMethodExit(Opcodes.ISTORE); return; case Opcodes.FRETURN: onMethodExit(Opcodes.FSTORE); return; case Opcodes.DRETURN: onMethodExit(Opcodes.DSTORE); return; case Opcodes.LRETURN: onMethodExit(Opcodes.LSTORE); return; case Opcodes.ARETURN: onMethodExit(Opcodes.ASTORE); return; default: mv.visitInsn(opcode); } } /** * Writes the advise for the instrumented method's end. * * @param store The return type's store instruction. */ private void onMethodExit(int store) { variable(store); mv.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. */ protected void variable(int opcode) { variable(opcode, NO_OFFSET); } /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. * @param offset The additional offset of the variable. */ protected void variable(int opcode, int offset) { mv.visitVarInsn(opcode, instrumentedMethod.getStackSize() + methodEnter.getEnterType().getStackSize().getSize() + offset); } @Override public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { metaDataHandler.translateFrame(mv, frameType, localVariableLength, localVariable, stackSize, stack); } @Override public void visitMaxs(int maxStack, int maxLocals) { onUserEnd(); mv.visitLabel(endOfMethod); metaDataHandler.injectCompletionFrame(mv, false); append(methodExit); variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize()); Label exceptionalReturn = new Label(); mv.visitJumpInsn(Opcodes.IFNONNULL, exceptionalReturn); if (instrumentedMethod.getReturnType().represents(void.class)) { mv.visitInsn(Opcodes.RETURN); } else { Type returnType = Type.getType(instrumentedMethod.getReturnType().asErasure().getDescriptor()); variable(returnType.getOpcode(Opcodes.ILOAD)); mv.visitInsn(returnType.getOpcode(Opcodes.IRETURN)); } mv.visitLabel(exceptionalReturn); metaDataHandler.injectCompletionFrame(mv, true); variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize()); mv.visitInsn(Opcodes.ATHROW); super.visitMaxs(metaDataHandler.compoundStackSize(maxStack), metaDataHandler.compoundLocalVariableSize(maxLocals)); } /** * Writes the advise for completing the instrumented method. */ protected abstract void onUserEnd(); /** * Appends the byte code of the supplied dispatcher. * * @param dispatcher The dispatcher for which the byte code should be appended. */ private void append(Dispatcher.Resolved dispatcher) { classReader.accept(new CodeCopier(dispatcher), ClassReader.SKIP_DEBUG | metaDataHandler.getReaderHint()); } /** * A visitor for copying an advise method's byte code. */ protected class CodeCopier extends ClassVisitor { /** * The dispatcher to use. */ private final Dispatcher.Resolved dispatcher; /** * Creates a new code copier. * * @param dispatcher The dispatcher to use. */ protected CodeCopier(Dispatcher.Resolved dispatcher) { super(Opcodes.ASM5); this.dispatcher = dispatcher; } @Override public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) { return dispatcher.apply(internalName, descriptor, mv, metaDataHandler, instrumentedMethod); } @Override public String toString() { return "Advice.AdviceVisitor.CodeCopier{" + "outer=" + AdviceVisitor.this + ", dispatcher=" + dispatcher + '}'; } } /** * An advise visitor that captures exceptions by weaving try-catch blocks around user code. */ protected static class WithExceptionHandling extends AdviceVisitor { /** * Indicates that any throwable should be captured. */ private static final String ANY_THROWABLE = null; private final Label userStart; private final Label userEnd; /** * Creates a new advise visitor that captures exception by weaving try-catch blocks around user code. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param binaryRepresentation The binary representation of the advise methods' class file. */ protected WithExceptionHandling(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation, int writerFlags, int readerFlags) { super(methodVisitor, instrumentedMethod, methodEnter, methodExit, binaryRepresentation, writerFlags, readerFlags); userStart = new Label(); userEnd = new Label(); } @Override protected void onUserStart() { mv.visitTryCatchBlock(userStart, userEnd, userEnd, ANY_THROWABLE); mv.visitLabel(userStart); } @Override protected void onUserEnd() { mv.visitLabel(userEnd); metaDataHandler.injectHandlerFrame(mv); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); storeDefaultReturn(); mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } /** * Stores a default return value in the designated slot of the local variable array. */ private void storeDefaultReturn() { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { mv.visitInsn(Opcodes.ICONST_0); variable(Opcodes.ISTORE); } else if (instrumentedMethod.getReturnType().represents(long.class)) { mv.visitInsn(Opcodes.LCONST_0); variable(Opcodes.LSTORE); } else if (instrumentedMethod.getReturnType().represents(float.class)) { mv.visitInsn(Opcodes.FCONST_0); variable(Opcodes.FSTORE); } else if (instrumentedMethod.getReturnType().represents(double.class)) { mv.visitInsn(Opcodes.DCONST_0); variable(Opcodes.DSTORE); } else if (!instrumentedMethod.getReturnType().represents(void.class)) { mv.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE); } } @Override public String toString() { return "Advice.AdviceVisitor.WithExceptionHandling{" + "instrumentedMethod=" + instrumentedMethod + '}'; } } /** * An advise visitor that does not capture exceptions. */ protected static class WithoutExceptionHandling extends AdviceVisitor { /** * Creates a new advise visitor that does not capture exceptions. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param binaryRepresentation The binary representation of the advise methods' class file. */ protected WithoutExceptionHandling(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation, int writerFlags, int readerFlags) { super(methodVisitor, instrumentedMethod, methodEnter, methodExit, binaryRepresentation, writerFlags, readerFlags); } @Override protected void onUserStart() { /* empty */ } @Override protected void onUserEnd() { /* empty */ } @Override public String toString() { return "Advice.AdviceVisitor.WithoutExceptionHandling{" + "instrumentedMethod=" + instrumentedMethod + '}'; } } } /** * A dispatcher for implementing advise. */ protected interface Dispatcher { /** * Indicates that a method does not represent advise and does not need to be visited. */ MethodVisitor IGNORE_METHOD = null; /** * Returns {@code true} if this dispatcher is alive. * * @return {@code true} if this dispatcher is alive. */ boolean isAlive(); /** * Resolves this dispatcher as a dispatcher for entering a method. * * @return This dispatcher as a dispatcher for entering a method. */ Resolved.ForMethodEnter asMethodEnter(); /** * Resolves this dispatcher as a dispatcher for exiting a method. * * @param dispatcher The dispatcher for entering a method. * @return This dispatcher as a dispatcher for exiting a method. */ Resolved.ForMethodExit asMethodExitTo(Resolved.ForMethodEnter dispatcher); /** * Represents a resolved dispatcher. */ interface Resolved { /** * Applies this dispatcher for a method that is discovered in the advice class's class file. * * @param internalName The discovered method's internal name. * @param descriptor The discovered method's descriptor. * @param methodVisitor The method visitor for writing the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @return A method visitor for reading the discovered method or {@code null} if the discovered method is of no interest. */ MethodVisitor apply(String internalName, String descriptor, MethodVisitor methodVisitor, MetaDataHandler.ForInstrumentedMethod metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod); /** * Represents a resolved dispatcher for entering a method. */ interface ForMethodEnter extends Resolved { /** * Returns the type that this dispatcher supplies as a result of its advise or a description of {@code void} if * no type is supplied as a result of the enter advise. * * @return The type that this dispatcher supplies as a result of its advise or a description of {@code void}. */ TypeDescription getEnterType(); } /** * Represents a resolved dispatcher for exiting a method. */ interface ForMethodExit extends Resolved { /** * Indicates if this advise requires to be called when the instrumented method terminates exceptionally. * * @return {@code true} if this advise requires to be called when the instrumented method terminates exceptionally. */ boolean isSkipThrowable(); } } /** * An implementation for inactive devise that does not write any byte code. */ enum Inactive implements Dispatcher, Resolved.ForMethodEnter, Resolved.ForMethodExit { /** * The singleton instance. */ INSTANCE; @Override public boolean isAlive() { return false; } @Override public boolean isSkipThrowable() { return true; } @Override public TypeDescription getEnterType() { return TypeDescription.VOID; } @Override public Resolved.ForMethodEnter asMethodEnter() { return this; } @Override public Resolved.ForMethodExit asMethodExitTo(Resolved.ForMethodEnter dispatcher) { return this; } @Override public MethodVisitor apply(String internalName, String descriptor, MethodVisitor methodVisitor, MetaDataHandler.ForInstrumentedMethod metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod) { return IGNORE_METHOD; } @Override public String toString() { return "Advice.Dispatcher.Inactive." + name(); } } /** * A dispatcher for active advise. */ class Active implements Dispatcher { /** * The advise method. */ protected final MethodDescription.InDefinedShape adviseMethod; /** * Creates a dispatcher for active advise. * * @param adviseMethod The advise method. */ protected Active(MethodDescription.InDefinedShape adviseMethod) { this.adviseMethod = adviseMethod; } @Override public boolean isAlive() { return true; } @Override public Dispatcher.Resolved.ForMethodEnter asMethodEnter() { return new Resolved.ForMethodEnter(adviseMethod); } @Override public Dispatcher.Resolved.ForMethodExit asMethodExitTo(Dispatcher.Resolved.ForMethodEnter dispatcher) { return new Resolved.ForMethodExit(adviseMethod, dispatcher.getEnterType()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && adviseMethod.equals(((Active) other).adviseMethod); } @Override public int hashCode() { return adviseMethod.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active{" + "adviseMethod=" + adviseMethod + '}'; } /** * A resolved version of a dispatcher. */ protected abstract static class Resolved implements Dispatcher.Resolved { /** * Indicates a read-only mapping for an offset. */ private static final boolean READ_ONLY = true; /** * The represented advise method. */ protected final MethodDescription.InDefinedShape adviseMethod; /** * An unresolved mapping of offsets of the advise method based on the annotations discovered on each method parameter. */ protected final Map<Integer, OffsetMapping> offsetMappings; /** * Creates a new resolved version of a dispatcher. * * @param adviseMethod The represented advise method. * @param factory An unresolved mapping of offsets of the advise method based on the annotations discovered on each method parameter. */ protected Resolved(MethodDescription.InDefinedShape adviseMethod, OffsetMapping.Factory... factory) { this.adviseMethod = adviseMethod; offsetMappings = new HashMap<Integer, OffsetMapping>(); for (ParameterDescription.InDefinedShape parameterDescription : adviseMethod.getParameters()) { OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED; for (OffsetMapping.Factory aFactory : factory) { OffsetMapping possible = aFactory.make(parameterDescription); if (possible != null) { if (offsetMapping == null) { offsetMapping = possible; } else { throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping); } } } offsetMappings.put(parameterDescription.getOffset(), offsetMapping == null ? new OffsetMapping.ForParameter(parameterDescription.getIndex(), READ_ONLY, parameterDescription.getType().asErasure()) : offsetMapping); } } @Override public MethodVisitor apply(String internalName, String descriptor, MethodVisitor methodVisitor, MetaDataHandler.ForInstrumentedMethod metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod) { return adviseMethod.getInternalName().equals(internalName) && adviseMethod.getDescriptor().equals(descriptor) ? apply(methodVisitor, metaDataHandler, instrumentedMethod) : IGNORE_METHOD; } /** * Applies a resolution for a given instrumented method. * * @param methodVisitor A method visitor for writing byte code to the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @return A method visitor for visiting the advise method's byte code. */ protected abstract MethodVisitor apply(MethodVisitor methodVisitor, MetaDataHandler.ForInstrumentedMethod metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod); @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Resolved resolved = (Resolved) other; return adviseMethod.equals(resolved.adviseMethod) && offsetMappings.equals(resolved.offsetMappings); } @Override public int hashCode() { int result = adviseMethod.hashCode(); result = 31 * result + offsetMappings.hashCode(); return result; } /** * Represents an offset mapping for an advise method to an alternative offset. */ interface OffsetMapping { /** * Resolves an offset mapping to a given target offset. * * @param instrumentedMethod The instrumented method for which the mapping is to be resolved. * @param enterType The type returned by the enter advice or {@code void} if there is no enter type to consider. * @return A suitable target mapping. */ Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType); /** * A target offset of an offset mapping. */ interface Target { /** * Applies this offset mapping for a {@link MethodVisitor#visitVarInsn(int, int)} instruction. * * @param methodVisitor The method visitor onto which this offset mapping is to be applied. * @param opcode The opcode of the original instruction. */ void resolveAccess(MethodVisitor methodVisitor, int opcode); void resolveIncrement(MethodVisitor methodVisitor, int increment); /** * Loads a default value onto the stack or pops the accessed value off it. */ enum ForDefaultValue implements Target { /** * The singleton instance. */ INSTANCE; @Override public void resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ALOAD: methodVisitor.visitInsn(Opcodes.ACONST_NULL); break; case Opcodes.ILOAD: methodVisitor.visitInsn(Opcodes.ICONST_0); break; case Opcodes.LLOAD: methodVisitor.visitInsn(Opcodes.LCONST_0); break; case Opcodes.FLOAD: methodVisitor.visitInsn(Opcodes.FCONST_0); break; case Opcodes.DLOAD: methodVisitor.visitInsn(Opcodes.DCONST_0); break; case Opcodes.ISTORE: case Opcodes.FSTORE: case Opcodes.ASTORE: methodVisitor.visitInsn(Opcodes.POP); break; case Opcodes.LSTORE: case Opcodes.DSTORE: methodVisitor.visitInsn(Opcodes.POP2); break; default: throw new IllegalStateException("Unexpected opcode: " + opcode); } } @Override public void resolveIncrement(MethodVisitor methodVisitor, int increment) { /* do nothing */ } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Target.ForDefaultValue." + name(); } } /** * A read-write target mapping. */ class ForParameter implements Target { /** * The mapped offset. */ private final int offset; /** * Creates a new read-write target mapping. * * @param offset The mapped offset. */ protected ForParameter(int offset) { this.offset = offset; } @Override public void resolveAccess(MethodVisitor methodVisitor, int opcode) { methodVisitor.visitVarInsn(opcode, offset); } @Override public void resolveIncrement(MethodVisitor methodVisitor, int increment) { methodVisitor.visitIincInsn(offset, increment); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForParameter forParameter = (ForParameter) object; return offset == forParameter.offset; } @Override public int hashCode() { return offset; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Target.ForParameter{" + "offset=" + offset + '}'; } } /** * A read-only target mapping. */ class ForReadOnlyParameter implements Target { /** * The mapped offset. */ private final int offset; /** * Creates a new read-only target mapping. * * @param offset The mapped offset. */ protected ForReadOnlyParameter(int offset) { this.offset = offset; } @Override public void resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ISTORE: case Opcodes.LSTORE: case Opcodes.FSTORE: case Opcodes.DSTORE: case Opcodes.ASTORE: throw new IllegalStateException("Cannot write to read-only parameter at offset " + offset); case Opcodes.ILOAD: case Opcodes.LLOAD: case Opcodes.FLOAD: case Opcodes.DLOAD: case Opcodes.ALOAD: methodVisitor.visitVarInsn(opcode, offset); break; default: throw new IllegalArgumentException("Did not expect opcode: " + opcode); } } @Override public void resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot write to read-only parameter at offset " + offset); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForReadOnlyParameter forReadOnlyParameter = (ForReadOnlyParameter) object; return offset == forReadOnlyParameter.offset; } @Override public int hashCode() { return offset; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Target.ForReadOnlyParameter{" + "offset=" + offset + '}'; } } /** * An offset mapping for a field. */ class ForField implements Target { /** * The field being read. */ private final FieldDescription fieldDescription; /** * Creates a new offset mapping for a field. * * @param fieldDescription The field being read. */ protected ForField(FieldDescription fieldDescription) { this.fieldDescription = fieldDescription; } @Override public void resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ISTORE: case Opcodes.ASTORE: case Opcodes.FSTORE: case Opcodes.LSTORE: case Opcodes.DSTORE: throw new IllegalStateException("Cannot write to field: " + fieldDescription); case Opcodes.ILOAD: case Opcodes.FLOAD: case Opcodes.ALOAD: case Opcodes.LLOAD: case Opcodes.DLOAD: int accessOpcode; if (fieldDescription.isStatic()) { accessOpcode = Opcodes.GETSTATIC; } else { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); accessOpcode = Opcodes.GETFIELD; } methodVisitor.visitFieldInsn(accessOpcode, fieldDescription.getDeclaringType().asErasure().getInternalName(), fieldDescription.getInternalName(), fieldDescription.getDescriptor()); break; default: throw new IllegalArgumentException("Did not expect opcode: " + opcode); } } @Override public void resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot write to field: " + fieldDescription); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForField forField = (ForField) object; return fieldDescription.equals(forField.fieldDescription); } @Override public int hashCode() { return fieldDescription.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Target.ForField{" + "fieldDescription=" + fieldDescription + '}'; } } /** * An offset mapping for a constant pool value. */ class ForConstantPoolValue implements Target { /** * The constant pool value. */ private final Object value; /** * Creates a mapping for a constant pool value. * * @param value The constant pool value. */ protected ForConstantPoolValue(Object value) { this.value = value; } @Override public void resolveAccess(MethodVisitor methodVisitor, int opcode) { switch (opcode) { case Opcodes.ISTORE: case Opcodes.ASTORE: case Opcodes.FSTORE: case Opcodes.LSTORE: case Opcodes.DSTORE: throw new IllegalStateException("Cannot write to fixed value: " + value); case Opcodes.ILOAD: case Opcodes.FLOAD: case Opcodes.ALOAD: case Opcodes.LLOAD: case Opcodes.DLOAD: methodVisitor.visitLdcInsn(value); break; default: throw new IllegalArgumentException("Did not expect opcode: " + opcode); } // TODO: test } @Override public void resolveIncrement(MethodVisitor methodVisitor, int increment) { throw new IllegalStateException("Cannot write to fixed value: " + value); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForConstantPoolValue that = (ForConstantPoolValue) object; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Target.ForConstantPoolValue{" + "value=" + value + '}'; } } } /** * Represents a factory for creating a {@link OffsetMapping} for a given parameter. */ interface Factory { /** * Indicates that an offset mapping is undefined. */ OffsetMapping UNDEFINED = null; /** * Creates a new offset mapping for the supplied parameter if possible. * * @param parameterDescription The parameter description for which to resolve an offset mapping. * @return A resolved offset mapping or {@code null} if no mapping can be resolved for this parameter. */ OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription); } /** * An offset mapping for a given parameter of the instrumented method. */ class ForParameter implements OffsetMapping { /** * The index of the parameter. */ private final int index; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type expected by the advise method. */ private final TypeDescription targetType; /** * Creates a new offset mapping for a parameter. * * @param argument The annotation for which the mapping is to be created. * @param targetType Determines if the parameter is to be treated as read-only. */ protected ForParameter(Argument argument, TypeDescription targetType) { this(argument.value(), argument.readOnly(), targetType); } /** * Creates a new offset mapping for a parameter of the instrumented method. * * @param index The index of the parameter. * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The type expected by the advise method. */ protected ForParameter(int index, boolean readOnly, TypeDescription targetType) { this.index = index; this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { ParameterList<?> parameters = instrumentedMethod.getParameters(); if (parameters.size() <= index) { throw new IllegalStateException(instrumentedMethod + " does not define an index " + index); } else if (!readOnly && !parameters.get(index).getType().asErasure().equals(targetType)) { throw new IllegalStateException("read-only " + targetType + " is not equal to type of " + parameters.get(index)); } else if (readOnly && !parameters.get(index).getType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException(targetType + " is not assignable to " + parameters.get(index)); } return readOnly ? new Target.ForReadOnlyParameter(parameters.get(index).getOffset()) : new Target.ForParameter(parameters.get(index).getOffset()); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForParameter that = (ForParameter) object; return index == that.index && readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { int result = index; result = 31 * result + (readOnly ? 1 : 0); result = 31 * result + targetType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForParameter{" + "index=" + index + ", readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForParameter} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Argument> annotation = parameterDescription.getDeclaredAnnotations().ofType(Argument.class); return annotation == null ? UNDEFINED : new ForParameter(annotation.loadSilent(), parameterDescription.getType().asErasure()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForParameter.Factory." + name(); } } } /** * An offset mapping that provides access to the {@code this} reference of the instrumented method. */ class ForThisReference implements OffsetMapping { /** * The offset of the this reference in a Java method. */ private static final int THIS_REFERENCE = 0; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type that the advise method expects for the {@code this} reference. */ private final TypeDescription targetType; /** * Creates a new offset mapping for a {@code this} reference. * * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The type that the advise method expects for the {@code this} reference. */ protected ForThisReference(boolean readOnly, TypeDescription targetType) { this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { if (instrumentedMethod.isStatic()) { throw new IllegalStateException("Cannot map this reference for static method " + instrumentedMethod); } else if (!readOnly && !instrumentedMethod.getDeclaringType().equals(targetType)) { throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not equal to read-only " + targetType); } else if (readOnly && !instrumentedMethod.getDeclaringType().isAssignableTo(targetType)) { throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not assignable to " + targetType); } return readOnly ? new Target.ForReadOnlyParameter(THIS_REFERENCE) : new Target.ForParameter(THIS_REFERENCE); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForThisReference that = (ForThisReference) object; return readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { int result = (readOnly ? 1 : 0); result = 31 * result + targetType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForThisReference{" + "readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForThisReference} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<This> annotation = parameterDescription.getDeclaredAnnotations().ofType(This.class); return annotation == null ? UNDEFINED : new ForThisReference(annotation.loadSilent().readOnly(), parameterDescription.getType().asErasure()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForThisReference.Factory." + name(); } } } /** * An offset mapping for a field. */ abstract class ForField implements OffsetMapping { /** * The name of the field. */ protected final String name; /** * The expected type that the field can be assigned to. */ protected final TypeDescription targetType; /** * Creates an offset mapping for a field. * * @param name The name of the field. * @param targetType The expected type that the field can be assigned to. */ protected ForField(String name, TypeDescription targetType) { this.name = name; this.targetType = targetType; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForField forField = (ForField) object; return name.equals(forField.name) && targetType.equals(forField.targetType); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + targetType.hashCode(); return result; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { FieldLocator.Resolution resolution = fieldLocator(instrumentedMethod.getDeclaringType()).locate(name); if (!resolution.isResolved()) { throw new IllegalStateException("Cannot locate field named " + name + " for " + instrumentedMethod); } else if (!resolution.getField().getType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException("Cannot assign type of field " + resolution.getField() + " to " + targetType); } else if (!resolution.getField().isStatic() && instrumentedMethod.isStatic()) { throw new IllegalStateException("Cannot read non-static field " + resolution.getField() + " from static method " + instrumentedMethod); } return new Target.ForField(resolution.getField()); } /** * Returns a field locator for this instance. * * @param instrumentedType The instrumented type. * @return An appropriate field locator. */ protected abstract FieldLocator fieldLocator(TypeDescription instrumentedType); /** * An offset mapping for a field with an implicit declaring type. */ protected static class WithImplicitType extends ForField { /** * Creates an offset mapping for a field with an implicit declaring type. * * @param name The name of the field. * @param targetType The expected type that the field can be assigned to. */ protected WithImplicitType(String name, TypeDescription targetType) { super(name, targetType); } @Override protected FieldLocator fieldLocator(TypeDescription instrumentedType) { return new FieldLocator.ForClassHierarchy(instrumentedType); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForField.WithImplicitType{" + "name=" + name + ", targetType=" + targetType + '}'; } } /** * An offset mapping for a field with an explicit declaring type. */ protected static class WithExplicitType extends ForField { /** * The type declaring the field. */ private final TypeDescription explicitType; /** * Creates an offset mapping for a field with an explicit declaring type. * * @param name The name of the field. * @param targetType The expected type that the field can be assigned to. * @param locatedType The type declaring the field. */ protected WithExplicitType(String name, TypeDescription targetType, TypeDescription locatedType) { super(name, targetType); this.explicitType = locatedType; } @Override protected FieldLocator fieldLocator(TypeDescription instrumentedType) { if (!instrumentedType.isAssignableTo(explicitType)) { throw new IllegalStateException(explicitType + " is no super type of " + instrumentedType); } return new FieldLocator.ForExactType(explicitType); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; if (!super.equals(object)) return false; WithExplicitType that = (WithExplicitType) object; return explicitType.equals(that.explicitType); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + explicitType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForField.WithExplicitType{" + "name=" + name + ", targetType=" + targetType + ", explicitType=" + explicitType + '}'; } } /** * A factory for a {@link ForField} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; /** * Creates a new factory for a {@link ForField} offset mapping. */ Factory() { MethodList<MethodDescription.InDefinedShape> methods = new TypeDescription.ForLoadedType(FieldValue.class).getDeclaredMethods(); value = methods.filter(named("value")).getOnly(); definingType = methods.filter(named("declaringType")).getOnly(); } /** * The {@link FieldValue#value()} method. */ private final MethodDescription.InDefinedShape value; /** * The {@link FieldValue#declaringType()}} method. */ private final MethodDescription.InDefinedShape definingType; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription annotation = parameterDescription.getDeclaredAnnotations().ofType(FieldValue.class); if (annotation == null) { return UNDEFINED; } else { TypeDescription definingType = annotation.getValue(this.definingType, TypeDescription.class); String name = annotation.getValue(value, String.class); TypeDescription targetType = parameterDescription.getType().asErasure(); return definingType.represents(void.class) ? new WithImplicitType(name, targetType) : new WithExplicitType(name, targetType, definingType); } } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForField.Factory." + name(); } } } /** * An offset mapping for the {@link Advice.Origin} annotation. */ class ForOrigin implements OffsetMapping { /** * The delimiter character. */ private static final char DELIMITER = ' /** * The escape character. */ private static final char ESCAPE = '\\'; /** * The method name symbol. */ private static final char METHOD_NAME = 'm'; /** * The type name symbol. */ private static final char TYPE_NAME = 't'; /** * The descriptor symbol. */ private static final char DESCRIPTOR = 'd'; /** * The renderers to apply. */ private final List<Renderer> renderers; /** * Creates a new offset mapping for an origin value. * * @param renderers The renderers to apply. */ protected ForOrigin(List<Renderer> renderers) { this.renderers = renderers; } /** * Parses a pattern of an origin annotation. * * @param pattern The supplied pattern. * @return An appropriate offset mapping. */ protected static OffsetMapping parse(String pattern) { if (pattern.equals(Origin.DEFAULT)) { return new ForOrigin(Collections.<Renderer>singletonList(Renderer.ForStringRepresentation.INSTANCE)); } else { List<Renderer> renderers = new ArrayList<Renderer>(pattern.length()); int from = 0; for (int to = pattern.indexOf(DELIMITER); to != -1; to = pattern.indexOf(DELIMITER, from)) { if (to != 0 && pattern.charAt(to - 1) == ESCAPE && (to == 1 || pattern.charAt(to - 2) != ESCAPE)) { renderers.add(new Renderer.ForConstantValue(pattern.substring(from, Math.max(0, to - 1)) + DELIMITER)); from = to + 1; continue; } else if (pattern.length() == to + 1) { throw new IllegalStateException("Missing sort descriptor for " + pattern + " at index " + to); } renderers.add(new Renderer.ForConstantValue(pattern.substring(from, to).replace("" + ESCAPE + ESCAPE, "" + ESCAPE))); switch (pattern.charAt(to + 1)) { case METHOD_NAME: renderers.add(Renderer.ForMethodName.INSTANCE); break; case TYPE_NAME: renderers.add(Renderer.ForTypeName.INSTANCE); break; case DESCRIPTOR: renderers.add(Renderer.ForDescriptor.INSTANCE); break; default: throw new IllegalStateException("Illegal sort descriptor " + pattern.charAt(to + 1) + " for " + pattern); } from = to + 2; } renderers.add(new Renderer.ForConstantValue(pattern.substring(from))); return new ForOrigin(renderers); } } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { StringBuilder stringBuilder = new StringBuilder(); for (Renderer renderer : renderers) { stringBuilder.append(renderer.apply(instrumentedMethod)); } return new Target.ForConstantPoolValue(stringBuilder.toString()); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForOrigin forOrigin = (ForOrigin) object; return renderers.equals(forOrigin.renderers); } @Override public int hashCode() { return renderers.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForOrigin{" + "renderers=" + renderers + '}'; } /** * A renderer for an origin pattern element. */ protected interface Renderer { /** * Returns a string representation for this renderer. * * @param instrumentedMethod The method being rendered. * @return The string representation. */ String apply(MethodDescription.InDefinedShape instrumentedMethod); /** * A renderer for a method's internal name. */ enum ForMethodName implements Renderer { /** * The singleton instance. */ INSTANCE; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.getInternalName(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForOrigin.Renderer.ForMethodName." + name(); } } /** * A renderer for a method declaring type's binary name. */ enum ForTypeName implements Renderer { /** * The singleton instance. */ INSTANCE; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.getDeclaringType().getName(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForOrigin.Renderer.ForTypeName." + name(); } } /** * A renderer for a method descriptor. */ enum ForDescriptor implements Renderer { /** * The singleton instance. */ INSTANCE; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.getDescriptor(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForOrigin.Renderer.ForDescriptor." + name(); } } /** * A renderer for a method's {@link Object#toString()} representation. */ enum ForStringRepresentation implements Renderer { /** * The singleton instance. */ INSTANCE; @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return instrumentedMethod.toString(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForOrigin.Renderer.ForStringRepresentation." + name(); } } /** * A renderer for a constant value. */ class ForConstantValue implements Renderer { /** * The constant value. */ private final String value; /** * Creates a new renderer for a constant value. * * @param value The constant value. */ protected ForConstantValue(String value) { this.value = value; } @Override public String apply(MethodDescription.InDefinedShape instrumentedMethod) { return value; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForConstantValue that = (ForConstantValue) object; return value.equals(that.value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForOrigin.Renderer.ForConstantValue{" + "value='" + value + '\'' + '}'; } } } /** * A factory for a method origin. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Origin> origin = parameterDescription.getDeclaredAnnotations().ofType(Origin.class); if (origin == null) { return UNDEFINED; } else { if (!parameterDescription.getType().asErasure().isAssignableFrom(String.class)) { throw new IllegalStateException("Non-String type " + parameterDescription + " for origin annotation"); } return ForOrigin.parse(origin.loadSilent().value()); } } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForOrigin.Factory." + name(); } } } /** * An offset mapping for a parameter where assignments are fully ignored and that always return the parameter type's default value. */ enum ForIgnored implements OffsetMapping, Factory { /** * The singleton instance. */ INSTANCE; @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { return Target.ForDefaultValue.INSTANCE; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { return parameterDescription.getDeclaredAnnotations().isAnnotationPresent(Ignored.class) ? this : UNDEFINED; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForIgnored." + name(); } } /** * An offset mapping that provides access to the value that is returned by the enter advise. */ enum ForEnterValue implements OffsetMapping { /** * Enables writing to the mapped offset. */ WRITABLE(false), /** * Only allows for reading the mapped offset. */ READ_ONLY(true); /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * Creates a new offset mapping for an enter value. * * @param readOnly Determines if the parameter is to be treated as read-only. */ ForEnterValue(boolean readOnly) { this.readOnly = readOnly; } /** * Resolves an offset mapping for an enter value. * * @param readOnly {@code true} if the value is to be treated as read-only. * @return An appropriate offset mapping. */ public static OffsetMapping of(boolean readOnly) { return readOnly ? READ_ONLY : WRITABLE; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { return readOnly ? new Target.ForReadOnlyParameter(instrumentedMethod.getStackSize()) : new Target.ForParameter(instrumentedMethod.getStackSize()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForEnterValue." + name(); } /** * A factory for creating a {@link ForEnterValue} offset mapping. */ protected static class Factory implements OffsetMapping.Factory { /** * The supplied type of the enter method. */ private final TypeDescription enterType; /** * Creates a new factory for creating a {@link ForEnterValue} offset mapping. * * @param enterType The supplied type of the enter method. */ protected Factory(TypeDescription enterType) { this.enterType = enterType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Enter> annotation = parameterDescription.getDeclaredAnnotations().ofType(Enter.class); if (annotation != null) { boolean readOnly = annotation.loadSilent().readOnly(); if (!readOnly && !enterType.equals(parameterDescription.getType().asErasure())) { throw new IllegalStateException("read-only type of " + parameterDescription + " does not equal " + enterType); } else if (readOnly && !enterType.isAssignableTo(parameterDescription.getType().asErasure())) { throw new IllegalStateException("Cannot assign the type of " + parameterDescription + " to supplied type " + enterType); } return ForEnterValue.of(readOnly); } else { return UNDEFINED; } } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && enterType.equals(((Factory) other).enterType); } @Override public int hashCode() { return enterType.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForEnterValue.Factory{" + "enterType=" + enterType + '}'; } } } /** * An offset mapping that provides access to the value that is returned by the instrumented method. */ class ForReturnValue implements OffsetMapping { /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type that the advise method expects for the {@code this} reference. */ private final TypeDescription targetType; /** * Creates an offset mapping for accessing the return type of the instrumented method. * * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The expected target type of the return type. */ protected ForReturnValue(boolean readOnly, TypeDescription targetType) { this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { if (!readOnly && !instrumentedMethod.getReturnType().asErasure().equals(targetType)) { throw new IllegalStateException("read-only return type of " + instrumentedMethod + " is not equal to " + targetType); } else if (readOnly && !instrumentedMethod.getReturnType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException("Cannot assign return type of " + instrumentedMethod + " to " + targetType); } return readOnly ? new Target.ForReadOnlyParameter(instrumentedMethod.getStackSize() + enterType.getStackSize().getSize()) : new Target.ForParameter(instrumentedMethod.getStackSize() + enterType.getStackSize().getSize()); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ForReturnValue that = (ForReturnValue) other; return readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { return (readOnly ? 1 : 0) + 31 * targetType.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForReturnValue{" + "readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForReturnValue} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Return> annotation = parameterDescription.getDeclaredAnnotations().ofType(Return.class); return annotation == null ? UNDEFINED : new ForReturnValue(annotation.loadSilent().readOnly(), parameterDescription.getType().asErasure()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForReturnValue.Factory." + name(); } } } /** * An offset mapping for accessing a {@link Throwable} of the instrumented method. */ enum ForThrowable implements OffsetMapping, Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { if (parameterDescription.getDeclaredAnnotations().isAnnotationPresent(Thrown.class)) { if (!parameterDescription.getType().represents(Throwable.class)) { throw new IllegalStateException("Parameter must be of type Throwable for " + parameterDescription); } return this; } else { return UNDEFINED; } } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, TypeDescription enterType) { return new Target.ForParameter(instrumentedMethod.getStackSize() + enterType.getStackSize().getSize() + instrumentedMethod.getReturnType().getStackSize().getSize()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForThrowable." + name(); } } class Illegal implements Factory { private final List<? extends Class<? extends Annotation>> annotations; //@SafeVarargs protected Illegal(Class<? extends Annotation>... annotation) { this(Arrays.asList(annotation)); } protected Illegal(List<? extends Class<? extends Annotation>> annotations) { this.annotations = annotations; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { for (Class<? extends Annotation> annotation : annotations) { if (parameterDescription.getDeclaredAnnotations().isAnnotationPresent(annotation)) { throw new IllegalStateException("Illegal annotation " + annotation + " for " + parameterDescription); } } return UNDEFINED; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Illegal illegal = (Illegal) other; return annotations.equals(illegal.annotations); } @Override public int hashCode() { return annotations.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Illegal{" + "annotations=" + annotations + '}'; } } } /** * A resolved dispatcher for implementing method enter advise. */ protected static class ForMethodEnter extends Resolved implements Dispatcher.Resolved.ForMethodEnter { /** * The {@code suppress} property of the {@link OnMethodEnter} type. */ private static final MethodDescription.InDefinedShape SUPPRESS; /* * Extracts the suppress property. */ static { SUPPRESS = new TypeDescription.ForLoadedType(OnMethodEnter.class).getDeclaredMethods().filter(named("suppress")).getOnly(); } /** * Creates a new resolved dispatcher for implementing method enter advise. * * @param adviseMethod The represented advise method. */ @SuppressWarnings("all") // In absence of @SafeVarargs for Java 6 protected ForMethodEnter(MethodDescription.InDefinedShape adviseMethod) { super(adviseMethod, OffsetMapping.ForParameter.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, OffsetMapping.ForField.Factory.INSTANCE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForIgnored.INSTANCE, new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class)); } @Override public TypeDescription getEnterType() { return adviseMethod.getReturnType().asErasure(); } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, MetaDataHandler.ForInstrumentedMethod metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, TypeDescription.VOID)); } return new CodeTranslationVisitor.ForMethodEnter(methodVisitor, metaDataHandler.bindEntry(adviseMethod), instrumentedMethod, adviseMethod, offsetMappings, adviseMethod.getDeclaredAnnotations().ofType(OnMethodEnter.class).getValue(SUPPRESS, TypeDescription.class)); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.ForMethodEnter{" + "adviseMethod=" + adviseMethod + ", offsetMappings=" + offsetMappings + '}'; } } /** * A resolved dispatcher for implementing method exit advise. */ protected static class ForMethodExit extends Resolved implements Dispatcher.Resolved.ForMethodExit { /** * The {@code suppress} method of the {@link OnMethodExit} annotation. */ private static final MethodDescription.InDefinedShape SUPPRESS; /* * Extracts the suppress method. */ static { SUPPRESS = new TypeDescription.ForLoadedType(OnMethodExit.class).getDeclaredMethods().filter(named("suppress")).getOnly(); } /** * The additional stack size to consider when accessing the local variable array. */ private final TypeDescription enterType; /** * Creates a new resolved dispatcher for implementing method exit advise. * * @param adviseMethod The represented advise method. * @param enterType The type of the value supplied by the enter advise method or a description of {@code void} if * no such value exists. */ @SuppressWarnings("all") // In absence of @SafeVarargs for Java 6 protected ForMethodExit(MethodDescription.InDefinedShape adviseMethod, TypeDescription enterType) { super(adviseMethod, OffsetMapping.ForParameter.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, OffsetMapping.ForField.Factory.INSTANCE, OffsetMapping.ForOrigin.Factory.INSTANCE, OffsetMapping.ForIgnored.INSTANCE, new OffsetMapping.ForEnterValue.Factory(enterType), OffsetMapping.ForReturnValue.Factory.INSTANCE, adviseMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).loadSilent().onThrowable() ? OffsetMapping.ForThrowable.INSTANCE : new OffsetMapping.Illegal(Thrown.class)); this.enterType = enterType; } @Override public boolean isSkipThrowable() { return !adviseMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).loadSilent().onThrowable(); } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, MetaDataHandler.ForInstrumentedMethod metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, enterType)); } return new CodeTranslationVisitor.ForMethodExit(methodVisitor, metaDataHandler.bindExit(adviseMethod, enterType), instrumentedMethod, adviseMethod, offsetMappings, adviseMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).getValue(SUPPRESS, TypeDescription.class), enterType); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && super.equals(other) && enterType == ((Resolved.ForMethodExit) other).enterType; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + enterType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.ForMethodExit{" + "adviseMethod=" + adviseMethod + ", offsetMappings=" + offsetMappings + ", enterType=" + enterType + '}'; } } } /** * A producer for a default return value if this is applicable. */ interface ReturnValueProducer { /** * Sets a default return value for an advised method. * * @param methodVisitor The instrumented method's method visitor. */ void makeDefault(MethodVisitor methodVisitor); } /** * A visitor for translating an advise method's byte code for inlining into the instrumented method. */ protected abstract static class CodeTranslationVisitor extends MethodVisitor implements ReturnValueProducer { /** * Indicates that an annotation should not be read. */ private static final AnnotationVisitor IGNORE_ANNOTATION = null; /** * The frame translator to use. */ protected final MetaDataHandler.ForAdvice metaDataHandler; /** * The instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The advise method. */ protected final MethodDescription.InDefinedShape adviseMethod; /** * A mapping of offsets to resolved target offsets in the instrumented method. */ private final Map<Integer, Resolved.OffsetMapping.Target> offsetMappings; /** * A handler for optionally suppressing exceptions. */ private final SuppressionHandler suppressionHandler; /** * A label indicating the end of the advise byte code. */ protected final Label endOfMethod; /** * Creates a new code translation visitor. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param metaDataHandler The frame translator to use. * @param instrumentedMethod The instrumented method. * @param adviseMethod The advise method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. * @param throwableType A throwable type to be suppressed or {@link NoSuppression} if no suppression should be applied. */ protected CodeTranslationVisitor(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviseMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings, TypeDescription throwableType) { super(Opcodes.ASM5, methodVisitor); this.metaDataHandler = metaDataHandler; this.instrumentedMethod = instrumentedMethod; this.adviseMethod = adviseMethod; this.offsetMappings = offsetMappings; suppressionHandler = throwableType.represents(NoSuppression.class) ? SuppressionHandler.NoOp.INSTANCE : new SuppressionHandler.Suppressing(throwableType); endOfMethod = new Label(); } @Override public void visitParameter(String name, int modifiers) { /* do nothing */ } @Override public AnnotationVisitor visitAnnotationDefault() { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitTypeAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitParameterAnnotation(int index, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public void visitAttribute(Attribute attribute) { /* do nothing */ } @Override public void visitCode() { suppressionHandler.onStart(mv, metaDataHandler); } @Override public void visitFrame(int frameType, int localVariableLength, Object[] localVariable, int stackSize, Object[] stack) { metaDataHandler.translateFrame(mv, frameType, localVariableLength, localVariable, stackSize, stack); } @Override public void visitLineNumber(int line, Label start) { /* do nothing */ } @Override public void visitEnd() { suppressionHandler.onEnd(mv, metaDataHandler, this); mv.visitLabel(endOfMethod); metaDataHandler.injectCompletionFrame(mv, false); } @Override public void visitMaxs(int maxStack, int maxLocals) { metaDataHandler.recordMaxima(maxStack, maxLocals); } @Override public void visitVarInsn(int opcode, int offset) { Resolved.OffsetMapping.Target target = offsetMappings.get(offset); if (target != null) { target.resolveAccess(mv, opcode); } else { mv.visitVarInsn(opcode, adjust(offset + instrumentedMethod.getStackSize() - adviseMethod.getStackSize())); } } @Override public void visitIincInsn(int offset, int increment) { Resolved.OffsetMapping.Target target = offsetMappings.get(offset); if (target != null) { target.resolveIncrement(mv, increment); } else { mv.visitIincInsn(adjust(offset + instrumentedMethod.getStackSize() - adviseMethod.getStackSize()), increment); } } /** * Adjusts the offset of a variable instruction within the advise method such that no arguments to * the instrumented method are overridden. * * @param offset The original offset. * @return The adjusted offset. */ protected abstract int adjust(int offset); @Override public abstract void visitInsn(int opcode); /** * A suppression handler for optionally suppressing exceptions. */ protected interface SuppressionHandler { /** * Invoked at the start of a method. * * @param methodVisitor The method visitor of the instrumented method. * @param metaDataHandler The frame translator to use. */ void onStart(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler); /** * Invoked at the end of a method. * * @param methodVisitor The method visitor of the instrumented method. * @param metaDataHandler The frame translator to use. * @param returnValueProducer A producer for defining a default return value of the advised method. */ void onEnd(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer); /** * A non-operational suppression handler that does not suppress any method. */ enum NoOp implements SuppressionHandler { /** * The singleton instance. */ INSTANCE; @Override public void onStart(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler) { /* do nothing */ } @Override public void onEnd(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer) { /* do nothing */ } @Override public String toString() { return "Advice.Dispatcher.Active.CodeTranslationVisitor.SuppressionHandler.NoOp." + name(); } } /** * A suppression handler that suppresses a given throwable type. */ class Suppressing implements SuppressionHandler { /** * The suppressed throwable type. */ private final TypeDescription throwableType; /** * A label indicating the start of the method. */ private final Label startOfMethod; private final Label endOfMethod; /** * Creates a new suppressing suppression handler. * * @param throwableType The suppressed throwable type. */ protected Suppressing(TypeDescription throwableType) { this.throwableType = throwableType; startOfMethod = new Label(); endOfMethod = new Label(); } @Override public void onStart(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler) { methodVisitor.visitTryCatchBlock(startOfMethod, endOfMethod, endOfMethod, throwableType.getInternalName()); methodVisitor.visitLabel(startOfMethod); } @Override public void onEnd(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, ReturnValueProducer returnValueProducer) { Label endOfHandler = new Label(); methodVisitor.visitLabel(endOfMethod); metaDataHandler.injectHandlerFrame(methodVisitor); methodVisitor.visitInsn(Opcodes.POP); returnValueProducer.makeDefault(methodVisitor); methodVisitor.visitLabel(endOfHandler); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Suppressing that = (Suppressing) object; return throwableType.equals(that.throwableType); } @Override public int hashCode() { return throwableType.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.CodeTranslationVisitor.SuppressionHandler.Suppressing{" + "throwableType=" + throwableType + ", startOfMethod=" + startOfMethod + '}'; } } } /** * A code translation visitor that retains the return value of the represented advise method. */ protected static class ForMethodEnter extends CodeTranslationVisitor { protected ForMethodEnter(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviseMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings, TypeDescription throwableType) { super(methodVisitor, metaDataHandler, instrumentedMethod, adviseMethod, offsetMappings, throwableType); } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: break; case Opcodes.IRETURN: mv.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize()); break; case Opcodes.LRETURN: mv.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize()); break; case Opcodes.ARETURN: mv.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize()); break; case Opcodes.FRETURN: mv.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize()); break; case Opcodes.DRETURN: mv.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize()); break; default: mv.visitInsn(opcode); return; } mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } @Override protected int adjust(int offset) { return offset; } @Override public void makeDefault(MethodVisitor methodVisitor) { if (adviseMethod.getReturnType().represents(boolean.class) || adviseMethod.getReturnType().represents(byte.class) || adviseMethod.getReturnType().represents(short.class) || adviseMethod.getReturnType().represents(char.class) || adviseMethod.getReturnType().represents(int.class)) { methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize()); } else if (adviseMethod.getReturnType().represents(long.class)) { methodVisitor.visitInsn(Opcodes.LCONST_0); methodVisitor.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize()); } else if (adviseMethod.getReturnType().represents(float.class)) { methodVisitor.visitInsn(Opcodes.FCONST_0); methodVisitor.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize()); } else if (adviseMethod.getReturnType().represents(double.class)) { methodVisitor.visitInsn(Opcodes.DCONST_0); methodVisitor.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize()); } else if (!adviseMethod.getReturnType().represents(void.class)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize()); } } @Override public String toString() { return "Advice.Dispatcher.Active.CodeTranslationVisitor.ForMethodEnter{" + "instrumentedMethod=" + instrumentedMethod + ", adviseMethod=" + adviseMethod + '}'; } } /** * A code translation visitor that discards the return value of the represented advise method. */ protected static class ForMethodExit extends CodeTranslationVisitor { /** * The size of the exception slot for the instrumented method's potential exception. */ private static final int EXCEPTION_SIZE = 1; /** * The type returned by the method method entry advice if any. */ private final TypeDescription enterType; protected ForMethodExit(MethodVisitor methodVisitor, MetaDataHandler.ForAdvice metaDataHandler, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviseMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings, TypeDescription throwableType, TypeDescription enterType) { super(methodVisitor, metaDataHandler, instrumentedMethod, adviseMethod, offsetMappings, throwableType); this.enterType = enterType; } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: break; case Opcodes.IRETURN: case Opcodes.ARETURN: case Opcodes.FRETURN: mv.visitInsn(Opcodes.POP); break; case Opcodes.LRETURN: case Opcodes.DRETURN: mv.visitInsn(Opcodes.POP2); break; default: mv.visitInsn(opcode); return; } mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } @Override protected int adjust(int offset) { return offset + instrumentedMethod.getReturnType().getStackSize().getSize() + enterType.getStackSize().getSize() + EXCEPTION_SIZE; } @Override public void makeDefault(MethodVisitor methodVisitor) { /* do nothing */ } @Override public String toString() { return "Advice.Dispatcher.Active.CodeTranslationVisitor.ForMethodExit{" + "instrumentedMethod=" + instrumentedMethod + ", adviseMethod=" + adviseMethod + ", enterType=" + enterType + '}'; } } } } } /** * <p> * Indicates that this method should be inlined before the matched method is invoked. Any class must declare * at most one method with this annotation. The annotated method must be static. When instrumenting constructors, * the {@code this} values can only be accessed for writing fields but not for reading fields or invoking methods. * </p> * <p> * The annotated method can return a value that is made accessible to another method annotated by {@link OnMethodExit}. * </p> * * @see Advice * @see Argument * @see This */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMethodEnter { /** * Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution. * * @return The type of {@link Throwable} to suppress. */ Class<? extends Throwable> suppress() default NoSuppression.class; } /** * <p> * Indicates that this method should be inlined before the matched method is invoked. Any class must declare * at most one method with this annotation. The annotated method must be static. * </p> * <p> * The annotated method can imply to not be invoked when the instrumented method terminates exceptionally by * setting the {@link OnMethodExit#onThrowable()} property. * </p> * * @see Advice * @see Argument * @see This * @see Enter * @see Return * @see Thrown */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMethodExit { /** * Indicates that the advise method should also be called when a method terminates exceptionally. * * @return {@code true} if the advise method should be invoked when a method terminates exceptionally. */ boolean onThrowable() default true; /** * Indicates that this advice should suppress any {@link Throwable} type being thrown during the advice's execution. * * @return The type of {@link Throwable} to suppress. */ Class<? extends Throwable> suppress() default NoSuppression.class; } /** * Indicates that the annotated parameter should be mapped to the parameter with index {@link Argument#value()} of * the instrumented method. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Argument { /** * Returns the index of the mapped parameter. * * @return The index of the mapped parameter. */ int value(); /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * <p> * Indicates that the annotated parameter should be mapped to the {@code this} reference of the instrumented method. * </p> * <p> * <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with * {@link OnMethodEnter} where the {@code this} reference is not available. * </p> * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface This { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to a field in the scope of the instrumented method. All * field references are always <i>read-only</i>. * <p> * <b>Important</b>: Parameters with this option must not be used when from a constructor in combination with * {@link OnMethodEnter} and a non-static field where the {@code this} reference is not available. * </p> * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface FieldValue { /** * Returns the name of the field. * * @return The name of the field. */ String value(); /** * Returns the type that declares the field that should be mapped to the annotated parameter. If this property * is set to {@code void}, the field is looked up implicitly within the instrumented class's class hierarchy. * * @return The type that declares the field or {@code void} if this type should be determined implicitly. */ Class<?> declaringType() default void.class; } /** * Indicates that the annotated parameter should be mapped to a string representation of the instrumented method. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Origin { /** * Indicates that the origin string should be indicated by the {@link Object#toString()} representation of the instrumented method. */ String DEFAULT = ""; /** * Returns the pattern the annotated parameter should be assigned. By default, the {@link Origin#toString()} representation * of the method is assigned. Alternatively, a pattern can be assigned where {@code #t} inserts the method's declaring type, * {@code #m} inserts the name of the method ({@code <init>} for constructors and {@code <clinit>} for static initializers) * and {@code #d} for the method's descriptor. Any other {@code #} character must be escaped by {@code \} which can be * escaped by itself. * * @return The pattern the annotated parameter should be assigned. */ String value() default DEFAULT; } /** * Indicates that the annotated parameter should always return a default value (i.e. {@code 0} for numeric values, {@code false} * for {@code boolean} types and {@code null} for reference types). * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Ignored { /* empty */ } /** * Indicates that the annotated parameter should be mapped to the value that is returned by the advise method that is annotated * by {@link OnMethodEnter}. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Enter { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented * method terminates exceptionally, the type's default value is assigned to the parameter, i.e. {@code 0} for numeric types * and {@code null} for reference types. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Return { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. For this to be valid, * the parameter must be of type {@link Throwable}. If the instrumented method terminates regularly, {@code null} is assigned to * the annotated parameter. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Thrown { /* empty */ } /** * A marker class that indicates that an advice method does not suppress any {@link Throwable}. */ private static class NoSuppression extends Throwable { /** * A private constructor as this class is not supposed to be invoked. */ private NoSuppression() { throw new UnsupportedOperationException("This marker class is not supposed to be instantiated"); } } }
package nl.mpi.arbil.ui; import java.awt.Point; import java.util.Arrays; import nl.mpi.arbil.util.WindowManager; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.arbil.ui.menu.ArbilMenuBar; import nl.mpi.arbil.userstorage.ArbilSessionStorage; import nl.mpi.arbil.data.ArbilTreeHelper; import nl.mpi.arbil.data.ArbilDataNode; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.KeyboardFocusManager; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.FilenameFilter; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Vector; import javax.swing.JDesktopPane; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ProgressMonitor; import javax.swing.SwingUtilities; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.InternalFrameAdapter; import javax.swing.event.InternalFrameEvent; import javax.swing.filechooser.FileFilter; import javax.swing.plaf.FontUIResource; import nl.mpi.arbil.ui.fieldeditors.ArbilLongFieldEditor; import nl.mpi.arbil.ArbilVersion; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.util.ApplicationVersion; import nl.mpi.arbil.util.ApplicationVersionManager; public class ArbilWindowManager implements MessageDialogHandler, WindowManager { private Hashtable<String, Component[]> windowList = new Hashtable<String, Component[]>(); private Hashtable windowStatesHashtable; public JDesktopPane desktopPane; //TODO: this is public for the dialog boxes to use, but will change when the strings are loaded from the resources public JFrame linorgFrame; private final static int defaultWindowX = 50; private final static int defaultWindowY = 50; private final static int nextWindowWidth = 800; private final static int nextWindowHeight = 600; private int nextWindowX = defaultWindowX; private int nextWindowY = defaultWindowY; float fontScale = 1; private Hashtable<String, String> messageDialogQueue = new Hashtable<String, String>(); private boolean messagesCanBeShown = false; boolean showMessageThreadrunning = false; static private ArbilWindowManager singleInstance = null; private static ApplicationVersionManager versionManager; public static void setVersionManager(ApplicationVersionManager versionManagerInstance) { versionManager = versionManagerInstance; } static synchronized public ArbilWindowManager getSingleInstance() { // System.out.println("LinorgWindowManager getSingleInstance"); if (singleInstance == null) { singleInstance = new ArbilWindowManager(); } return singleInstance; } private ArbilWindowManager() { desktopPane = new JDesktopPane(); desktopPane.setBackground(new java.awt.Color(204, 204, 204)); ArbilDragDrop.getSingleInstance().setTransferHandlerOnComponent(desktopPane); } public void setMessagesCanBeShown(boolean messagesCanBeShown) { // this should be set to true whent the main window has been shown, before this stage of loading messages should not be shown this.messagesCanBeShown = messagesCanBeShown; } public void loadGuiState(JFrame linorgFrameLocal) { linorgFrame = linorgFrameLocal; try { // load the saved states windowStatesHashtable = (Hashtable) ArbilSessionStorage.getSingleInstance().loadObject("windowStates"); // set the main window position and size. Also puts window on the correct screen (relevant for maximization) Object linorgFrameBounds = windowStatesHashtable.get("linorgFrameBounds"); if (linorgFrameBounds != null) { linorgFrame.setBounds((Rectangle) linorgFrameBounds); } // set window state (i.e. maximized or not) linorgFrame.setExtendedState((Integer) windowStatesHashtable.get("linorgFrameExtendedState")); if (linorgFrame.getExtendedState() == JFrame.ICONIFIED) { // start up iconified is just too confusing to the user linorgFrame.setExtendedState(JFrame.NORMAL); } if (windowStatesHashtable.containsKey("ScreenDeviceCount")) { int screenDeviceCount = ((Integer) windowStatesHashtable.get("ScreenDeviceCount")); if (screenDeviceCount > GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length) { linorgFrame.setLocationRelativeTo(null); // make sure the main frame is visible. for instance when a second monitor has been removed. Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize(); if (linorgFrame.getBounds().intersects(new Rectangle(screenDimension))) { linorgFrame.setBounds(linorgFrame.getBounds().intersection(new Rectangle(screenDimension))); } else { linorgFrame.setBounds(0, 0, 800, 600); linorgFrame.setLocationRelativeTo(null); } } } } catch (Exception ex) { System.out.println("load windowStates failed: " + ex.getMessage()); System.out.println("setting default windowStates"); windowStatesHashtable = new Hashtable(); linorgFrame.setBounds(0, 0, 800, 600); linorgFrame.setLocationRelativeTo(null); linorgFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); } // set the split pane positions loadSplitPlanes(linorgFrame.getContentPane().getComponent(0)); } public void openAboutPage() { ApplicationVersion appVersion = versionManager.getApplicationVersion(); String messageString = "Archive Builder\n" + "A local tool for organising linguistic data.\n" + "Max Planck Institute for Psycholinguistics\n\n" + "Application design and programming by Peter Withers\n" + "Arbil also uses components of the IMDI API and Lamus Type Checker\n\n" + "Version: " + appVersion.currentMajor + "." + appVersion.currentMinor + "." + appVersion.currentRevision + "\n" + appVersion.lastCommitDate + "\n" + "Compile Date: " + appVersion.compileDate + "\n\n" + "Java version: " + System.getProperty("java.version") + " by " + System.getProperty("java.vendor"); JOptionPane.showMessageDialog(linorgFrame, messageString, "About " + appVersion.applicationTitle, JOptionPane.PLAIN_MESSAGE); } public void offerUserToSaveChanges() throws Exception { if (ArbilDataNodeLoader.getSingleInstance().nodesNeedSave()) { if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(ArbilWindowManager.getSingleInstance().linorgFrame, "There are unsaved changes.\nSave now?", "Save Changes", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) { ArbilDataNodeLoader.getSingleInstance().saveNodesNeedingSave(true); } else { throw new Exception("user canceled save action"); } } } public File showEmptyExportDirectoryDialogue(String titleText) { boolean fileSelectDone = false; try { while (!fileSelectDone) { File[] selectedFiles = ArbilWindowManager.getSingleInstance().showFileSelectBox(titleText + " Destination Directory", true, false, false); if (selectedFiles != null && selectedFiles.length > 0) { File destinationDirectory = selectedFiles[0]; boolean mkdirsOkay = true; if (destinationDirectory != null && !destinationDirectory.exists()/* && parentDirectory.getParentFile().exists()*/) { // create the directory provided that the parent directory exists // ths is here due the the way the mac file select gui leads the user to type in a new directory name mkdirsOkay = destinationDirectory.mkdirs(); } if (destinationDirectory == null || !mkdirsOkay || !destinationDirectory.exists()) { JOptionPane.showMessageDialog(linorgFrame, "The export directory\n\"" + destinationDirectory + "\"\ndoes not exist.\nPlease select or create a directory.", titleText, JOptionPane.PLAIN_MESSAGE); } else { // if (!createdDirectory) { // String newDirectoryName = JOptionPane.showInputDialog(linorgFrame, "Enter Export Name", titleText, JOptionPane.PLAIN_MESSAGE, null, null, "arbil_export").toString(); // try { // destinationDirectory = new File(parentDirectory.getCanonicalPath() + File.separatorChar + newDirectoryName); // destinationDirectory.mkdir(); // } catch (Exception e) { // JOptionPane.showMessageDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "Could not create the export directory + \'" + newDirectoryName + "\'", titleText, JOptionPane.PLAIN_MESSAGE); if (destinationDirectory.exists()) { if (destinationDirectory.list().length == 0) { fileSelectDone = true; return destinationDirectory; } else { if (showConfirmDialogBox("The selected export directory is not empty.\nTo continue will merge and may overwrite files.\nDo you want to continue?", titleText)) { return destinationDirectory; } //JOptionPane.showMessageDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "The export directory must be empty", titleText, JOptionPane.PLAIN_MESSAGE); } } } } else { fileSelectDone = true; } } } catch (Exception e) { System.out.println("aborting export: " + e.getMessage()); } return null; } public File[] showFileSelectBox(String titleText, boolean directorySelectOnly, boolean multipleSelect, boolean requireMetadataFiles) { // test for os: if mac or file then awt else for other and directory use swing // save/load last directory accoring to the title of the dialogue //Hashtable<String, File> fileSelectLocationsHashtable; File workingDirectory = null; String workingDirectoryPathString = ArbilSessionStorage.getSingleInstance().loadString("fileSelect." + titleText); if (workingDirectoryPathString == null) { workingDirectory = new File(System.getProperty("user.home")); } else { workingDirectory = new File(workingDirectoryPathString); } File lastUsedWorkingDirectory; File[] returnFile; boolean isMac = true; // TODO: set this correctly boolean useAtwSelect = false; //directorySelectOnly && isMac && !multipleSelect; if (useAtwSelect) { if (directorySelectOnly) { System.setProperty("apple.awt.fileDialogForDirectories", "true"); } else { System.setProperty("apple.awt.fileDialogForDirectories", "false"); } FileDialog fileDialog = new FileDialog(linorgFrame); if (requireMetadataFiles) { fileDialog.setFilenameFilter(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".imdi"); } }); } fileDialog.setDirectory(workingDirectory.getAbsolutePath()); fileDialog.setVisible(true); String selectedFile = fileDialog.getFile(); lastUsedWorkingDirectory = new File(fileDialog.getDirectory()); if (selectedFile != null) { returnFile = new File[]{new File(selectedFile)}; } else { returnFile = null; } } else { JFileChooser fileChooser = new JFileChooser(); if (requireMetadataFiles) { FileFilter imdiFileFilter = new FileFilter() { public String getDescription() { return "IMDI"; } @Override public boolean accept(File selectedFile) { // the test for exists is unlikey to do anything here, paricularly regarding the Mac dialogues text entry field return (selectedFile.exists() && (selectedFile.isDirectory() || selectedFile.getName().toLowerCase().endsWith(".imdi"))); } }; fileChooser.addChoosableFileFilter(imdiFileFilter); } if (directorySelectOnly) { // this filter is only cosmetic but gives the user an indication of what to select FileFilter imdiFileFilter = new FileFilter() { public String getDescription() { return "Directories"; } @Override public boolean accept(File selectedFile) { return (selectedFile.exists() && selectedFile.isDirectory()); } }; fileChooser.addChoosableFileFilter(imdiFileFilter); } if (directorySelectOnly) { fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } else { fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); } fileChooser.setCurrentDirectory(workingDirectory); fileChooser.setMultiSelectionEnabled(multipleSelect); if (JFileChooser.APPROVE_OPTION == fileChooser.showDialog(ArbilWindowManager.getSingleInstance().linorgFrame, titleText)) { returnFile = fileChooser.getSelectedFiles(); if (returnFile.length == 0) { returnFile = new File[]{fileChooser.getSelectedFile()}; } } else { returnFile = null; } if (returnFile != null && returnFile.length == 1 && !returnFile[0].exists()) { // if the selected file does not exist then the "unusable" mac file select is usually to blame so try to clean up returnFile[0] = returnFile[0].getParentFile(); // if the result still does not exist then abort the select by returning null if (!returnFile[0].exists()) { returnFile = null; } } lastUsedWorkingDirectory = fileChooser.getCurrentDirectory(); } // save last use working directory ArbilSessionStorage.getSingleInstance().saveString("fileSelect." + titleText, lastUsedWorkingDirectory.getAbsolutePath()); return returnFile; } public boolean showConfirmDialogBox(String messageString, String messageTitle) { if (messageTitle == null) { messageTitle = "Arbil"; } if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(ArbilWindowManager.getSingleInstance().linorgFrame, messageString, messageTitle, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) { return true; } else { return false; } } public void addMessageDialogToQueue(String messageString, String messageTitle) { if (messageTitle == null) { messageTitle = versionManager.getApplicationVersion().applicationTitle; } String currentMessage = messageDialogQueue.get(messageTitle); if (currentMessage != null) { messageString = messageString + "\n } messageDialogQueue.put(messageTitle, messageString); showMessageDialogQueue(); } private void applyWindowDefaults(JInternalFrame currentInternalFrame) { int tempWindowWidth, tempWindowHeight; if (desktopPane.getWidth() > nextWindowWidth) { tempWindowWidth = nextWindowWidth; } else { tempWindowWidth = desktopPane.getWidth() - 50; } if (desktopPane.getHeight() > nextWindowHeight) { tempWindowHeight = nextWindowHeight; } else { tempWindowHeight = desktopPane.getHeight() - 50; } if (tempWindowHeight < 100) { tempWindowHeight = 100; } currentInternalFrame.setSize(tempWindowWidth, tempWindowHeight); currentInternalFrame.setClosable(true); currentInternalFrame.setIconifiable(true); currentInternalFrame.setMaximizable(true); currentInternalFrame.setResizable(true); currentInternalFrame.setVisible(true); // selectedFilesFrame.setSize(destinationComp.getWidth(), 300); // selectedFilesFrame.setRequestFocusEnabled(false); // selectedFilesFrame.getContentPane().add(selectedFilesPanel, java.awt.BorderLayout.CENTER); // selectedFilesFrame.setBounds(0, 0, 641, 256); // destinationComp.add(selectedFilesFrame, javax.swing.JLayeredPane.DEFAULT_LAYER); // set the window position so that they are cascaded currentInternalFrame.setLocation(nextWindowX, nextWindowY); nextWindowX += Math.max(10, currentInternalFrame.getInsets().left); nextWindowY += Math.max(10, currentInternalFrame.getInsets().top - 10); // TODO: it would be nice to use the JInternalFrame's title bar height to increment the position if (nextWindowX + tempWindowWidth > desktopPane.getWidth()) { nextWindowX = 0; } if (nextWindowY + tempWindowHeight > desktopPane.getHeight()) { nextWindowY = 0; } } private synchronized void showMessageDialogQueue() { if (!showMessageThreadrunning) { new Thread("showMessageThread") { public void run() { try { sleep(100); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } showMessageThreadrunning = true; if (messagesCanBeShown) { while (messageDialogQueue.size() > 0) { String messageTitle = messageDialogQueue.keys().nextElement(); String messageText = messageDialogQueue.remove(messageTitle); if (messageText != null) { JOptionPane.showMessageDialog(ArbilWindowManager.getSingleInstance().linorgFrame, messageText, messageTitle, JOptionPane.PLAIN_MESSAGE); } } } showMessageThreadrunning = false; } }.start(); } } public void openIntroductionPage() { // open the introduction page // TODO: always get this page from the server if available, but also save it for off line use // URL introductionUrl = this.getClass().getResource("/nl/mpi/arbil/resources/html/Introduction.html"); // openUrlWindowOnce("Introduction", introductionUrl); // get remote file to local disk // if local file exists then open that // else open the one in the jar file // The features html file has been limited to the version in the jar (not the server), so that it is specific to the version of linorg in the jar. // // String cachePath = GuiHelper.linorgSessionStorage.updateCache(remoteUrl, true); // System.out.println("cachePath: " + cachePath); // URL destinationUrl = null; // try { // if (new File(cachePath).exists()) { // destinationUrl = new File(cachePath).toURL(); // } catch (Exception ex) { // if (destinationUrl == null) { // destinationUrl = this.getClass().getResource("/nl/mpi/arbil/resources/html/Features.html"); // System.out.println("destinationUrl: " + destinationUrl); // openUrlWindowOnce("Features/Known Bugs", destinationUrl); initWindows(); if (!ArbilTreeHelper.getSingleInstance().locationsHaveBeenAdded()) { System.out.println("no local locations found, showing help window"); ArbilHelp helpComponent = ArbilHelp.getSingleInstance(); if (null == focusWindow(ArbilHelp.helpWindowTitle)) { createWindow(ArbilHelp.helpWindowTitle, helpComponent); } helpComponent.setCurrentPage(ArbilHelp.INTRODUCTION_PAGE); } startKeyListener(); setMessagesCanBeShown(true); showMessageDialogQueue(); } /** * Loads previously saved windows and restores their state */ private void initWindows() { try { // load the saved windows Hashtable windowListHashtable = (Hashtable) ArbilSessionStorage.getSingleInstance().loadObject("openWindows"); for (Enumeration windowNamesEnum = windowListHashtable.keys(); windowNamesEnum.hasMoreElements();) { String currentWindowName = windowNamesEnum.nextElement().toString(); System.out.println("currentWindowName: " + currentWindowName); ArbilWindowState windowState; Object windowStateObject = windowListHashtable.get(currentWindowName); // Vector imdiURLs; // Point windowLocation = null; // Dimension windowSize = null; if (windowStateObject instanceof Vector) { // In previous versions or Arbil, window state was stored as a vector of IMDI urls windowState = new ArbilWindowState(); windowState.currentNodes = (Vector) windowStateObject; } else if (windowStateObject instanceof ArbilWindowState) { windowState = (ArbilWindowState) windowStateObject; } else { throw new Exception("Unknown window state format"); } //= (Vector) windowListHashtable.get(currentWindowName); // System.out.println("imdiEnumeration: " + imdiEnumeration); if (windowState.currentNodes != null) { ArbilDataNode[] imdiObjectsArray = new ArbilDataNode[windowState.currentNodes.size()]; for (int arrayCounter = 0; arrayCounter < imdiObjectsArray.length; arrayCounter++) { try { imdiObjectsArray[arrayCounter] = (ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(windowState.currentNodes.elementAt(arrayCounter).toString()))); } catch (URISyntaxException ex) { GuiHelper.linorgBugCatcher.logError(ex); } } // Create window array for open method to put new window reference in Component[] window = new Component[1]; if (windowState.windowType == ArbilWindowState.ArbilWindowType.nodeTable) { openFloatingTableGetModel(imdiObjectsArray, currentWindowName, window, windowState.fieldView); } else if (windowState.windowType == ArbilWindowState.ArbilWindowType.subnodesPanel) { openFloatingSubnodesWindowOnce(imdiObjectsArray[0], currentWindowName, window); } if (window[0] != null) { // Set size of new window from saved state if (windowState.size != null) { window[0].setSize(windowState.size); } // Set location new window from saved state if (windowState.location != null) { window[0].setLocation(fixLocation(windowState.location)); } } } //openFloatingTable(null, currentWindowName); } System.out.println("done loading windowStates"); } catch (Exception ex) { windowStatesHashtable = new Hashtable(); System.out.println("load windowStates failed: " + ex.getMessage()); } } public void loadSplitPlanes(Component targetComponent) { //System.out.println("loadSplitPlanes: " + targetComponent); if (targetComponent instanceof JSplitPane) { System.out.println("loadSplitPlanes: " + targetComponent.getName()); Object linorgSplitPosition = windowStatesHashtable.get(targetComponent.getName()); if (linorgSplitPosition instanceof Integer) { System.out.println(targetComponent.getName() + ": " + linorgSplitPosition); ((JSplitPane) targetComponent).setDividerLocation((Integer) linorgSplitPosition); } else { if (targetComponent.getName().equals("rightSplitPane")) { ((JSplitPane) targetComponent).setDividerLocation(150); } else { //leftSplitPane leftLocalSplitPane rightSplitPane) ((JSplitPane) targetComponent).setDividerLocation(200); } } for (Component childComponent : ((JSplitPane) targetComponent).getComponents()) { loadSplitPlanes(childComponent); } } if (targetComponent instanceof JPanel) { for (Component childComponent : ((JPanel) targetComponent).getComponents()) { loadSplitPlanes(childComponent); } } } public void saveSplitPlanes(Component targetComponent) { //System.out.println("saveSplitPlanes: " + targetComponent); if (targetComponent instanceof JSplitPane) { System.out.println("saveSplitPlanes: " + targetComponent.getName()); windowStatesHashtable.put(targetComponent.getName(), ((JSplitPane) targetComponent).getDividerLocation()); for (Component childComponent : ((JSplitPane) targetComponent).getComponents()) { saveSplitPlanes(childComponent); } } if (targetComponent instanceof JPanel) { for (Component childComponent : ((JPanel) targetComponent).getComponents()) { saveSplitPlanes(childComponent); } } } /** * Resets all windows to default size and location */ public void resetWindows() { nextWindowX = defaultWindowX; nextWindowY = defaultWindowY; for (Enumeration windowNamesEnum = windowList.keys(); windowNamesEnum.hasMoreElements();) { String currentWindowName = windowNamesEnum.nextElement().toString(); System.out.println("currentWindowName: " + currentWindowName); // set the value of the windowListHashtable to be the imdi urls rather than the windows Object windowObject = ((Component[]) windowList.get(currentWindowName))[0]; if (windowObject != null) { applyWindowDefaults((JInternalFrame) windowObject); } } } public void saveWindowStates() { // loop windowList and make a hashtable of window names with a vector of the imdinodes displayed, then save the hashtable try { // collect the main window size and position for saving windowStatesHashtable.put("linorgFrameBounds", linorgFrame.getBounds()); windowStatesHashtable.put("ScreenDeviceCount", GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices().length); windowStatesHashtable.put("linorgFrameExtendedState", linorgFrame.getExtendedState()); // collect the split pane positions for saving saveSplitPlanes(linorgFrame.getContentPane().getComponent(0)); // save the collected states ArbilSessionStorage.getSingleInstance().saveObject(windowStatesHashtable, "windowStates"); // save the windows Hashtable windowListHashtable = new Hashtable(); //Hashtable windowDimensions = new Hashtable(); //Hashtable windowLocations = new Hashtable(); //(Hashtable) windowList.clone(); for (Enumeration windowNamesEnum = windowList.keys(); windowNamesEnum.hasMoreElements();) { ArbilWindowState windowState = new ArbilWindowState(); String currentWindowName = windowNamesEnum.nextElement().toString(); System.out.println("currentWindowName: " + currentWindowName); // set the value of the windowListHashtable to be the imdi urls rather than the windows Object windowObject = ((Component[]) windowList.get(currentWindowName))[0]; try { if (windowObject != null) { windowState.location = ((JInternalFrame) windowObject).getLocation(); windowState.size = ((JInternalFrame) windowObject).getSize(); Object currentComponent = ((JInternalFrame) windowObject).getContentPane().getComponent(0); if (currentComponent != null) { if (currentComponent instanceof ArbilSplitPanel) { // Store as a node table window windowState.windowType = ArbilWindowState.ArbilWindowType.nodeTable; // if this table has no nodes then don't save it if (0 < ((ArbilSplitPanel) currentComponent).arbilTable.getRowCount()) { ArbilTable table = ((ArbilSplitPanel) currentComponent).arbilTable; // Store field view (columns shown + widths) table.updateStoredColumnWidhts(); windowState.fieldView = table.getArbilTableModel().getFieldView(); Vector currentNodesVector = new Vector(Arrays.asList(table.getArbilTableModel().getArbilDataNodesURLs())); windowState.currentNodes = currentNodesVector; System.out.println("saved"); } } else if (currentComponent instanceof ArbilSubnodesScrollPane) { // Store as a subnodes panel window windowState.windowType = ArbilWindowState.ArbilWindowType.subnodesPanel; // Set top level node as only entry in the current nodes vector Vector nodeVector = new Vector(1); nodeVector.add(((ArbilSubnodesScrollPane) currentComponent).getDataNode().getUrlString()); windowState.currentNodes = nodeVector; } } windowListHashtable.put(currentWindowName, windowState); } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); // System.out.println("Exception: " + ex.getMessage()); } } // save the windows ArbilSessionStorage.getSingleInstance().saveObject(windowListHashtable, "openWindows"); System.out.println("saved windowStates"); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); // System.out.println("save windowStates exception: " + ex.getMessage()); } } private String addWindowToList(String windowName, final JInternalFrame windowFrame) { int instanceCount = 0; String currentWindowName = windowName; while (windowList.containsKey(currentWindowName)) { currentWindowName = windowName + "(" + ++instanceCount + ")"; } JMenuItem windowMenuItem = new JMenuItem(); windowMenuItem.setText(currentWindowName); windowMenuItem.setName(currentWindowName); windowFrame.setName(currentWindowName); windowMenuItem.setActionCommand(currentWindowName); windowMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { focusWindow(evt.getActionCommand()); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } }); windowFrame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { String windowName = e.getInternalFrame().getName(); System.out.println("Closing window: " + windowName); Component[] windowAndMenu = windowList.get(windowName); // Remove from windows menu if (ArbilMenuBar.windowMenu != null && windowAndMenu != null) { ArbilMenuBar.windowMenu.remove(windowAndMenu[1]); } // Check if the child component(s) implement ArbilWindowComponent. If so, call their window closed method for (Component childComponent : ((JInternalFrame) windowFrame).getContentPane().getComponents()) { if (childComponent instanceof ArbilWindowComponent) { ((ArbilWindowComponent) childComponent).arbilWindowClosed(); } } windowList.remove(windowName); super.internalFrameClosed(e); } }); windowList.put(currentWindowName, new Component[]{windowFrame, windowMenuItem}); if (ArbilMenuBar.windowMenu != null) { ArbilMenuBar.windowMenu.add(windowMenuItem); } return currentWindowName; } public void stopEditingInCurrentWindow() { // when saving make sure the current editing table or long field editor saves its data first Component focusedComponent = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); while (focusedComponent != null) { if (focusedComponent instanceof ArbilLongFieldEditor) { ((ArbilLongFieldEditor) focusedComponent).storeChanges(); } focusedComponent = focusedComponent.getParent(); } } public void closeAllWindows() { for (JInternalFrame focusedWindow : desktopPane.getAllFrames()) { if (focusedWindow != null) { String windowName = focusedWindow.getName(); Component[] windowAndMenu = (Component[]) windowList.get(windowName); if (windowAndMenu != null && ArbilMenuBar.windowMenu != null) { ArbilMenuBar.windowMenu.remove(windowAndMenu[1]); } windowList.remove(windowName); desktopPane.remove(focusedWindow); } } desktopPane.repaint(); } public JInternalFrame focusWindow(String windowName) { if (windowList.containsKey(windowName)) { Object windowObject = ((Component[]) windowList.get(windowName))[0]; try { if (windowObject != null) { ((JInternalFrame) windowObject).setIcon(false); ((JInternalFrame) windowObject).setSelected(true); return (JInternalFrame) windowObject; } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); // System.out.println(ex.getMessage()); } } return null; } private void startKeyListener() { // desktopPane.addKeyListener(new KeyAdapter() { // @Override // public void keyPressed(KeyEvent e) { // System.out.println("keyPressed"); // if (e.VK_W == e.getKeyCode()){ // System.out.println("VK_W"); // super.keyPressed(e); Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() { public void eventDispatched(AWTEvent e) { boolean isKeybordRepeat = false; if (e instanceof KeyEvent) { // only consider key release events if (e.getID() == KeyEvent.KEY_RELEASED) { // work around for jvm in linux // due to the bug in the jvm for linux the keyboard repeats are shown as real key events, so we attempt to prevent ludicrous key events being used here KeyEvent nextPress = (KeyEvent) Toolkit.getDefaultToolkit().getSystemEventQueue().peekEvent(KeyEvent.KEY_PRESSED); if (nextPress != null) { // the next key event is at the same time as this event if ((nextPress.getWhen() == ((KeyEvent) e).getWhen())) { // the next key code is the same as this event if (((nextPress.getKeyCode() == ((KeyEvent) e).getKeyCode()))) { isKeybordRepeat = true; } } } // end work around for jvm in linux if (!isKeybordRepeat) { // System.out.println("KeyEvent.paramString: " + ((KeyEvent) e).paramString()); // System.out.println("KeyEvent.getWhen: " + ((KeyEvent) e).getWhen()); if ((((KeyEvent) e).isMetaDown() || ((KeyEvent) e).isControlDown()) && ((KeyEvent) e).getKeyCode() == KeyEvent.VK_W) { JInternalFrame[] windowsToClose; if (((KeyEvent) e).isShiftDown()) { windowsToClose = desktopPane.getAllFrames(); } else { windowsToClose = new JInternalFrame[]{desktopPane.getSelectedFrame()}; } for (JInternalFrame focusedWindow : windowsToClose) { if (focusedWindow != null) { String windowName = focusedWindow.getName(); Component[] windowAndMenu = (Component[]) windowList.get(windowName); if (windowAndMenu != null && ArbilMenuBar.windowMenu != null) { ArbilMenuBar.windowMenu.remove(windowAndMenu[1]); } windowList.remove(windowName); desktopPane.remove(focusedWindow); try { JInternalFrame[] allWindows = desktopPane.getAllFrames(); if (allWindows.length > 0) { JInternalFrame topMostWindow = allWindows[0]; if (topMostWindow != null) { System.out.println("topMostWindow: " + topMostWindow); topMostWindow.setIcon(false); topMostWindow.setSelected(true); } } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); // System.out.println(ex.getMessage()); } } } desktopPane.repaint(); } if ((((KeyEvent) e).getKeyCode() == KeyEvent.VK_TAB && ((KeyEvent) e).isControlDown())) { // the [meta `] is consumed by the operating system, the only way to enable the back quote key for window switching is to use separate windows and rely on the OS to do the switching // || (((KeyEvent) e).getKeyCode() == KeyEvent.VK_BACK_QUOTE && ((KeyEvent) e).isMetaDown()) try { JInternalFrame[] allWindows = desktopPane.getAllFrames(); int targetLayerInt; if (((KeyEvent) e).isShiftDown()) { allWindows[0].moveToBack(); targetLayerInt = 1; } else { targetLayerInt = allWindows.length - 1; } allWindows[targetLayerInt].setIcon(false); allWindows[targetLayerInt].setSelected(true); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); // System.out.println(ex.getMessage()); } } if ((((KeyEvent) e).isMetaDown() || ((KeyEvent) e).isControlDown()) && (((KeyEvent) e).getKeyCode() == KeyEvent.VK_MINUS || ((KeyEvent) e).getKeyCode() == KeyEvent.VK_EQUALS || ((KeyEvent) e).getKeyCode() == KeyEvent.VK_PLUS)) { if (((KeyEvent) e).getKeyCode() != KeyEvent.VK_MINUS) { fontScale = fontScale + (float) 0.1; } else { fontScale = fontScale - (float) 0.1; } if (fontScale < 1) { fontScale = 1; } System.out.println("fontScale: " + fontScale); UIDefaults defaults = UIManager.getDefaults(); Enumeration keys = defaults.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = defaults.get(key); if (value != null && value instanceof Font) { UIManager.put(key, null); Font font = UIManager.getFont(key); if (font != null) { float size = font.getSize2D(); UIManager.put(key, new FontUIResource(font.deriveFont(size * fontScale))); } } } SwingUtilities.updateComponentTreeUI(desktopPane.getParent().getParent()); } if ((((KeyEvent) e).isMetaDown() || ((KeyEvent) e).isControlDown()) && ((KeyEvent) e).getKeyCode() == KeyEvent.VK_F) { JInternalFrame windowToSearch = desktopPane.getSelectedFrame(); //System.out.println(windowToSearch.getContentPane()); for (Component childComponent : windowToSearch.getContentPane().getComponents()) { // loop through all the child components in the window (there will probably only be one) if (childComponent instanceof ArbilSplitPanel) { ((ArbilSplitPanel) childComponent).showSearchPane(); } } } } } } } }, AWTEvent.KEY_EVENT_MASK); } public JInternalFrame createWindow(String windowTitle, Component contentsComponent) { JInternalFrame currentInternalFrame = new javax.swing.JInternalFrame(); currentInternalFrame.setLayout(new BorderLayout()); // GuiHelper.arbilDragDrop.addTransferHandler(currentInternalFrame); currentInternalFrame.add(contentsComponent, BorderLayout.CENTER); windowTitle = addWindowToList(windowTitle, currentInternalFrame); currentInternalFrame.setTitle(windowTitle); currentInternalFrame.setToolTipText(windowTitle); currentInternalFrame.setName(windowTitle); applyWindowDefaults(currentInternalFrame); desktopPane.add(currentInternalFrame, 0); try { // prevent the frame focus process consuming mouse events that should be recieved by the jtable etc. currentInternalFrame.setSelected(true); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); // System.out.println(ex.getMessage()); } // Add frame listener that puts windows with negative y-positions back on the desktop pane currentInternalFrame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameDeactivated(InternalFrameEvent e) { fixLocation(e.getInternalFrame()); } @Override public void internalFrameActivated(InternalFrameEvent e) { fixLocation(e.getInternalFrame()); } private void fixLocation(final JInternalFrame frame) { if (frame.getLocation().getY() < 0) { frame.setLocation(new Point((int) frame.getLocation().getX(), 0)); } } }); return currentInternalFrame; } public JEditorPane openUrlWindowOnce(String frameTitle, URL locationUrl) { JEditorPane htmlDisplay = new JEditorPane(); htmlDisplay.setEditable(false); htmlDisplay.setContentType("text/html"); try { htmlDisplay.setPage(locationUrl); htmlDisplay.addHyperlinkListener(new ArbilHyperlinkListener()); //gridViewInternalFrame.setMaximum(true); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); // System.out.println(ex.getMessage()); } JInternalFrame existingWindow = focusWindow(frameTitle); if (existingWindow == null) { // return openUrlWindow(frameTitle, htmlDisplay); JScrollPane jScrollPane6; jScrollPane6 = new javax.swing.JScrollPane(); jScrollPane6.setViewportView(htmlDisplay); createWindow(frameTitle, jScrollPane6); } else { ((JScrollPane) existingWindow.getContentPane().getComponent(0)).setViewportView(htmlDisplay); } return htmlDisplay; } public void openSearchTable(ArbilNode[] selectedNodes, String frameTitle) { // Create tabel with model and split panel to show it in ArbilTableModel resultsTableModel = new ArbilTableModel(); ArbilTable arbilTable = new ArbilTable(resultsTableModel, frameTitle); arbilTable.setAllowNodeDrop(false); ArbilSplitPanel tablePanel = new ArbilSplitPanel(arbilTable); // Create window with search table in center JInternalFrame searchFrame = this.createWindow(frameTitle, tablePanel); // Add search panel above ArbilNodeSearchPanel searchPanel = new ArbilNodeSearchPanel(searchFrame, resultsTableModel, selectedNodes); searchFrame.add(searchPanel, BorderLayout.NORTH); // Prepare table panel and window for display tablePanel.setSplitDisplay(); tablePanel.addFocusListener(searchFrame); searchFrame.pack(); } public void openFloatingTableOnce(URI[] rowNodesArray, String frameTitle) { openFloatingTableOnceGetModel(rowNodesArray, frameTitle); } public void openFloatingTableOnce(ArbilDataNode[] rowNodesArray, String frameTitle) { openFloatingTableOnceGetModel(rowNodesArray, frameTitle); } public void openFloatingTable(ArbilDataNode[] rowNodesArray, String frameTitle) { openFloatingTableGetModel(rowNodesArray, frameTitle, null, null); } public ArbilTableModel openFloatingTableOnceGetModel(URI[] rowNodesArray, String frameTitle) { ArbilDataNode[] tableNodes = new ArbilDataNode[rowNodesArray.length]; ArrayList<String> fieldPathsToHighlight = new ArrayList<String>(); for (int arrayCounter = 0; arrayCounter < rowNodesArray.length; arrayCounter++) { try { if (rowNodesArray[arrayCounter] != null) { ArbilDataNode parentNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(rowNodesArray[arrayCounter].toString().split(" // parentNode.waitTillLoaded(); String fieldPath = rowNodesArray[arrayCounter].getFragment(); String parentNodeFragment; if (parentNode.nodeTemplate == null) { GuiHelper.linorgBugCatcher.logError(new Exception("nodeTemplate null in: " + parentNode.getUrlString())); parentNodeFragment = ""; } else { parentNodeFragment = parentNode.nodeTemplate.getParentOfField(fieldPath); } URI targetNode; // note that the url has already be encoded and so we must not use the separate parameter version of new URI otherwise it would be encoded again which we do not want if (parentNodeFragment.length() > 0) { targetNode = new URI(rowNodesArray[arrayCounter].toString().split("#")[0] + "#" + parentNodeFragment); } else { targetNode = new URI(rowNodesArray[arrayCounter].toString().split(" } tableNodes[arrayCounter] = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, targetNode); fieldPathsToHighlight.add(fieldPath); } } catch (URISyntaxException ex) { GuiHelper.linorgBugCatcher.logError(ex); } } ArbilTableModel targetTableModel = openFloatingTableOnceGetModel(tableNodes, frameTitle); targetTableModel.highlightMatchingFieldPaths(fieldPathsToHighlight.toArray(new String[]{})); return targetTableModel; } public ArbilTableModel openAllChildNodesInFloatingTableOnce(URI[] rowNodesArray, String frameTitle) { HashSet<ArbilDataNode> tableNodes = new HashSet(); for (int arrayCounter = 0; arrayCounter < rowNodesArray.length; arrayCounter++) { // try { ArbilDataNode currentNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, rowNodesArray[arrayCounter]); tableNodes.add(currentNode); for (ArbilDataNode currentChildNode : currentNode.getAllChildren()) { tableNodes.add(currentChildNode); } // } catch (URISyntaxException ex) { // GuiHelper.linorgBugCatcher.logError(ex); } return openFloatingTableOnceGetModel(tableNodes.toArray(new ArbilDataNode[]{}), frameTitle); } public ArbilTableModel openFloatingTableOnceGetModel(ArbilDataNode[] rowNodesArray, String frameTitle) { if (rowNodesArray.length == 1 && rowNodesArray[0] != null && rowNodesArray[0].isInfoLink) { try { if (rowNodesArray[0].getUrlString().toLowerCase().endsWith(".html") || rowNodesArray[0].getUrlString().toLowerCase().endsWith(".txt")) { openUrlWindowOnce(rowNodesArray[0].toString(), rowNodesArray[0].getURI().toURL()); return null; } } catch (MalformedURLException exception) { GuiHelper.linorgBugCatcher.logError(exception); } } // open find a table containing exactly the same nodes as requested or create a new table for (Component[] currentWindow : windowList.values().toArray(new Component[][]{})) { // loop through all the windows for (Component childComponent : ((JInternalFrame) currentWindow[0]).getContentPane().getComponents()) { // loop through all the child components in the window (there will probably only be one) if (childComponent instanceof ArbilSplitPanel) { // only consider components with a LinorgSplitPanel ArbilTableModel currentTableModel = ((ArbilSplitPanel) childComponent).arbilTable.getArbilTableModel(); if (currentTableModel.getArbilDataNodeCount() == rowNodesArray.length) { // first check that the number of nodes in the table matches boolean tableMatches = true; for (ArbilDataNode currentItem : rowNodesArray) { // compare each node for a verbatim match if (!currentTableModel.containsArbilDataNode(currentItem)) { // // ignore this window because the nodes do not match tableMatches = false; break; } } if (tableMatches) { // System.out.println("tableMatches"); try { ((JInternalFrame) currentWindow[0]).setIcon(false); ((JInternalFrame) currentWindow[0]).setSelected(true); return currentTableModel; } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } } } } } // if through the above process a table containing all and only the nodes requested has not been found then create a new table return openFloatingTableGetModel(rowNodesArray, frameTitle, null, null); } /** * * @param rowNodesArray * @param frameTitle * @param window Array in which created window is inserted (at index 0). If left null, this is skipped * @param fieldView Field view to initialize table model with. If left null, the default field view will be used * @return Table model for newly created table window */ private ArbilTableModel openFloatingTableGetModel(ArbilDataNode[] rowNodesArray, String frameTitle, Component[] window, ArbilFieldView fieldView) { if (frameTitle == null) { if (rowNodesArray.length == 1) { frameTitle = rowNodesArray[0].toString(); } else { frameTitle = "Selection"; } } ArbilTableModel arbilTableModel = fieldView == null ? new ArbilTableModel() : new ArbilTableModel(fieldView); ArbilTable arbilTable = new ArbilTable(arbilTableModel, frameTitle); ArbilSplitPanel arbilSplitPanel = new ArbilSplitPanel(arbilTable); arbilTableModel.addArbilDataNodes(rowNodesArray); arbilSplitPanel.setSplitDisplay(); JInternalFrame tableFrame = this.createWindow(frameTitle, arbilSplitPanel); arbilSplitPanel.addFocusListener(tableFrame); if (window != null && window.length > 0) { window[0] = tableFrame; } return arbilTableModel; } /** * Opens a new window containing a scrollpane with a nested collection of tables * for the specified node and all of its subnodes. * @param arbilDataNode Node to open window for * @param frameTitle Title of window to be created */ public void openFloatingSubnodesWindows(ArbilDataNode[] arbilDataNodes) { for (ArbilDataNode arbilDataNode : arbilDataNodes) { openFloatingSubnodesWindowOnce(arbilDataNode, arbilDataNode.toString(), null); } } private void openFloatingSubnodesWindowOnce(ArbilDataNode arbilDataNode, String frameTitle, Component[] window) { // Check if no subnodes window is opened with the same data node as top level node yet for (String currentWindowName : windowList.keySet()) { Component[] currentWindow = (Component[]) windowList.get(currentWindowName); for (Component childComponent : ((JInternalFrame) currentWindow[0]).getContentPane().getComponents()) { // loop through all the child components in the window (there will probably only be one) if (childComponent instanceof ArbilSubnodesScrollPane) { if (((ArbilSubnodesScrollPane) childComponent).getDataNode().equals(arbilDataNode)) { // Make window get focus - a window was requested after all focusWindow(currentWindowName); // Return so a new window does not get created return; } } } } ArbilSubnodesScrollPane scrollPane = new ArbilSubnodesScrollPane(arbilDataNode); JInternalFrame tableFrame = createWindow(frameTitle, scrollPane); tableFrame.addInternalFrameListener(scrollPane.getInternalFrameListener()); if (window != null && window.length > 0) { window[0] = tableFrame; } } //JOptionPane.showConfirmDialog(ArbilWindowManager.getSingleInstance().linorgFrame, //"Moving files from:\n" + fromDirectory + "\nto:\n" + preferedCacheDirectory + "\n" //+ "Arbil will need to close all tables once the files are moved.\nDo you wish to continue?", "Arbil", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) /** * * @param message Message of the dialog * @param title Title of the dialog * @param optionType Option type, one of the constants of JOptionPane * @param messageType Message type, one of the constants of JOptionPane * @return One of the JOptionPane constants indicating the chosen option * * @see javax.swing.JOptionPane */ public int showDialogBox(String message, String title, int optionType, int messageType) { return JOptionPane.showConfirmDialog(linorgFrame, message, title, optionType, messageType); } public ProgressMonitor newProgressMonitor(Object message, String note, int min, int max) { return new ProgressMonitor(desktopPane, message, note, min, max); } public JFrame getMainFrame() { return linorgFrame; } public boolean askUserToSaveChanges(String entityName) { return showConfirmDialogBox("This action will save all pending changes on " + entityName + " to disk. Continue?", "Save to disk?"); } private Point fixLocation(Point location) { if (location.getY() < 0) { location.move((int) location.getX(), Math.max(0, (int) location.getY())); } return location; } }
package com.xlythe.view.camera; import android.location.Location; import android.support.annotation.Nullable; import android.support.media.ExifInterface; import android.util.Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Modifies metadata on JPEG files. Call {@link #save()} to persist changes to disc. */ public class Exif { private static final String TAG = Exif.class.getSimpleName(); private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy:MM:dd", Locale.ENGLISH); private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH); private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.ENGLISH); private final ExifInterface mExifInterface; // When true, avoid saving any time. This is a privacy issue. private boolean mRemoveTimestamp = false; public Exif(File file) throws IOException { this(file.toString()); } public Exif(String filePath) throws IOException { this(new ExifInterface(filePath)); } public Exif(InputStream is) throws IOException { this(new ExifInterface(is)); } private Exif(ExifInterface exifInterface) { mExifInterface = exifInterface; } /** * Persists changes to disc. */ public void save() throws IOException { if (!mRemoveTimestamp) { attachLastModifiedTimestamp(); } mExifInterface.saveAttributes(); } @Override public String toString() { return String.format(Locale.ENGLISH, "Exif{width=%s, height=%s, rotation=%d, " + "isFlippedVertically=%s, isFlippedHorizontally=%s, location=%s, " + "timestamp=%s, description=%s}", getWidth(), getHeight(), getRotation(), isFlippedVertically(), isFlippedHorizontally(), getLocation(), getTimestamp(), getDescription()); } private int getOrientation() { return mExifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); } /** * Returns the width of the photo in pixels. */ public int getWidth() { return mExifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0); } /** * Returns the height of the photo in pixels. */ public int getHeight() { return mExifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0); } @Nullable public String getDescription() { return mExifInterface.getAttribute(ExifInterface.TAG_IMAGE_DESCRIPTION); } public void setDescription(@Nullable String description) { mExifInterface.setAttribute(ExifInterface.TAG_IMAGE_DESCRIPTION, description); } /** * @return The degree of rotation (eg. 0, 90, 180, 270). */ public int getRotation() { switch (getOrientation()) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: return 0; case ExifInterface.ORIENTATION_ROTATE_180: return 180; case ExifInterface.ORIENTATION_FLIP_VERTICAL: return 180; case ExifInterface.ORIENTATION_TRANSPOSE: return 270; case ExifInterface.ORIENTATION_ROTATE_90: return 90; case ExifInterface.ORIENTATION_TRANSVERSE: return 90; case ExifInterface.ORIENTATION_ROTATE_270: return 270; case ExifInterface.ORIENTATION_NORMAL: // Fall-through case ExifInterface.ORIENTATION_UNDEFINED: // Fall-through default: return 0; } } /** * @return True if the image is flipped vertically after rotation. */ public boolean isFlippedVertically() { switch (getOrientation()) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: return false; case ExifInterface.ORIENTATION_ROTATE_180: return false; case ExifInterface.ORIENTATION_FLIP_VERTICAL: return true; case ExifInterface.ORIENTATION_TRANSPOSE: return true; case ExifInterface.ORIENTATION_ROTATE_90: return false; case ExifInterface.ORIENTATION_TRANSVERSE: return true; case ExifInterface.ORIENTATION_ROTATE_270: return false; case ExifInterface.ORIENTATION_NORMAL: // Fall-through case ExifInterface.ORIENTATION_UNDEFINED: // Fall-through default: return false; } } /** * @return True if the image is flipped horizontally after rotation. */ public boolean isFlippedHorizontally() { switch (getOrientation()) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: return true; case ExifInterface.ORIENTATION_ROTATE_180: return false; case ExifInterface.ORIENTATION_FLIP_VERTICAL: return false; case ExifInterface.ORIENTATION_TRANSPOSE: return false; case ExifInterface.ORIENTATION_ROTATE_90: return false; case ExifInterface.ORIENTATION_TRANSVERSE: return false; case ExifInterface.ORIENTATION_ROTATE_270: return false; case ExifInterface.ORIENTATION_NORMAL: // Fall-through case ExifInterface.ORIENTATION_UNDEFINED: // Fall-through default: return false; } } private void attachLastModifiedTimestamp() { long now = System.currentTimeMillis(); String datetime = convertToExifDateTime(now); mExifInterface.setAttribute(ExifInterface.TAG_DATETIME, datetime); try { String subsec = Long.toString(now - convertFromExifDateTime(datetime).getTime()); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME, subsec); } catch (ParseException e) {} } /** * @return The timestamp (in millis) that this picture was modified, or -1 if no time is available. */ public long getLastModifiedTimestamp() { long timestamp = parseTimestamp(mExifInterface.getAttribute(ExifInterface.TAG_DATETIME)); if (timestamp == -1) { return -1; } String subSecs = mExifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME); if (subSecs != null) { try { long sub = Long.parseLong(subSecs); while (sub > 1000) { sub /= 10; } timestamp += sub; } catch (NumberFormatException e) { // Ignored } } return timestamp; } /** * @return The timestamp (in millis) that this picture was taken, or -1 if no time is available. */ public long getTimestamp() { long timestamp = parseTimestamp(mExifInterface.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL)); if (timestamp == -1) { return -1; } String subSecs = mExifInterface.getAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL); if (subSecs != null) { try { long sub = Long.parseLong(subSecs); while (sub > 1000) { sub /= 10; } timestamp += sub; } catch (NumberFormatException e) { // Ignored } } return timestamp; } /** * @return The location this picture was taken, or null if no location is available. */ @Nullable public Location getLocation() { String provider = mExifInterface.getAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD); double[] latlng = mExifInterface.getLatLong(); double altitude = mExifInterface.getAltitude(0); double speed = mExifInterface.getAttributeDouble(ExifInterface.TAG_GPS_SPEED, 0) * mExifInterface.getAttributeDouble(ExifInterface.TAG_GPS_SPEED_REF, 1); long timestamp = parseTimestamp( mExifInterface.getAttribute(ExifInterface.TAG_GPS_DATESTAMP), mExifInterface.getAttribute(ExifInterface.TAG_GPS_TIMESTAMP)); if (latlng == null) { return null; } if (provider == null) { provider = TAG; } Location location = new Location(provider); location.setLatitude(latlng[0]); location.setLongitude(latlng[1]); if (altitude != 0) { location.setAltitude(altitude); } if (speed != 0) { location.setSpeed((float) speed); } if (timestamp != -1) { location.setTime(timestamp); } return location; } /** * Rotates the image by the given degrees. Can only rotate by right angles (eg. 90, 180, -90). * Other increments will set the orientation to undefined. */ public void rotate(int degrees) { if (degrees % 90 != 0) { Log.w(TAG, String.format("Can only rotate in right angles (eg. 0, 90, 180, 270). %d is unsupported.", degrees)); mExifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_UNDEFINED)); return; } degrees %= 360; int orientation = getOrientation(); while (degrees < 0) { degrees += 90; switch (orientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = ExifInterface.ORIENTATION_TRANSPOSE; break; case ExifInterface.ORIENTATION_ROTATE_180: orientation = ExifInterface.ORIENTATION_ROTATE_90; break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = ExifInterface.ORIENTATION_TRANSVERSE; break; case ExifInterface.ORIENTATION_TRANSPOSE: orientation = ExifInterface.ORIENTATION_FLIP_VERTICAL; break; case ExifInterface.ORIENTATION_ROTATE_90: orientation = ExifInterface.ORIENTATION_NORMAL; break; case ExifInterface.ORIENTATION_TRANSVERSE: orientation = ExifInterface.ORIENTATION_FLIP_HORIZONTAL; break; case ExifInterface.ORIENTATION_ROTATE_270: orientation = ExifInterface.ORIENTATION_ROTATE_90; break; case ExifInterface.ORIENTATION_NORMAL: // Fall-through case ExifInterface.ORIENTATION_UNDEFINED: // Fall-through default: orientation = ExifInterface.ORIENTATION_ROTATE_270; break; } } while (degrees > 0) { degrees -= 90; switch (orientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = ExifInterface.ORIENTATION_TRANSVERSE; break; case ExifInterface.ORIENTATION_ROTATE_180: orientation = ExifInterface.ORIENTATION_ROTATE_270; break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = ExifInterface.ORIENTATION_TRANSPOSE; break; case ExifInterface.ORIENTATION_TRANSPOSE: orientation = ExifInterface.ORIENTATION_FLIP_HORIZONTAL; break; case ExifInterface.ORIENTATION_ROTATE_90: orientation = ExifInterface.ORIENTATION_ROTATE_180; break; case ExifInterface.ORIENTATION_TRANSVERSE: orientation = ExifInterface.ORIENTATION_FLIP_VERTICAL; break; case ExifInterface.ORIENTATION_ROTATE_270: orientation = ExifInterface.ORIENTATION_NORMAL; break; case ExifInterface.ORIENTATION_NORMAL: // Fall-through case ExifInterface.ORIENTATION_UNDEFINED: // Fall-through default: orientation = ExifInterface.ORIENTATION_ROTATE_90; break; } } mExifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation)); } /** * Flips the image over the horizon so that the top and bottom are reversed. */ public void flipVertically() { int orientation; switch (getOrientation()) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = ExifInterface.ORIENTATION_ROTATE_180; break; case ExifInterface.ORIENTATION_ROTATE_180: orientation = ExifInterface.ORIENTATION_FLIP_HORIZONTAL; break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = ExifInterface.ORIENTATION_NORMAL; break; case ExifInterface.ORIENTATION_TRANSPOSE: orientation = ExifInterface.ORIENTATION_ROTATE_270; break; case ExifInterface.ORIENTATION_ROTATE_90: orientation = ExifInterface.ORIENTATION_TRANSVERSE; break; case ExifInterface.ORIENTATION_TRANSVERSE: orientation = ExifInterface.ORIENTATION_ROTATE_90; break; case ExifInterface.ORIENTATION_ROTATE_270: orientation = ExifInterface.ORIENTATION_TRANSPOSE; break; case ExifInterface.ORIENTATION_NORMAL: // Fall-through case ExifInterface.ORIENTATION_UNDEFINED: // Fall-through default: orientation = ExifInterface.ORIENTATION_FLIP_VERTICAL; break; } mExifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation)); } /** * Flips the image over the vertical so that the left and right are reversed. */ public void flipHorizontally() { int orientation; switch (getOrientation()) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientation = ExifInterface.ORIENTATION_NORMAL; break; case ExifInterface.ORIENTATION_ROTATE_180: orientation = ExifInterface.ORIENTATION_FLIP_VERTICAL; break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientation = ExifInterface.ORIENTATION_ROTATE_180; break; case ExifInterface.ORIENTATION_TRANSPOSE: orientation = ExifInterface.ORIENTATION_ROTATE_90; break; case ExifInterface.ORIENTATION_ROTATE_90: orientation = ExifInterface.ORIENTATION_TRANSPOSE; break; case ExifInterface.ORIENTATION_TRANSVERSE: orientation = ExifInterface.ORIENTATION_ROTATE_270; break; case ExifInterface.ORIENTATION_ROTATE_270: orientation = ExifInterface.ORIENTATION_TRANSVERSE; break; case ExifInterface.ORIENTATION_NORMAL: // Fall-through case ExifInterface.ORIENTATION_UNDEFINED: // Fall-through default: orientation = ExifInterface.ORIENTATION_FLIP_HORIZONTAL; break; } mExifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation)); } /** * Attaches the current timestamp to the file. */ public void attachTimestamp() { long now = System.currentTimeMillis(); String datetime = convertToExifDateTime(now); mExifInterface.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, datetime); mExifInterface.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, datetime); try { String subsec = Long.toString(now - convertFromExifDateTime(datetime).getTime()); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, subsec); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, subsec); } catch (ParseException e) {} mRemoveTimestamp = false; } /** * Removes the timestamp from the file. */ public void removeTimestamp() { mExifInterface.setAttribute(ExifInterface.TAG_DATETIME, null); mExifInterface.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, null); mExifInterface.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, null); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME, null); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, null); mExifInterface.setAttribute(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, null); mRemoveTimestamp = true; } /** * Attaches the given location to the file. */ public void attachLocation(Location location) { mExifInterface.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, location.getProvider()); mExifInterface.setLatLong(location.getLatitude(), location.getLongitude()); if (location.hasAltitude()) { mExifInterface.setAttribute(ExifInterface.TAG_GPS_ALTITUDE, Double.toString(location.getAltitude())); mExifInterface.setAttribute(ExifInterface.TAG_GPS_ALTITUDE_REF, Integer.toString(1)); } if (location.hasSpeed()) { mExifInterface.setAttribute(ExifInterface.TAG_GPS_SPEED, Float.toString(location.getSpeed())); mExifInterface.setAttribute(ExifInterface.TAG_GPS_SPEED_REF, Integer.toString(1)); } mExifInterface.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, convertToExifDate(location.getTime())); mExifInterface.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, convertToExifTime(location.getTime())); } /** * Removes the location from the file. */ public void removeLocation() { mExifInterface.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, null); mExifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, null); mExifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, null); mExifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, null); mExifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, null); mExifInterface.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, null); mExifInterface.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, null); } /** * @return The timestamp (in millis), or -1 if no time is available. */ private long parseTimestamp(@Nullable String date, @Nullable String time) { if (date == null && time == null) { return -1; } if (time == null) { try { return convertFromExifDate(date).getTime(); } catch (ParseException e) { return -1; } } if (date == null) { try { return convertFromExifTime(time).getTime(); } catch (ParseException e) { return -1; } } return parseTimestamp(date + " " + time); } /** * @return The timestamp (in millis), or -1 if no time is available. */ private long parseTimestamp(@Nullable String datetime) { if (datetime == null) { return -1; } try { return convertFromExifDateTime(datetime).getTime(); } catch (ParseException e) { return -1; } } private static String convertToExifDateTime(long timestamp) { return DATETIME_FORMAT.format(new Date(timestamp)); } private static Date convertFromExifDateTime(String dateTime) throws ParseException { return DATETIME_FORMAT.parse(dateTime); } private static String convertToExifDate(long timestamp) { return DATE_FORMAT.format(new Date(timestamp)); } private static Date convertFromExifDate(String date) throws ParseException { return DATE_FORMAT.parse(date); } private static String convertToExifTime(long timestamp) { return TIME_FORMAT.format(new Date(timestamp)); } private static Date convertFromExifTime(String time) throws ParseException { return TIME_FORMAT.parse(time); } }
package crazypants.enderio.teleport; import java.util.ArrayList; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.packet.Packet; import net.minecraft.tileentity.TileEntity; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.PacketHandler; import crazypants.util.BlockCoord; import crazypants.util.PacketUtil; public class TileTravelAnchor extends TileEntity implements ITravelAccessable { private static final int REND_DIST_SQ = TravelSource.getMaxDistanceSq(); enum AccessMode { PUBLIC, PRIVATE, PROTECTED } private AccessMode accessMode = AccessMode.PUBLIC; private ItemStack[] password = new ItemStack[5]; private String placedBy; private List<String> authorisedUsers = new ArrayList<String>(); public boolean canBlockBeAccessed(String playerName) { if(accessMode == AccessMode.PUBLIC) { return true; } if(accessMode == AccessMode.PRIVATE) { return placedBy != null && placedBy.equals(playerName); } if(placedBy != null && placedBy.equals(playerName)) { return true; } return authorisedUsers.contains(playerName); } @Override public void clearAuthorisedUsers() { authorisedUsers.clear(); } public BlockCoord getLocation() { return new BlockCoord(this); } private boolean checkPassword(ItemStack[] pwd) { if(pwd == null || pwd.length != password.length) { return false; } for (int i = 0; i < pwd.length; i++) { ItemStack pw = password[i]; ItemStack tst = pwd[i]; if(pw == null && tst != null) { return false; } if(pw != null) { if(tst == null || !ItemStack.areItemStacksEqual(pw, tst)) { return false; } } } return true; } @Override public boolean getRequiresPassword(String username) { return getAccessMode() != AccessMode.PUBLIC && !canUiBeAccessed(username) && !authorisedUsers.contains(username); } @Override public boolean authoriseUser(String username, ItemStack[] password) { if(checkPassword(password)) { authorisedUsers.add(username); return true; } return false; } public boolean canUiBeAccessed(String playerName) { return placedBy != null && placedBy.equals(playerName); } public boolean canSeeBlock(String playerName) { if(accessMode != AccessMode.PRIVATE) { return true; } return placedBy != null && placedBy.equals(playerName); } public AccessMode getAccessMode() { return accessMode; } public void setAccessMode(AccessMode accessMode) { this.accessMode = accessMode; } public ItemStack[] getPassword() { return password; } public void setPassword(ItemStack[] password) { this.password = password; } public String getPlacedBy() { return placedBy; } public void setPlacedBy(String placedBy) { this.placedBy = placedBy; } @Override public boolean canUpdate() { return false; } @Override @SideOnly(Side.CLIENT) public double getMaxRenderDistanceSquared() { return TravelSource.getMaxDistanceSq(); } @Override public boolean shouldRenderInPass(int pass) { return pass == 1; } @Override public void readFromNBT(NBTTagCompound root) { super.readFromNBT(root); if(root.hasKey("accessMode")) { accessMode = AccessMode.values()[root.getShort("accessMode")]; } else { //keep behaviour the same for blocks placed prior to this update accessMode = AccessMode.PUBLIC; } placedBy = root.getString("placedBy"); for (int i = 0; i < password.length; i++) { if(root.hasKey("password" + i)) { NBTTagCompound stackRoot = (NBTTagCompound) root.getTag("password" + i); password[i] = ItemStack.loadItemStackFromNBT(stackRoot); } else { password[i] = null; } } authorisedUsers.clear(); String userStr = root.getString("authorisedUsers"); if(userStr != null && userStr.length() > 0) { String[] users = userStr.split(","); for (String user : users) { if(user != null) { user = user.trim(); if(user.length() > 0) { authorisedUsers.add(user); } } } } } @Override public void writeToNBT(NBTTagCompound root) { super.writeToNBT(root); root.setShort("accessMode", (short) accessMode.ordinal()); if(placedBy != null && placedBy.trim().length() > 0) { root.setString("placedBy", placedBy); } for (int i = 0; i < password.length; i++) { ItemStack stack = password[i]; if(stack != null) { NBTTagCompound stackRoot = new NBTTagCompound(); stack.writeToNBT(stackRoot); root.setTag("password" + i, stackRoot); } } StringBuffer userStr = new StringBuffer(); for (String user : authorisedUsers) { if(user != null && user.trim().length() > 0) { userStr.append(user); userStr.append(","); } } if(authorisedUsers.size() > 0) { root.setString("authorisedUsers", userStr.toString()); } } @Override public Packet getDescriptionPacket() { return PacketUtil.createTileEntityPacket(PacketHandler.CHANNEL, PacketHandler.ID_TILE_ENTITY, this); } }
package net.silentchaos512.gems.item.tool; import java.lang.reflect.Method; import java.util.List; import com.google.common.collect.Lists; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.IItemPropertyGetter; import net.minecraft.item.Item; import net.minecraft.item.ItemArrow; import net.minecraft.item.ItemBow; import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.ShapedOreRecipe; import net.silentchaos512.gems.SilentGems; import net.silentchaos512.gems.api.ITool; import net.silentchaos512.gems.item.ModItems; import net.silentchaos512.gems.item.ToolRenderHelper; import net.silentchaos512.gems.lib.EnumGem; import net.silentchaos512.gems.lib.Names; import net.silentchaos512.gems.util.ToolHelper; import net.silentchaos512.lib.registry.IRegistryObject; public class ItemGemBow extends ItemBow implements IRegistryObject, ITool { public static final float ENCHANTABILITY_MULTIPLIER = 0.45f; public static final ResourceLocation RESOURCE_PULL = new ResourceLocation("pull"); public static final ResourceLocation RESOURCE_PULLING = new ResourceLocation("pulling"); private List<ItemStack> subItems = null; public ItemGemBow() { setUnlocalizedName(SilentGems.RESOURCE_PREFIX + Names.BOW); addPropertyOverride(RESOURCE_PULL, new IItemPropertyGetter() { @Override public float apply(ItemStack stack, World worldIn, EntityLivingBase entityIn) { if (entityIn == null) return 0f; ItemStack itemstack = entityIn.getActiveItemStack(); return itemstack != null && ToolHelper.areToolsEqual(stack, itemstack) ? (stack.getMaxItemUseDuration() - entityIn.getItemInUseCount()) / getDrawDelay(stack) : 0f; } }); } // = ITool overrides = @Override public ItemStack constructTool(ItemStack rod, ItemStack... materials) { if (materials.length == 1) return constructTool(rod, materials[0], materials[0], materials[0]); return ToolHelper.constructTool(this, rod, materials); } @Override public float getMeleeDamage(ItemStack tool) { return 0; } @Override public float getMagicDamage(ItemStack tool) { return 0; } @Override public float getBaseMeleeDamageModifier() { return 0; } @Override public float getBaseMeleeSpeedModifier() { return 0; } // = Bow stuff = public float getDrawDelay(ItemStack stack) { float mspeed = ToolHelper.getMeleeSpeed(stack); float dspeed = ToolHelper.getDigSpeedOnProperMaterial(stack); return Math.max(38.4f - 1.4f * mspeed * dspeed, 5); } public float getArrowVelocity(ItemStack stack, int charge) { float f = charge / getDrawDelay(stack); f = (f * f + f * 2f) / 3f; return f > 1f ? 1f : f; } protected ItemStack findAmmo(EntityPlayer player) { if (this.isArrow(player.getHeldItem(EnumHand.OFF_HAND))) { return player.getHeldItem(EnumHand.OFF_HAND); } else if (this.isArrow(player.getHeldItem(EnumHand.MAIN_HAND))) { return player.getHeldItem(EnumHand.MAIN_HAND); } else { for (int i = 0; i < player.inventory.getSizeInventory(); ++i) { ItemStack itemstack = player.inventory.getStackInSlot(i); if (this.isArrow(itemstack)) { return itemstack; } } return null; } } // Same as vanilla bow, except it can be fired without arrows with infinity. @Override public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) { boolean hasAmmo = findAmmo(player) != null || EnchantmentHelper.getEnchantmentLevel(Enchantments.INFINITY, stack) > 0; boolean isBroken = ToolHelper.isBroken(stack); if (isBroken) return new ActionResult(EnumActionResult.PASS, stack); ActionResult<ItemStack> ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(stack, world, player, hand, hasAmmo); if (ret != null) return ret; if (!player.capabilities.isCreativeMode && !hasAmmo) { return !hasAmmo ? new ActionResult(EnumActionResult.FAIL, stack) : new ActionResult(EnumActionResult.PASS, stack); } else { player.setActiveHand(hand); return new ActionResult(EnumActionResult.SUCCESS, stack); } } @Override public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft) { if (entityLiving instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) entityLiving; boolean flag = player.capabilities.isCreativeMode || EnchantmentHelper.getEnchantmentLevel(Enchantments.INFINITY, stack) > 0; ItemStack ammo = this.findAmmo(player); int i = this.getMaxItemUseDuration(stack) - timeLeft; i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(stack, worldIn, (EntityPlayer) entityLiving, i, ammo != null || flag); if (i < 0) return; if (ammo != null || flag) { if (ammo == null) { ammo = new ItemStack(Items.ARROW); } float velocity = getArrowVelocity(stack, i); if ((double) velocity >= 0.1D) { boolean flag1 = player.capabilities.isCreativeMode || (ammo.getItem() instanceof ItemArrow ? ((ItemArrow) ammo.getItem()).isInfinite(ammo, stack, player) : false); if (!worldIn.isRemote) { ItemArrow itemarrow = (ItemArrow) ((ItemArrow) (ammo.getItem() instanceof ItemArrow ? ammo.getItem() : Items.ARROW)); EntityArrow entityarrow = itemarrow.createArrow(worldIn, ammo, player); entityarrow.setAim(player, player.rotationPitch, player.rotationYaw, 0.0F, velocity * 3.0F, 1.0F); if (velocity == 1.0F) { entityarrow.setIsCritical(true); } int power = EnchantmentHelper.getEnchantmentLevel(Enchantments.POWER, stack); if (power > 0) { // TODO: Damage modifier? entityarrow.setDamage(entityarrow.getDamage() + (double) power * 0.5D + 0.5D); } int k = EnchantmentHelper.getEnchantmentLevel(Enchantments.PUNCH, stack); if (k > 0) { entityarrow.setKnockbackStrength(k); } if (EnchantmentHelper.getEnchantmentLevel(Enchantments.FLAME, stack) > 0) { entityarrow.setFire(100); } stack.damageItem(1, player); if (flag1) { entityarrow.pickupStatus = EntityArrow.PickupStatus.CREATIVE_ONLY; } worldIn.spawnEntityInWorld(entityarrow); } worldIn.playSound((EntityPlayer) null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.NEUTRAL, 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + velocity * 0.5F); if (!flag1) { --ammo.stackSize; if (ammo.stackSize == 0) { player.inventory.deleteStack(ammo); } } player.addStat(StatList.getObjectUseStats(this)); // Shots fired statistic ToolHelper.incrementStatShotsFired(stack, 1); } } } } // = Item overrides = @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advanced) { ToolRenderHelper.getInstance().addInformation(stack, player, list, advanced); } @Override public void getSubItems(Item item, CreativeTabs tab, List list) { if (subItems == null) subItems = ToolHelper.getSubItems(item, 3); list.addAll(subItems); } @Override public int getMaxDamage(ItemStack stack) { return ToolHelper.getMaxDamage(stack); } @Override public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) { return ToolRenderHelper.instance.shouldCauseReequipAnimation(oldStack, newStack, slotChanged); } @Override public boolean hasEffect(ItemStack stack) { return ToolRenderHelper.instance.hasEffect(stack); } @Override public int getItemEnchantability(ItemStack stack) { return Math.round(ToolHelper.getItemEnchantability(stack) * ENCHANTABILITY_MULTIPLIER); } @Override public void onUpdate(ItemStack tool, World world, Entity entity, int itemSlot, boolean isSelected) { ToolHelper.onUpdate(tool, world, entity, itemSlot, isSelected); } // = IRegistryObject overrides = @Override public void addOreDict() { } @Override public void addRecipes() { String line1 = "sgw"; String line2 = "g w"; String line3 = "sgw"; ItemStack flint = new ItemStack(Items.FLINT); ItemStack rodWood = new ItemStack(Items.STICK); ItemStack rodIron = ModItems.craftingMaterial.toolRodIron; ItemStack rodGold = ModItems.craftingMaterial.toolRodGold; // Flint GameRegistry.addRecipe(new ShapedOreRecipe(constructTool(rodWood, flint), line1, line2, line3, 'g', flint, 's', "stickWood", 'w', Items.STRING)); for (EnumGem gem : EnumGem.values()) { // Regular GameRegistry.addRecipe(new ShapedOreRecipe(constructTool(rodIron, gem.getItem()), line1, line2, line3, 'g', gem.getItem(), 's', rodIron, 'w', Items.STRING)); // Super GameRegistry.addRecipe( new ShapedOreRecipe(constructTool(rodGold, gem.getItemSuper()), line1, line2, line3, 'g', gem.getItemSuper(), 's', rodGold, 'w', ModItems.craftingMaterial.gildedString)); } } @Override public String getFullName() { return getModId() + ":" + getName(); } @Override public String getModId() { return SilentGems.MOD_ID; } @Override public String getName() { return Names.BOW; } @Override public List<ModelResourceLocation> getVariants() { return Lists.newArrayList(ToolRenderHelper.SMART_MODEL); } @Override public boolean registerModels() { return false; } }
package ch.frontg8.lib.connection; import android.app.Activity; import com.google.protobuf.ByteString; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.net.ssl.SSLContext; import ch.frontg8.lib.config.LibConfig; import ch.frontg8.lib.crypto.KeyNotFoundException; import ch.frontg8.lib.crypto.LibSSLContext; import ch.frontg8.lib.message.InvalidMessageException; import ch.frontg8.lib.message.MessageHelper; import ch.frontg8.lib.message.MessageType; import ch.frontg8.lib.protobuf.Frontg8Client; import static ch.frontg8.lib.crypto.LibCrypto.encryptMSG; import static ch.frontg8.lib.message.MessageHelper.addMessageHeader; import static ch.frontg8.lib.message.MessageHelper.buildDataMessage; import static ch.frontg8.lib.message.MessageHelper.buildEncryptedMessage; import static ch.frontg8.lib.message.MessageHelper.getDecryptedContent; public class TlsTest { Activity context; public TlsTest(Activity context) { this.context = context; } public void RunTlsTest() { Logger Log = new Logger(context, "DeveloperActivity"); String serverName = LibConfig.getServerName(context); int serverPort = LibConfig.getServerPort(context); SSLContext sslContext = LibSSLContext.getSSLContext("root", context); TlsClient tlsClient = new TlsClient(serverName, serverPort, Log, sslContext); tlsClient.connect(); String plainMessage = "frontg8 Test Message"; // TODO: Encryption of data UUID uuid = UUID.fromString("11111111-1111-1111-1111-111111111111"); Log.TRACE(Arrays.toString(plainMessage.getBytes())); Frontg8Client.Data dataMessage = buildDataMessage(plainMessage,"0", 0); byte[] encryptedDataMessage = new byte[0]; try { encryptedDataMessage = encryptMSG(uuid, dataMessage.toByteArray(),context); } catch (KeyNotFoundException e) { encryptedDataMessage = dataMessage.toByteArray(); e.printStackTrace(); } byte[] encryptedMessageSemi = addMessageHeader(buildEncryptedMessage(ByteString.copyFrom(encryptedDataMessage)), MessageType.Encrypted); byte[] encryptedMessage = MessageHelper.buildFullEncryptedMessage(plainMessage.getBytes(), "0".getBytes(), 0, uuid, context); Log.TRACE("---\n Is: " + MessageHelper.byteArrayAsHexString(encryptedMessage)); Log.TRACE("---\n Should: " + MessageHelper.byteArrayAsHexString(encryptedMessageSemi)); Log.TRACE(" // SEND Message tlsClient.sendBytes(encryptedMessage); // RECEIVE List<Frontg8Client.Encrypted> messages = MessageHelper.getEncryptedMessagesFromNotification(MessageHelper.getNotificationMessage(tlsClient)); Log.TRACE("Num of messages: " + messages.size()); for (Frontg8Client.Encrypted message: messages) { // TODO: Decription of data String text = null; try { text = new String(getDecryptedContent(message, context)); } catch (InvalidMessageException e) { Log.e("Invalid MSG"); } Log.TRACE(text); } // SEND Message Request Message byte[] requestMessage = MessageHelper.addMessageHeader(MessageHelper.buildMessageRequestMessage("0").toByteArray(), MessageType.MessageRequest); Log.TRACE("---\n" + MessageHelper.byteArrayAsHexString(requestMessage)); tlsClient.sendBytes(requestMessage); // RECEIVE messages = MessageHelper.getEncryptedMessagesFromNotification(MessageHelper.getNotificationMessage(tlsClient)); Log.TRACE("Num of messages: " + messages.size()); for (Frontg8Client.Encrypted message: messages) { // TODO: Decription of data String text = null; try { text = new String(getDecryptedContent(message,context)); Log.TRACE(text); } catch (InvalidMessageException e) { Log.e("Invalid MSG"); } } tlsClient.close(); } }
package com.app.kongsin.sliduplayout; import android.animation.Animator; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class Item extends FrameLayout { private RelativeLayout mRootItemLayout; private LinearLayout mContentItem; private TextView mItemText; private ImageView mItemImage; private View mShadow; public Item(Context context) { super(context); initView(null); } public Item(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initView(attrs); } public Item(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(attrs); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public Item(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initView(attrs); } private void initView(@Nullable AttributeSet attributeSet) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.item_layout, this); mRootItemLayout = (RelativeLayout) findViewById(R.id.rootItemGroup); mContentItem = (LinearLayout) findViewById(R.id.linearLayout_itemContent_itemLayout); mItemText = (TextView) findViewById(R.id.textView_itemText_itemLayout); mItemImage = (ImageView) findViewById(R.id.imageView_itemImage_itemLayout); mShadow = findViewById(R.id.view); if (attributeSet != null){ TypedArray a = getContext().obtainStyledAttributes(attributeSet, R.styleable.Item); int count = a.getIndexCount(); for (int i = 0; i < count; i++) { switch (a.getIndex(i)){ case R.styleable.Item_tabBackground: int color = a.getColor(a.getIndex(i), Color.DKGRAY); setBackgroundColor(color); break; case R.styleable.Item_tabText: String text = a.getString(a.getIndex(i)); mItemText.setText(text); break; case R.styleable.Item_tabIcon: Drawable icon = a.getDrawable(a.getIndex(i)); setBackground(icon); break; } } a.recycle(); } post(new Runnable() { @Override public void run() { final int rotation = getContext().getResources().getConfiguration().orientation; if (rotation == Configuration.ORIENTATION_LANDSCAPE) { mItemImage.setVisibility(GONE); } } }); } public void showShadow(boolean show){ mShadow.setVisibility(show ? VISIBLE : INVISIBLE); } public void showImage(final boolean show){ final int rotation = getContext().getResources().getConfiguration().orientation; if (rotation == Configuration.ORIENTATION_PORTRAIT) { mItemImage.animate().alpha(show ? 1 : 0).start(); } else { mItemImage.setVisibility(GONE); } } public void setItemText(String text) { this.mItemText.setText(text); } @Override public void setBackgroundColor(@ColorInt int color) { if (mContentItem != null) mContentItem.setBackgroundColor(color); } @Override public void setBackground(Drawable background) { if (mContentItem != null) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mContentItem.setBackground(background); } else { mContentItem.setBackgroundDrawable(background); } } @Override public void setBackgroundResource(@DrawableRes int resid) { if (mContentItem != null) mContentItem.setBackgroundResource(resid); } }
package com.dyhpoon.fodex; import android.graphics.Point; import android.support.v4.app.Fragment; import android.test.ActivityInstrumentationTestCase2; import android.view.Display; import com.dyhpoon.fodex.fodexView.FodexBaseFragment; import com.robotium.solo.Solo; import com.squareup.spoon.Spoon; public class ScreenshotTest extends ActivityInstrumentationTestCase2<MainActivity> { private Solo solo; private FodexBaseFragment fodexFragment; public ScreenshotTest() { super(MainActivity.class); } @Override protected void setUp() throws Exception { solo = new Solo(getInstrumentation(), getActivity()); Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.container); if (fragment instanceof FodexBaseFragment) { fodexFragment = (FodexBaseFragment) fragment; fodexFragment.injectMock(true); scrollDown(); // refresh solo.sleep(3000); } else { throw new RuntimeException("Invalid fragment, expecting fragment to be an instance of FodexBaseFragment"); } } @Override protected void tearDown() throws Exception { solo.finishOpenedActivities(); } public void testScreenshotMain() { Spoon.screenshot(solo.getCurrentActivity(), "main"); solo.sleep(1000); solo.clickLongInList(0); Spoon.screenshot(solo.getCurrentActivity(), "main_dialog"); } public void testScreenshotNavigation() { Point deviceSize = new Point(); solo.getCurrentActivity().getWindowManager().getDefaultDisplay().getSize(deviceSize); int screenWidth = deviceSize.x; int screenHeight = deviceSize.y; int fromX = 0; int toX = screenWidth / 2; int fromY = screenHeight / 2; int toY = fromY; solo.drag(fromX, toX, fromY, toY, 1); Spoon.screenshot(solo.getCurrentActivity(), "navigation"); } public void testScreenshotFullscreen() { gotoFullscreen(); Spoon.screenshot(solo.getCurrentActivity(), "fullscreen"); } public void testScreenshotFullscreenShare() { gotoFullscreen(); Display display = solo.getCurrentActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; solo.clickLongOnScreen(width/2, height/2); Spoon.screenshot(solo.getCurrentActivity(), "fullscreen_share"); } private void scrollDown() { Display display = solo.getCurrentActivity().getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; solo.drag(width/2, width/2, height/2 - 50, height - 20, 10); } private void gotoFullscreen() { solo.clickInList(0); solo.sleep(1000); } }
package com.kickstarter.libs; import android.content.Intent; import android.os.Bundle; import android.support.annotation.AnimRes; import android.support.annotation.CallSuper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Pair; import com.kickstarter.libs.qualifiers.RequiresViewModel; import com.kickstarter.libs.utils.BundleUtils; import com.kickstarter.ui.data.ActivityResult; import com.trello.rxlifecycle.ActivityEvent; import com.trello.rxlifecycle.RxLifecycle; import com.trello.rxlifecycle.components.ActivityLifecycleProvider; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import timber.log.Timber; public class BaseActivity<ViewModelType extends ViewModel> extends AppCompatActivity implements ActivityLifecycleProvider, LifecycleType { private final PublishSubject<Void> back = PublishSubject.create(); private final BehaviorSubject<ActivityEvent> lifecycle = BehaviorSubject.create(); protected ViewModelType viewModel; private static final String VIEW_MODEL_KEY = "viewModel"; private final List<Subscription> subscriptions = new ArrayList<>(); /** * Get viewModel. */ public ViewModelType viewModel() { return viewModel; } /** * Returns an observable of the activity's lifecycle events. */ public final Observable<ActivityEvent> lifecycle() { return lifecycle.asObservable(); } /** * Completes an observable when an {@link ActivityEvent} occurs in the activity's lifecycle. */ public final <T> Observable.Transformer<T, T> bindUntilEvent(final ActivityEvent event) { return RxLifecycle.bindUntilActivityEvent(lifecycle, event); } /** * Completes an observable when the lifecycle event opposing the current lifecyle event is emitted. * For example, if a subscription is made during {@link ActivityEvent#CREATE}, the observable will be completed * in {@link ActivityEvent#DESTROY}. */ public final <T> Observable.Transformer<T, T> bindToLifecycle() { return RxLifecycle.bindActivity(lifecycle); } /** * Sends activity result data to the view model. */ @CallSuper @Override protected void onActivityResult(final int requestCode, final int resultCode, final @Nullable Intent intent) { super.onActivityResult(requestCode, resultCode, intent); viewModel.activityResult(ActivityResult.create(requestCode, resultCode, intent)); } @CallSuper @Override protected void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.d("onCreate %s", this.toString()); lifecycle.onNext(ActivityEvent.CREATE); fetchViewModel(savedInstanceState); viewModel.intent(getIntent()); } /** * Called when an activity is set to `singleTop` and it is relaunched while at the top of the activity stack. */ @CallSuper @Override protected void onNewIntent(final Intent intent) { super.onNewIntent(intent); viewModel.intent(intent); } @CallSuper @Override protected void onStart() { super.onStart(); Timber.d("onStart %s", this.toString()); lifecycle.onNext(ActivityEvent.START); back .compose(bindUntilEvent(ActivityEvent.STOP)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(__ -> goBack()); } @CallSuper @Override protected void onResume() { super.onResume(); Timber.d("onResume %s", this.toString()); lifecycle.onNext(ActivityEvent.RESUME); fetchViewModel(null); if (viewModel != null) { viewModel.onResume(this); } } @CallSuper @Override protected void onPause() { lifecycle.onNext(ActivityEvent.PAUSE); super.onPause(); Timber.d("onPause %s", this.toString()); if (viewModel != null) { viewModel.onPause(); } } @CallSuper @Override protected void onStop() { lifecycle.onNext(ActivityEvent.STOP); super.onStop(); Timber.d("onStop %s", this.toString()); } @CallSuper @Override protected void onDestroy() { lifecycle.onNext(ActivityEvent.DESTROY); super.onDestroy(); Timber.d("onDestroy %s", this.toString()); for (final Subscription subscription : subscriptions) { subscription.unsubscribe(); } if (isFinishing()) { if (viewModel != null) { ViewModels.getInstance().destroy(viewModel); viewModel = null; } } } @CallSuper @Override @Deprecated public void onBackPressed() { back(); } /** * Call when the user wants triggers a back event, e.g. clicking back in a toolbar or pressing the device back button. */ public void back() { back.onNext(null); } /** * Override in subclasses for custom exit transitions. First item in pair is the enter animation, * second item in pair is the exit animation. */ protected @Nullable Pair<Integer, Integer> exitTransition() { return null; } @CallSuper @Override protected void onSaveInstanceState(final @NonNull Bundle outState) { super.onSaveInstanceState(outState); Timber.d("onSaveInstanceState %s", this.toString()); final Bundle viewModelEnvelope = new Bundle(); if (viewModel != null) { ViewModels.getInstance().save(viewModel, viewModelEnvelope); } outState.putBundle(VIEW_MODEL_KEY, viewModelEnvelope); } protected final void startActivityWithTransition(final @NonNull Intent intent, final @AnimRes int enterAnim, final @AnimRes int exitAnim) { startActivity(intent); overridePendingTransition(enterAnim, exitAnim); } /** * @deprecated Use {@link #bindToLifecycle()} or {@link #bindUntilEvent(ActivityEvent)} instead. */ @Deprecated protected final void addSubscription(final @NonNull Subscription subscription) { subscriptions.add(subscription); } /** * Triggers a back press with an optional transition. */ private void goBack() { super.onBackPressed(); final Pair<Integer, Integer> exitTransitions = exitTransition(); if (exitTransitions != null) { overridePendingTransition(exitTransitions.first, exitTransitions.second); } } private void fetchViewModel(final @Nullable Bundle viewModelEnvelope) { if (viewModel == null) { final RequiresViewModel annotation = getClass().getAnnotation(RequiresViewModel.class); final Class<ViewModelType> viewModelClass = annotation == null ? null : (Class<ViewModelType>) annotation.value(); if (viewModelClass != null) { viewModel = ViewModels.getInstance().fetch(this, viewModelClass, BundleUtils.maybeGetBundle(viewModelEnvelope, VIEW_MODEL_KEY)); } } } }
package org.jboss.modules; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.security.SecureClassLoader; import java.util.ArrayDeque; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; /** * @author <a href="mailto:jbailey@redhat.com">John Bailey</a> * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ModuleClassLoader extends SecureClassLoader { static { try { final Method method = ClassLoader.class.getMethod("registerAsParallelCapable"); method.invoke(null); } catch (Exception e) { // ignore } } private final Module module; private final Set<Module.Flag> flags; private final Map<String, Class<?>> cache = new HashMap<String, Class<?>>(256); ModuleClassLoader(final Module module, final Set<Module.Flag> flags, final AssertionSetting setting) { this.module = module; this.flags = flags; if (setting != AssertionSetting.INHERIT) { setDefaultAssertionStatus(setting == AssertionSetting.ENABLED); } } @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { return loadClass(name, false); } @Override protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { if (className == null) { throw new IllegalArgumentException("name is null"); } if (className.startsWith("java.")) { // always delegate to system final Class<?> systemClass = findSystemClass(className); if (resolve) resolveClass(systemClass); return systemClass; } if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, resolve, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (LoaderThreadHolder.REQUEST_QUEUE) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } else { // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. // Check if we have already loaded it.. Class<?> loadedClass; final Map<String, Class<?>> cache = this.cache; final boolean missing; synchronized (this) { missing = cache.containsKey(className); loadedClass = cache.get(className); } if (loadedClass != null) { return loadedClass; } if (missing) { throw new ClassNotFoundException(className); } final Set<Module.Flag> flags = this.flags; if (flags.contains(Module.Flag.CHILD_FIRST)) { loadedClass = loadClassLocal(className); if (loadedClass == null) { loadedClass = module.getImportedClass(className); } if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } } else { loadedClass = module.getImportedClass(className); if (loadedClass == null) try { loadedClass = findSystemClass(className); } catch (ClassNotFoundException e) { } if (loadedClass == null) { loadedClass = loadClassLocal(className); } } if (loadedClass == null) { if (! flags.contains(Module.Flag.NO_BLACKLIST)) { synchronized (this) { cache.put(className, null); } } throw new ClassNotFoundException(className); } synchronized (this) { cache.put(className, loadedClass); } if (loadedClass != null && resolve) resolveClass(loadedClass); return loadedClass; } } private Class<?> loadClassLocal(String name) throws ClassNotFoundException { // Check to see if we can load it ClassSpec classSpec = null; try { classSpec = module.getLocalClassSpec(name); } catch (IOException e) { throw new ClassNotFoundException(name, e); } catch (RuntimeException e) { System.err.print("Unexpected runtime exception in module loader: "); e.printStackTrace(System.err); throw new ClassNotFoundException(name, e); } catch (Error e) { System.err.print("Unexpected error in module loader: "); e.printStackTrace(System.err); throw new ClassNotFoundException(name, e); } if (classSpec == null) return null; return defineClass(name, classSpec); } private Class<?> defineClass(final String name, final ClassSpec classSpec) { // Ensure that the package is loaded final int lastIdx = name.lastIndexOf('.'); if (lastIdx != -1) { // there's a package name; get the Package for it final String packageName = name.substring(0, lastIdx); final Package pkg = getPackage(packageName); if (pkg != null) { // Package is defined already if (pkg.isSealed() && ! pkg.isSealed(classSpec.getCodeSource().getLocation())) { // use the same message as the JDK throw new SecurityException("sealing violation: package " + packageName + " is sealed"); } } else { final PackageSpec spec; try { spec = getModule().getLocalPackageSpec(name); definePackage(name, spec); } catch (IOException e) { definePackage(name, null); } } } final Class<?> newClass = defineClass(name, classSpec.getBytes(), 0, classSpec.getBytes().length, classSpec.getCodeSource()); final AssertionSetting setting = classSpec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setClassAssertionStatus(name, setting == AssertionSetting.ENABLED); } return newClass; } private Package definePackage(final String name, final PackageSpec spec) { if (spec == null) { return definePackage(name, null, null, null, null, null, null, null); } else { final Package pkg = definePackage(name, spec.getSpecTitle(), spec.getSpecVersion(), spec.getSpecVendor(), spec.getImplTitle(), spec.getImplVersion(), spec.getImplVendor(), spec.getSealBase()); final AssertionSetting setting = spec.getAssertionSetting(); if (setting != AssertionSetting.INHERIT) { setPackageAssertionStatus(name, setting == AssertionSetting.ENABLED); } return pkg; } } @Override protected String findLibrary(final String libname) { return module.getLocalLibrary(libname); } @Override public URL getResource(String name) { final Resource resource = module.getExportedResource(name); return resource == null ? null : resource.getURL(); } @Override public Enumeration<URL> getResources(String name) throws IOException { final Iterable<Resource> resources = module.getExportedResources(name); final Iterator<Resource> iterator = resources.iterator(); return new Enumeration<URL>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public URL nextElement() { return iterator.next().getURL(); } }; } @Override public InputStream getResourceAsStream(final String name) { try { final Resource resource = module.getExportedResource(name); return resource == null ? null : resource.openStream(); } catch (IOException e) { return null; } } /** * Get the module for this class loader. * * @return the module */ public Module getModule() { return module; } public String toString() { return "ClassLoader for " + module; } public static ModuleClassLoader forModule(ModuleIdentifier identifier) throws ModuleLoadException { return Module.getModule(identifier).getClassLoader(); } public static ModuleClassLoader forModuleName(String identifier) throws ModuleLoadException { return forModule(ModuleIdentifier.fromString(identifier)); } private static final class LoaderThreadHolder { private static final Thread LOADER_THREAD; private static final Queue<LoadRequest> REQUEST_QUEUE = new ArrayDeque<LoadRequest>(); static { Thread thr = new LoaderThread(); thr.setName("ModuleClassLoader Thread"); // This thread will always run as long as the VM is alive. thr.setDaemon(true); thr.start(); LOADER_THREAD = thr; } private LoaderThreadHolder() { } } static class LoadRequest { private final String className; private final ModuleClassLoader requester; private Class<?> result; private boolean resolve; private boolean done; public LoadRequest(final String className, final boolean resolve, final ModuleClassLoader requester) { this.className = className; this.resolve = resolve; this.requester = requester; } } static class LoaderThread extends Thread { @Override public void interrupt() { // no interruption } @Override public void run() { final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; for (; ;) { try { LoadRequest request; synchronized (queue) { while ((request = queue.poll()) == null) { queue.wait(); } } final ModuleClassLoader loader = request.requester; Class<?> result = null; synchronized (loader) { try { result = loader.loadClass(request.className, request.resolve); } finally { // no matter what, the requester MUST be notified request.result = result; request.done = true; loader.notifyAll(); } } } catch (Throwable t) { // ignore } } } } }
package attackontinytim.barquest; import android.os.Handler; import android.support.design.widget.TabLayout; import android.util.Log; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TableLayout; import android.widget.TextView; import org.w3c.dom.Text; import java.util.List; import java.util.Collections; import attackontinytim.barquest.Database.InventoryRepo; import attackontinytim.barquest.Database.Monster; import attackontinytim.barquest.Database.MonsterRepo; import attackontinytim.barquest.Database.Weapon; import attackontinytim.barquest.Database.WeaponRepo; import attackontinytim.barquest.Database.ConsumableItem; import attackontinytim.barquest.Database.ConsumableRepo; public class BattleActivity extends AppCompatActivity /*implements Parcelable*/{ private Battle battle; private Hero hero; private Monster enemy; // Return static public int MAIN_RETURN_CODE = 1; // Buttons private static Button attack; private static Button item; private static Button flee; // Description variables private String attacker; private String defender; private int damage; // This is what is done when the BattleActivity is created @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.battle_laout); Bundle bundle = getIntent().getExtras(); hero = bundler.unbundleHero(bundle); // enemy = new Monster(/*some sort of Cursor*/); try{ enemy = MonsterRepo.getMonsterFromHash(bundle.getInt("MonsterHash")); } catch (Exception e){ Log.d("HERE", e.getMessage()); enemy = new Monster(1,"Bob", 100, 50, "Close", 5.0, 1, "Common", 5, 5, 5); } battle = new Battle(hero, enemy); // Hook up UI variables to backend variables for Hero TextView Name = (TextView) findViewById(R.id.CharName); TextView LvlStat = (TextView) findViewById(R.id.lvlstat); TextView TotalHPStat = (TextView) findViewById(R.id.hpstat); TextView CurrHPStat = (TextView) findViewById(R.id.currCharHP); ProgressBar HeroHPBar = (ProgressBar) findViewById(R.id.CharHPBar); Name.setText(String.valueOf(battle.hero.getName())); LvlStat.setText(String.valueOf(battle.hero.getLevel())); TotalHPStat.setText(String.valueOf(hero.getHP())); CurrHPStat.setText(String.valueOf(battle.battleHero.getHP())); HeroHPBar.setMax(battle.hero.getHP()); HeroHPBar.setProgress(battle.hero.getHP()); // Hook up UI variables to backend variables for Monster TextView MonName = (TextView) findViewById(R.id.MonName); TextView MonLvl = (TextView) findViewById(R.id.monlvl); TextView TotalMonHP = (TextView) findViewById(R.id.monhp); TextView CurrMonHP = (TextView) findViewById(R.id.currMonHP); ProgressBar MonHPBar = (ProgressBar) findViewById(R.id.MonHPBar); MonName.setText(String.valueOf(battle.enemy.getName())); MonLvl.setText(String.valueOf(battle.enemy.getLevel())); TotalMonHP.setText(String.valueOf(enemy.getHP())); CurrMonHP.setText(String.valueOf(battle.battleEnemy.getHP())); MonHPBar.setVisibility(View.VISIBLE); MonHPBar.setMax(battle.enemy.getHP()); MonHPBar.setProgress(battle.enemy.getHP()); onClickButtonListener(); } public void onClickButtonListener() { attack = (Button) findViewById(R.id.attackButton); item = (Button) findViewById(R.id.itemButton); flee = (Button) findViewById(R.id.fleeButton); //TODO: implement item functionality attack.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { final TextView CurrMonHP = (TextView) findViewById(R.id.currMonHP); final TextView CurrHPStat = (TextView) findViewById(R.id.currCharHP); if(battle.heroPriority()) { damage = battle.battleEnemy.getHP(); battle.heroTurn(); attacker = battle.hero.getName(); defender = battle.enemy.getName(); damage = damage - battle.battleEnemy.getHP(); reloadBattleScreen(); } else { battle.enemyTurn(); attacker = battle.enemy.getName(); defender = battle.hero.getName(); damage = battle.enemy.getAttack(); reloadBattleScreen(); } if (battle.isLost()) { /** Disable buttons for safety */ attack.setClickable(false); item.setClickable(false); flee.setClickable(false); /** Lose money (10%) */ hero.setMoney(hero.getMoney() - (hero.getMoney()/10)); end(); } if (battle.isWon()) { /** Disable buttons for safety */ attack.setClickable(false); item.setClickable(false); flee.setClickable(false); /** Update Quest */ hero.getCurrentQuest().updateQuestProgress(battle.battleEnemy); /** Gain Money */ hero.setMoney(hero.getMoney() + 100); /** Loot Drop */ int rand = (int)Math.random()*10; if(rand < 2) { /** Drop Random Weapon (20%) */ List<Weapon> wList = WeaponRepo.getAllItems(); Collections.shuffle(wList); InventoryRepo.addItemToInventory(wList.get(0)); } else { /** Drop Random Consumable (80%) */ List<ConsumableItem> cList = ConsumableRepo.getAllConsumables(); Collections.shuffle(cList); InventoryRepo.addItemToInventory(cList.get(0)); } /** Gain XP + Level Up */ int xp = hero.getXP(); hero.inc_experience(enemy.getXP()); if(xp + enemy.getXP() > 100) { Intent intent = new Intent("attackontinytim.barquest.LevelUpActivity"); Bundle bundle = bundler.generateBundle(hero); intent.putExtras(bundle); startActivityForResult(intent, MAIN_RETURN_CODE); } end(); } //insert pause here for dramatic effect final Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run(){ if(battle.heroPriority()) { battle.enemyTurn(); attacker = battle.enemy.getName(); defender = battle.hero.getName(); damage = battle.enemy.getAttack(); reloadBattleScreen(); } else { damage = battle.battleEnemy.getHP(); battle.heroTurn(); attacker = battle.hero.getName(); defender = battle.enemy.getName(); damage = damage - battle.battleEnemy.getHP(); reloadBattleScreen(); } handler.postDelayed(new Runnable() { public void run(){ if (battle.isLost()) { /** Disable buttons for safety */ attack.setClickable(false); item.setClickable(false); flee.setClickable(false); /** Lose money (10%) */ hero.setMoney(hero.getMoney() - (hero.getMoney()/10)); end(); } if (battle.isWon()) { /** Disable buttons for safety */ attack.setClickable(false); item.setClickable(false); flee.setClickable(false); /** Update Quest */ hero.getCurrentQuest().updateQuestProgress(battle.battleEnemy); /** Gain Money */ hero.setMoney(hero.getMoney() + 100); /** Loot Drop */ int rand = (int)Math.random()*10; if(rand < 2) { /** Drop Random Weapon (20%) */ List<Weapon> wList = WeaponRepo.getAllItems(); Collections.shuffle(wList); InventoryRepo.addItemToInventory(wList.get(0)); } else { /** Drop Random Consumable (80%) */ List<ConsumableItem> cList = ConsumableRepo.getAllConsumables(); Collections.shuffle(cList); InventoryRepo.addItemToInventory(cList.get(0)); } /** Gain XP + Level Up */ int xp = hero.getXP(); hero.inc_experience(enemy.getXP()); if(xp + enemy.getXP() > 100) { Intent intent = new Intent("attackontinytim.barquest.LevelUpActivity"); Bundle bundle = bundler.generateBundle(hero); intent.putExtras(bundle); startActivityForResult(intent, MAIN_RETURN_CODE); } end(); } } },1500); } }, 1000); //wait 1s } } ); item.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { // temporary; need to find a way to click "back" and not go back to MainActivity // CHECK COMMENTS BELOW Intent intent = new Intent("attackontinytim.barquest.InventoryActivity"); Bundle bundle = bundler.generateBundle(hero); intent.putExtras(bundle); startActivityForResult(intent, MAIN_RETURN_CODE); } } ); // Robert says: Check out the end function below flee.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent("attackontinytim.barquest.MainActivity"); Bundle bundle = bundler.generateBundle(hero); setResult(RESULT_OK,getIntent().putExtras(bundle)); if (battle.calc_flee()){ end(); } else{ battle.enemyTurn(); attacker = battle.enemy.getName(); defender = battle.hero.getName(); damage = battle.enemy.getAttack(); reloadBattleScreen(); if (battle.isLost()) { /** Disable buttons for safety */ attack.setClickable(false); item.setClickable(false); flee.setClickable(false); /** Lose money (10%) */ hero.setMoney(hero.getMoney() - (hero.getMoney()/10)); end(); } } //TODO: add some kind of pause+"flee was successful/failed" output } } ); } // Completion of activity; not the same as pressing back @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_CANCELED) { switch (requestCode) { default: end(); } } } // This is what is called when back is pressed @Override public void onBackPressed() { // Change it to whatever you want; right now it just ends end(); } // end the activity private void end(){ Bundle bundle = bundler.generateBundle(hero); setResult(RESULT_OK,getIntent().putExtras(bundle)); finish(); } protected void reloadBattleScreen() { /* Reloads the Battle Screen to update certain stat values rather than reloading the entire page from scratch */ // Update battle description TableLayout battleDesc = (TableLayout) findViewById(R.id.battleDescription); battleDesc.setVisibility(View.VISIBLE); TextView attackerText = (TextView) findViewById(R.id.attackerText); TextView defenderText = (TextView) findViewById(R.id.defenderText); TextView damageText = (TextView) findViewById(R.id.damageText); attackerText.setText(attacker); defenderText.setText(defender); damageText.setText(String.valueOf(damage)); // Update Player stats TextView CurrHPStat = (TextView) findViewById(R.id.currCharHP); ProgressBar HeroHPBar = (ProgressBar) findViewById(R.id.CharHPBar); CurrHPStat.setText(String.valueOf(battle.battleHero.getHP())); HeroHPBar.setProgress(battle.battleHero.getHP()); // Update Monster stats TextView CurrMonHP = (TextView) findViewById(R.id.currMonHP); ProgressBar MonHPBar = (ProgressBar) findViewById(R.id.MonHPBar); CurrMonHP.setText(String.valueOf(battle.battleEnemy.getHP())); MonHPBar.setProgress(battle.battleEnemy.getHP()); // Attack effects ImageView attackPic = (ImageView) findViewById(R.id.attackPic); attackPic.setVisibility(View.VISIBLE); if(attacker == battle.hero.getName()) attackPic.setScaleX(1); else if(attacker == battle.enemy.getName()) attackPic.setScaleX(-1); } }
package com.sgwares.android; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.messaging.FirebaseMessaging; import com.sgwares.android.models.User; public class LoginActivity extends AppCompatActivity { private static final String TAG = "LoginActivity"; private FirebaseAuth mAuth; private DatabaseReference usersRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mAuth = FirebaseAuth.getInstance(); if (mAuth.getCurrentUser() != null) { finish(); } usersRef = FirebaseDatabase.getInstance().getReference("users"); Button notNow = (Button) findViewById(R.id.not_now); notNow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAuth.signInAnonymously().addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInAnonymously onComplete: " + task.isSuccessful()); if (task.isSuccessful()) { processSignIn(); } } }); } }); } private void processSignIn() { User user = new User(mAuth.getCurrentUser()); FirebaseMessaging.getInstance().subscribeToTopic(user.getKey()); DatabaseReference newUser = usersRef.child(user.getKey()); newUser.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Log.d(TAG, "Create user onComplete: " + task.isSuccessful()); finish(); } }); } }
package org.nakedobjects.distribution; import org.nakedobjects.NakedObjects; import org.nakedobjects.object.Naked; import org.nakedobjects.object.NakedObject; import org.nakedobjects.object.NakedObjectSpecification; import org.nakedobjects.object.control.Hint; import org.nakedobjects.object.reflect.AbstractActionPeer; import org.nakedobjects.object.reflect.Action; import org.nakedobjects.object.reflect.ActionPeer; import org.nakedobjects.object.reflect.MemberIdentifier; import org.nakedobjects.object.reflect.ReflectiveActionException; import org.apache.log4j.Logger; public final class ProxyAction extends AbstractActionPeer { private final static Logger LOG = Logger.getLogger(ProxyAction.class); private Distribution connection; private boolean fullProxy = false; private final DataFactory dataFactory; public ProxyAction(final ActionPeer local, final Distribution connection, DataFactory objectDataFactory) { super(local); this.connection = connection; this.dataFactory = objectDataFactory; } public Naked execute(MemberIdentifier identifier, NakedObject target, Naked[] parameters) throws ReflectiveActionException { if (executeRemotely(target)) { Data[] parameterObjectData = parameterValues(parameters); LOG.debug(debug("execute remotely", identifier, target, parameters)); ObjectData targetReference = dataFactory.createDataForActionTarget(target); Data result = connection.executeAction(NakedObjects.getCurrentSession(), getType().getName(), getName(), targetReference, parameterObjectData); Naked returnedObject; returnedObject = result instanceof NullData ? null : DataHelper.recreateNaked((ObjectData) result); return returnedObject; } else { LOG.debug(debug("execute locally", identifier, target, parameters)); return super.execute(identifier, target, parameters); } } private boolean executeRemotely(NakedObject target) { boolean remoteOverride = getTarget() == Action.REMOTE; boolean localOverride = getTarget() == Action.LOCAL; if (localOverride) { return false; } if (remoteOverride) { return true; } boolean remoteAsPersistent = target.getOid() != null; return remoteAsPersistent; } private Data[] parameterValues(Naked[] parameters) { NakedObjectSpecification[] parameterTypes = parameterTypes(); Data parameterObjectData[] = new Data[parameters.length]; for (int i = 0; i < parameters.length; i++) { Naked parameter = parameters[i]; String type = parameterTypes[i].getFullName(); parameterObjectData[i] = dataFactory.createDataForParameter(type, parameter); } return parameterObjectData; } public Hint getHint(MemberIdentifier identifier, NakedObject target, Naked[] parameters) { if (executeRemotely(target) && fullProxy) { Data[] parameterObjectData = parameterValues(parameters); LOG.debug(debug("get hint remotely", identifier, target, parameters)); ObjectData targetReference = dataFactory.createDataForActionTarget(target); return connection.getActionHint(NakedObjects.getCurrentSession(), getType().getName(), getName(), targetReference, parameterObjectData); } else { LOG.debug(debug("get hint locally", identifier, target, parameters)); return super.getHint(identifier, target, parameters); } } private String debug(String message, MemberIdentifier identifier, NakedObject target, Naked[] parameters) { if (LOG.isDebugEnabled()) { StringBuffer str = new StringBuffer(); str.append(message); str.append(" "); str.append(identifier); str.append(" on "); str.append(target); for (int i = 0; i < parameters.length; i++) { if (i > 0) { str.append(','); } str.append(parameters[i]); } return str.toString(); } else { return ""; } } }
package doit.study.droid; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.Observable; import java.util.Observer; public class QuestionFragment extends LifecycleLoggingFragment implements View.OnClickListener, Observer { private static final boolean DEBUG = true; private int mQuestionId; private OnAnswerCheckListener mOnAnswerCheckListener; private OnFragmentChangeListener mOnFragmentChangeListener; // keys for bundle, to save state private static final String ID_KEY = "doit.study.dodroid.id_key"; private static final String COMMIT_BUTTON_STATE_KEY = "doit.study.dodroid.commit_button_state_key"; // model stuff private Question mCurrentQuestion; private QuizData mQuizData; private int isEnabledCommitButton = 1; // view stuff private View mView; private ArrayList<CheckBox> mvCheckBoxes; private Button mvCommitButton; private TextView mvQuestionText; private LinearLayout mvAnswersLayout; private TextView mvRight; private TextView mvWrong; private Button mvNextButton; private Toast toast; // Host Activity must implement these interfaces public interface OnFragmentChangeListener { void updateFragments(); void swipeToNext(int delay); } public interface OnAnswerCheckListener { void onAnswer(int questionId, boolean isRight); } public static QuestionFragment newInstance(int questionId) { if (DEBUG) Log.i("NSA", "newInstance "+questionId); // add Bundle args if needed here before returning new instance of this class QuestionFragment fragment = new QuestionFragment(); Bundle bundle = new Bundle(); bundle.putInt(ID_KEY, questionId); fragment.setArguments(bundle); return fragment; } @Override public void update(Observable observable, Object data) { populate(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater){ super.onCreateOptionsMenu(menu, menuInflater); menuInflater.inflate(R.menu.fragment_question, menu); } @Override public boolean onOptionsItemSelected(MenuItem menuItem){ switch(menuItem.getItemId()){ case(R.id.doc_reference):{ if (mCurrentQuestion.getDocRef().isEmpty()) Toast.makeText(getActivity(), "Not yet", Toast.LENGTH_SHORT).show(); else { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(mCurrentQuestion.getDocRef())); startActivity(intent); } return true; } default: return super.onOptionsItemSelected(menuItem); } } @Override public void onAttach(Context activity){ // for a logging purpose ID = ((Integer) getArguments().getInt(ID_KEY)).toString(); super.onAttach(activity); try { mOnFragmentChangeListener = (OnFragmentChangeListener) activity; mOnAnswerCheckListener = (OnAnswerCheckListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentChangeListener and OnAnswerCheckListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mQuestionId = getArguments().getInt(ID_KEY); mQuizData = ((GlobalData)getActivity().getApplication()).getQuizData(); mCurrentQuestion = mQuizData.getById(mQuestionId); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mkViewsLinks(inflater, container); updateModel(); updateView(); populate(); if (savedInstanceState != null) { Log.i(TAG, "isEnabledCommitButton " + savedInstanceState.getInt("COMMIT_BUTTON_ENABLED")); isEnabledCommitButton = savedInstanceState.getInt(COMMIT_BUTTON_STATE_KEY); mvCommitButton.setEnabled(isEnabledCommitButton == 1); } return mView; } private void mkViewsLinks(LayoutInflater inflater, ViewGroup container){ if (DEBUG) Log.i(TAG, "mkViewsLinks "+ID); // You can not use the findViewById method the way you can in an Activity in a Fragment // So we get a reference to the view/layout_file that we used for this Fragment // That allows use to then reference the views by id in that file mView = inflater.inflate(R.layout.fragment_questions, container, false); mvQuestionText = (TextView) mView.findViewById(R.id.question); mvAnswersLayout = (LinearLayout) mView.findViewById(R.id.answers); mvCommitButton = (Button) mView.findViewById(R.id.commit_button); mvNextButton = (Button) mView.findViewById(R.id.next_button); // You can not add onclick listener to a button in a fragment's xml // So we implement OnClickListener interface, check onClick() method mvCommitButton.setOnClickListener(this); mvNextButton.setOnClickListener(this); mvRight = (TextView) mView.findViewById(R.id.right_counter); mvWrong = (TextView) mView.findViewById(R.id.wrong_counter); } private void updateView(){ } private void updateModel(){ } // Map data from the current Question to the View elements public void populate() { if (DEBUG) Log.i(TAG, "populate "+ID); mvQuestionText.setText(mCurrentQuestion.getText()); mvRight.setText("" + mQuizData.getTotalRightCounter()); mvRight.setTextColor(Color.GREEN); mvWrong.setText(" " + mQuizData.getTotalWrongCounter()); mvWrong.setTextColor(Color.RED); mvAnswersLayout.removeAllViewsInLayout(); ArrayList<String> allAnswers = new ArrayList<>(); allAnswers.addAll(mCurrentQuestion.getRightItems()); allAnswers.addAll(mCurrentQuestion.getWrongItems()); Collections.shuffle(allAnswers); mvCheckBoxes = new ArrayList<>(); // create checkboxes dynamically for (int i = 0; i < allAnswers.size(); i++) { // Can not use "this" keyword for constructor here. Requires a Context and Fragment class does not inherit from Context CheckBox checkBox = new CheckBox(getContext()); checkBox.setText(allAnswers.get(i)); mvAnswersLayout.addView(checkBox); mvCheckBoxes.add(checkBox); } } public Boolean checkAnswers() { if (DEBUG) Log.i(TAG, "checkAnswers "+ID); Boolean goodJob = true; for (CheckBox cb : mvCheckBoxes) { // you can have multiple right answers String cbText = cb.getText().toString(); if (cb.isChecked()) { if (!mCurrentQuestion.getRightItems().contains(cbText)) { goodJob = false; break; } } else if (mCurrentQuestion.getRightItems().contains(cbText)) { goodJob = false; break; } } toast = Toast.makeText(getContext(), "", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); TextView v = (TextView) toast.getView().findViewById(android.R.id.message); if (goodJob) { toast.setText("Right"); v.setTextColor(Color.GREEN); mQuizData.incrementRightCounter(mQuestionId); mvRight.setText("" + mQuizData.getTotalRightCounter()); mvCommitButton.setEnabled(false); isEnabledCommitButton = 0; } else { toast.setText("Wrong"); v.setTextColor(Color.RED); mQuizData.incrementWrongCounter(mQuestionId); mvWrong.setText(" " + mQuizData.getTotalWrongCounter()); } mOnFragmentChangeListener.updateFragments(); toast.show(); return goodJob; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(COMMIT_BUTTON_STATE_KEY, isEnabledCommitButton); } @Override public void onClick(View v) { int delay = 2000; switch (v.getId()) { case (R.id.commit_button): boolean isRight = checkAnswers(); mOnAnswerCheckListener.onAnswer(mQuestionId, isRight); if (!isRight) { v.setVisibility(View.GONE); mvNextButton.setVisibility(View.VISIBLE); } else { mOnFragmentChangeListener.swipeToNext(delay); } break; case (R.id.next_button): delay = 0; mOnFragmentChangeListener.swipeToNext(delay); break; } Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { toast.cancel(); } }, delay); } }
package com.breadwallet.tools.security; import android.app.Activity; import android.content.Context; import android.util.Log; import com.breadwallet.R; import com.breadwallet.presenter.customviews.BRDialogView; import com.breadwallet.presenter.entities.PaymentItem; import com.breadwallet.presenter.interfaces.BRAuthCompletion; import com.breadwallet.tools.animation.BRAnimator; import com.breadwallet.tools.animation.BRDialog; import com.breadwallet.tools.manager.BRApiManager; import com.breadwallet.tools.manager.BRReportsManager; import com.breadwallet.tools.manager.BRSharedPrefs; import com.breadwallet.tools.threads.BRExecutor; import com.breadwallet.tools.util.BRConstants; import com.breadwallet.tools.util.BRCurrency; import com.breadwallet.tools.util.BRExchange; import com.breadwallet.wallet.BRWalletManager; import com.google.firebase.crash.FirebaseCrash; import java.math.BigDecimal; import java.util.Locale; import java.util.logging.Handler; public class BRSender { private static final String TAG = BRSender.class.getName(); private static BRSender instance; private final static long FEE_EXPIRATION_MILLIS = 72 * 60 * 60 * 1000L; private boolean timedOut; private boolean sending; private BRSender() { } public static BRSender getInstance() { if (instance == null) instance = new BRSender(); return instance; } /** * Create tx from the PaymentItem object and try to send it */ public void sendTransaction(final Context app, final PaymentItem request) { //array in order to be able to modify the first element from an inner block (can't be final) final String[] errTitle = {null}; final String[] errMessage = {null}; BRExecutor.getInstance().forLightWeightBackgroundTasks().execute(new Runnable() { @Override public void run() { try { if (sending) { FirebaseCrash.report(new NullPointerException("sendTransaction returned because already sending..")); return; } sending = true; long now = System.currentTimeMillis(); //if the fee was updated more than 24 hours ago then try updating the fee if (now - BRSharedPrefs.getFeeTime(app) >= FEE_EXPIRATION_MILLIS) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } if (sending) timedOut = true; } }).start(); BRApiManager.updateFeePerKb(app); //if the fee is STILL out of date then fail with network problem message long time = BRSharedPrefs.getFeeTime(app); if (time <= 0 || now - time >= FEE_EXPIRATION_MILLIS) { Log.e(TAG, "sendTransaction: fee out of date even after fetching..."); throw new FeeOutOfDate(BRSharedPrefs.getFeeTime(app), now); } } if (!timedOut) tryPay(app, request); else FirebaseCrash.report(new NullPointerException("did not send, timedOut!")); return; //return so no error is shown } catch (InsufficientFundsException ignored) { errTitle[0] = app.getString(R.string.Alerts_sendFailure); // errMessage[0] = app.getString(R.string.insufficient_funds); } catch (AmountSmallerThanMinException e) { long minAmount = BRWalletManager.getInstance().getMinOutputAmountRequested(); errTitle[0] = app.getString(R.string.Alerts_sendFailure); errMessage[0] = String.format(Locale.getDefault(), app.getString(R.string.PaymentProtocol_Errors_smallPayment), BRConstants.bitcoinLowercase + new BigDecimal(minAmount).divide(new BigDecimal(100), BRConstants.ROUNDING_MODE)); } catch (SpendingNotAllowed spendingNotAllowed) { showSpendNotAllowed(app); return; } catch (FeeNeedsAdjust feeNeedsAdjust) { //offer to change amount, so it would be enough for fee // showFailed(app); //just show failed for now showAdjustFee((Activity) app, request); return; } catch (FeeOutOfDate ex) { //Fee is out of date, show not connected error FirebaseCrash.report(ex); BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() { @Override public void run() { BRDialog.showCustomDialog(app, app.getString(R.string.Alerts_sendFailure), app.getString(R.string.NodeSelector_notConnected), app.getString(R.string.Button_ok), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismiss(); } }, null, null, 0); } }); return; } finally { sending = false; timedOut = false; } //show the message if we have one to show if (errTitle[0] != null && errMessage[0] != null) BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() { @Override public void run() { BRDialog.showCustomDialog(app, errTitle[0], errMessage[0], app.getString(R.string.Button_ok), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismiss(); } }, null, null, 0); } }); } }); } /** * Try transaction and throw appropriate exceptions if something was wrong * BLOCKS */ public void tryPay(final Context app, final PaymentItem paymentRequest) throws InsufficientFundsException, AmountSmallerThanMinException, SpendingNotAllowed, FeeNeedsAdjust { if (paymentRequest == null || paymentRequest.addresses == null) { Log.e(TAG, "handlePay: WRONG PARAMS"); String message = paymentRequest == null ? "paymentRequest is null" : "addresses is null"; BRReportsManager.reportBug(new RuntimeException("paymentRequest is malformed: " + message), true); } long amount = paymentRequest.amount; long balance = BRWalletManager.getInstance().getBalance(app); final BRWalletManager m = BRWalletManager.getInstance(); long minOutputAmount = BRWalletManager.getInstance().getMinOutputAmount(); final long maxOutputAmount = BRWalletManager.getInstance().getMaxOutputAmount(); // check if spending is allowed if (!BRSharedPrefs.getAllowSpend(app)) { throw new SpendingNotAllowed(); } //check if amount isn't smaller than the min amount if (isSmallerThanMin(app, paymentRequest)) { throw new AmountSmallerThanMinException(amount, balance); } //amount is larger than balance if (isLargerThanBalance(app, paymentRequest)) { throw new InsufficientFundsException(amount, balance); } //not enough for fee if (notEnoughForFee(app, paymentRequest)) { //weird bug when the core BRWalletManager is NULL if (maxOutputAmount == -1) { BRReportsManager.reportBug(new RuntimeException("getMaxOutputAmount is -1, meaning _wallet is NULL"), true); } // max you can spend is smaller than the min you can spend if (maxOutputAmount < minOutputAmount) { throw new InsufficientFundsException(amount, balance); } long feeForTx = m.feeForTransaction(paymentRequest.addresses[0], paymentRequest.amount); throw new FeeNeedsAdjust(amount, balance, feeForTx); } // payment successful BRExecutor.getInstance().forLightWeightBackgroundTasks().execute(new Runnable() { @Override public void run() { byte[] tmpTx = m.tryTransaction(paymentRequest.addresses[0], paymentRequest.amount); if (tmpTx == null) { //something went wrong, failed to create tx ((Activity) app).runOnUiThread(new Runnable() { @Override public void run() { BRDialog.showCustomDialog(app, "", app.getString(R.string.Alerts_sendFailure), app.getString(R.string.AccessibilityLabels_close), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismiss(); } }, null, null, 0); } }); return; } paymentRequest.serializedTx = tmpTx; PostAuth.getInstance().setPaymentItem(paymentRequest); confirmPay(app, paymentRequest); } }); } private void showAdjustFee(final Activity app, PaymentItem item) { BRWalletManager m = BRWalletManager.getInstance(); long maxAmountDouble = m.getMaxOutputAmount(); if (maxAmountDouble == -1) { BRReportsManager.reportBug(new RuntimeException("getMaxOutputAmount is -1, meaning _wallet is NULL")); return; } if (maxAmountDouble == 0) { BRDialog.showCustomDialog(app, app.getString(R.string.Alerts_sendFailure), "Insufficient amount for transaction fee", app.getString(R.string.Button_ok), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismissWithAnimation(); } }, null, null, 0); } else { // long fee = m.feeForTransaction(item.addresses[0], maxAmountDouble); // feeForTx += (m.getBalance(app) - request.amount) % 100; // BRDialog.showCustomDialog(app, app.getString(R.string.Alerts_sendFailure), "Insufficient amount for transaction fee", app.getString(R.string.Button_ok), null, new BRDialogView.BROnClickListener() { // @Override // public void onClick(BRDialogView brDialogView) { // brDialogView.dismissWithAnimation(); // }, null, null, 0); BRDialog.showCustomDialog(app, app.getString(R.string.Alerts_sendFailure), "Insufficient amount for transaction fee", app.getString(R.string.Button_ok), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismissWithAnimation(); } }, null, null, 0); //todo fix this fee adjustment } } private void showFailed(final Context app) { BRDialog.showCustomDialog(app, app.getString(R.string.Alerts_sendFailure), "", app.getString(R.string.AccessibilityLabels_close), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismissWithAnimation(); } }, null, null, 0); // final long maxOutputAmount = BRWalletManager.getInstance().getMaxOutputAmount(); // final BRWalletManager m = BRWalletManager.getInstance(); // final long amountToReduce = request.amount - maxOutputAmount; // String iso = BRSharedPrefs.getIso(app); // final String reduceBits = BRCurrency.getFormattedCurrencyString(app, "BTC", BRExchange.getAmountFromSatoshis(app, "BTC", new BigDecimal(amountToReduce))); // final String reduceCurrency = BRCurrency.getFormattedCurrencyString(app, iso, BRExchange.getAmountFromSatoshis(app, iso, new BigDecimal(amountToReduce))); // final String reduceBitsMinus = BRCurrency.getFormattedCurrencyString(app, "BTC", BRExchange.getAmountFromSatoshis(app, "BTC", new BigDecimal(amountToReduce).negate())); // final String reduceCurrencyMinus = BRCurrency.getFormattedCurrencyString(app, iso, BRExchange.getAmountFromSatoshis(app, iso, new BigDecimal(amountToReduce).negate())); // ((Activity) app).runOnUiThread(new Runnable() { // @Override // public void run() { // BRDialog.showCustomDialog(app, app.getString(R.string.Alerts_sendFailure), String.format(app.getString(R.string.reduce_payment_amount_by), // reduceBits, reduceCurrency), String.format("%s (%s)", reduceBitsMinus, reduceCurrencyMinus), "Cancel", new BRDialogView.BROnClickListener() { // @Override // public void onClick(BRDialogView brDialogView) { // new Thread(new Runnable() { // @Override // public void run() { // final long newAmount = request.amount - amountToReduce; // final byte[] tmpTx2 = m.tryTransaction(request.addresses[0], newAmount); // if (tmpTx2 != null) { // request.serializedTx = tmpTx2; // PostAuth.getInstance().setPaymentItem(request); // request.amount = newAmount; // confirmPay(app, request); // } else { // ((Activity) app).runOnUiThread(new Runnable() { // @Override // public void run() { // Log.e(TAG, "tmpTxObject2 is null!"); // BRToast.showCustomToast(app, app.getString(R.string.Alerts_sendFailure), // BreadActivity.screenParametersPoint.y / 2, Toast.LENGTH_LONG, 0); // }).start(); // brDialogView.dismiss(); // }, new BRDialogView.BROnClickListener() { // @Override // public void onClick(BRDialogView brDialogView) { // brDialogView.dismiss(); // }, null, 0); } public void confirmPay(final Context ctx, final PaymentItem request) { if (ctx == null) { Log.e(TAG, "confirmPay: context is null"); return; } String message = createConfirmation(ctx, request); double minOutput; if (request.isAmountRequested) { minOutput = BRWalletManager.getInstance().getMinOutputAmountRequested(); } else { minOutput = BRWalletManager.getInstance().getMinOutputAmount(); } //amount can't be less than the min if (request.amount < minOutput) { final String bitcoinMinMessage = String.format(Locale.getDefault(), ctx.getString(R.string.PaymentProtocol_Errors_smallTransaction), BRConstants.bitcoinLowercase + new BigDecimal(minOutput).divide(new BigDecimal("100"))); ((Activity) ctx).runOnUiThread(new Runnable() { @Override public void run() { BRDialog.showCustomDialog(ctx, ctx.getString(R.string.Alerts_sendFailure), bitcoinMinMessage, ctx.getString(R.string.AccessibilityLabels_close), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismiss(); } }, null, null, 0); } }); return; } boolean forcePin = false; Log.e(TAG, "confirmPay: totalSent: " + BRWalletManager.getInstance().getTotalSent()); Log.e(TAG, "confirmPay: request.amount: " + request.amount); Log.e(TAG, "confirmPay: total limit: " + AuthManager.getInstance().getTotalLimit(ctx)); Log.e(TAG, "confirmPay: limit: " + BRKeyStore.getSpendLimit(ctx)); if (BRWalletManager.getInstance().getTotalSent() + request.amount > AuthManager.getInstance().getTotalLimit(ctx)) { forcePin = true; } //successfully created the transaction, authenticate user AuthManager.getInstance().authPrompt(ctx, "", message, forcePin, false, new BRAuthCompletion() { @Override public void onComplete() { BRExecutor.getInstance().forLightWeightBackgroundTasks().execute(new Runnable() { @Override public void run() { PostAuth.getInstance().onPublishTxAuth(ctx, false); BRExecutor.getInstance().forMainThreadTasks().execute(new Runnable() { @Override public void run() { BRAnimator.killAllFragments((Activity) ctx); BRAnimator.startBreadIfNotStarted((Activity) ctx); } }); } }); } @Override public void onCancel() { //nothing } }); } public String createConfirmation(Context ctx, PaymentItem request) { String receiver = getReceiver(request); String iso = BRSharedPrefs.getIso(ctx); BRWalletManager m = BRWalletManager.getInstance(); long feeForTx = m.feeForTransaction(request.addresses[0], request.amount); if (feeForTx == 0) { long maxAmount = m.getMaxOutputAmount(); if (maxAmount == -1) { BRReportsManager.reportBug(new RuntimeException("getMaxOutputAmount is -1, meaning _wallet is NULL"), true); } if (maxAmount == 0) { BRDialog.showCustomDialog(ctx, "", ctx.getString(R.string.Alerts_sendFailure), ctx.getString(R.string.AccessibilityLabels_close), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismiss(); } }, null, null, 0); return null; } feeForTx = m.feeForTransaction(request.addresses[0], maxAmount); feeForTx += (BRWalletManager.getInstance().getBalance(ctx) - request.amount) % 100; } final long total = request.amount + feeForTx; String formattedAmountBTC = BRCurrency.getFormattedCurrencyString(ctx, "BTC", BRExchange.getBitcoinForSatoshis(ctx, new BigDecimal(request.amount))); String formattedFeeBTC = BRCurrency.getFormattedCurrencyString(ctx, "BTC", BRExchange.getBitcoinForSatoshis(ctx, new BigDecimal(feeForTx))); String formattedTotalBTC = BRCurrency.getFormattedCurrencyString(ctx, "BTC", BRExchange.getBitcoinForSatoshis(ctx, new BigDecimal(total))); String formattedAmount = BRCurrency.getFormattedCurrencyString(ctx, iso, BRExchange.getAmountFromSatoshis(ctx, iso, new BigDecimal(request.amount))); String formattedFee = BRCurrency.getFormattedCurrencyString(ctx, iso, BRExchange.getAmountFromSatoshis(ctx, iso, new BigDecimal(feeForTx))); String formattedTotal = BRCurrency.getFormattedCurrencyString(ctx, iso, BRExchange.getAmountFromSatoshis(ctx, iso, new BigDecimal(total))); //formatted text return receiver + "\n\n" + ctx.getString(R.string.Confirmation_amountLabel) + " " + formattedAmountBTC + " (" + formattedAmount + ")" + "\n" + ctx.getString(R.string.Confirmation_feeLabel) + " " + formattedFeeBTC + " (" + formattedFee + ")" + "\n" + ctx.getString(R.string.Confirmation_totalLabel) + " " + formattedTotalBTC + " (" + formattedTotal + ")" + (request.comment == null ? "" : "\n\n" + request.comment); } public String getReceiver(PaymentItem item) { String receiver; boolean certified = false; if (item.cn != null && item.cn.length() != 0) { certified = true; } StringBuilder allAddresses = new StringBuilder(); for (String s : item.addresses) { allAddresses.append(s + ", "); } receiver = allAddresses.toString(); allAddresses.delete(allAddresses.length() - 2, allAddresses.length()); if (certified) { receiver = "certified: " + item.cn + "\n"; } return receiver; } public boolean isSmallerThanMin(Context app, PaymentItem paymentRequest) { long minAmount = BRWalletManager.getInstance().getMinOutputAmountRequested(); return paymentRequest.amount < minAmount; } public boolean isLargerThanBalance(Context app, PaymentItem paymentRequest) { return paymentRequest.amount > BRWalletManager.getInstance().getBalance(app) && paymentRequest.amount > 0; } public boolean notEnoughForFee(Context app, PaymentItem paymentRequest) { BRWalletManager m = BRWalletManager.getInstance(); long feeForTx = m.feeForTransaction(paymentRequest.addresses[0], paymentRequest.amount); if (feeForTx == 0) { feeForTx = m.feeForTransaction(paymentRequest.addresses[0], m.getMaxOutputAmount()); return feeForTx != 0; } return false; } public static void showSpendNotAllowed(final Context app) { Log.d(TAG, "showSpendNotAllowed"); ((Activity) app).runOnUiThread(new Runnable() { @Override public void run() { BRDialog.showCustomDialog(app, app.getString(R.string.Alert_error), app.getString(R.string.Send_isRescanning), app.getString(R.string.Button_ok), null, new BRDialogView.BROnClickListener() { @Override public void onClick(BRDialogView brDialogView) { brDialogView.dismissWithAnimation(); } }, null, null, 0); } }); } private class InsufficientFundsException extends Exception { public InsufficientFundsException(long amount, long balance) { super("Balance: " + balance + " satoshis, amount: " + amount + " satoshis."); } } private class AmountSmallerThanMinException extends Exception { public AmountSmallerThanMinException(long amount, long balance) { super("Balance: " + balance + " satoshis, amount: " + amount + " satoshis."); } } private class SpendingNotAllowed extends Exception { public SpendingNotAllowed() { super("spending is not allowed at the moment"); } } private class FeeNeedsAdjust extends Exception { public FeeNeedsAdjust(long amount, long balance, long fee) { super("Balance: " + balance + " satoshis, amount: " + amount + " satoshis, fee: " + fee + " satoshis."); } } private class FeeOutOfDate extends Exception { public FeeOutOfDate(long timestamp, long now) { super("FeeOutOfDate: timestamp: " + timestamp + ",now: " + now); } } }
package es.jagarciavi.photospat; import android.app.Activity; import android.app.ProgressDialog; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class PhotoSpat extends AppCompatActivity { private WebView webview; private ProgressDialog progressDialog; private int counter = 0; private int firstLoad = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo_spat); webview = (WebView) findViewById(R.id.webview); final Activity activity = this; // Enable JavaScript and lets the browser go back webview.getSettings().setJavaScriptEnabled(true); webview.canGoBack(); webview.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { //counter = 0; view.loadUrl(url); return true; } public void onLoadResource(WebView view, String url) { // Check to see if there is a progress dialog if (progressDialog == null) { // If no progress dialog, make one and set message progressDialog = new ProgressDialog(activity); progressDialog.setMessage(getResources().getString(R.string.loading)); progressDialog.show(); // Hide the webview while loading webview.setEnabled(false); } } public void onPageFinished(WebView view, String url) { // Page is done loading; // hide the progress dialog and show the webview Log.i(null, "The app is in the onPageFinished method"); String finalUrl = webview.getUrl().toString(); Log.i(null, "finalurl string is " + finalUrl); if (finalUrl.equals("https://instagram.com/accounts/login/")) { if(firstLoad == 1) { Log.i(null, "The strings are equal, we'll set counter value to 4"); counter = 4; } else { Log.i(null, "It's not the load of the login page..."); firstLoad = 1; } } if (progressDialog.isShowing() && counter == 4) { Log.i(null, "On loop -> Dismiss progress dialog "); progressDialog.dismiss(); //progressDialog = null; webview.setEnabled(true); counter = 0; } Log.i(null, "Counter value is " + counter); counter++; } public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) { // Disable webview and progress dialog in app because of an error webview.setEnabled(false); setContentView(R.layout.activity_photo_spat); progressDialog.dismiss(); // Show error message (in future versions it will be changed by dialog error Toast.makeText(PhotoSpat.this, getResources().getString(R.string.errorToast) + description, Toast.LENGTH_LONG).show(); // Exit the app after 5s Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { finish(); } }, 5000); } }); webview.loadUrl("https: } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.menu_photo_spat, 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package me.anuraag.barter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.FirebaseException; import com.firebase.client.Query; import com.firebase.client.ValueEventListener; import com.parse.Parse; import com.parse.ParseObject; import com.parse.ParseUser; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; public class ListingActivity extends Activity { private String[] drawerListViewItems; private ListView drawerListView; private DrawerLayout drawerLayout; private View mCustomView; private ImageView menu; private Query curUserQuery; private String friendUserId,curUserId; private ListView listview; private Button startChat; private Firebase curUserRef,friendUserRef; private ParseUser myuser; private Firebase myref; private TextView title,address,description,creator; private TextView mTitleTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listing_fragment_view); Firebase.setAndroidContext(this); Parse.initialize(this, "CZUQqTZcedP8pSmLPqHvBkxd41pmfTF7vyEch1xq", "f3aQ4TYpBwSZ4K8BkJpbkSrm1DrWKrxJH5LR3OK8"); try{ myuser = ParseUser.getCurrentUser(); Log.i(myuser.getEmail(), myuser.getEmail()); }catch (NullPointerException n){ Log.d(n.toString(),n.toString()); startActivity(new Intent(getApplicationContext(),SignIn.class)); } myref = new Firebase("https://barter.firebaseio.com/"); title = (TextView)findViewById(R.id.textView2); creator = (TextView)findViewById(R.id.poster); description = (TextView)findViewById(R.id.description); address = (TextView)findViewById(R.id.address); startChat = (Button)findViewById(R.id.chat); title.setText(getIntent().getStringExtra("title")); creator.setText(getIntent().getStringExtra("creator")); description.setText(getIntent().getStringExtra("description")); address.setText(getIntent().getStringExtra("address")); startChat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { curUserId = ""; friendUserId = ""; Firebase firebaseRef = new Firebase("https://barter.firebaseio.com/Users/"); curUserQuery = firebaseRef; curUserQuery.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Iterable<DataSnapshot> myiterator = dataSnapshot.getChildren(); for(DataSnapshot f: myiterator){ if(f.child("email").getValue()!=null) { String swag = f.child("email").getValue().toString(); if(swag.equals(myuser.getEmail())){ curUserId = f.getKey(); } if(swag.equals(creator.getText().toString())) { friendUserId = f.getKey(); } Log.d("Child", f.child("email").getValue().toString()); }else{ Log.d("null","email is null hoe"); } } curUserQuery.removeEventListener(this); Log.d("Me",curUserId); Log.d("Firend",friendUserId); curUserRef = new Firebase("https://barter.firebaseio.com/Users/" + curUserId).child("Chat").push(); friendUserRef = new Firebase("https://barter.firebaseio.com/Users/" + friendUserId).child("Chat").push(); Map<String,String> chatobj = new HashMap<String,String>(); chatobj.put("User1",myuser.getEmail()); chatobj.put("User2",creator.getText().toString()); try { Log.i("Me",chatobj.toString()); curUserRef.setValue(chatobj); // friendUserRef.setValue(chatobj); }catch (FirebaseException j) { Log.i("SOmething si happening", j.toString()); } //Lets check if AndroidStudio Pushing Works } @Override public void onCancelled(FirebaseError firebaseError) { Log.d("error",firebaseError.toString()); } }); //TODO Add Chat objects under Firebase Users //TODO Create ListView Chat Page //TODO Create Chats } }); android.app.ActionBar mActionBar = getActionBar(); mActionBar.setDisplayShowHomeEnabled(false); mActionBar.setDisplayShowTitleEnabled(false); LayoutInflater mInflater = LayoutInflater.from(this); mCustomView = mInflater.inflate(R.layout.custom_actionbar, null); mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text); mTitleTextView.setText("Listing"); menu = (ImageView)mCustomView.findViewById(R.id.imageView1); menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doThis(); } }); mActionBar.setCustomView(mCustomView); mActionBar.setDisplayShowCustomEnabled(true); drawerListViewItems = getResources().getStringArray(R.array.Items); // get ListView defined in activity_main.xml drawerListView = (ListView) findViewById(R.id.left_drawer); // Set the adapter for the list view drawerListView.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_listview_item, drawerListViewItems)); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerListView.setOnItemClickListener(new DrawerItemClickListener()); drawerListView.setOnFocusChangeListener(new DrawerItemDismissedListener()); } public void doThis(){ if(drawerLayout.isDrawerOpen(Gravity.START)) { drawerLayout.closeDrawer(Gravity.START); mTitleTextView.setText("Listing"); } else{ drawerLayout.openDrawer(Gravity.START); mTitleTextView.setText("Menu"); } } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { String name = ((TextView)view).getText().toString(); if(name.equals("Create Listing")){ Intent myintent = new Intent(getApplicationContext(),CreateListing.class); startActivity(myintent); } if(name.equals("Home")){ Intent myintent = new Intent(getApplicationContext(),HomePage.class); startActivity(myintent); } Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_LONG).show(); doThis(); } } private class DrawerItemDismissedListener implements View.OnFocusChangeListener { @Override public void onFocusChange(View v, boolean hasFocus) { if(!hasFocus){ mTitleTextView.setText("Listing"); }else{ mTitleTextView.setText("Menu"); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_listing, 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.demo.navigator.navigation; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.databinding.ViewDataBinding; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.content.res.AppCompatResources; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.demo.navigator.R; import com.demo.navigator.app.App; import com.demo.navigator.bus.CloseNavigatorEvent; import com.demo.navigator.bus.EntryClickEvent; import com.demo.navigator.bus.OpenUriEvent; import com.demo.navigator.databinding.FragmentNavigatorBinding; import com.demo.navigator.ds.DsRepository; import com.demo.navigator.ds.DsSource; import com.demo.navigator.ds.model.Entry; import javax.inject.Inject; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; public final class Navigator implements Toolbar.OnMenuItemClickListener, View.OnClickListener, FragmentManager.OnBackStackChangedListener, NavigatorContract.Presenter { private @Nullable FragmentNavigatorBinding mBinding; private final DsRepository mDsRepository; private final NavigatorContract.View mView; @Inject Navigator(DsRepository dsRepository, NavigatorContract.View view) { mDsRepository = dsRepository; mView = view; } @Inject void onReadySetPresenter() { mView.setPresenter(this); } @Override public void start(ViewDataBinding binding) { mBinding = (FragmentNavigatorBinding) binding; setupMenuBar(); mView.showEntry(); } void load() { mDsRepository.loadEntry(new DsSource.EntryLoadedCallback() { @Override public void onLoaded(@NonNull Entry entry) { if (mBinding == null) { return; } navigateEntry(entry, true); mBinding.getFragment() .getChildFragmentManager() .addOnBackStackChangedListener(Navigator.this); } }); } /** * Handler for {@link EntryClickEvent}. * * @param e Event {@link EntryClickEvent}. */ @SuppressWarnings("unused") @Subscribe public void onEvent(EntryClickEvent e) { if (mBinding == null) { return; } //Normal link if (TextUtils.equals(e.getEntry() .getType(), "link")) { EventBus.getDefault() .post(new OpenUriEvent(Uri.parse(e.getEntry() .getUrl()))); EventBus.getDefault() .post(new CloseNavigatorEvent()); return; } //External link, then to browser if (TextUtils.equals(e.getEntry() .getType(), "external-link")) { EventBus.getDefault() .post(new CloseNavigatorEvent()); try { Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(e.getEntry() .getUrl())); mBinding.getFragment() .startActivity(myIntent); } catch (ActivityNotFoundException ex) { try { Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.android.chrome")); mBinding.getFragment() .startActivity(myIntent); } catch (ActivityNotFoundException exx) { Toast.makeText(App.Instance, "Cannot open external-link, cannot find browser.", Toast.LENGTH_SHORT) .show(); } } return; } //Navigate to next entry mBinding.navigatorContentFl.show(0, 0, 800); navigateEntry(e.getEntry(), false); } private void setupMenuBar() { if (mBinding == null) { return; } mBinding.menuBar.setTitle(R.string.main_menu); mBinding.menuBar.inflateMenu(R.menu.menu_navigator); mBinding.menuBar.setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_close_navigator: EventBus.getDefault() .post(new CloseNavigatorEvent()); break; } return false; } private void navigateEntry(@NonNull Entry entry, boolean isRoot) { if (mBinding == null) { return; } Fragment fragment = mBinding.getFragment(); Activity activity = fragment.getActivity(); if (activity != null) { FragmentTransaction transaction = fragment.getChildFragmentManager() .beginTransaction() .add(mBinding.navigatorContentFl.getId(), EntryFragment.newInstance(activity, entry)); if (isRoot) { transaction.commit(); return; } transaction.addToBackStack(null) .commit(); if (mBinding.menuBar.getNavigationIcon() == null) { mBinding.menuBar.setNavigationIcon(AppCompatResources.getDrawable(App.Instance, R.drawable.ic_back)); mBinding.menuBar.setNavigationOnClickListener(this); } } } @Override public void onClick(View v) { if (mBinding == null) { return; } Fragment fragment = mBinding.getFragment(); fragment.getChildFragmentManager() .popBackStack(); } @Override public void onBackStackChanged() { if (mBinding == null) { return; } if (mBinding.getFragment() .getChildFragmentManager() .getBackStackEntryCount() == 0) { mBinding.menuBar.setNavigationIcon(null); } } }
package com.examples.shivani.calcii; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ Button clear,delete,one,two,three,four,five,six,seven,eight,nine,zero,plus,minus,multiply,divide,equal,point; TextView view; long opr1,opr2; boolean add,sub,div,mul; String chr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view=(TextView)findViewById(R.id.view); clear=(Button)findViewById(R.id.clearAll); delete=(Button)findViewById(R.id.delete); one=(Button)findViewById(R.id.one); two=(Button)findViewById(R.id.two); three=(Button)findViewById(R.id.three); four=(Button)findViewById(R.id.four); five=(Button)findViewById(R.id.five); six=(Button)findViewById(R.id.six); seven=(Button)findViewById(R.id.seven); eight=(Button)findViewById(R.id.eight); nine=(Button)findViewById(R.id.nine); zero=(Button)findViewById(R.id.zero); plus=(Button)findViewById(R.id.plus); minus=(Button)findViewById(R.id.minus); multiply=(Button)findViewById(R.id.multiply); divide=(Button)findViewById(R.id.divide); equal=(Button)findViewById(R.id.equal); point=(Button)findViewById(R.id.point); clear.setOnClickListener(this); delete.setOnClickListener(this); one.setOnClickListener(this); two.setOnClickListener(this); three.setOnClickListener(this); four.setOnClickListener(this); five.setOnClickListener(this); six.setOnClickListener(this); seven.setOnClickListener(this); eight.setOnClickListener(this); nine.setOnClickListener(this); zero.setOnClickListener(this); plus.setOnClickListener(this); minus.setOnClickListener(this); multiply.setOnClickListener(this); divide.setOnClickListener(this); equal.setOnClickListener(this); point.setOnClickListener(this); view.setCursorVisible(true); view.setHint("0"); /*Animation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(100); //You can manage the blinking time with this parameter anim.setStartOffset(20); anim.setRepeatMode(Animation.REVERSE); anim.setRepeatCount(Animation.INFINITE);*/ } @Override public void onClick(View v) { switch(v.getId()) { case R.id.clearAll: if(view.getText().length()!=0){ view.setText(view.getText().toString().substring(0,view.getText().length() -view.getText().length())); } else{ view.append(""); } break; case R.id.delete: if(view.getText().length()!=0){ view.setText(view.getText().toString().substring(0,view.getText().length() - 1)); } else{ view.append(""); } break; case R.id.one: view.append("1"); break; case R.id.two: view.append("2"); break; case R.id.three: view.append("3"); break; case R.id.four: view.append("4"); break; case R.id.five: view.append("5"); break; case R.id.six: view.append("6"); break; case R.id.seven: view.append("7"); break; case R.id.eight: view.append("8"); break; case R.id.nine: view.append("9"); break; case R.id.zero: view.append("0"); break; case R.id.plus: opr1=Long.parseLong(view.getText()+""); add=true; view.setText(null); //view.append("+"); break; case R.id.minus: opr1=Long.parseLong(view.getText()+""); sub=true; view.setText(null); // view.append("-"); break; case R.id.multiply: opr1=Long.parsLong(view.getText()+""); mul=true; view.setText(null); //view.append("*"); break; case R.id.divide: opr1=Long.parseLong(view.getText()+""); div=true; view.setText(null); //view.append("/"); break; case R.id.equal: /* for(int i=0;i>=0;i++) { chr.charAt(i); } if(chr.equals("+")){ opr2=Integer.parseInt(view.getText().toString()); opr1=opr1+opr2; view.setText(Integer.toString(opr1)); } else if(chr.equals("-")) { opr2=Integer.parseInt(view.getText().toString()); opr1=opr1-opr2; view.setText(Integer.toString(opr1)); } else if(chr.equals("*")) { opr2=Integer.parseInt(view.getText().toString()); opr1=opr1*opr2; view.setText(Integer.toString(opr1)); } else if(chr.equals("/")){ opr2=Integer.parseInt(view.getText().toString()); opr1=opr1/opr2; view.setText(Integer.toString(opr1)); } else if(chr.equals("^")){ opr2=Integer.parseInt(view.getText().toString()); opr1=opr1^opr2; view.setText(Integer.toString(opr1)); }*/ opr2=Long.parseLong(view.getText()+""); if (add==true) { view.setText(opr1+opr2+""); add=false; } if (sub==true) { view.setText(opr1-opr2+""); sub=false; } if (mul==true) { view.setText(opr1*opr2+""); mul=false; } if (div==true) { view.setText(opr1/opr2+""); div=false; } break; case R.id.point: view.append("."); break; } } }
package com.ilkkalaukkanen.haavi; import android.util.Xml; import com.google.inject.Inject; import com.ilkkalaukkanen.haavi.model.Podcast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import rx.Observable; import rx.Subscriber; import java.io.IOException; import java.util.Locale; public class FeedDownloader { public static final String TAG_TITLE = "title"; public static final String TAG_DESCRIPTION = "description"; public static final String TAG_PUBDATE = "pubDate"; public static final String TAG_ENCLOSURE = "enclosure"; public static final String TAG_GUID = "guid"; public static final DateTimeFormatter RSS_PUBDATE_FORMATTER = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z").withLocale(Locale.ENGLISH); @Inject HttpClient client; @Inject public FeedDownloader() { } public Observable<Podcast> getFeed(final String url) { return Observable.create(new Observable.OnSubscribe<Podcast>() { @Override public void call(final Subscriber<? super Podcast> subscriber) { try { final HttpResponse response = client.execute(new HttpGet(url)); final HttpEntity entity = response.getEntity(); if (entity != null) { final XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(entity.getContent(), null); parser.nextTag(); parseEntries(parser, subscriber); } subscriber.onCompleted(); } catch (IOException e) { subscriber.onError(e); } catch (XmlPullParserException e) { e.printStackTrace(); } } }); } private void parseEntries(final XmlPullParser parser, final Subscriber<? super Podcast> subscriber) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, "rss"); // skip to channel start while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } final String name = parser.getName(); if ("channel".equals(name)) { break; } } // parse items while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } final String name = parser.getName(); if ("item".equals(name)) { parseItem(parser, subscriber); } else { skip(parser); } } } private void parseItem(final XmlPullParser parser, final Subscriber<? super Podcast> subscriber) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, "item"); String title = null; String description = null; DateTime pubDate = null; String url = null; String length = null; String type = null; String guid = null; while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } final String tagName = parser.getName(); if (TAG_TITLE.equals(tagName)) { title = readNodeAsText(parser, TAG_TITLE); } else if (TAG_DESCRIPTION.equals(tagName)) { description = readNodeAsText(parser, TAG_DESCRIPTION); } else if (TAG_PUBDATE.equals(tagName)) { pubDate = DateTime.parse(readNodeAsText(parser, TAG_PUBDATE), RSS_PUBDATE_FORMATTER); } else if (TAG_ENCLOSURE.equals(tagName)) { url = parser.getAttributeValue(null, "url"); length = parser.getAttributeValue(null, "length"); type = parser.getAttributeValue(null, "type"); skip(parser); } else if (TAG_GUID.equals(tagName)) { guid = readNodeAsText(parser, TAG_GUID); } else { skip(parser); } } subscriber.onNext(new Podcast(title, description, pubDate, url, length, type, guid)); } private String readNodeAsText(final XmlPullParser parser, final String tagName) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, tagName); final String title = readText(parser); parser.require(XmlPullParser.END_TAG, null, tagName); return title; } private String readText(final XmlPullParser parser) throws IOException, XmlPullParserException { String result = ""; if (parser.next() == XmlPullParser.TEXT) { result = parser.getText(); parser.nextTag(); } return result; } private void skip(final XmlPullParser parser) throws XmlPullParserException, IOException { if (parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException("Not on a start tag"); } int depth = 1; while (depth != 0) { switch (parser.next()) { case XmlPullParser.END_TAG: depth break; case XmlPullParser.START_TAG: depth++; break; } } } }
package com.iuridiniz.checkmyecg; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.view.WindowManager; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.interpolation.SplineInterpolator; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.CameraBridgeViewBase; import org.opencv.android.OpenCVLoader; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfPoint; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.List; interface Filter { public Mat apply(Mat src); }; class GradeFilter implements Filter { private Mat mGray, mMaskRed1, mMaskRed2; /* CV_8UC1 */ private Mat mRgb, mHsv; /* CV_8UC3 */ private Mat mRgba; /* CV_8UC4 */ private Scalar mLowerRed1, mUpperRed1; private Scalar mLowerRed2, mUpperRed2; public GradeFilter(int rows, int cols) { mGray = new Mat(rows, cols, CvType.CV_8UC1); mMaskRed1 = new Mat(rows, cols, CvType.CV_8UC1); mMaskRed2 = new Mat(rows, cols, CvType.CV_8UC1); mHsv = new Mat(rows, cols, CvType.CV_8UC3); mRgb = new Mat(rows, cols, CvType.CV_8UC3); mRgba = new Mat(rows, cols, CvType.CV_8UC4); mLowerRed1 = new Scalar(0, 100, 100); mUpperRed1 = new Scalar(15, 255, 255); mLowerRed2 = new Scalar(230, 100, 100); mUpperRed2 = new Scalar(255, 255, 255); } @Override public Mat apply(Mat rgba) { /* HSV first */ Imgproc.cvtColor(rgba, mRgb, Imgproc.COLOR_RGBA2RGB); Imgproc.cvtColor(mRgb, mHsv, Imgproc.COLOR_RGB2HSV); /* get first red range */ Core.inRange(mHsv, mLowerRed1, mUpperRed1, mMaskRed1); /* get second red range */ Core.inRange(mHsv, mLowerRed1, mUpperRed1, mMaskRed1); Core.inRange(mHsv, mLowerRed2, mUpperRed2, mMaskRed2); /* merge it */ Core.bitwise_or(mMaskRed1, mMaskRed2, mMaskRed1); /* invert it */ Core.bitwise_not(mMaskRed1, mMaskRed1); /* convert back to colorspace expected */ Imgproc.cvtColor(mMaskRed1, mRgba, Imgproc.COLOR_GRAY2RGBA); return mRgba; } } class GraphFilter2 extends GraphFilter { private final Size mKSize; protected Mat mBlurred; protected Mat mEdged; protected Mat mHierarchy; protected List<MatOfPoint> mContours = new ArrayList<MatOfPoint>(); public GraphFilter2(int rows, int cols) { super(rows, cols); mBlurred = new Mat(rows, cols, CvType.CV_8UC1); mEdged = new Mat(rows, cols, CvType.CV_8UC1); mKSize = new Size(11, 11); mHierarchy = new Mat(); } @Override public Mat apply(Mat rgba) { super.apply(rgba); mRgbaDst = rgba.clone(); /* get mask black and find contours */ Imgproc.GaussianBlur(mMatMaskBlackInv, mBlurred, mKSize, 0); Imgproc.Canny(mBlurred, mEdged, 30, 150); mContours.clear(); /* FIXME: there's a kind of memory leak here (findContours), We need to call gc.collect in order to free resources */ Imgproc.findContours(mEdged, mContours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE); Imgproc.drawContours(mRgbaDst, mContours, -1, new Scalar(0,255,0), 2); return mRgbaDst; } } class GraphFilter implements Filter { protected Mat mGray; protected Mat mMatMaskBlack; protected Mat mMatMaskBlackInv; /* CV_8UC1 */ protected Mat mRgb, mHsv; /* CV_8UC3 */ protected Mat mRgbaDst; /* CV_8UC4 */ protected Scalar mLowerBlack, mUpperBlack; public GraphFilter(int rows, int cols) { mGray = new Mat(rows, cols, CvType.CV_8UC1); mMatMaskBlack = new Mat(rows, cols, CvType.CV_8UC1); mMatMaskBlackInv = new Mat(rows, cols, CvType.CV_8UC1); mHsv = new Mat(rows, cols, CvType.CV_8UC3); mRgb = new Mat(rows, cols, CvType.CV_8UC3); //mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4, new Scalar(255)); mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4); mLowerBlack = new Scalar(0, 0, 0); mUpperBlack = new Scalar(255, 255, 50); } @Override public Mat apply(Mat rgba) { /* HSV first */ Imgproc.cvtColor(rgba, mRgb, Imgproc.COLOR_RGBA2RGB); Imgproc.cvtColor(mRgb, mHsv, Imgproc.COLOR_RGB2HSV); /* get only black */ Core.inRange(mHsv, mLowerBlack, mUpperBlack, mMatMaskBlack); /* invert it */ Core.bitwise_not(mMatMaskBlack, mMatMaskBlackInv); /* convert back to colorspace expected */ Imgproc.cvtColor(mMatMaskBlackInv, mRgbaDst, Imgproc.COLOR_GRAY2RGBA); return mRgbaDst; } } class NormalizerFilter implements Filter { private Mat mRgbaDst; /* CV_8UC4 */ private double mAlpha, mBeta; private int mNormType; NormalizerFilter(int cols, int rows, double mAlpha, double mBeta, int mNormType) { mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4); setAlpha(mAlpha); setBeta(mBeta); setNormType(mNormType); } NormalizerFilter(int cols, int rows, double mAlpha, double mBeta) { this(cols, rows, mAlpha, mBeta, Core.NORM_MINMAX); } NormalizerFilter(int cols, int rows) { this(cols, rows, 0.0, 255.0); } @Override public Mat apply(Mat src) { Core.normalize(src, mRgbaDst, mAlpha, mBeta, mNormType); return mRgbaDst; } public double getAlpha() { return mAlpha; } public void setAlpha(double mAlpha) { this.mAlpha = mAlpha; } public double getBeta() { return mBeta; } public void setBeta(double mBeta) { this.mBeta = mBeta; } public int getNormType() { return mNormType; } public void setNormType(int mNormType) { this.mNormType = mNormType; } } class ContrastFilter implements Filter { private final Mat mRgbaDst; private final Mat mLut; public ContrastFilter(int rows, int cols, int mMin, int mMax) { mRgbaDst = new Mat(rows, cols, CvType.CV_8UC4); mLut = new MatOfInt(); SplineInterpolator si = new SplineInterpolator(); UnivariateFunction f = si.interpolate(new double[]{0, mMin, mMax, 255}, new double[]{0, 0, 255, 255}); /* create my mLut */ mLut.create(256, 1, CvType.CV_8UC4); for (int i = 0; i < 256; i++) { final double v = f.value(i); /* r, g, b */ mLut.put(i, 0, v, v, v, i); /* alpha not touched */ } } @Override public Mat apply(Mat src) { Core.LUT(src, mLut, mRgbaDst); return mRgbaDst; } } public class CameraActivity extends Activity implements CameraBridgeViewBase.CvCameraViewListener2 { private static final String TAG = "ActivityCamera"; private boolean mOpenCvLoaded = false; private CameraBridgeViewBase mPreview; private GraphFilter2 mGraphFilter2; private ContrastFilter mContrastFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); /* Keep the screen on */ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); /* start openCV */ /* try static initialization */ if (OpenCVLoader.initDebug()) { Log.i(TAG, "OpenCV loaded successfully (static initialization)"); mOpenCvLoaded = true; return; } /* binaries not included, use OpenCV manager */ Log.i(TAG, "OpenCV libs not included on APK, trying async initialization"); OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_10, this, new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case BaseLoaderCallback.SUCCESS: Log.i(TAG, "OpenCV loaded successfully (async initialization)"); runOnUiThread(new Runnable() { @Override public void run() { mOpenCvLoaded = true; createCameraPreview(); } }); break; default: super.onManagerConnected(status); break; } } }); } private void createCameraPreview() { /* Create our Preview */ if (mPreview == null) { mPreview = (CameraBridgeViewBase) findViewById(R.id.camera_view); mPreview.setVisibility(SurfaceView.VISIBLE); mPreview.setCvCameraViewListener(this); } if (mOpenCvLoaded) { mPreview.enableView(); } } @Override public void onResume() { super.onResume(); createCameraPreview(); } @Override protected void onDestroy() { super.onDestroy(); if (mPreview != null) { mPreview.disableView(); } } @Override protected void onStop() { super.onStop(); if (mPreview != null) { mPreview.disableView(); } } @Override public void onCameraViewStarted(int width, int height) { mGraphFilter2 = new GraphFilter2(height, width); mContrastFilter = new ContrastFilter(height, width, 100, 140); } @Override public void onCameraViewStopped() { } @Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { /* show previews */ Mat src = null, bottomLeft = null, topLeft = null, topRight = null, bottomRight = null; src = inputFrame.rgba(); Mat srcNormalized = mContrastFilter.apply(src); Mat graph = mGraphFilter2.apply(srcNormalized); topLeft = src; drawMini(graph, topLeft, bottomLeft, topRight, bottomRight); return graph; } private void drawMini(Mat dst, Mat topLeft, Mat bottomLeft, Mat topRight, Mat bottomRight) { int dstHeight = dst.rows(); int dstWidth = dst.cols(); int dstRoiHeight = dstHeight / 3; int dstRoiWidth = dstWidth / 3; Mat dstRoi; if (topLeft != null) { /* draw topLeft into top left corner */ dstRoi = dst.submat(0, dstRoiHeight, 0, dstRoiWidth); Imgproc.resize(topLeft, dstRoi, dstRoi.size()); } if (bottomLeft != null) { /* draw bottomLeft into bottom left corner */ dstRoi = dst.submat(dstHeight - dstRoiHeight, dstHeight, 0, dstRoiWidth); Imgproc.resize(bottomLeft, dstRoi, dstRoi.size()); } if (topRight != null) { /* draw topRight into top right corner */ dstRoi = dst.submat(0, dstRoiHeight, dstWidth - dstRoiWidth, dstWidth); Imgproc.resize(topRight, dstRoi, dstRoi.size()); } if (bottomRight != null) { /* draw bottomRight into bottom right corner */ dstRoi = dst.submat(dstHeight - dstRoiHeight, dstHeight, dstWidth - dstRoiWidth, dstWidth); Imgproc.resize(bottomRight, dstRoi, dstRoi.size()); } } }
package com.jamieadkins.gwent.main; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.jamieadkins.gwent.BuildConfig; import com.jamieadkins.gwent.ComingSoonFragment; import com.jamieadkins.gwent.R; import com.jamieadkins.gwent.settings.BasePreferenceActivity; import com.jamieadkins.gwent.settings.SettingsActivity; import com.jamieadkins.gwent.base.AuthenticationActivity; import com.jamieadkins.gwent.card.CardFilter; import com.jamieadkins.gwent.card.CardFilterListener; import com.jamieadkins.gwent.card.CardFilterProvider; import com.jamieadkins.gwent.card.list.CardListFragment; import com.jamieadkins.gwent.card.list.CardsContract; import com.jamieadkins.gwent.card.list.CardsPresenter; import com.jamieadkins.gwent.collection.CollectionContract; import com.jamieadkins.gwent.collection.CollectionFragment; import com.jamieadkins.gwent.collection.CollectionPresenter; import com.jamieadkins.gwent.data.Faction; import com.jamieadkins.gwent.data.Type; import com.jamieadkins.gwent.data.Rarity; import com.jamieadkins.gwent.data.interactor.CardsInteractorFirebase; import com.jamieadkins.gwent.data.interactor.CollectionInteractorFirebase; import com.jamieadkins.gwent.data.interactor.DecksInteractorFirebase; import com.jamieadkins.gwent.deck.list.DecksContract; import com.jamieadkins.gwent.deck.list.DecksPresenter; import com.jamieadkins.gwent.deck.list.DeckListFragment; import com.mikepenz.materialdrawer.AccountHeader; import com.mikepenz.materialdrawer.AccountHeaderBuilder; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem; import com.mikepenz.materialdrawer.model.SectionDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IProfile; import java.util.HashMap; import java.util.Map; public class MainActivity extends AuthenticationActivity implements CardFilterProvider { private static final String TAG_CARD_DB = "com.jamieadkins.gwent.CardDb"; private static final String TAG_PUBLIC_DECKS = "com.jamieadkins.gwent.PublicDecks"; private static final String TAG_USER_DECKS = "com.jamieadkins.gwent.UserDecks"; private static final String TAG_COLLECTION = "com.jamieadkins.gwent.Collection"; private static final String TAG_RESULTS_TRACKER = "com.jamieadkins.gwent.ResultsTracker"; private static final int ACCOUNT_IDENTIFIER = 1000; private static final int SIGN_IN_IDENTIFIER = 1001; private static final int SIGN_OUT_IDENTIFIER = 1002; private static final int NO_LAUNCH_ATTEMPT = -1; private DecksPresenter mDecksPresenter; private DecksPresenter mPublicDecksPresenter; private CardFilterListener mCardFilterListener; private CardsPresenter mCardsPresenter; private CollectionPresenter mCollectionPresenter; private Map<Integer, CardFilter> mCardFilters; private int mCurrentTab; private int mAttemptedToLaunchTab = NO_LAUNCH_ATTEMPT; private Drawer mNavigationDrawer; private AccountHeader mAccountHeader; private ProfileDrawerItem mProfile; private Map<Integer, PrimaryDrawerItem> mDrawerItems; private final View.OnClickListener signInClickListener = new View.OnClickListener() { @Override public void onClick(View view) { startSignInProcess(); } }; @Override public void initialiseContentView() { setContentView(R.layout.activity_main); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCardFilters = new HashMap<>(); mCardFilters.put(R.id.tab_card_db, new CardFilter()); mCardFilters.put(R.id.tab_collection, new CardFilter()); mCardFilters.get(R.id.tab_collection).setCollectibleOnly(true); mProfile = new ProfileDrawerItem() .withIdentifier(ACCOUNT_IDENTIFIER) .withEmail(getString(R.string.signed_out)) .withNameShown(false); final ProfileSettingDrawerItem signIn = new ProfileSettingDrawerItem() .withIcon(R.drawable.ic_account_circle) .withIdentifier(SIGN_IN_IDENTIFIER) .withName(getString(R.string.sign_in)); mAccountHeader = new AccountHeaderBuilder() .withHeaderBackground(R.drawable.header) .withSelectionListEnabledForSingleProfile(true) .addProfiles( mProfile, signIn) .withProfileImagesVisible(false) .withActivity(this) .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { @Override public boolean onProfileChanged(View view, IProfile profile, boolean current) { switch ((int) profile.getIdentifier()) { case SIGN_IN_IDENTIFIER: startSignInProcess(); break; case SIGN_OUT_IDENTIFIER: startSignOutProcess(); break; case ACCOUNT_IDENTIFIER: // View Account. break; } return false; } }) .build(); Drawer.OnDrawerItemClickListener drawerItemClickListener = new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { if (mCurrentTab == drawerItem.getIdentifier()) { return false; } mAttemptedToLaunchTab = (int) drawerItem.getIdentifier(); Fragment fragment; String tag; switch ((int) drawerItem.getIdentifier()) { case R.id.tab_card_db: fragment = new CardListFragment(); tag = TAG_CARD_DB; // Create the presenter. mCardsPresenter = new CardsPresenter((CardsContract.View) fragment, new CardsInteractorFirebase()); mCardFilterListener = (CardFilterListener) fragment; break; case R.id.tab_decks: // Hide this feature in release versions for now. if (!BuildConfig.DEBUG) { showSnackbar(String.format( getString(R.string.is_coming_soon), getString(R.string.my_decks))); // Don't display the item as the selected item. return false; } // Stop authenticated only tabs from being selected. if (!isAuthenticated()) { showSnackbar( String.format(getString(R.string.sign_in_to_view), getString(R.string.decks)), getString(R.string.sign_in), signInClickListener); // Don't display the item as the selected item. return false; } // Else, if authenticated. fragment = new DeckListFragment(); tag = TAG_USER_DECKS; // Create the presenter. mDecksPresenter = new DecksPresenter((DecksContract.View) fragment, new DecksInteractorFirebase()); break; case R.id.tab_collection: // Hide this feature in release versions for now. if (!BuildConfig.DEBUG && !BuildConfig.BETA) { showSnackbar(String.format( getString(R.string.is_coming_soon), getString(R.string.my_collection))); // Don't display the item as the selected item. return false; } // Stop authenticated only tabs from being selected. if (!isAuthenticated()) { showSnackbar( String.format(getString(R.string.sign_in_to_view), getString(R.string.collection)), getString(R.string.sign_in), signInClickListener); // Don't display the item as the selected item. return false; } // Else, if authenticated. fragment = new CollectionFragment(); tag = TAG_COLLECTION; mCollectionPresenter = new CollectionPresenter( (CollectionContract.View) fragment, new CollectionInteractorFirebase(), new CardsInteractorFirebase()); mCardFilterListener = (CardFilterListener) fragment; break; case R.id.tab_results: // Hide this feature in release versions for now. if (!BuildConfig.DEBUG) { showSnackbar(String.format( getString(R.string.is_coming_soon), getString(R.string.results))); // Don't display the item as the selected item. return false; } // Stop authenticated only tabs from being selected. if (!isAuthenticated()) { showSnackbar( String.format(getString(R.string.sign_in_to_view), getString(R.string.your_results)), getString(R.string.sign_in), signInClickListener); // Don't display the item as the selected item. return false; } // Else, if authenticated. fragment = new ComingSoonFragment(); tag = TAG_RESULTS_TRACKER; break; case R.id.tab_public_decks: // Hide this feature in release versions for now. if (!BuildConfig.DEBUG) { showSnackbar(String.format( getString(R.string.are_coming_soon), getString(R.string.public_decks))); // Don't display the item as the selected item. return false; } fragment = DeckListFragment.newInstance(false); tag = TAG_PUBLIC_DECKS; // Create the presenter. mPublicDecksPresenter = new DecksPresenter((DecksContract.View) fragment, new DecksInteractorFirebase(true)); break; case R.id.action_about: Intent about = new Intent(MainActivity.this, BasePreferenceActivity.class); about.putExtra(BasePreferenceActivity.EXTRA_PREFERENCE_LAYOUT, R.xml.about); about.putExtra(BasePreferenceActivity.EXTRA_PREFERENCE_TITLE, R.string.about); startActivity(about); // Return true to not close the navigation drawer. return true; case R.id.action_settings: Intent settings = new Intent(MainActivity.this, SettingsActivity.class); settings.putExtra(BasePreferenceActivity.EXTRA_PREFERENCE_LAYOUT, R.xml.settings); settings.putExtra(BasePreferenceActivity.EXTRA_PREFERENCE_TITLE, R.string.settings); startActivity(settings); // Return true to not close the navigation drawer. return true; default: showSnackbar(getString(R.string.coming_soon)); // Don't display the item as the selected item. return false; } launchFragment(fragment, tag); mCurrentTab = (int) drawerItem.getIdentifier(); return false; } }; initialiseDrawerItems(); mNavigationDrawer = new DrawerBuilder() .withActivity(this) .withToolbar((Toolbar) findViewById(R.id.toolbar)) .withShowDrawerOnFirstLaunch(true) .withAccountHeader(mAccountHeader) .addDrawerItems( new SectionDrawerItem() .withName(R.string.gwent) .withDivider(false), mDrawerItems.get(R.id.tab_card_db), mDrawerItems.get(R.id.tab_public_decks), new SectionDrawerItem() .withName(R.string.my_stuff) .withDivider(false), mDrawerItems.get(R.id.tab_decks), mDrawerItems.get(R.id.tab_collection), mDrawerItems.get(R.id.tab_results) ) .addStickyDrawerItems( new PrimaryDrawerItem() .withIdentifier(R.id.action_settings). withName(R.string.settings) .withIcon(R.drawable.ic_settings) .withSelectable(false), new PrimaryDrawerItem() .withIdentifier(R.id.action_about). withName(R.string.about) .withIcon(R.drawable.ic_info) .withSelectable(false) ) .withOnDrawerItemClickListener(drawerItemClickListener) .build(); handleDrawerAuthentication(); if (savedInstanceState == null) { // Cold start, launch card db fragment. mNavigationDrawer.setSelection(R.id.tab_card_db); } else { // Need to find out which fragment we have on screen. Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.contentContainer); switch (fragment.getTag()) { case TAG_CARD_DB: mCurrentTab = R.id.tab_card_db; mCardsPresenter = new CardsPresenter((CardsContract.View) fragment, new CardsInteractorFirebase()); mCardFilterListener = (CardFilterListener) fragment; break; case TAG_PUBLIC_DECKS: mCurrentTab = R.id.tab_public_decks; mPublicDecksPresenter = new DecksPresenter((DecksContract.View) fragment, new DecksInteractorFirebase(true)); break; case TAG_COLLECTION: mCurrentTab = R.id.tab_collection; mCollectionPresenter = new CollectionPresenter( (CollectionContract.View) fragment, new CollectionInteractorFirebase(), new CardsInteractorFirebase()); mCardFilterListener = (CardFilterListener) fragment; break; case TAG_USER_DECKS: mCurrentTab = R.id.tab_decks; mDecksPresenter = new DecksPresenter((DecksContract.View) fragment, new DecksInteractorFirebase()); break; case TAG_RESULTS_TRACKER: mCurrentTab = R.id.tab_results; break; } mNavigationDrawer.setSelection(mCurrentTab); } } private void initialiseDrawerItems() { mDrawerItems = new HashMap<>(); mDrawerItems.put(R.id.tab_card_db, new PrimaryDrawerItem() .withIdentifier(R.id.tab_card_db) .withName(R.string.card_database) .withIcon(R.drawable.ic_database)); mDrawerItems.put(R.id.tab_public_decks, new PrimaryDrawerItem() .withIdentifier(R.id.tab_public_decks) .withName(R.string.public_decks) .withSelectable(BuildConfig.DEBUG) .withIcon(R.drawable.ic_public)); mDrawerItems.put(R.id.tab_decks, new PrimaryDrawerItem() .withIdentifier(R.id.tab_decks) .withName(R.string.my_decks) .withIcon(R.drawable.ic_cards_filled)); mDrawerItems.put(R.id.tab_collection, new PrimaryDrawerItem() .withIdentifier(R.id.tab_collection) .withName(R.string.my_collection) .withIcon(R.drawable.ic_cards_outline)); mDrawerItems.put(R.id.tab_results, new PrimaryDrawerItem() .withIdentifier(R.id.tab_results) .withName(R.string.results) .withIcon(R.drawable.ic_chart)); } private void launchFragment(Fragment fragment, String tag) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace( R.id.contentContainer, fragment, tag); fragmentTransaction.commit(); mAttemptedToLaunchTab = NO_LAUNCH_ATTEMPT; // Our options menu will be different for different tabs. invalidateOptionsMenu(); } private void handleDrawerAuthentication() { // Reset by removing both. mAccountHeader.removeProfileByIdentifier(SIGN_IN_IDENTIFIER); mAccountHeader.removeProfileByIdentifier(SIGN_OUT_IDENTIFIER); if (isAuthenticated()) { mAccountHeader.updateProfile( mProfile.withEmail(getCurrentUser().getEmail())); mAccountHeader.addProfiles( new ProfileSettingDrawerItem() .withIdentifier(SIGN_OUT_IDENTIFIER) .withName(getString(R.string.sign_out)) .withIcon(R.drawable.ic_account_circle)); mDrawerItems.get(R.id.tab_collection).withSelectable(true); mNavigationDrawer.updateItem(mDrawerItems.get(R.id.tab_collection)); mDrawerItems.get(R.id.tab_decks).withSelectable(BuildConfig.DEBUG); mNavigationDrawer.updateItem(mDrawerItems.get(R.id.tab_decks)); mDrawerItems.get(R.id.tab_results).withSelectable(BuildConfig.DEBUG); mNavigationDrawer.updateItem(mDrawerItems.get(R.id.tab_results)); } else { mAccountHeader.updateProfile( mProfile.withEmail(getString(R.string.signed_out))); mAccountHeader.removeProfileByIdentifier(SIGN_OUT_IDENTIFIER); mAccountHeader.addProfiles( new ProfileSettingDrawerItem() .withIdentifier(SIGN_IN_IDENTIFIER) .withName(getString(R.string.sign_in)) .withIcon(R.drawable.ic_account_circle)); // If we are currently in an activity that requires authentication, switch to another. if (mCurrentTab == R.id.tab_collection || mCurrentTab == R.id.tab_decks || mCurrentTab == R.id.tab_results) { mNavigationDrawer.setSelection(R.id.tab_card_db); } mDrawerItems.get(R.id.tab_collection).withSelectable(false); mNavigationDrawer.updateItem(mDrawerItems.get(R.id.tab_collection)); mDrawerItems.get(R.id.tab_decks).withSelectable(false); mNavigationDrawer.updateItem(mDrawerItems.get(R.id.tab_decks)); mDrawerItems.get(R.id.tab_results).withSelectable(false); mNavigationDrawer.updateItem(mDrawerItems.get(R.id.tab_results)); } } @Override protected void onSignedIn() { super.onSignedIn(); invalidateOptionsMenu(); handleDrawerAuthentication(); // User tried to access a different tab before they tried to sign in. if (mAttemptedToLaunchTab != NO_LAUNCH_ATTEMPT) { mNavigationDrawer.setSelection(mAttemptedToLaunchTab); } } @Override protected void onSignedOut() { super.onSignedOut(); invalidateOptionsMenu(); handleDrawerAuthentication(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if (mCurrentTab == R.id.tab_card_db || mCurrentTab == R.id.tab_collection) { inflater.inflate(R.menu.search, menu); MenuItem myActionMenuItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) myActionMenuItem.getActionView(); searchView.setQueryHint(getString(R.string.search_hint)); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String query) { if (query.equals("")) { // Don't search for everything! mCardFilters.get(mCurrentTab).setSearchQuery(null); return false; } mCardFilters.get(mCurrentTab).setSearchQuery(query); mCardFilterListener.onCardFilterUpdated(); return false; } }); searchView.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { mCardFilters.get(mCurrentTab).setSearchQuery(null); mCardFilterListener.onCardFilterUpdated(); return false; } }); inflater.inflate(R.menu.card_filters, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // We may waste this Dialog if it is not a filter item, but it makes for cleaner code. AlertDialog.Builder builder = new AlertDialog.Builder(this); switch (item.getItemId()) { case R.id.filter_reset: mCardFilters.get(mCurrentTab).clearFilters(); mCardFilterListener.onCardFilterUpdated(); return true; case R.id.filter_faction: boolean[] factions = new boolean[Faction.ALL_FACTIONS.length]; for (String key : Faction.ALL_FACTIONS) { factions[Faction.CONVERT_STRING.get(key)] = mCardFilters.get(mCurrentTab).get(key); } builder.setMultiChoiceItems( R.array.factions_array_with_neutral, factions, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean selected) { mCardFilters.get(mCurrentTab) .put(Faction.CONVERT_INT.get(i), selected); mCardFilterListener.onCardFilterUpdated(); } }); break; case R.id.filter_rarity: boolean[] rarities = new boolean[Rarity.ALL_RARITIES.length]; for (String key : Rarity.ALL_RARITIES) { rarities[Rarity.CONVERT_STRING.get(key)] = mCardFilters.get(mCurrentTab).get(key); } builder.setMultiChoiceItems( R.array.rarity_array, rarities, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean selected) { mCardFilters.get(mCurrentTab) .put(Rarity.CONVERT_INT.get(i), selected); mCardFilterListener.onCardFilterUpdated(); } }); break; case R.id.filter_type: boolean[] types = new boolean[Type.ALL_TYPES.length]; for (String key : Type.ALL_TYPES) { types[Type.CONVERT_STRING.get(key)] = mCardFilters.get(mCurrentTab).get(key); } builder.setMultiChoiceItems( R.array.types_array, types, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean selected) { mCardFilters.get(mCurrentTab) .put(Type.CONVERT_INT.get(i), selected); mCardFilterListener.onCardFilterUpdated(); } }); break; default: return super.onOptionsItemSelected(item); } builder.setPositiveButton(R.string.button_done, null); builder.show(); return true; } @Override public CardFilter getCardFilter() { return mCardFilters.get(mCurrentTab); } }
package com.odong.buddhismhomework; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initButtonEvent(); initDownloadDialog(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_download: List<String> names = new ArrayList<String>(); for (String s : getResources().getStringArray(R.array.lv_books)) { names.add("books/" + s + ".txt"); } for (String s : getResources().getStringArray(R.array.lv_musics)) { names.add("musics/" + s.split("\\|")[0] + ".mp3"); } for (String s : getResources().getStringArray(R.array.lv_courses)) { names.add("courses/" + s + ".txt"); names.add("courses/" + s + ".mp3"); } new Downloader().execute(names.toArray(new String[names.size()])); // new AlertDialog.Builder( // MainActivity.this).setMessage( // R.string.lbl_error_download).setPositiveButton( // android.R.string.ok, null).create().show(); break; case R.id.action_settings: startActivity(new Intent(MainActivity.this, SettingsActivity.class)); break; case R.id.action_about_me: AlertDialog.Builder adbAboutMe = new AlertDialog.Builder(this); adbAboutMe.setMessage(R.string.lbl_about_me).setTitle(R.string.action_about_me); adbAboutMe.setPositiveButton(android.R.string.ok, null); adbAboutMe.create().show(); break; default: return super.onOptionsItemSelected(item); } return true; } private void initButtonEvent() { //Map<Integer, View.OnClickListener> events = new HashMap<Integer, View.OnClickListener>(); SparseArray<View.OnClickListener> events = new SparseArray<View.OnClickListener>(); events.put(R.id.btn_main_morning, new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, CourseActivity.class); intent.putExtra("name", "morning"); startActivity(intent); } }); events.put(R.id.btn_main_night, new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, CourseActivity.class); intent.putExtra("name", "night"); startActivity(intent); } }); events.put(R.id.btn_main_sitting, new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, SittingActivity.class)); } }); events.put(R.id.btn_main_courses, new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ItemsActivity.class); intent.putExtra("name", "courses"); startActivity(intent); } }); events.put(R.id.btn_main_books, new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ItemsActivity.class); intent.putExtra("name", "books"); startActivity(intent); } }); events.put(R.id.btn_main_music, new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ItemsActivity.class); intent.putExtra("name", "musics"); startActivity(intent); } }); for (int i = 0; i < events.size(); i++) { findViewById(events.keyAt(i)).setOnClickListener(events.valueAt(i)); } } private void initDownloadDialog() { dlgDownload = new ProgressDialog(this); dlgDownload.setTitle(R.string.action_download); dlgDownload.setMessage(getString(R.string.lbl_download)); dlgDownload.setCancelable(true); dlgDownload.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); } private class Downloader extends AsyncTask<String, String, Boolean> { @Override protected Boolean doInBackground(String... names) { dlgDownload.setMax(names.length); dlgDownload.setProgress(0); dlgDownload.show(); try { for (String name : names) { String fn = name.replace('/', '-'); if (!new File(fn).exists()) { DataInputStream dis = new DataInputStream( new URL( "http://192.168.1.102/tools/" + name).openStream()); byte[] buf = new byte[1024]; int len; FileOutputStream fos = openFileOutput(fn, Context.MODE_PRIVATE); while ((len = dis.read(buf)) > 0) { fos.write(buf, 0, len); } fos.flush(); } dlgDownload.incrementProgressBy(1); } } catch (MalformedURLException e) { Log.e("", "", e); } catch (IOException e) { Log.e("", "IO", e); } catch (SecurityException e) { Log.e("", "", e); } boolean success = dlgDownload.getProgress() == dlgDownload.getMax(); dlgDownload.dismiss(); return success; } } private ProgressDialog dlgDownload; }
package com.ternaryop.tumblr; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.scribe.model.OAuthRequest; /** * Convert a OAuthRequest POST into a multi-part OAuthRequest * @author jc */ public class MultipartConverter { private final String boundary; private final OAuthRequest originalRequest; private Integer bodyLength = 0; private List<Object> responsePieces; public MultipartConverter(OAuthRequest request, Map<String, ?> bodyMap) throws IOException { this.originalRequest = request; this.boundary = Long.toHexString(System.nanoTime()); this.computeBody(bodyMap); } public OAuthRequest getRequest() { OAuthRequest request = new OAuthRequest(originalRequest.getVerb(), originalRequest.getUrl()); request.addHeader("Authorization", originalRequest.getHeaders().get("Authorization")); request.addHeader("Content-Type", "multipart/form-data, boundary=" + boundary); request.addHeader("Content-length", bodyLength.toString()); request.addPayload(complexPayload()); return request; } private byte[] complexPayload() { int used = 0; byte[] payload = new byte[bodyLength]; byte[] local; for (Object piece : responsePieces) { if (piece instanceof StringBuilder) { local = piece.toString().getBytes(); } else { local = (byte[]) piece; } System.arraycopy(local, 0, payload, used, local.length); used += local.length; } return payload; } private void addResponsePiece(byte[] arr) { responsePieces.add(arr); bodyLength += arr.length; } private void addResponsePiece(StringBuilder builder) { responsePieces.add(builder); bodyLength += builder.toString().getBytes().length; } private void computeBody(Map<String, ?> bodyMap) throws IOException { responsePieces = new ArrayList<Object>(); StringBuilder message = new StringBuilder(); message.append("Content-Type: multipart/form-data; boundary=").append(boundary).append("\r\n\r\n"); for (String key : bodyMap.keySet()) { Object object = bodyMap.get(key); if (object == null) { continue; } if (object instanceof File) { File f = (File) object; String mime = URLConnection.guessContentTypeFromName(f.getName()); DataInputStream dis = null; byte[] result = new byte[(int)f.length()]; try { dis = new DataInputStream(new BufferedInputStream(new FileInputStream(f))); dis.readFully(result); } finally { if (dis != null) try { dis.close(); } catch (Exception ignored) {} } message.append("--").append(boundary).append("\r\n"); message.append("Content-Disposition: form-data; name=\"").append(key).append("\"; filename=\"").append(f.getName()).append("\"\r\n"); message.append("Content-Type: ").append(mime).append("\r\n\r\n"); this.addResponsePiece(message); this.addResponsePiece(result); message = new StringBuilder("\r\n"); } else { message.append("--").append(boundary).append("\r\n"); message.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n\r\n"); message.append(object.toString()).append("\r\n"); } } message.append("--").append(boundary).append("--\r\n"); this.addResponsePiece(message); } }
package com.turlir.abakgists.utils; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.AttrRes; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.turlir.abakgists.R; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import timber.log.Timber; public class SwitchLayout extends FrameLayout { private static final int MAX_CHILD = 3; public static final int CONTENT = 0, ERROR = 1, LOADING = 1 << 1; private int mIndex; private Setting mLastItem; public SwitchLayout(@NonNull Context context) { this(context, null); } public SwitchLayout(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public SwitchLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SwitchLayout, 0, 0); try { mIndex = ta.getInteger(R.styleable.SwitchLayout_init, LOADING); // default } finally { ta.recycle(); } } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (getChildCount() > MAX_CHILD) { throw new IllegalStateException("getChildCount() must be between 0 and 2"); } super.addView(child, index, params); final int i; if (index > 0) { i = index; } else { i = getChildCount() - 1; } applyGroupByChild(i); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new SwitchLayoutParams(getContext(), attrs); } @Override protected LayoutParams generateDefaultLayoutParams() { return new SwitchLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { return generateDefaultLayoutParams(); } @Override protected Parcelable onSaveInstanceState() { Parcelable instance = super.onSaveInstanceState(); return new SwitchLayoutState(instance, this); } @Override protected void onRestoreInstanceState(Parcelable state) { super.onRestoreInstanceState(state); SwitchLayoutState now = (SwitchLayoutState) state; now.apply(this); changeGroup(mIndex); } public void toContent() { changeGroup(CONTENT); } public void toError() { changeGroup(ERROR); } public void toLoading() { changeGroup(LOADING); } @Group public int currentGroup() { return mIndex; } private boolean applyGroupByChild(int child) { if (mLastItem != null) { if (child == mLastItem.getPosition()) { showChild(child); return true; } else { hideChild(child); return false; } } else { if (doesViewToGroup(mIndex, child)) { mLastItem = new Setting(mIndex, child); showChild(child); return true; } else { hideChild(child); return false; } } } private int changeGroup(int group) { if (mLastItem != null) { if (group != mLastItem.getGroup()) { hideChild(mLastItem.getPosition()); int position = getChildIndexByGroup(group); mLastItem = new Setting(group, position); showChild(mLastItem.getPosition()); } return mIndex = group; } else { int index = getChildIndexByGroup(group); showChild(index); mLastItem = new Setting(group, index); return mIndex = group; } } private boolean doesViewToGroup(int group, int index) { return group == index; } private int getChildIndexByGroup(int group) { return group; } private void hideChild(int i) { Timber.i("hideChild %d", i); View child = getChildAt(i); ViewGroup.LayoutParams lp = child.getLayoutParams(); int def = ((SwitchLayoutParams) lp).getHideVisibility(); //noinspection WrongConstant child.setVisibility(def); } private void showChild(int i) { Timber.i("showChild %d", i); getChildAt(i).setVisibility(View.VISIBLE); } private static class SwitchLayoutParams extends FrameLayout.LayoutParams { private final int mHided; SwitchLayoutParams(int width, int height) { super(width, height); mHided = View.INVISIBLE; } SwitchLayoutParams(@NonNull Context c, @Nullable AttributeSet attrs) { super(c, attrs); TypedArray ta = c.obtainStyledAttributes(attrs, R.styleable.SwitchLayout_Layout, 0, 0); try { mHided = ta.getInteger(R.styleable.SwitchLayout_Layout_hided, View.INVISIBLE); // default } finally { ta.recycle(); } } int getHideVisibility() { return mHided; } } private static final class SwitchLayoutState extends BaseSavedState { public static final Parcelable.Creator<SwitchLayoutState> CREATOR = new Parcelable.Creator<SwitchLayoutState>() { public SwitchLayoutState createFromParcel(Parcel in) { return new SwitchLayoutState(in); } public SwitchLayoutState[] newArray(int size) { return new SwitchLayoutState[size]; } }; int index; private SwitchLayoutState(Parcelable in, SwitchLayout layout) { super(in); index = layout.mIndex; } private SwitchLayoutState(Parcel source) { super(source); index = source.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(index); } private void apply(SwitchLayout layout) { layout.mIndex = index; } } @IntDef(flag = true, value = { CONTENT, ERROR, LOADING }) @Retention(RetentionPolicy.SOURCE) @interface Group { } private static class Setting { private int mGroup; private int mPosition; Setting(int group, int position) { this.mGroup = group; this.mPosition = position; } private int getGroup() { return mGroup; } private int getPosition() { return mPosition; } } }
package de.bitdroid.flooding.utils; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.MenuItem; import de.bitdroid.flooding.R; public abstract class BaseActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); getActionBar().setDisplayShowHomeEnabled(false); } @Override public void onBackPressed() { super.onBackPressed(); showExitAnimation(); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch(menuItem.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(menuItem); } protected void showExitAnimation() { overridePendingTransition(R.anim.slide_enter_from_left, R.anim.slide_exit_to_right); } }
package info.nightscout.androidaps.data; import android.support.v4.util.LongSparseArray; import com.crashlytics.android.Crashlytics; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.DecimalFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.ToastUtils; public class Profile { private static Logger log = LoggerFactory.getLogger(Profile.class); private JSONObject json; private String units = null; double dia = Constants.defaultDIA; TimeZone timeZone = TimeZone.getDefault(); JSONArray isf; private LongSparseArray<Double> isf_v = null; // oldest at index 0 JSONArray ic; private LongSparseArray<Double> ic_v = null; // oldest at index 0 JSONArray basal; private LongSparseArray<Double> basal_v = null; // oldest at index 0 JSONArray targetLow; JSONArray targetHigh; public Profile(JSONObject json, String units) { this(json); if (this.units == null) { if (units != null) this.units = units; else { Crashlytics.log("Profile failover failed too"); this.units = Constants.MGDL; } } } public Profile(JSONObject json) { this.json = json; try { if (json.has("units")) units = json.getString("units").toLowerCase(); if (json.has("dia")) dia = json.getDouble("dia"); if (json.has("dia")) dia = json.getDouble("dia"); if (json.has("timezone")) timeZone = TimeZone.getTimeZone(json.getString("timezone")); isf = json.getJSONArray("sens"); if (getIsf(0) == null) { int defaultISF = units.equals(Constants.MGDL) ? 400 : 20; isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultISF + "\",\"timeAsSeconds\":\"0\"}]"); Notification noisf = new Notification(Notification.ISF_MISSING, MainApp.sResources.getString(R.string.isfmissing), Notification.URGENT); MainApp.bus().post(new EventNewNotification(noisf)); } else { MainApp.bus().post(new EventDismissNotification(Notification.ISF_MISSING)); } ic = json.getJSONArray("carbratio"); if (getIc(0) == null) { int defaultIC = 25; isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultIC + "\",\"timeAsSeconds\":\"0\"}]"); Notification noic = new Notification(Notification.IC_MISSING, MainApp.sResources.getString(R.string.icmissing), Notification.URGENT); MainApp.bus().post(new EventNewNotification(noic)); } else { MainApp.bus().post(new EventDismissNotification(Notification.IC_MISSING)); } basal = json.getJSONArray("basal"); if (getBasal(0) == null) { double defaultBasal = 0.1d; isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultBasal + "\",\"timeAsSeconds\":\"0\"}]"); Notification nobasal = new Notification(Notification.BASAL_MISSING, MainApp.sResources.getString(R.string.basalmissing), Notification.URGENT); MainApp.bus().post(new EventNewNotification(nobasal)); } else { MainApp.bus().post(new EventDismissNotification(Notification.BASAL_MISSING)); } targetLow = json.getJSONArray("target_low"); if (getTargetLow(0) == null) { double defaultLow = units.equals(Constants.MGDL) ? 120 : 6; isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultLow + "\",\"timeAsSeconds\":\"0\"}]"); Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notarget)); } else { MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING)); } targetHigh = json.getJSONArray("target_high"); if (getTargetHigh(0) == null) { double defaultHigh = units.equals(Constants.MGDL) ? 160 : 8; isf = new JSONArray("[{\"time\":\"00:00\",\"value\":\"" + defaultHigh + "\",\"timeAsSeconds\":\"0\"}]"); Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notarget)); } else { MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING)); } } catch (JSONException e) { e.printStackTrace(); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.invalidprofile)); } } public String log() { String ret = "\n"; for (Integer hour = 0; hour < 24; hour++) { double value = getBasal((Integer) (hour * 60 * 60)); ret += "NS basal value for " + hour + ":00 is " + value + "\n"; } ret += "NS units: " + getUnits(); return ret; } public JSONObject getData() { if (!json.has("units")) try { json.put("units", units); } catch (JSONException e) { e.printStackTrace(); } return json; } public double getDia() { return dia; } // mmol or mg/dl public String getUnits() { return units; } public TimeZone getTimeZone() { return timeZone; } private LongSparseArray<Double> convertToSparseArray(JSONArray array) { LongSparseArray<Double> sparse = new LongSparseArray<>(); for (Integer index = 0; index < array.length(); index++) { try { JSONObject o = array.getJSONObject(index); long tas = o.getLong("timeAsSeconds"); Double value = o.getDouble("value"); sparse.put(tas, value); } catch (JSONException e) { e.printStackTrace(); } } return sparse; } private Double getValueToTime(JSONArray array, Integer timeAsSeconds) { Double lastValue = null; for (Integer index = 0; index < array.length(); index++) { try { JSONObject o = array.getJSONObject(index); Integer tas = o.getInt("timeAsSeconds"); Double value = o.getDouble("value"); if (lastValue == null) lastValue = value; if (timeAsSeconds < tas) { break; } lastValue = value; } catch (JSONException e) { e.printStackTrace(); } } return lastValue; } private Double getValueToTime(LongSparseArray<Double> array, long timeAsSeconds) { Double lastValue = null; for (Integer index = 0; index < array.size(); index++) { long tas = array.keyAt(index); double value = array.valueAt(index); if (lastValue == null) lastValue = value; if (timeAsSeconds < tas) { break; } lastValue = value; } return lastValue; } private String getValuesList(JSONArray array, JSONArray array2, DecimalFormat format, String units) { String retValue = ""; for (Integer index = 0; index < array.length(); index++) { try { JSONObject o = array.getJSONObject(index); retValue += o.getString("time"); retValue += " "; retValue += format.format(o.getDouble("value")); if (array2 != null) { JSONObject o2 = array2.getJSONObject(index); retValue += " - "; retValue += format.format(o2.getDouble("value")); } retValue += " " + units; if (index + 1 < array.length()) retValue += "\n"; } catch (JSONException e) { e.printStackTrace(); } } return retValue; } public Double getIsf() { return getIsf(secondsFromMidnight(System.currentTimeMillis())); } public Double getIsf(long time) { return getIsf(secondsFromMidnight(time)); } public Double getIsf(Integer timeAsSeconds) { if (isf_v == null) isf_v = convertToSparseArray(isf); return getValueToTime(isf_v, timeAsSeconds); } public String getIsfList() { return getValuesList(isf, null, new DecimalFormat("0.0"), getUnits() + "/U"); } public Double getIc() { return getIc(secondsFromMidnight(System.currentTimeMillis())); } public Double getIc(long time) { return getIc(secondsFromMidnight(time)); } public Double getIc(Integer timeAsSeconds) { if (ic_v == null) ic_v = convertToSparseArray(ic); return getValueToTime(ic_v, timeAsSeconds); } public String getIcList() { return getValuesList(ic, null, new DecimalFormat("0.0"), " g/U"); } public Double getBasal() { return getBasal(secondsFromMidnight(System.currentTimeMillis())); } public Double getBasal(long time) { return getBasal(secondsFromMidnight(time)); } public Double getBasal(Integer timeAsSeconds) { if (basal_v == null) basal_v = convertToSparseArray(basal); return getValueToTime(basal_v, timeAsSeconds); } public String getBasalList() { return getValuesList(basal, null, new DecimalFormat("0.00"), "U"); } public class BasalValue { public BasalValue(Integer timeAsSeconds, Double value) { this.timeAsSeconds = timeAsSeconds; this.value = value; } public Integer timeAsSeconds; public Double value; } public BasalValue[] getBasalValues() { try { BasalValue[] ret = new BasalValue[basal.length()]; for (Integer index = 0; index < basal.length(); index++) { JSONObject o = basal.getJSONObject(index); Integer tas = o.getInt("timeAsSeconds"); Double value = o.getDouble("value"); ret[index] = new BasalValue(tas, value); } return ret; } catch (JSONException e) { e.printStackTrace(); } return new BasalValue[0]; } public Double getTargetLow() { return getTargetLow(secondsFromMidnight(System.currentTimeMillis())); } public Double getTargetLow(long time) { return getTargetLow(secondsFromMidnight(time)); } public Double getTargetLow(Integer timeAsSeconds) { return getValueToTime(targetLow, timeAsSeconds); } public Double getTargetHigh() { return getTargetHigh(secondsFromMidnight(System.currentTimeMillis())); } public Double getTargetHigh(long time) { return getTargetHigh(secondsFromMidnight(time)); } public Double getTargetHigh(Integer timeAsSeconds) { return getValueToTime(targetHigh, timeAsSeconds); } public String getTargetList() { return getValuesList(targetLow, targetHigh, new DecimalFormat("0.0"), getUnits()); } public double getMaxDailyBasal() { Double max = 0d; for (Integer hour = 0; hour < 24; hour++) { double value = getBasal((Integer)(hour * 60 * 60)); if (value > max) max = value; } return max; } public static Integer secondsFromMidnight() { Calendar c = Calendar.getInstance(); long now = c.getTimeInMillis(); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); long passed = now - c.getTimeInMillis(); return (int) (passed / 1000); } public static Integer secondsFromMidnight(Date date) { Calendar c = Calendar.getInstance(); long now = date.getTime(); c.setTime(date); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); long passed = now - c.getTimeInMillis(); return (int) (passed / 1000); } public static Integer secondsFromMidnight(long date) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(date); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); long passed = date - c.getTimeInMillis(); return (int) (passed / 1000); } public static Double toMgdl(Double value, String units) { if (units.equals(Constants.MGDL)) return value; else return value * Constants.MMOLL_TO_MGDL; } public static Double fromMgdlToUnits(Double value, String units) { if (units.equals(Constants.MGDL)) return value; else return value * Constants.MGDL_TO_MMOLL; } public static Double toUnits(Double valueInMgdl, Double valueInMmol, String units) { if (units.equals(Constants.MGDL)) return valueInMgdl; else return valueInMmol; } public static String toUnitsString(Double valueInMgdl, Double valueInMmol, String units) { if (units.equals(Constants.MGDL)) return DecimalFormatter.to0Decimal(valueInMgdl); else return DecimalFormatter.to1Decimal(valueInMmol); } // targets are stored in mg/dl public static String toTargetRangeString(double low, double high, String units) { if (low == high) return toUnitsString(low, Profile.fromMgdlToUnits(low, Constants.MMOL), units); else return toUnitsString(low, Profile.fromMgdlToUnits(low, Constants.MMOL), units) + " - " + toUnitsString(high, Profile.fromMgdlToUnits(high, Constants.MMOL), units); } }
package io.khe.kenthackenough; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.widget.TextView; /** * A view to render a string such as "A minute ago" * dynamically based on a supplied date from setTime(long time) */ public class FriendlyTimeSince extends TextView { private long time = System.currentTimeMillis(); private Handler timer = new Handler(); private final FriendlyTimeSince self = this; private Runnable updateMessage = new Runnable() { @Override public void run() { self.setText(self.getFriendlyTimeSince()); timer.postDelayed(this, nextChange()); } }; public FriendlyTimeSince(Context context) { super(context); timer.postDelayed(updateMessage, 0); } public FriendlyTimeSince(Context context, AttributeSet attrs) { super(context, attrs); String timeString = attrs.getAttributeValue("app","time"); if (timeString != null) { time = Long.parseLong(timeString); } timer.postDelayed(updateMessage, 0); } public FriendlyTimeSince(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); String timeString = attrs.getAttributeValue("app","time"); if (timeString != null) { time = Long.parseLong(timeString); } timer.postDelayed(updateMessage, 0); } /** * Use to set the time to calculate the message based on * @param time the time in milliseconds */ public void setTime(long time) { this.time = time; timer.removeCallbacks(updateMessage); timer.postDelayed(updateMessage, 0); } public long getTime() { return time; } private int nextChange() { long deltaMills = System.currentTimeMillis() - time; long deltaSeconds = deltaMills / 1000; long deltaMinutes = deltaSeconds / 60; long deltaHours = deltaMinutes / 60; long deltaDays = deltaHours / 24; if (deltaDays > 0) { return 86400000; // one day worth of milliseconds } else if (deltaHours != 0) { return 3600000; // one hour worth of milliseconds } else if (deltaMinutes != 0) { return 60000; // one minute worth of milliseconds } else { return 1000; //never update faster than one a second } } private String getFriendlyTimeSince() { double deltaMills = System.currentTimeMillis() - time; double deltaSeconds = deltaMills / 1000; double deltaMinutes = deltaSeconds / 60; double deltaHours = deltaMinutes / 60; double deltaDays = deltaHours / 24; String noun; long value; if (deltaDays > 1.) { noun = "day"; value = (long)(deltaDays + 0.5); } else if (deltaHours > 1.) { noun = "hour"; value = (long)(deltaHours + 0.5); } else if (deltaMinutes > 1.) { noun = "minute"; value = (long)(deltaMinutes + 0.5); } else if (deltaSeconds > 1.) { noun = "second"; value = (long)(deltaSeconds+ 0.5); } else { noun = "second"; value = 1; } if (value == 1) { return "About a" + (noun.charAt(0) == 'h' ? "n " : " ") + noun + " ago"; } else { return Long.toString(value) + " " + noun + "s ago"; } } }
package me.devsaki.hentoid.parsers; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.List; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.enums.AttributeType; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.util.AttributeMap; import me.devsaki.hentoid.util.HttpClientHelper; import timber.log.Timber; public class HitomiParser extends BaseParser { // Reproduction of the Hitomi.la Javascript to find the hostname of the image server (see subdomain_from_url@reader.js) private final static int NUMBER_OF_FRONTENDS = 2; private final static String HOSTNAME_SUFFIX = "a"; private final static char HOSTNAME_PREFIX_BASE = 97; @Override protected Content parseContent(Document doc) { Content result = null; Elements content = doc.select(".content"); if (content.size() > 0) { result = new Content(); String coverImageUrl = "https:" + content.select(".cover img").attr("src"); result.setCoverImageUrl(coverImageUrl); Element info = content.select(".gallery").first(); Element titleElement = info.select("h1").first(); // Nota Bene : Non-video entries have their title inside a hyperlink // whereas video entries have it directly in the H1 tag, hence a silent crash when trying to parse videos // (no problem here since they are not supported by the downloader anyway) String url = titleElement.select("a").first().attr("href").replace("/reader", ""); result.setUrl(url); String title = titleElement.text(); result.setTitle(title); AttributeMap attributes = new AttributeMap(); result.setAttributes(attributes); parseAttributes(attributes, AttributeType.ARTIST, info.select("h2").select("a")); Elements rows = info.select("tr"); for (Element element : rows) { Element td = element.select("td").first(); if (td.html().startsWith("Group")) { parseAttributes(attributes, AttributeType.CIRCLE, element.select("a")); } else if (td.html().startsWith("Series")) { parseAttributes(attributes, AttributeType.SERIE, element.select("a")); } else if (td.html().startsWith("Character")) { parseAttributes(attributes, AttributeType.CHARACTER, element.select("a")); } else if (td.html().startsWith("Tags")) { parseAttributes(attributes, AttributeType.TAG, element.select("a")); } else if (td.html().startsWith("Language")) { parseAttributes(attributes, AttributeType.LANGUAGE, element.select("a")); } else if (td.html().startsWith("Type")) { parseAttributes(attributes, AttributeType.CATEGORY, element.select("a")); } } int pages = doc.select(".thumbnail-container").size(); result.setQtyPages(pages) .setSite(Site.HITOMI); } return result; } @Override protected List<String> parseImages(Content content) throws Exception { List<String> result = new ArrayList<>(); String url = content.getReaderUrl(); String html = HttpClientHelper.call(url); Timber.d("Parsing: %s", url); Document doc = Jsoup.parse(html); Elements imgElements = doc.select(".img-url"); // New Hitomi image URLs starting from june 2018 // If book ID is even, starts with 'aa'; else starts with 'ba' int referenceId = Integer.parseInt(content.getUniqueSiteId()) % 10; if (1 == referenceId) referenceId = 0; // Yes, this is what Hitomi actually does (see common.js) String imageHostname = Character.toString((char) (HOSTNAME_PREFIX_BASE + (referenceId % NUMBER_OF_FRONTENDS) )) + HOSTNAME_SUFFIX; for (Element element : imgElements) { result.add("https:" + element.text().replace("//g.", "//" + imageHostname + ".")); } return result; } }
package me.dylanburton.blastarreborn; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.View; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import me.dylanburton.blastarreborn.enemies.Enemy; import me.dylanburton.blastarreborn.enemies.Fighter; import me.dylanburton.blastarreborn.lasers.ShipLaser; /** * Represents the main screen of play for the game. * */ public class PlayScreen extends Screen { private MainActivity act; private Paint p; //how fast the spaceship moves backwards private final int DECAY_SPEED=5; private final int LEVEL_FIGHTER = 1; // level where different ships are added private final int LEVEL_IMPERIAL = 3; private final int LEVEL_BATTLECRUISER = 4; private final int LEVEL_BATTLESHIP = 5; private final int LEVEL_BERSERKER = 6; static final long ONESEC_NANOS = 1000000000L; private enum State { RUNNING, STARTROUND, ROUNDSUMMARY, STARTGAME, PLAYERDIED, GAMEOVER } private volatile State gamestate = State.STARTGAME; //lists private List<Enemy> enemiesFlying = Collections.synchronizedList(new LinkedList<Enemy>()); // enemies that are still alive private List<ShipExplosion> shipExplosions = new LinkedList<ShipExplosion>(); // ship explosions private List<ShipLaser> enemyShipLasers; // Enemy ships lasers //width and height of screen private int width = 0; private int height = 0; //bitmap with a rect used for drawing private Bitmap starbackground, spaceship[], spaceshipLaser, fighter, fighterOrb, hitFighter, explosion[]; private Rect scaledDst = new Rect(); //main spaceships location and bound, using 1000 for spaceshipy and x because of a weird glitch where the spaceship is drawn at 0,0 for 100 ms private int spaceshipY=0; private int spaceshipX=0; private int currentSpaceshipFrame=0; //frame of spaceship for animation private Rect spaceshipBounds; private boolean spaceshipIsMoving; private int spaceshipLaserX; private int spaceshipLaserY; //used to move the background image, need two pairs of these vars for animation private int mapAnimatorX; private int mapAnimatorY; private int secondaryMapAnimatorX; private int secondaryMapAnimatorY; //time stuff private long hitContactTime = 0; //for if the laser hits the enemy private long spaceshipFrameSwitchTime = 0; //for spaceships fire animation private long frtime = 0; //the global time private long gameStartTime = 0; private int fps = 0; //various game things private int minRoundPass; private int currentLevel; private int score; private int lives; private int highscore=0, highlev=1; private static final String HIGHSCORE_FILE = "highscore.dat"; private static final int START_NUMLIVES = 3; private Map<Integer, String> levelMap = new HashMap<>(); //some AI Movement vars, to see how it works, look in Enemy class private boolean startDelayReached = false; private Random rand = new Random(); public PlayScreen(MainActivity act) { p = new Paint(); this.act = act; AssetManager assetManager = act.getAssets(); try { //background InputStream inputStream = assetManager.open("sidescrollingstars.jpg"); starbackground = BitmapFactory.decodeStream(inputStream); inputStream.close(); //your spaceship and laser spaceship = new Bitmap[2]; spaceship[0] = act.getScaledBitmap("spaceship/spaceshiptopview1.png"); spaceship[1] = act.getScaledBitmap("spaceship/spaceshiptopview2.png"); spaceshipLaser = act.getScaledBitmap("spaceshiplaser.png"); //fighter fighter = act.getScaledBitmap("fighter.png"); hitFighter = act.getScaledBitmap("hitfighter.png"); fighterOrb = act.getScaledBitmap("enemyorbs.png"); //explosion explosion = new Bitmap[12]; for(int i = 0; i < 12; i++) { explosion[i] = act.getScaledBitmap("explosion/explosion"+(i+1)+".png"); } p.setTypeface(act.getGameFont()); currentLevel = 1; } catch (IOException e) { Log.d(act.LOG_ID, "why tho?", e); } } /** * initialize and start a game */ void initGame() { //used for slight delays on spawning things at the beginning gameStartTime = System.nanoTime(); score = 0; currentLevel = 1; lives = START_NUMLIVES; highscore = 0; if(currentLevel == 1){ enemiesFlying.add(new Fighter(fighter, fighterOrb)); enemiesFlying.add(new Fighter(fighter, fighterOrb)); } try { BufferedReader f = new BufferedReader(new FileReader(act.getFilesDir() + HIGHSCORE_FILE)); highscore = Integer.parseInt(f.readLine()); highlev = Integer.parseInt(f.readLine()); f.close(); } catch (Exception e) { Log.d(MainActivity.LOG_ID, "ReadHighScore", e); } gamestate = State.STARTGAME; } public void resetGame(){ gamestate = State.STARTROUND; width = 0; height = 0; enemiesFlying.clear(); startDelayReached = false; for(Enemy e: enemiesFlying){ e.setFinishedVelocityChange(false); e.setAIStarted(false); } } /** * init game for current round */ private void initRound() { // how many enemies do we need to kill to progress? if (currentLevel == 1) minRoundPass = 10; else if (currentLevel < 4) minRoundPass = 30; else minRoundPass = 40; gamestate = State.RUNNING; } /** * player lost a life */ private void loseLife() { lives if (lives == 0) { // game over! wrap things up and write high score file gamestate = State.GAMEOVER; try { BufferedWriter f = new BufferedWriter(new FileWriter(act.getFilesDir() + HIGHSCORE_FILE)); f.write(Integer.toString(highscore)+"\n"); f.write(Integer.toString(highlev)+"\n"); f.close(); } catch (Exception e) { // if we can't write the high score file...oh well. Log.d(MainActivity.LOG_ID, "WriteHiScore", e); } } else gamestate = State.PLAYERDIED; } @Override public void update(View v) { long newtime = System.nanoTime(); float elapsedsecs = (float) (newtime - frtime) / ONESEC_NANOS; frtime = newtime; fps = (int) (1 / elapsedsecs); if (gamestate == State.STARTROUND) { initRound(); return; } if (width == 0) { // set variables that rely on screen size width = v.getWidth(); height = v.getHeight(); spaceshipX = width / 2; spaceshipY = height * 2 / 3; spaceshipLaserX = spaceshipX+spaceship[0].getWidth()/8; spaceshipLaserY = spaceshipY+spaceship[0].getHeight()/3; mapAnimatorX = width; mapAnimatorY = height; secondaryMapAnimatorX = width; secondaryMapAnimatorY = height; } if (gamestate == State.RUNNING) { } synchronized (enemiesFlying) { Iterator<Enemy> enemiesIterator = enemiesFlying.iterator(); while (enemiesIterator.hasNext()) { Enemy e = enemiesIterator.next(); //delay of 100 ms before enemies spawn if (gameStartTime + (ONESEC_NANOS / 10) < frtime) { startDelayReached = true; } /* * Firing AI */ if(e.getEnemyFiringTime()+ (e.getRandomlyGeneratedEnemyFiringTimeInSeconds()*ONESEC_NANOS) < frtime && startDelayReached){ e.setEnemyFiringTime(System.nanoTime()); e.setRandomlyGeneratedEnemyFiringTimeInSeconds((rand.nextInt(3000))/1000); e.spawnShipLasers(); } //updates ships laser positions if(e.getShipLaserPositionsList().size() > 0){ e.updateShipLaserPositions(); } /* * Movement AI */ //handles collision for multiple enemies for (int i = 0; i < enemiesFlying.size(); i++) { if ((e != enemiesFlying.get(i))) { if ((e.getX() >= enemiesFlying.get(i).getX() - enemiesFlying.get(i).getBitmap().getWidth() && e.getX() <= enemiesFlying.get(i).getX() + enemiesFlying.get(i).getBitmap().getWidth()) && (e.getY() >= enemiesFlying.get(i).getY() - enemiesFlying.get(i).getBitmap().getHeight() && e.getY() <= enemiesFlying.get(i).getY() + enemiesFlying.get(i).getBitmap().getHeight())) { e.setVx(-e.getVx()); } } } if (!e.isAIStarted()) { e.setX(rand.nextInt(width * 4 / 5)); e.setY(-height / 10); e.setFinishedVelocityChange(true); e.setAIStarted(true); } if (startDelayReached) { e.setX(e.getX() + e.getVx()); e.setY(e.getY() + e.getVy()); } if (e.isFinishedVelocityChange()) { e.setRandomVelocityGeneratorX((rand.nextInt(10000) + 1000) / 1000); e.setRandomVelocityGeneratorY((rand.nextInt(10000) + 1000) / 1000); //makes it negative if it is bigger than 5 if (e.getRandomVelocityGeneratorX() > 5) { e.setRandomVelocityGeneratorX(e.getRandomVelocityGeneratorX() - 11); } if (e.getRandomVelocityGeneratorY() > 5) { e.setRandomVelocityGeneratorY(e.getRandomVelocityGeneratorY() - 11); } //makes the ship change direction soon if they are in a naughty area if (e.getY() > height / 6) { if (e.getRandomVelocityGeneratorY() > 0) { e.setRandomVelocityGeneratorY(-e.getRandomVelocityGeneratorY()); } } else if (e.getY() < height / 12) { if (e.getRandomVelocityGeneratorY() < 0) { e.setRandomVelocityGeneratorY(-e.getRandomVelocityGeneratorY()); } } if (!e.isSlowingDown()) { e.setSpeedingUp(true); } e.setFinishedRandomGeneratorsTime(System.nanoTime()); //just initiating these guys e.setLastSlowedDownVelocityTime(e.getFinishedRandomGeneratorsTime()); e.setLastSpedUpVelocityTime(e.getFinishedRandomGeneratorsTime()); e.setFinishedVelocityChange(false); } if (e.isSlowingDown() && (frtime > e.getLastSlowedDownVelocityTime() + (ONESEC_NANOS / 100))) { //obv will never be 0. Half a second for slowing down, then speeding up e.setVx(e.getVx() - (e.getVx() / 50)); e.setVy(e.getVy() - (e.getVy() / 50)); //borders if (e.getX() < 0 || e.getX() > width * 4 / 5) { //this check disables the ability for ship to get too far and then freeze in place if (e.getX() < 0) { e.setX(0); } else if (e.getX() > width * 4 / 5) { e.setX(width * 4 / 5); } e.setVx(-e.getVx()); e.setRandomVelocityGeneratorX(-e.getRandomVelocityGeneratorX()); } //so we do this if ((e.getVx() > -1 && e.getVx() < 1) && (e.getVy() > -1 && e.getVy() < 1)) { e.setSlowingDown(false); e.setSpeedingUp(true); } //delays this slowing down process a little e.setLastSlowedDownVelocityTime(System.nanoTime()); } else if (e.isSpeedingUp() && (frtime > e.getLastSpedUpVelocityTime() + (ONESEC_NANOS / 100))) { //will not have asymptotes like the last one e.setVx(e.getVx() + (e.getRandomVelocityGeneratorX() / 50)); e.setVy(e.getVy() + (e.getRandomVelocityGeneratorY() / 50)); //borders for x and y if (e.getX() < 0 || e.getX() > width * 4 / 5) { //this check disables the ability for ship to get too far and then freeze in place if (e.getX() < 0) { e.setX(0); } else if (e.getX() > width * 4 / 5) { e.setX(width * 4 / 5); } e.setVx(-e.getVx()); e.setRandomVelocityGeneratorX(-e.getRandomVelocityGeneratorX()); } //just adding a margin of error regardless though, if the nanoseconds were slightly off it would not work if ((e.getVx() > e.getRandomVelocityGeneratorX() - 1 && e.getVx() < e.getRandomVelocityGeneratorX() + 1) && (e.getVy() > e.getRandomVelocityGeneratorY() - 1 || e.getVy() < e.getRandomVelocityGeneratorY() + 1)) { e.setSlowingDown(true); e.setSpeedingUp(false); e.setFinishedVelocityChange(true); } e.setLastSpedUpVelocityTime(System.nanoTime()); } } } //spaceship decay if (spaceshipY < height * 4 / 5 && !spaceshipIsMoving) { spaceshipY += DECAY_SPEED; } //resets spaceship laser spaceshipLaserY -= 20.0f; if (spaceshipLaserY < -height / 6) { spaceshipLaserY = spaceshipY + spaceship[0].getHeight() / 3; spaceshipLaserX = spaceshipX + spaceship[0].getWidth() / 8; } //animator for map background mapAnimatorY += 2.0f; secondaryMapAnimatorY += 2.0f; //this means the stars are off the screen if (mapAnimatorY >= height * 2) { mapAnimatorY = height; } else if (secondaryMapAnimatorY >= height * 2) { secondaryMapAnimatorY = height; } //resets spaceship laser spaceshipLaserY -= 20.0f; if (spaceshipLaserY < -height / 6) { spaceshipLaserY = spaceshipY + spaceship[0].getHeight() / 3; spaceshipLaserX = spaceshipX + spaceship[0].getWidth() / 8; } } @Override public void draw(Canvas c, View v) { try { // actually draw the screen scaledDst.set(mapAnimatorX-width, mapAnimatorY-height, mapAnimatorX, mapAnimatorY); c.drawBitmap(starbackground,null,scaledDst,p); //secondary background for animation. Same as last draw, but instead, these are a height-length higher c.drawBitmap(starbackground,null,new Rect(secondaryMapAnimatorX-width, secondaryMapAnimatorY-(height*2),secondaryMapAnimatorX, secondaryMapAnimatorY-height),p); synchronized (shipExplosions) { for(ShipExplosion se: shipExplosions){ c.drawBitmap(explosion[se.currentFrame],se.x,se.y,p); //semi-clever way of adding a very precise delay (yes, I am scratching my own ass) if(hitContactTime + (ONESEC_NANOS/50) < frtime) { hitContactTime = System.nanoTime(); se.nextFrame(); } if(se.currentFrame == 11){ shipExplosions.remove(se.getExplosionNumber()); } } } synchronized (enemiesFlying) { for(Enemy e: enemiesFlying) { if(startDelayReached) { //drawing enemy lasers if(e.getShipLaserPositionsList().size() > 0){ this.enemyShipLasers = e.getShipLaserPositionsList(); for(ShipLaser sl: enemyShipLasers){ c.drawBitmap(sl.getBmp(), sl.getX(), sl.getY(), p); } } //puts like a red tinge on the enemy for 100 ms if hes hit if(e.isEnemyHitButNotDead()){ c.drawBitmap(hitFighter, e.getX(), e.getY(), p); if(hitContactTime + (ONESEC_NANOS/10) <frtime){ e.setEnemyIsHitButNotDead(false); } }else { c.drawBitmap(e.getBitmap(), e.getX(), e.getY(), p); } if ((e.hasCollision(spaceshipLaserX, spaceshipLaserY) || e.hasCollision(spaceshipLaserX + spaceship[0].getWidth() * 64 / 100, spaceshipLaserY))) { spaceshipLaserX = 4000; hitContactTime = System.nanoTime(); //subtract a life e.setLives(e.getLives()-1); //fun explosions if(e.getLives() == 0) { shipExplosions.add(new ShipExplosion(e.getX() - e.getBitmap().getWidth() * 3 / 4, e.getY() - e.getBitmap().getHeight() / 2, shipExplosions.size())); //bye bye e.setX(10000); e.setY(10000); e.setExplosionActivateTime(System.nanoTime()); }else{ e.setEnemyIsHitButNotDead(true); } } //deletes ship in 5 seconds if(e.getExplosionActivateTime() + (ONESEC_NANOS*5) < frtime && e.getLives() == 0){ enemiesFlying.remove(e); } } } } //main spaceship lasers c.drawBitmap(spaceshipLaser, spaceshipLaserX, spaceshipLaserY, p); c.drawBitmap(spaceshipLaser, spaceshipLaserX + spaceship[0].getWidth() * 64 / 100, spaceshipLaserY, p); //main spaceship for(int i = 0; i<spaceship.length; i++) { if(i == currentSpaceshipFrame && frtime>spaceshipFrameSwitchTime + (ONESEC_NANOS/10)) { if(currentSpaceshipFrame == spaceship.length-1){ currentSpaceshipFrame = 0; }else{ currentSpaceshipFrame++; } c.drawBitmap(spaceship[i], spaceshipX, spaceshipY, p); spaceshipFrameSwitchTime = System.nanoTime(); }else if(i==currentSpaceshipFrame){ c.drawBitmap(spaceship[i], spaceshipX, spaceshipY, p); } } p.setColor(Color.WHITE); p.setTextSize(act.TS_NORMAL); p.setTypeface(act.getGameFont()); if (score >= highscore) { highscore = score; highlev = currentLevel; } if (gamestate == State.ROUNDSUMMARY || gamestate == State.STARTGAME || gamestate == State.PLAYERDIED || gamestate == State.GAMEOVER) { if (gamestate != State.STARTGAME) { // round ended, by completion or player death, display stats if (gamestate == State.ROUNDSUMMARY) { } else if (gamestate == State.PLAYERDIED || gamestate == State.GAMEOVER){ } } if (gamestate != State.PLAYERDIED && gamestate != State.GAMEOVER) { } if (gamestate != State.GAMEOVER) { } } if (gamestate == State.GAMEOVER) { /*p.setTextSize(act.TS_BIG); p.setColor(Color.RED); drawCenteredText(c, "GamE oVeR!", height /2, p, -2); drawCenteredText(c, "Touch to end game", height * 4 /5, p, -2); p.setColor(Color.WHITE); drawCenteredText(c, "GamE oVeR!", height /2, p, 0); drawCenteredText(c, "Touch to end game", height * 4 /5, p, 0);*/ } } catch (Exception e) { Log.e(MainActivity.LOG_ID, "draw", e); e.printStackTrace(); } } //center text private void drawCenteredText(Canvas c, String msg, int height, Paint p, int shift) { c.drawText(msg, (width - p.measureText(msg)) / 2 + shift, height, p); } DisplayMetrics dm = new DisplayMetrics(); @Override public boolean onTouch(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: synchronized (spaceship){ spaceshipBounds = new Rect(spaceshipX,spaceshipY,spaceshipX+spaceship[0].getWidth(),spaceshipY+spaceship[0].getHeight()); if(spaceshipBounds.contains((int) e.getX(),(int) e.getY())){ spaceshipIsMoving = true; spaceshipX = (int) e.getX()-spaceship[0].getWidth()/2; spaceshipY = (int) e.getY()-spaceship[0].getHeight()/2; } } break; case MotionEvent.ACTION_UP: spaceshipIsMoving=false; break; } return true; } //this is for creating multiple ship explosion animations private class ShipExplosion{ float x=0; float y=0; int currentFrame = 0; int explosionNumber = 0; public ShipExplosion(float x, float y, int explosionNumber){ this.x = x; this.y = y; this.explosionNumber = explosionNumber; } public int getCurrentFrame(){ return currentFrame; } public void nextFrame(){ currentFrame++; } public int getExplosionNumber(){ return explosionNumber; } } }
package uk.co.pilllogger.dialogs; import android.graphics.Typeface; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import uk.co.pilllogger.R; import uk.co.pilllogger.models.Pill; import uk.co.pilllogger.state.State; import uk.co.pilllogger.tasks.UpdatePillTask; import uk.co.pilllogger.views.ColourIndicator; public class PillInfoDialog extends InfoDialog { private PillInfoDialogListener _listener; public PillInfoDialog(){ super(); } public PillInfoDialog(Pill pill, PillInfoDialogListener listener) { super(pill); _listener = listener; } @Override protected int getLayoutId() { return R.layout.pill_info_dialog; } @Override protected void setupMenu(View view) { TextView addConsumption = (TextView) view.findViewById(R.id.info_dialog_add_consumption); TextView delete = (TextView) view.findViewById(R.id.info_dialog_delete); final TextView changeColour = (TextView) view.findViewById(R.id.info_dialog_change_colour); TextView favourite = (TextView) view.findViewById(R.id.info_dialog_set_favourite); Typeface typeface = State.getSingleton().getTypeface(); addConsumption.setTypeface(typeface); delete.setTypeface(typeface); changeColour.setTypeface(typeface); favourite.setTypeface(typeface); if(_pill == null) { dismiss(); return; } if (_pill.isFavourite()) favourite.setText(getResources().getString(R.string.info_dialog_unset_favourite)); addConsumption.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _listener.onDialogAddConsumption(_pill, PillInfoDialog.this); } }); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _listener.onDialogDelete(_pill, PillInfoDialog.this); } }); favourite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _listener.setDialogFavourite(_pill, PillInfoDialog.this); } }); final View mainView = view; final uk.co.pilllogger.views.ColourIndicator colourTop = (uk.co.pilllogger.views.ColourIndicator) view.findViewById(R.id.colour); changeColour.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final View colourHolder = mainView.findViewById(R.id.info_dialog_colour_picker_container); final ViewGroup colourContainer = (ViewGroup) colourHolder.findViewById(R.id.colour_container); if (colourHolder.getVisibility() == View.VISIBLE) { int colourCount = colourContainer.getChildCount(); for (int i = 0; i < colourCount; i++) { View colourView = colourContainer.getChildAt(i); if (colourView != null) { colourView.setOnClickListener(null); } } colourHolder.setVisibility(View.GONE); } else { colourHolder.setVisibility(View.VISIBLE); int colourCount = colourContainer.getChildCount(); for (int i = 0; i < colourCount; i++) { View colourView = colourContainer.getChildAt(i); if (colourView != null) { colourView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int colour = ((ColourIndicator) view).getColour(); colourTop.setColour(colour); colourHolder.setVisibility(View.GONE); _pill.setColour(colour); _listener.onDialogChangePillColour(_pill, PillInfoDialog.this); } }); } } } } }); } public interface PillInfoDialogListener { public void onDialogAddConsumption(Pill pill, InfoDialog dialog); public void onDialogDelete(Pill pill, InfoDialog dialog); public void setDialogFavourite(Pill pill, InfoDialog dialog); public void onDialogChangePillColour(Pill pill, InfoDialog dialog); } }
package org.commcare.android.references; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.logic.GlobalConstants; import org.javarosa.core.reference.Reference; import org.javarosa.core.services.Logger; /** * @author ctsims * */ public class JavaHttpReference implements Reference { private String uri; public JavaHttpReference(String uri) { this.uri = uri; } /* (non-Javadoc) * @see org.javarosa.core.reference.Reference#doesBinaryExist() */ public boolean doesBinaryExist() throws IOException { //For now.... return true; } /* (non-Javadoc) * @see org.javarosa.core.reference.Reference#getOutputStream() */ public OutputStream getOutputStream() throws IOException { throw new IOException("Http references are read only!"); } /* (non-Javadoc) * @see org.javarosa.core.reference.Reference#getStream() */ public InputStream getStream() throws IOException { URL url = new URL(uri); HttpURLConnection con = (HttpURLConnection) url.openConnection(); setup(con); // Start the query con.connect(); //It's possible we're getting redirected from http to https //if so, we need to handle it explicitly if(con.getResponseCode() == 301) { //only allow one level of redirection here for now. Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Attempting 1 stage redirect from " + uri + " to " + con.getURL().toString()); URL newUrl = con.getURL(); con.disconnect(); con = (HttpURLConnection) newUrl.openConnection(); setup(con); con.connect(); } //Don't allow redirects _from_ https _to_ https unless they are redirecting to the same server. if(!isValidRedirect(url, con.getURL())) { Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Invalid redirect from " + uri + " to " + con.getURL().toString()); throw new IOException("Invalid redirect from secure server to insecure server"); } return con.getInputStream(); } private boolean isValidRedirect(URL url, URL newUrl) { //unless it's https, don't worry about it if(!url.getProtocol().equals("https")) { return true; } //if it is, verify that we're on the same server. if(url.getHost().equals(newUrl.getHost())) { return true; } else { //otherwise we got redirected from a secure link to a different //link, which isn't acceptable for now. return false; } } private void setup(HttpURLConnection con) throws IOException { con.setConnectTimeout(GlobalConstants.CONNECTION_TIMEOUT); con.setRequestMethod("GET"); con.setDoInput(true); con.setInstanceFollowRedirects(true); } /* (non-Javadoc) * @see org.javarosa.core.reference.Reference#getURI() */ public String getURI() { return uri; } /* (non-Javadoc) * @see org.javarosa.core.reference.Reference#isReadOnly() */ public boolean isReadOnly() { return true; } /* (non-Javadoc) * @see org.javarosa.core.reference.Reference#remove() */ public void remove() throws IOException { throw new IOException("Http references are read only!"); } public String getLocalURI() { return uri; } public Reference[] probeAlternativeReferences() { return new Reference [0]; } }
package cn.sunner.sms2calendar; import org.junit.Test; import java.util.Calendar; import java.util.GregorianCalendar; import static org.junit.Assert.*; public class N12306ParserTest { @Test public void testOneSeat() throws Exception { SMSParser parser = new N12306Parser("EC11541789,124D22451413F19:11"); assertTrue(parser.isValid()); assertEquals("D22451413F", parser.getTitle()); assertEquals("", parser.getLocation()); assertEquals(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), 1, 24, 19, 11), parser.getBeginTime()); } @Test public void testTwoSeatsAndChanged() throws Exception { SMSParser parser = new N12306Parser("EC71177015,129D22451412D4C19:11"); assertTrue(parser.isValid()); assertEquals("D22451412D4C", parser.getTitle()); assertEquals("", parser.getLocation()); assertEquals(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), 12, 9, 19, 11), parser.getBeginTime()); } @Test public void testTwoBeds() throws Exception { SMSParser parser = new N12306Parser("EC76805753,21Z1761231369:30"); assertTrue(parser.isValid()); assertEquals("Z176123136", parser.getTitle()); assertEquals("", parser.getLocation()); assertEquals(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), 2, 1, 9, 30), parser.getBeginTime()); } @Test public void testNotValid() throws Exception { SMSParser parser = new N12306Parser("24G7394815B2EC84941031001001222209833"); assertFalse(parser.isValid()); } }
package org.commcare.dalvik.application; import java.io.File; import net.sqlcipher.database.SQLiteDatabase; import org.commcare.android.database.DbHelper; import org.commcare.android.database.SqlStorage; import org.commcare.android.database.app.DatabaseAppOpenHelper; import org.commcare.android.database.global.models.ApplicationRecord; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.logic.GlobalConstants; import org.commcare.android.references.JavaFileRoot; import org.commcare.android.storage.framework.Table; import org.commcare.android.util.AndroidCommCarePlatform; import org.commcare.android.util.Stylizer; import org.commcare.dalvik.preferences.CommCarePreferences; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.services.storage.StorageFullException; import org.javarosa.core.util.UnregisteredLocaleException; import android.content.SharedPreferences; import android.util.Log; /** * This (awkwardly named!) container is responsible for keeping track of a single * CommCare "App". It should be able to set up an App, break it back down, and * maintain all of the code needed to sandbox applicaitons * * @author ctsims */ public class CommCareApp { private final ApplicationRecord record; private JavaFileRoot fileRoot; private final AndroidCommCarePlatform platform; private static final String TAG = CommCareApp.class.getSimpleName(); private static final Object lock = new Object(); // This unfortunately can't be managed entirely by the application object, // so we have to do some here public static CommCareApp currentSandbox; private final Object appDbHandleLock = new Object(); private SQLiteDatabase appDatabase; private static Stylizer mStylizer; public CommCareApp(ApplicationRecord record) { this.record = record; // Now, we need to identify the state of the application resources int[] version = CommCareApplication._().getCommCareVersion(); // TODO: Badly coupled platform = new AndroidCommCarePlatform(version[0], version[1], this); } public Stylizer getStylizer(){ return mStylizer; } public String storageRoot() { // This External Storage Directory will always destroy your data when you upgrade, which is stupid. Unfortunately // it's also largely unavoidable until Froyo's fix for this problem makes it to the phones. For now we're going // to rely on the fact that the phone knows how to fix missing/corrupt directories every time it upgrades. return CommCareApplication._().getAndroidFsRoot() + "app/" + record.getApplicationId() + "/"; } void createPaths() { String[] paths = new String[]{"", GlobalConstants.FILE_CC_INSTALL, GlobalConstants.FILE_CC_UPGRADE, GlobalConstants.FILE_CC_CACHE, GlobalConstants.FILE_CC_FORMS, GlobalConstants.FILE_CC_MEDIA, GlobalConstants.FILE_CC_LOGS, GlobalConstants.FILE_CC_ATTACHMENTS}; for (String path : paths) { File f = new File(fsPath(path)); if (!f.exists()) { f.mkdirs(); } } } public String fsPath(String relative) { return storageRoot() + relative; } private void initializeFileRoots() { synchronized (lock) { String root = storageRoot(); fileRoot = new JavaFileRoot(root); String testFileRoot = "jr://file/mytest.file"; // Assertion: There should be _no_ other file roots when we initialize try { String testFilePath = ReferenceManager._().DeriveReference(testFileRoot).getLocalURI(); String message = "Cannot setup sandbox. An Existing file root is set up, which directs to: " + testFilePath; Logger.log(AndroidLogger.TYPE_ERROR_DESIGN, message); throw new IllegalStateException(message); } catch (InvalidReferenceException ire) { // Expected. } ReferenceManager._().addReferenceFactory(fileRoot); // Double check that things point to the right place? } } public SharedPreferences getAppPreferences() { return CommCareApplication._().getSharedPreferences(getPreferencesFilename(), 0); } public void setupSandbox() { setupSandbox(true); } void initializeStylizer() { mStylizer = new Stylizer(CommCareApplication._().getApplicationContext()); } /** * @param createFilePaths True if file paths should be created as usual. False otherwise */ public void setupSandbox(boolean createFilePaths) { synchronized (lock) { Logger.log(AndroidLogger.TYPE_RESOURCES, "Staging Sandbox: " + record.getApplicationId()); if (currentSandbox != null) { currentSandbox.teardownSandbox(); } // general setup if (createFilePaths) { createPaths(); } initializeFileRoots(); currentSandbox = this; } } /** * If the CommCare app being initialized was first installed on this device with pre-Multiple * Apps build of CommCare, then its ApplicationRecord will have been generated from an * older format with missing fields. This method serves to fill in those missing fields, * and is called after initializeApplication, if and only if the ApplicationRecord has just * been generated from the old format. Once the update for an AppRecord performs once, it will * not be performed again. */ private void updateAppRecord() { // uniqueId and displayName will be missing, so pull them from the app's profile file record.setUniqueId(getUniqueId()); record.setDisplayName(getDisplayName()); // Similarly, the default value this field was set to may be incorrect, so check it record.setResourcesStatus(areResourcesValidated()); // Set this to false so we don't try to update this app record every time we seat it record.setConvertedByDbUpgrader(false); // Commit changes CommCareApplication._().getGlobalStorage(ApplicationRecord.class).write(record); } public boolean initializeApplication() { boolean appReady = initializeApplicationHelper(); if (appReady) { if (record.convertedByDbUpgrader()) { updateAppRecord(); } } return appReady; } public boolean initializeApplicationHelper() { setupSandbox(); ResourceTable global = platform.getGlobalResourceTable(); ResourceTable upgrade = platform.getUpgradeResourceTable(); ResourceTable recovery = platform.getRecoveryTable(); Log.d(TAG, "Global\n" + global.toString()); Log.d(TAG, "Upgrade\n" + upgrade.toString()); Log.d(TAG, "Recovery\n" + recovery.toString()); // See if any of our tables got left in a weird state if (global.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNCOMMITED) { global.rollbackCommits(); Log.d(TAG, "Global after rollback\n" + global.toString()); } if (upgrade.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNCOMMITED) { upgrade.rollbackCommits(); Log.d(TAG, "upgrade after rollback\n" + upgrade.toString()); } // See if we got left in the middle of an update if(global.getTableReadiness() == ResourceTable.RESOURCE_TABLE_UNSTAGED) { // If so, repair the global table. (Always takes priority over maintaining the update) global.repairTable(upgrade); } // TODO: This, but better. Resource profile = global.getResourceWithId("commcare-application-profile"); if (profile != null && profile.getStatus() == Resource.RESOURCE_STATUS_INSTALLED) { platform.initialize(global); try { Localization.setLocale(getAppPreferences().getString("cur_locale", "default")); } catch (UnregisteredLocaleException urle) { Localization.setLocale(Localization.getGlobalLocalizerAdvanced().getAvailableLocales()[0]); } initializeStylizer(); return true; } return false; } public boolean areResourcesValidated() { SharedPreferences appPreferences = getAppPreferences(); return (appPreferences.getBoolean("isValidated", false) || appPreferences.getString(CommCarePreferences.CONTENT_VALIDATED, "no").equals(CommCarePreferences.YES)); } public void setResourcesValidated() { SharedPreferences.Editor editor = getAppPreferences().edit(); editor.putBoolean("isValidated", true); editor.commit(); record.setResourcesStatus(true); CommCareApplication._().getGlobalStorage(ApplicationRecord.class).write(record); } public void teardownSandbox() { synchronized (lock) { Logger.log(AndroidLogger.TYPE_RESOURCES, "Tearing down sandbox: " + record.getApplicationId()); ReferenceManager._().removeReferenceFactory(fileRoot); synchronized (appDbHandleLock) { if (appDatabase != null) { appDatabase.close(); } appDatabase = null; } } } public AndroidCommCarePlatform getCommCarePlatform() { return platform; } public <T extends Persistable> SqlStorage<T> getStorage(Class<T> c) { return getStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getStorage(String name, Class<T> c) { return new SqlStorage<T>(name, c, new DbHelper(CommCareApplication._().getApplicationContext()) { /* * (non-Javadoc) * @see org.commcare.android.database.DbHelper#getHandle() */ @Override public SQLiteDatabase getHandle() { synchronized (appDbHandleLock) { if (appDatabase == null || !appDatabase.isOpen()) { appDatabase = new DatabaseAppOpenHelper(this.c, record.getApplicationId()).getWritableDatabase("null"); } return appDatabase; } } }); } public void writeInstalled() { record.setStatus(ApplicationRecord.STATUS_INSTALLED); record.setUniqueId(getUniqueId()); record.setDisplayName(getDisplayName()); record.setResourcesStatus(areResourcesValidated()); record.setPreMultipleAppsProfile(checkFromOldProfile()); try { CommCareApplication._().getGlobalStorage(ApplicationRecord.class).write(record); } catch (StorageFullException e) { throw new RuntimeException(e); } } public String getPreferencesFilename() { return record.getApplicationId(); } /** * @return whether this CommCareApp is from a profile file that was generated by a * pre-Multiple Apps build of CommCare */ private boolean checkFromOldProfile() { return getCommCarePlatform().getCurrentProfile().isOldVersion(); } /** * @return the uniqueId assigned to this app from HQ */ public String getUniqueId() { //If this record has already been assigned the unique id, pull it from there String id = record.getUniqueId(); if (id == null || id.equals("")) { //Otherwise, trying pulling it from the profile file id = getCommCarePlatform().getCurrentProfile().getUniqueId(); } return id; } /** * @return the app name assigned to this app from HQ -- either from the profile file if it was * included there, or from the localization strings if it was not */ private String getDisplayName() { String nameFromProfile = getCommCarePlatform().getCurrentProfile().getDisplayName(); if (!"".equals(nameFromProfile)) { return nameFromProfile; } return Localization.get("app.display.name"); } public ApplicationRecord getAppRecord() { return this.record; } }
package com.networknt.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Map; public class EnvConfig { static final Logger logger = LoggerFactory.getLogger(EnvConfig.class); public static void injectMapEnv(Map<String, Object> map) { for (Map.Entry<String, Object> entry : map.entrySet()) { String value = (String) entry.getValue(); if (isEnvReference(value)) { EnvEntity envEntity = getEnvEntity(value); if (envEntity != null) { String envName = envEntity.getEnvName(); Object envVariable = getEnvVariable(envName); if (envVariable != null) { map.put(entry.getKey(), envVariable); } else if (envEntity.getDefaultValue() != null) { map.put(entry.getKey(), envEntity.getDefaultValue()); } else if (envEntity.getErrorText() != null) { logger.info(envEntity.getErrorText()); map.put(entry.getKey(), null); } else { logger.info("The environment variable:" + envName + " cannot be expanded."); map.put(entry.getKey(), null); } } else { logger.info("The environment variable reference is empty."); map.put(entry.getKey(), null); } } else if (isEscapeReference(value)) { map.put(entry.getKey(), null); } } } public static void injectObjectEnv(Object obj) { String[] fieldNames = getFieldName(obj); for (int i = 0; i < fieldNames.length; i++) { String value = (String) getFieldValueByName(fieldNames[i], obj); if (isEnvReference(value)) { EnvEntity envEntity = getEnvEntity(value); if (envEntity != null) { String envName = envEntity.getEnvName(); Object envVariable = getEnvVariable(envName); if (envVariable != null) { setFieldValue(fieldNames[i], envVariable, obj); } else if (envEntity.getDefaultValue() != null) { setFieldValue(fieldNames[i], envEntity.getDefaultValue(), obj); } else if (envEntity.getErrorText() != null) { logger.info(envEntity.getErrorText()); setFieldValue(fieldNames[i], null, obj); } else { logger.info("The environment variable:" + envName + " cannot be expanded."); setFieldValue(fieldNames[i], null, obj); } } else { logger.info("The environment variable reference is empty."); setFieldValue(fieldNames[i], null, obj); } } else if (isEscapeReference(value)) { setFieldValue(fieldNames[i], null, obj); } } } private static EnvEntity getEnvEntity(String envReference) { String contents = getContents(envReference); EnvEntity envEntity = new EnvEntity(); if (contents == null || contents.equals("")) { return null; } String[] rfcArray = contents.split(":", 2); rfcArray[0] = rfcArray[0].trim(); if ("".equals(rfcArray[0])) { return null; } envEntity.setEnvName(rfcArray[0]); if (rfcArray.length == 2) { rfcArray[1] = rfcArray[1].trim(); if (rfcArray[1].startsWith("?")) { envEntity.setErrorText(rfcArray[1].substring(1)); } else { envEntity.setDefaultValue(rfcArray[1]); } } return envEntity; } private static Object getEnvVariable(String envName) { return System.getenv(envName); } private static boolean isEnvReference(String envName) { return envName.startsWith("${") && envName.endsWith("}"); } private static boolean isEscapeReference(String envName) { return envName.startsWith("$${") && envName.endsWith("}"); } private static String getContents(String envReference) { return envReference.substring(2, envReference.length() - 1); } private static String[] getFieldName(Object obj) { Field[] fields = obj.getClass().getDeclaredFields(); String[] fieldName = new String[fields.length]; for (int i = 0; i < fields.length; i++) { fieldName[i] = fields[i].getName(); } return fieldName; } private static Object getFieldValueByName(String fieldName, Object obj) { String getter = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Method method = obj.getClass().getMethod(getter, new Class[]{}); Object value = method.invoke(obj, new Object[]{}); return value; } catch (Exception e) { logger.error(e.getMessage(), e); return null; } } private static void setFieldValue(String fieldName, Object fieldValue, Object obj) { String setter = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); String getter = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Method method = obj.getClass().getMethod(setter, getReturnTypeFromGetterMethod(getter, obj)); method.invoke(obj, fieldValue); } catch (Exception e) { logger.error(e.getMessage(), e); } } private static Class<?> getReturnTypeFromGetterMethod(String getter, Object obj) { try { Method method = obj.getClass().getMethod(getter, new Class[]{}); return method.getReturnType(); } catch (NoSuchMethodException e) { logger.error(e.getMessage(), e); return null; } } private static class EnvEntity { private String envName; private String defaultValue; private String errorText; public String getErrorText() { return errorText; } public void setErrorText(String errorTest) { this.errorText = errorTest; } public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public String getEnvName() { return envName; } public void setEnvName(String envName) { this.envName = envName; } } }
package org.aksw.limes.spark; import com.google.common.collect.Lists; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.spark.api.java.function.MapFunction; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructType; public class Main { public static int partitions = 768; private final SparkSession spark = SparkSession.builder() .appName("LIMES HR3") .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") .config("spark.dynamicAllocation.enabled", false) .getOrCreate(); private static final StructType inType = new StructType() .add("url", DataTypes.StringType, false) .add("data", DataTypes.StringType, false); public void run(String sourceDatasetPath, String targetDatasetPath, double threshold, String evalUrl, String outputUrl, FileSystem fs) throws Exception { Dataset<Row> sourceDS = readInstancesFromCSV(sourceDatasetPath);//.cache(); Dataset<Row> targetDS = readInstancesFromCSV(targetDatasetPath);//.cache(); SparkHR3Mapper sparkHR3Mapper = new SparkHR3Mapper(); long init = System.currentTimeMillis(); // sparkHR3Mapper.getMapping(spark.createDataFrame(Lists.newArrayList(RowFactory.create("test","17.3,37.2")), inType), spark.createDataFrame(Lists.newArrayList(RowFactory.create("test","17.3,37.2")), inType), threshold, 4).count(); init = System.currentTimeMillis() - init; long sizeA = sourceDS.count(); long sizeB = targetDS.count(); partitions *= Math.pow(10,Math.ceil(Math.max(0, Math.log10(Math.max(sizeA, sizeB))-7))); if (sizeA > sizeB) { Dataset<Row> tmp = sourceDS; sourceDS = targetDS; targetDS = tmp; } Path evalPath = new Path(evalUrl); Path linksPath = new Path(outputUrl); try { FSDataOutputStream fin = fs.create(evalPath, true); fin.writeUTF("i\tt_comp\tt_write\tinit\tn_links\n"); for (int i = 0; i < 1; i++) { if (fs.exists(linksPath)) { fs.delete(linksPath, true); } long start = System.currentTimeMillis(); Dataset<Row> mapping = sparkHR3Mapper .getMapping(sourceDS, targetDS, threshold, 1) ;//.cache(); long count = mapping.count(); long comp = System.currentTimeMillis(); if (sizeA > sizeB) { mapping = mapping.map((MapFunction<Row, Row>) r -> RowFactory.create(r.get(1), r.get(0), r.get(2)), SparkHR3Mapper.outputEncoder); } mapping.write().csv(outputUrl); long finish = System.currentTimeMillis(); fin.writeUTF(i + "\t" + (comp - start) + "\t" + (finish - comp) + "\t" + init + "\t" + count + "\n"); mapping.unpersist(); } } catch (Exception e) { throw new RuntimeException(e); } finally { fs.close(); // sourceDS.unpersist(); // targetDS.unpersist(); } } // sourceDatasetPath, targetDatasetPath, threshold, evaluationOutputPath, linksOutputPath public static void main(String[] args) throws Exception { final GenericOptionsParser optionsParser = new GenericOptionsParser(args); final String[] posArgs = optionsParser.getRemainingArgs(); final org.apache.hadoop.conf.Configuration conf = optionsParser.getConfiguration(); FileSystem fs = FileSystem.get(conf); String sourceDatasetPath = posArgs[0]; String targetDatasetPath = posArgs[1]; double threshold = Double.parseDouble(posArgs[2]); String evaluationOutputPath = posArgs[3]; String linksOutputPath = posArgs[4]; new Main().run(sourceDatasetPath, targetDatasetPath, threshold, evaluationOutputPath, linksOutputPath, fs); } private Dataset<Row> readInstancesFromCSV(String path) { Dataset<Row> load = spark.read() .format("csv") .option("delimiter", ";") .option("header", "false") .option("mode", "DROPMALFORMED") .load(path); return load; } }
package io.mangoo.crypto; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.Objects; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import org.apache.commons.lang3.RegExUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.CryptoException; import org.bouncycastle.crypto.engines.AESLightEngine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.google.common.base.Charsets; import com.google.inject.Inject; import io.mangoo.core.Config; import io.mangoo.enums.Required; /** * Convenient class for encryption and decryption * * @author svenkubiak * */ public class Crypto { private static final Logger LOG = LogManager.getLogger(Crypto.class); private final PaddedBufferedBlockCipher paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESLightEngine())); private static final Base64.Encoder base64Encoder = Base64.getEncoder(); private static final Base64.Decoder base64Decoder = Base64.getDecoder(); private static final String ENCODING = "UTF8"; private static final String ENCRYPTION = "RSA/ECB/OAEPWithSHA512AndMGF1Padding"; private static final String ALGORITHM = "RSA"; private static final int KEYLENGTH = 2048; private static final int KEYINDEX_START = 0; private static final int MAX_KEY_LENGTH = 32; private Config config; @Inject public Crypto(Config config) { this.config = Objects.requireNonNull(config, Required.CONFIG.toString()); Security.addProvider(new BouncyCastleProvider()); } /** * Decrypts an given encrypted text using the application secret property (application.secret) as key * * @param encrytedText The encrypted text * @return The clear text or null if decryption fails */ public String decrypt(String encrytedText) { Objects.requireNonNull(encrytedText, Required.ENCRYPTED_TEXT.toString()); return decrypt(encrytedText, getSizedSecret(this.config.getApplicationSecret())); } /** * Decrypts an given encrypted text using the given key * * @param encrytedText The encrypted text * @param key The encryption key * @return The clear text or null if decryption fails */ public String decrypt(String encrytedText, String key) { Objects.requireNonNull(encrytedText, Required.ENCRYPTED_TEXT.toString()); Objects.requireNonNull(key, Required.KEY.toString()); CipherParameters cipherParameters = new ParametersWithRandom(new KeyParameter(getSizedSecret(key).getBytes(Charsets.UTF_8))); this.paddedBufferedBlockCipher.init(false, cipherParameters); return new String(cipherData(base64Decoder.decode(encrytedText)), Charsets.UTF_8); } /** * Encrypts a given plain text using the application secret property (application.secret) as key * * Encryption is done by using AES and CBC Cipher and a key length of 256 bit * * @param plainText The plain text to encrypt * @return The encrypted text or null if encryption fails */ public String encrypt(String plainText) { Objects.requireNonNull(plainText, Required.PLAIN_TEXT.toString()); return encrypt(plainText, getSizedSecret(this.config.getApplicationSecret())); } /** * Encrypts a given plain text using the given key * * Encryption is done by using AES and CBC Cipher and a key length of 256 bit * * @param plainText The plain text to encrypt * @param key The key to use for encryption * @return The encrypted text or null if encryption fails */ public String encrypt(final String plainText, final String key) { Objects.requireNonNull(plainText, Required.PLAIN_TEXT.toString()); Objects.requireNonNull(key, Required.KEY.toString()); CipherParameters cipherParameters = new ParametersWithRandom(new KeyParameter(getSizedSecret(key).getBytes(Charsets.UTF_8))); this.paddedBufferedBlockCipher.init(true, cipherParameters); return new String(base64Encoder.encode(cipherData(plainText.getBytes(Charsets.UTF_8))), Charsets.UTF_8); } /** * Encrypts or decrypts a given byte array of data * * @param data The data to encrypt or decrypt * @return A clear text or encrypted byte array */ private byte[] cipherData(final byte[] data) { byte[] result = null; try { final byte[] buffer = new byte[this.paddedBufferedBlockCipher.getOutputSize(data.length)]; final int processedBytes = this.paddedBufferedBlockCipher.processBytes(data, 0, data.length, buffer, 0); final int finalBytes = this.paddedBufferedBlockCipher.doFinal(buffer, processedBytes); result = new byte[processedBytes + finalBytes]; System.arraycopy(buffer, 0, result, 0, result.length); } catch (final CryptoException e) { LOG.error("Failed to encrypt/decrypt", e); } return result; } public String getSizedSecret(String secret) { Objects.requireNonNull(secret, Required.SECRET.toString()); String key = RegExUtils.replaceAll(secret, "[^\\x00-\\x7F]", ""); return key.length() < MAX_KEY_LENGTH ? key : key.substring(KEYINDEX_START, MAX_KEY_LENGTH); } /** * Generate key which contains a pair of private and public key using 4096 bytes * * @return key pair */ public KeyPair generateKeyPair() { KeyPair keyPair = null; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); keyPairGenerator.initialize(KEYLENGTH); keyPair = keyPairGenerator.generateKeyPair(); } catch (NoSuchAlgorithmException e) { LOG.error("Failed to create publi/private key pair", e); } return keyPair; } /** * Encrypt a text using public key * * @param text The plain text * @param key The public key * * @return Encrypted text */ public byte[] encrypt(byte[] text, PublicKey key) { Objects.requireNonNull(text, Required.PLAIN_TEXT.toString()); Objects.requireNonNull(text, Required.PUBLIC_KEY.toString()); byte[] encrypt = null; try { Cipher cipher = Cipher.getInstance(ENCRYPTION); cipher.init(Cipher.ENCRYPT_MODE, key); encrypt = cipher.doFinal(text); } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) { LOG.error("Failed to encrypt clear text with public key", e); } return encrypt; } /** * Encrypt a text using public key. The result is encoded to Base64. * * @param text The plain text * @param key The public key * * @return Encrypted string as base64 */ public String encrypt(String text, PublicKey key) { Objects.requireNonNull(text, Required.PLAIN_TEXT.toString()); Objects.requireNonNull(text, Required.PUBLIC_KEY.toString()); String encrypt = null; try { byte[] cipherText = encrypt(text.getBytes(ENCODING), key); encrypt = encodeBase64(cipherText); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encrypt; } /** * Decrypt text using private key * * @param text The encrypted text * @param key The private key * * @return The unencrypted text */ public byte[] decrypt(byte[] text, PrivateKey key) { Objects.requireNonNull(text, Required.ENCRYPTED_TEXT.toString()); Objects.requireNonNull(text, Required.PRIVATE_KEY.toString()); byte[] decrypt = null; try { Cipher cipher = Cipher.getInstance(ENCRYPTION); cipher.init(Cipher.DECRYPT_MODE, key); decrypt = cipher.doFinal(text); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { LOG.error("Failed to decrypt encrypted text with private key", e); } return decrypt; } /** * Decrypt Base64 encoded text using private key * * @param text The encrypted text, encoded as Base64 * @param key The private key * * @return The plain text encoded as UTF8 */ public String decrypt(String text, PrivateKey key) { Objects.requireNonNull(text, Required.ENCRYPTED_TEXT.toString()); Objects.requireNonNull(text, Required.PRIVATE_KEY.toString()); String decrypt = null; try { byte[] dectyptedText = decrypt(decodeBase64(text), key); decrypt = new String(dectyptedText, ENCODING); } catch (Exception e) { LOG.error("Failed to decrypt encrypted text with private key", e); } return decrypt; } /** * Convert a Key to string encoded as Base64 * * @param key The key (private or public) * @return A string representation of the key */ public String getKeyAsString(Key key) { Objects.requireNonNull(key, Required.KEY.toString()); return encodeBase64(key.getEncoded()); } /** * Generates Private Key from Base64 encoded string * * @param key Base64 encoded string which represents the key * @return The PrivateKey */ public PrivateKey getPrivateKeyFromString(String key) { Objects.requireNonNull(key, Required.KEY.toString()); try { return KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decodeBase64(key))); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { LOG.error("Failed to get private key from string", e); } return null; } /** * Generates Public Key from Base64 encoded string * * @param key Base64 encoded string which represents the key * @return The PublicKey */ public PublicKey getPublicKeyFromString(String key) { Objects.requireNonNull(key, Required.KEY.toString()); try { return KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(decodeBase64(key))); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { LOG.error("Failed to get pulbic key from string", e); } return null; } /** * Encode bytes array to Base64 string * * @param bytes * @return Encoded string */ private String encodeBase64(byte[] bytes) { Objects.requireNonNull(bytes, Required.BYTES.toString()); return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes); } /** * Decode Base64 encoded string to bytes array * * @param text The string * @return Bytes array * @throws IOException */ private byte[] decodeBase64(String text) { Objects.requireNonNull(text, Required.PLAIN_TEXT.toString()); return org.apache.commons.codec.binary.Base64.decodeBase64(text); } }
package io.mangoo.enums; import java.util.Collections; import java.util.Locale; import java.util.Map; import com.google.common.collect.Maps; /** * * @author svenkubiak * */ public enum Binding { AUTHENTICATION("io.mangoo.routing.bindings.Authentication"), BODY("io.mangoo.routing.bindings.Body"), DOUBLE("java.lang.Double"), DOUBLE_PRIMITIVE("double"), FLASH("io.mangoo.routing.bindings.Flash"), FLOAT("java.lang.Float"), FLOAT_PRIMITIVE("float"), FORM("io.mangoo.routing.bindings.Form"), INT_PRIMITIVE("int"), INTEGER("java.lang.Integer"), LOCALDATE("java.time.LocalDate"), LOCALDATETIME("java.time.LocalDateTime"), LONG("java.lang.Long"), LONG_PRIMITIVE("long"), MESSAGES("io.mangoo.i18n.Messages"), OPTIONAL("java.util.Optional"), REQUEST("io.mangoo.routing.bindings.Request"), SESSION("io.mangoo.routing.bindings.Session"), STRING("java.lang.String"), UNDEFINED("undefined"); private final String value; private static Map<String, Binding> values; static { Map<String, Binding> bindings = Maps.newHashMapWithExpectedSize(Binding.values().length); for (Binding binding : Binding.values()) { bindings.put(binding.toString().toLowerCase(Locale.ENGLISH), binding); } values = Collections.unmodifiableMap(bindings); } Binding (String value) { this.value = value; } public static Binding fromString(String value) { return values.get(value.toLowerCase(Locale.ENGLISH)); } @Override public String toString() { return this.value; } }
package cs263w16; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.util.logging.*; import com.google.appengine.api.datastore.*; import com.google.appengine.api.memcache.*; @SuppressWarnings("serial") public class DatastoreServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); String keyname = null; String value = null; Date date = null; resp.setContentType("text/html"); resp.getWriter().println("<html><body>"); Map<String, String[]> map = req.getParameterMap(); if (map.size() == 0) { Query q = new Query("TaskData"); PreparedQuery pq = datastore.prepare(q); ArrayList<String> keynames = new ArrayList<String>(); resp.getWriter().println("<ul>In DataStore"); for (Entity result : pq.asIterable()) { Key key = result.getKey(); keynames.add(key.getName()); value = (String) result.getProperty("value"); date = (Date) result.getProperty("date"); resp.getWriter().println("<li>" + key + " " + value + " " + date + " </li>"); } resp.getWriter().println("</ul>"); resp.getWriter().println("<ul>In MemCache"); for (String key_name : keynames) { value = (String)syncCache.get(key_name); if (value != null) { resp.getWriter().println("<li>" + key_name + " " + value + " </li>"); } } resp.getWriter().println("</ul>"); } else { if (map.containsKey("keyname")) { keyname = map.get("keyname")[0]; if (map.containsKey("value")) { value = map.get("value")[0]; Entity taskData = new Entity("TaskData", keyname); taskData.setProperty("value", value); taskData.setProperty("date", new Date()); datastore.put(taskData); syncCache.put(keyname, value); resp.getWriter().println("<h2>Stored " + keyname + " and " + value + " in Datastore</h2>"); } else { value = (String) syncCache.get(keyname); if (value == null) { Key key = KeyFactory.createKey("TaskData", keyname); try { Entity taskData = datastore.get(key); value = (String)taskData.getProperty("value"); syncCache.put(keyname, value); resp.getWriter().println("<h2>" + keyname + ": " + value + " (Datastore)</h2>"); } catch (EntityNotFoundException e) { resp.getWriter().println("<h2>Neither found</h2>"); } } else { resp.getWriter().println("<h2>" + keyname + ": " + value + " (Both)</h2>"); } } } else { resp.getWriter().println("<h2>Wrong parameters</h2>"); } } resp.getWriter().println("</body></html>"); } }
package xal.app.lebt; //import com.sun.javafx.charts.Legend; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.RadioButton; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.CheckBoxTableCell; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.InputMethodEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.StringConverter; import xal.ca.BatchConnectionRequest; import xal.ca.Channel; import xal.ca.ChannelFactory; import xal.ca.ConnectionException; import xal.ca.GetException; import xal.ca.PutException; import xal.extension.jels.smf.impl.Chopper; import xal.extension.jels.smf.impl.Doppler; import xal.extension.jels.smf.impl.EMU; import xal.extension.jels.smf.impl.ESSIonSourceCoil; import xal.extension.jels.smf.impl.ESSIonSourceMFC; import xal.extension.jels.smf.impl.ESSIonSourceMagnetron; import xal.extension.jels.smf.impl.Iris; import xal.extension.jels.smf.impl.NPM; import xal.extension.jels.smf.impl.RepellerElectrode; import xal.extension.jels.smf.impl.SpaceChargeCompensation; import xal.model.ModelException; import xal.smf.Accelerator; import xal.smf.AcceleratorNode; import xal.smf.AcceleratorSeq; import xal.smf.AcceleratorSeqCombo; import xal.smf.impl.CurrentMonitor; import xal.smf.impl.HDipoleCorr; import xal.smf.impl.MagnetPowerSupply; import xal.smf.impl.VDipoleCorr; import xal.tools.math.Complex; /** * The class handling the LEBT trajectory prediction. * * @author sofiaolsson */ public class FXMLController implements Initializable { //defining series private XYChart.Series seriesX; private XYChart.Series seriesY; private XYChart.Series seriesR; private XYChart.Series seriesPhi; private XYChart.Series[] seriesNPMpos; private XYChart.Series[] seriesNPMposCyl; private XYChart.Series[] seriesSigmaX; private XYChart.Series[] seriesSigmaY; private XYChart.Series[] seriesSigmaR; private XYChart.Series[] seriesNPMsigma; private XYChart.Series seriesNPMsigmaCyl; private XYChart.Series[] seriesSigmaOffsetX; private XYChart.Series[] seriesSigmaOffsetY; private XYChart.Series[] seriesSigmaOffsetR; private XYChart.Series[] seriesSurroundings; //defining simulation private SimulationRunner newRun; private SimpleBooleanProperty runNow; private double[][] surroundings; //defining data private ArrayList<Double>[] sigmaX; private ArrayList<Double>[] sigmaY; private ArrayList<Double>[] sigmaR; private ArrayList<Double>[] sigmaOffsetX; private ArrayList<Double>[] sigmaOffsetY; private ArrayList<Double>[] sigmaOffsetR; private ArrayList positions; private ArrayList posX; private ArrayList posY; private ArrayList posR; private ArrayList posPhi; //input beam parameters private double beamCurrent; private double spaceChargeComp; private double spaceChargeCompElectrode; //Map the live machine values private HashMap<Channel,Object> displayValues; private HashMap<Channel,TextField> setValues; private BatchConnectionRequest request; private final ChannelMonitor monitor = new ChannelMonitor(); @FXML private LineChart<Double, Double> plot1; @FXML private NumberAxis yAxis; @FXML private NumberAxis xAxis; @FXML private LineChart<Double, Double> plot2; @FXML private NumberAxis yAxis1; @FXML private NumberAxis xAxis1; @FXML private TextField textField_x; @FXML private TextField textField_xp; @FXML private TextField textField_y; @FXML private TextField textField_yp; @FXML private TextField textField_emittx; @FXML private TextField textField_betax; @FXML private TextField textField_alphax; @FXML private TextField textField_emitty; @FXML private TextField textField_betay; @FXML private TextField textField_alphay; @FXML private TextField textField_scc; @FXML private TextField textField_bc; @FXML private RadioButton radioButtonCart; @FXML private RadioButton radioButtonCyl; private ToggleGroup coordinateGroup; @FXML private RadioButton radioButtonOffsetOn; @FXML private RadioButton radioButtonOffsetOff; private ToggleGroup offsetGroup; @FXML private NumberAxis yAxis2; @FXML private TextField textFieldSigmaScale; private double scale; @FXML private TextField textField_coil1; @FXML private TextField textField_coil2; @FXML private TextField textField_coil3; @FXML private Label label_coil1RB; @FXML private Label label_coil2RB; @FXML private Label label_coil3RB; @FXML private TextField textField_magnetron; @FXML private Label label_magnetronRB; @FXML private TextField textField_H2flow; @FXML private Label label_H2flowRB; @FXML private TextField textField_highVoltage; @FXML private Label label_sol1currentRB; @FXML private Label label_sol2currentRB; @FXML private Label label_CV1currentRB; @FXML private Label label_CH1currentRB; @FXML private Label label_CV2currentRB; @FXML private Label label_CH2currentRB; @FXML private TextField textField_irisAperture; @FXML private Label label_irisApertureRB; @FXML private CheckBox comboBox_currentFC; @FXML private CheckBox comboBox_posNPM; @FXML private CheckBox comboBox_sigmaNPM; @FXML private Label label_highVoltageRB; @FXML private TextField textField_irisX; @FXML private TextField textField_irisY; @FXML private Label label_irisXRB; @FXML private Label label_irisYRB; @FXML private Label label_sol1fieldRB; @FXML private Label label_CV1fieldRB; @FXML private Label label_CH1fieldRB; @FXML private Label label_sol2fieldRB; @FXML private Label label_CV2fieldRB; @FXML private Label label_CH2fieldRB; @FXML private Label label_Doppler; @FXML private CheckBox checkBox_electrode; @FXML private Circle electrodeStatus; @FXML private TextField textField_sccelectrode; @FXML private ToggleGroup toggleGroup_currentBI; @FXML private TextField textField_chopperDelay; @FXML private Label label_chopperDelayRB; @FXML private TextField textField_chopperLength; @FXML private Label label_chopperLengthRB; @FXML private TextField textField_N2flow; @FXML private Label label_N2flowRB; @FXML private ComboBox<InputParameters> comboBox_inputSimul; @FXML private Circle chopperStatus; @FXML private RadioButton rb_CurrentMeasurement1; @FXML private RadioButton rb_CurrentMeasurement2; @FXML private Label label_CurrentMeasurement1; @FXML private Label label_CurrentMeasurement2; @FXML private AnchorPane mainPane; @FXML private TabPane mainTabPane; @FXML private Label label_transmission; @FXML private TextField textField_sol1current; @FXML private TextField textField_CV1current; @FXML private TextField textField_CH1current; @FXML private TextField textField_sol2current; @FXML private TextField textField_CV2current; @FXML private TextField textField_CH2current; @FXML private TextField textField_sol1field; @FXML private TextField textField_CV1field; @FXML private TextField textField_CH1field; @FXML private TextField textField_sol2field; @FXML private TextField textField_CV2field; @FXML private TextField textField_CH2field; @FXML private Label label_Field; @Override public void initialize(URL url, ResourceBundle rb) { //Check if the accelerator file contains the LEBT and Ion Source sequences if(MainFunctions.mainDocument.getAccelerator().findSequence("LEBT")==null || MainFunctions.mainDocument.getAccelerator().findSequence("ISRC")==null){ Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Error!"); alert.setHeaderText("Accelerator file has no LEBT and/or Ion Source sequence."); alert.setContentText("Check inputs and try again"); alert.showAndWait(); Logger.getLogger(FXMLController.class.getName()).log(Level.FINER, "Accelerator file has no LEBT and/or Ion Source sequence."); System.exit(0); } //Initializes simulations running and false runNow = new SimpleBooleanProperty(); runNow.set(false); //initializing toggle groups coordinateGroup = new ToggleGroup(); offsetGroup = new ToggleGroup(); radioButtonCart.setToggleGroup(coordinateGroup); radioButtonCart.setSelected(true); radioButtonCyl.setToggleGroup(coordinateGroup); radioButtonOffsetOff.setToggleGroup(offsetGroup); radioButtonOffsetOn.setToggleGroup(offsetGroup); radioButtonOffsetOff.setSelected(true); //initializing series seriesX = new XYChart.Series(); seriesY = new XYChart.Series(); seriesR = new XYChart.Series(); seriesPhi = new XYChart.Series(); seriesSigmaX = new XYChart.Series[2]; seriesSigmaY = new XYChart.Series[2]; seriesSigmaR = new XYChart.Series[2]; seriesSigmaOffsetX = new XYChart.Series[2]; seriesSigmaOffsetY = new XYChart.Series[2]; seriesSigmaOffsetR = new XYChart.Series[2]; seriesSurroundings = new XYChart.Series[2]; seriesNPMpos = new XYChart.Series[2]; seriesNPMsigma = new XYChart.Series[2]; seriesNPMposCyl = new XYChart.Series[2]; seriesNPMsigmaCyl = new XYChart.Series(); seriesX.setName("x"); seriesY.setName("y"); seriesR.setName("r"); seriesPhi.setName("φ"); for(int i = 0; i<seriesSurroundings.length;i++){ seriesSigmaX[i] = new XYChart.Series(); seriesSigmaY[i] = new XYChart.Series(); seriesSigmaR[i] = new XYChart.Series(); seriesSigmaOffsetX[i] = new XYChart.Series(); seriesSigmaOffsetY[i] = new XYChart.Series(); seriesSigmaOffsetR[i] = new XYChart.Series(); seriesSurroundings[i] = new XYChart.Series(); seriesNPMpos[i] = new XYChart.Series(); seriesNPMsigma[i] = new XYChart.Series(); seriesNPMposCyl[i] = new XYChart.Series(); } getVacuumChamber(null); //seriesSurroundings[0].getData().add(new XYChart.Data(0.0, 0.0)); //seriesSurroundings[1].getData().add(new XYChart.Data(0.0, 0.0)); seriesSigmaX[0].setName("σx"); seriesSigmaY[0].setName("σy"); seriesSigmaR[0].setName("σr"); seriesSigmaOffsetR[0].setName("σr"); seriesSigmaOffsetX[0].setName("σx"); seriesSigmaOffsetY[0].setName("σy"); seriesNPMpos[0].setName("NPM_x"); seriesNPMpos[1].setName("NPM_y"); seriesNPMsigma[0].setName("NPM_σx"); seriesNPMsigma[1].setName("NPM_σy"); seriesNPMposCyl[0].setName("NPM_r"); seriesNPMposCyl[1].setName("NPM_φ"); seriesNPMsigmaCyl.setName("NPM_σr"); //Add surroundings plot1.setAnimated(false); plot2.setAnimated(false); plot2.getData().add(seriesSurroundings[0]); plot2.getData().add(seriesSurroundings[1]); plot1.getStylesheets().add(this.getClass().getResource("/styles/TrajectoryPlot.css").toExternalForm()); plot2.getStylesheets().add(this.getClass().getResource("/styles/EnvelopePlot.css").toExternalForm()); //remove surrounding legend //Legend legend = (Legend)plot2.lookup(".chart-legend"); //legend.getItems().remove(0, 2); scale = 1; //Set textField formatting StringConverter<Double> formatter2d; StringConverter<Double> formatter3d; StringConverter<Double> formatter4d; StringConverter<Double> scientific3d; formatter4d = new StringConverter<Double>(){ @Override public Double fromString(String string) { return Double.parseDouble(string); } @Override public String toString(Double object) { if (object == null) return "0.0000"; return String.format("%.4f",object); } }; formatter3d = new StringConverter<Double>(){ @Override public Double fromString(String string) { return Double.parseDouble(string); } @Override public String toString(Double object) { if (object == null) return "0.000"; return String.format("%.3f",object); } }; formatter2d = new StringConverter<Double>(){ @Override public Double fromString(String string) { return Double.parseDouble(string); } @Override public String toString(Double object) { if (object == null) return "0.00"; return String.format("%.2f",object); } }; scientific3d = new StringConverter<Double>(){ @Override public Double fromString(String string) { return Double.parseDouble(string); } @Override public String toString(Double object) { if (object == null) return "0.000"; return String.format("%2.3e",object); } }; //Ion Source textField_magnetron.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_coil1.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_coil2.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_coil3.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_H2flow.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_highVoltage.setTextFormatter(new TextFormatter<Double>(formatter3d)); //LEBT textField_sol1current.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_sol2current.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_CV1current.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_CH1current.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_CV2current.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_CH2current.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_sol1field.setTextFormatter(new TextFormatter<Double>(scientific3d)); textField_sol2field.setTextFormatter(new TextFormatter<Double>(scientific3d)); textField_CV1field.setTextFormatter(new TextFormatter<Double>(scientific3d)); textField_CH1field.setTextFormatter(new TextFormatter<Double>(scientific3d)); textField_CV2field.setTextFormatter(new TextFormatter<Double>(scientific3d)); textField_CH2field.setTextFormatter(new TextFormatter<Double>(scientific3d)); textField_irisAperture.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_irisX.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_irisY.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_chopperDelay.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_chopperLength.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_N2flow.setTextFormatter(new TextFormatter<Double>(formatter3d)); //input values textField_x.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_xp.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_y.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_yp.setTextFormatter(new TextFormatter<Double>(formatter4d)); textField_betax.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_alphax.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_emittx.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_betay.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_alphay.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_emitty.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_bc.setTextFormatter(new TextFormatter<Double>(formatter3d)); textField_scc.setTextFormatter(new TextFormatter<Double>(formatter2d)); textField_sccelectrode.setTextFormatter(new TextFormatter<Double>(formatter2d)); textFieldSigmaScale.setTextFormatter(new TextFormatter<Double>(formatter2d)); textFieldSigmaScale.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try{ scale = Double.parseDouble(textFieldSigmaScale.getText().trim()); } catch(NumberFormatException e){ scale = 1.0; } textFieldSigmaScale.fireEvent(new RunEvent(runNow.get())); } }); //Map the channels to the label or textfield it belongs displayValues = new HashMap<Channel,Object>(); setValues = new HashMap<Channel,TextField>(); //Define Channel signals attached to textFields and displayFields setupChannelSignals(); setupInitialConditions(); yAxis1.setAutoRanging(true); yAxis.setAutoRanging(true); //Initialize arrays sigmaX = new ArrayList[2]; sigmaY = new ArrayList[2]; sigmaR = new ArrayList[2]; sigmaOffsetR = new ArrayList[2]; sigmaOffsetX = new ArrayList[2]; sigmaOffsetY = new ArrayList[2]; posX = new ArrayList<>(); posY = new ArrayList<>(); posR = new ArrayList<>(); posPhi = new ArrayList<>(); positions = new ArrayList<>(); for(int i = 0; i < sigmaR.length;i++){ sigmaR[i] = new ArrayList<Double>(); sigmaX[i] = new ArrayList<Double>(); sigmaY[i] = new ArrayList<Double>(); sigmaOffsetR[i] = new ArrayList<Double>(); sigmaOffsetX[i] = new ArrayList<Double>(); sigmaOffsetY[i] = new ArrayList<Double>(); } MainFunctions.mainDocument.getSequenceProperty().addListener((obs, oldVal, newVal) ->{ if(newVal != null && !newVal.matches("ISRC")){ //get Sequence String sequenceName = MainFunctions.mainDocument.getSequence(); String Sequence = MainFunctions.mainDocument.getAccelerator().getSequences().toString(); String ComboSequence = MainFunctions.mainDocument.getAccelerator().getComboSequences().toString(); //reset input values for Simulation ObservableList<InputParameters> options = FXCollections.observableArrayList(); comboBox_inputSimul.getItems().clear(); //initializing simulation if (Sequence.contains(sequenceName)) { //Update Vacuum chamber getVacuumChamber(MainFunctions.mainDocument.getAccelerator().getSequence(sequenceName)); newRun = new SimulationRunner(MainFunctions.mainDocument.getAccelerator().getSequence(sequenceName),MainFunctions.mainDocument.getModel().get()); options.add(new InputParameters(newRun.getProbe())); MainFunctions.mainDocument.getAccelerator().getSequence(sequenceName).getAllNodesOfType("NPM").forEach(mon -> options.add(new InputParameters(mon))); MainFunctions.mainDocument.getAccelerator().getSequence(sequenceName).getAllNodesOfType("EMU").forEach(mon -> options.add(new InputParameters(mon))); } else if (ComboSequence.contains(sequenceName)) { //Update Vacuum chamber getVacuumChamber(MainFunctions.mainDocument.getAccelerator().getComboSequence(sequenceName)); newRun = new SimulationRunner(MainFunctions.mainDocument.getAccelerator().getComboSequence(sequenceName),MainFunctions.mainDocument.getModel().get()); options.add(new InputParameters(newRun.getProbe())); MainFunctions.mainDocument.getAccelerator().getComboSequence(sequenceName).getAllNodesOfType("NPM").forEach(mon -> options.add(new InputParameters(mon))); MainFunctions.mainDocument.getAccelerator().getComboSequence(sequenceName).getAllNodesOfType("EMU").forEach(mon -> options.add(new InputParameters(mon))); } comboBox_inputSimul.setItems(options); comboBox_inputSimul.getSelectionModel().select(0); mainPane.addEventHandler(RunEvent.RUN_SIMULATION, new RunSimulationHandler(){ @Override public void onRunEvent(Boolean param0) { if(param0){UpdateSimulation();} } }); mainTabPane.setDisable(false); textField_sol1field.setVisible(false); textField_sol2field.setVisible(false); textField_CV1field.setVisible(false); textField_CV2field.setVisible(false); textField_CH1field.setVisible(false); textField_CH2field.setVisible(false); label_Field.setVisible(false); //assigning initial parameters and run the fisrt simulation getParameters(); runNow.set(true); mainTabPane.fireEvent(new RunEvent(runNow.get())); } }); MainFunctions.mainDocument.getAcceleratorProperty().addChangeListener((obs, oldVal, newVal) ->{ //Check if the accelerator file contains the LEBT and Ion Source sequences if(MainFunctions.mainDocument.getAccelerator().findSequence("LEBT")==null || MainFunctions.mainDocument.getAccelerator().findSequence("ISRC")==null){ Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Error!"); alert.setHeaderText("Accelerator file has no LEBT and/or Ion Source sequence."); alert.setContentText("Check inputs and try again"); alert.showAndWait(); Logger.getLogger(FXMLController.class.getName()).log(Level.FINER, "Accelerator file has no LEBT and/or Ion Source sequence."); System.exit(0); } //Define Channel signals attached to textFields and displayFields setupChannelSignals(); setupInitialConditions(); //stop simulation and disables inputs until sequence is chosen mainTabPane.setDisable(true); runNow.set(false); //clear plots for(int i = 0; i<seriesSurroundings.length;i++){ seriesSigmaX[i].getData().clear(); seriesSigmaY[i].getData().clear(); seriesSigmaR[i].getData().clear(); seriesSigmaOffsetX[i].getData().clear(); seriesSigmaOffsetY[i].getData().clear(); seriesSigmaOffsetR[i].getData().clear(); seriesSurroundings[i].getData().clear(); seriesNPMpos[i].getData().clear(); seriesNPMsigma[i].getData().clear(); seriesNPMposCyl[i].getData().clear(); } comboBox_posNPM.setSelected(false); comboBox_sigmaNPM.setSelected(false); comboBox_currentFC.setSelected(false); //Initializes TextField setConnectAndMonitor(); initBIElements(); initDisplayFields(); }); //Set input parameter for Simulation comboBox_inputSimul.setCellFactory(listview -> { return new ListCell<InputParameters>() { @Override public void updateItem(InputParameters item, boolean empty) { super.updateItem(item, empty); textProperty().unbind(); if (item != null) { setText(item.getName()); } else { setText(null); } } }; } ); comboBox_inputSimul.setButtonCell(new ListCell<InputParameters>() { { itemProperty().addListener((obs, oldValue, newValue) -> update()); emptyProperty().addListener((obs, oldValue, newValue) -> update()); } private void update() { if (isEmpty() || getItem() == null) { setText(null); } else { setText(getItem().getName()); getItem().updateValues(); textField_x.setText(String.format("%.4f",getItem().getX()*1e03)); textField_xp.setText(String.format("%.4f",getItem().getXP()*1e03)); textField_y.setText(String.format("%.4f",getItem().getY()*1e03)); textField_yp.setText(String.format("%.4f",getItem().getYP()*1e03)); textField_alphax.setText(String.format("%.3f",getItem().getALPHAX())); textField_betax.setText(String.format("%.3f",getItem().getBETAX())); textField_emittx.setText(String.format("%.3f",getItem().getEMITTX()*1e06)); textField_alphay.setText(String.format("%.3f",getItem().getALPHAY())); textField_betay.setText(String.format("%.3f",getItem().getBETAY())); textField_emitty.setText(String.format("%.3f",getItem().getEMITTY()*1e06)); } } }); //Disable text field in case Model type chages to Design MainFunctions.mainDocument.getModel().addListener((ObservableValue<? extends String> obs, String oldVal, String newVal) ->{ if(newVal.matches("DESIGN")){ setValues.forEach((channel,textField)->{ textField.setDisable(true); }); textField_sol1field.setVisible(true); textField_sol2field.setVisible(true); textField_CV1field.setVisible(true); textField_CV2field.setVisible(true); textField_CH1field.setVisible(true); textField_CH2field.setVisible(true); label_Field.setVisible(true); textField_sol1field.setText(label_sol1fieldRB.getText()); textField_sol2field.setText(label_sol2fieldRB.getText()); textField_CV1field.setText(label_CV1fieldRB.getText()); textField_CV2field.setText(label_CV2fieldRB.getText()); textField_CH1field.setText(label_CH1fieldRB.getText()); textField_CH2field.setText(label_CH2fieldRB.getText()); } else if (newVal.matches("LIVE")){ //set the magnets values as the readbacks from the channels Button applyButton = new Button("Apply Selection"); Button cancelButton = new Button("Keep Old Fields"); HBox hbox = new HBox(8); hbox.setPadding(new Insets(5, 10, 10, 5)); hbox.setAlignment(Pos.CENTER_RIGHT); hbox.getChildren().addAll(applyButton,cancelButton); TableView<Magnet> table = new TableView<Magnet>(); TableColumn<Magnet,Boolean> booleanColumn = new TableColumn<Magnet, Boolean>("Set?"); TableColumn<Magnet,String> elementColumn = new TableColumn<Magnet, String>("Element"); TableColumn<Magnet,String> newFieldColumn = new TableColumn<Magnet, String>("New Field"); TableColumn<Magnet,String> oldFieldColumn = new TableColumn<Magnet, String>("Old Field"); ObservableList<Magnet> inputMagnets = FXCollections.observableArrayList(); inputMagnets.add(new Magnet("LEBT-010:BMD-Sol-01",textField_sol1field.getText(),label_sol1fieldRB.getText(),false)); inputMagnets.add(new Magnet("LEBT-010:BMD-Sol-02",textField_sol2field.getText(),label_sol2fieldRB.getText(),false)); inputMagnets.add(new Magnet("LEBT-010:BMD-CV-01:1",textField_CV1field.getText(),label_CV1fieldRB.getText(),false)); inputMagnets.add(new Magnet("LEBT-010:BMD-CH-01:1",textField_CH1field.getText(),label_CH1fieldRB.getText(),false)); inputMagnets.add(new Magnet("LEBT-010:BMD-CV-02:1",textField_CV2field.getText(),label_CV2fieldRB.getText(),false)); inputMagnets.add(new Magnet("LEBT-010:BMD-CH-02:1",textField_CH2field.getText(),label_CH2fieldRB.getText(),false)); elementColumn.setCellValueFactory(new PropertyValueFactory<>("magnetName")); newFieldColumn.setCellValueFactory(new PropertyValueFactory<>("newField")); oldFieldColumn.setCellValueFactory(new PropertyValueFactory<>("oldField")); booleanColumn.setCellValueFactory( new PropertyValueFactory<>( "selected" )); booleanColumn.setCellFactory(tc -> new CheckBoxTableCell<>()); table.setItems(inputMagnets); table.setEditable(true); table.getColumns().addAll(booleanColumn,elementColumn,newFieldColumn,oldFieldColumn); BorderPane secondaryLayout = new BorderPane(); secondaryLayout.setTop(new Label("Choose magnets to restore new fields to machine:")); secondaryLayout.setCenter(table); secondaryLayout.setBottom(hbox); Scene secondScene = new Scene(secondaryLayout, 375, 258); Stage newWindow = new Stage(); newWindow.setTitle("Magnets Settings"); newWindow.setScene(secondScene); applyButton.setOnMouseClicked((MouseEvent event) -> { inputMagnets.forEach(mag->{ AcceleratorNode node = MainFunctions.mainDocument.getAccelerator().getNode(mag.getMagnetName()); if(mag.selectedProperty().get()){ double val = Double.parseDouble(mag.getNewField()); try { node.getChannel("fieldSet").putVal(val); } catch (ConnectionException | PutException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); newWindow.close(); }); cancelButton.setOnMouseClicked((MouseEvent event) -> { newWindow.close(); }); newWindow.show(); setValues.forEach((channel,textField)->{ textField.setDisable(false); }); textField_sol1field.setVisible(false); textField_sol2field.setVisible(false); textField_CV1field.setVisible(false); textField_CV2field.setVisible(false); textField_CH1field.setVisible(false); textField_CH2field.setVisible(false); label_Field.setVisible(false); mainTabPane.fireEvent(new RunEvent(runNow.get())); } }); //Lock main Pane before a Sequence is chosen mainTabPane.setDisable(true); //Initializes TextField setConnectAndMonitor(); initBIElements(); //initDisplayFields(); //Initializes Plots addTrajectorySeriesToPlot(); addEnvelopeSeriesToPlot(); displayPlots(); } private void setConnectAndMonitor(){ //Initializes TextField monitor.disconnectAndClearAll(); //Creates a batch of channels to request when updating GUI HashMap<Channel,Object> inputChannels = new HashMap<>(); setValues.keySet().forEach(channel -> inputChannels.put(channel,setValues.get(channel))); //Creates a batch of channels to request when updating GUI displayValues.keySet().forEach(channel -> inputChannels.put(channel,displayValues.get(channel))); monitor.connectAndMonitor(inputChannels); } private void setupChannelSignals(){ Accelerator accl = MainFunctions.mainDocument.getAccelerator(); AcceleratorSeq sequence; ChannelFactory CHANNEL_FACTORY = ChannelFactory.defaultFactory(); //Ion Source if(accl.findSequence("ISRC") != null){ sequence = accl.getSequence("ISRC"); if(sequence.getNodesOfType("ISM").size()>0){ AcceleratorNode Magnetron = sequence.getNodesOfType("ISM").get(0); displayValues.put(Magnetron.getChannel(ESSIonSourceMagnetron.FORWD_PRW_RB_HANDLE),label_magnetronRB); setValues.put(Magnetron.getChannel(ESSIonSourceMagnetron.FORWD_PRW_S_HANDLE),textField_magnetron); textField_magnetron.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_magnetron.getText()); if(val>=0 && val<=1500){ Magnetron.getChannel(ESSIonSourceMagnetron.FORWD_PRW_S_HANDLE).putVal(val); } else { textField_magnetron.setText(Double.toString(Magnetron.getChannel(ESSIonSourceMagnetron.FORWD_PRW_S_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_magnetronRB.setDisable(true); textField_magnetron.setDisable(true); } if(sequence.getNodesOfType("ISMFC").size()>0){ AcceleratorNode HighVoltage = sequence.getNodesOfType("ISMFC").get(0); displayValues.put(HighVoltage.getChannel(ESSIonSourceMFC.VOLTAGE_RB_HANDLE),label_highVoltageRB); setValues.put(HighVoltage.getChannel(ESSIonSourceMFC.VOLTAGE_SET_HANDLE),textField_highVoltage); textField_highVoltage.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_highVoltage.getText()); if(val>=70 && val<=80){ HighVoltage.getChannel(ESSIonSourceMFC.VOLTAGE_SET_HANDLE).putVal(val); } else { textField_highVoltage.setText(Double.toString(HighVoltage.getChannel(ESSIonSourceMFC.VOLTAGE_SET_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); displayValues.put(HighVoltage.getChannel(ESSIonSourceMFC.H_2_FLOW_RB_HANDLE),label_H2flowRB); setValues.put(HighVoltage.getChannel(ESSIonSourceMFC.H_2_FLOW_S_HANDLE),textField_H2flow); textField_H2flow.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_H2flow.getText()); if(val>=0 && val <=5){ HighVoltage.getChannel(ESSIonSourceMFC.H_2_FLOW_S_HANDLE).putVal(val); } else { textField_H2flow.setText(Double.toString(HighVoltage.getChannel(ESSIonSourceMFC.H_2_FLOW_S_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_highVoltageRB.setDisable(true); textField_highVoltage.setDisable(true); label_H2flowRB.setDisable(true); textField_H2flow.setDisable(true); } if(sequence.getNodesOfType("ISC").size()>0){ AcceleratorNode Coil1 = sequence.getNodesOfType("ISC").get(0); displayValues.put(Coil1.getChannel(ESSIonSourceCoil.I_HANDLE),label_coil1RB); setValues.put(Coil1.getChannel(ESSIonSourceCoil.I_SET_HANDLE),textField_coil1); textField_coil1.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_coil1.getText()); if(val>=0 && val <=300){ Coil1.getChannel(ESSIonSourceCoil.I_SET_HANDLE).putVal(val); } else { textField_coil1.setText(Double.toString(Coil1.getChannel(ESSIonSourceCoil.I_SET_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_coil2RB.setDisable(true); textField_coil2.setDisable(true); } if(sequence.getNodesOfType("ISC").size()>1){ AcceleratorNode Coil2 = sequence.getNodesOfType("ISC").get(1); displayValues.put(Coil2.getChannel(ESSIonSourceCoil.I_HANDLE),label_coil2RB); setValues.put(Coil2.getChannel(ESSIonSourceCoil.I_SET_HANDLE),textField_coil2); textField_coil2.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_coil2.getText()); if(val>=0 && val <=300){ Coil2.getChannel(ESSIonSourceCoil.I_SET_HANDLE).putVal(val); } else { textField_coil2.setText(Double.toString(Coil2.getChannel(ESSIonSourceCoil.I_SET_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_coil2RB.setDisable(true); textField_coil2.setDisable(true); } if(sequence.getNodesOfType("ISC").size()>2){ AcceleratorNode Coil3 = sequence.getNodesOfType("ISC").get(2); displayValues.put(Coil3.getChannel(ESSIonSourceCoil.I_HANDLE),label_coil3RB); setValues.put(Coil3.getChannel(ESSIonSourceCoil.I_SET_HANDLE),textField_coil3); textField_coil3.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_coil3.getText()); if(val>=0 && val <=300){ Coil3.getChannel(ESSIonSourceCoil.I_SET_HANDLE).putVal(val); } else { textField_coil3.setText(Double.toString(Coil3.getChannel(ESSIonSourceCoil.I_SET_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_coil3RB.setDisable(true); textField_coil3.setDisable(true); } } //LEBT if(accl.findSequence("LEBT") != null){ sequence = accl.getSequence("LEBT"); if(sequence.getNodesOfType("SFM").size()>1 || sequence.getNodesOfType("MFM").size()>1){ AcceleratorNode Solenoid1 = sequence.getNodeWithId("LEBT-010:BMD-Sol-01"); displayValues.put(Solenoid1.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE),label_sol1currentRB); displayValues.put(Solenoid1.getChannel("fieldRB"),label_sol1fieldRB); //displayValues.put(Solenoid1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),label_sol1current); setValues.put(Solenoid1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),textField_sol1current); textField_sol1current.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ if(MainFunctions.mainDocument.getModel().get().matches("LIVE")){ try { double val = Double.parseDouble(textField_sol1current.getText()); if(val>=0 && val<450){ Solenoid1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE).putVal(val); } else { textField_sol1current.setText(Double.toString(Solenoid1.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { textField_sol1current.fireEvent(new RunEvent(runNow.get())); } } }); textField_sol1field.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ textField_sol1field.fireEvent(new RunEvent(runNow.get())); } }); //set the magnets Readback display as change listener for changes -> run Model label_sol1fieldRB.textProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal.equals(oldVal)){ label_sol1fieldRB.fireEvent(new RunEvent(runNow.get())); } }); AcceleratorNode Solenoid2 = sequence.getNodeWithId("LEBT-010:BMD-Sol-02"); displayValues.put(Solenoid2.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE),label_sol2currentRB); displayValues.put(Solenoid2.getChannel("fieldRB"),label_sol2fieldRB); //displayValues.put(Solenoid2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),label_sol2current); setValues.put(Solenoid2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),textField_sol2current); textField_sol2current.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ if(MainFunctions.mainDocument.getModel().get().matches("LIVE")){ try { double val = Double.parseDouble(textField_sol2current.getText()); if(val>=0 && val<450){ Solenoid2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE).putVal(val); } else { textField_sol2current.setText(Double.toString(Solenoid2.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { textField_sol2field.fireEvent(new RunEvent(runNow.get())); } } }); textField_sol2field.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ textField_sol2field.fireEvent(new RunEvent(runNow.get())); } }); label_sol2fieldRB.textProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal.equals(oldVal)){ label_sol2fieldRB.fireEvent(new RunEvent(runNow.get())); } }); } else { label_sol1currentRB.setDisable(true); label_sol1fieldRB.setDisable(true); textField_sol1current.setDisable(true); label_sol2currentRB.setDisable(true); label_sol2fieldRB.setDisable(true); textField_sol2current.setDisable(true); } if(sequence.getNodesOfType("DCV").size()>1){ AcceleratorNode CV1 = sequence.getNodesOfType("DCV").get(0); displayValues.put(CV1.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE),label_CV1currentRB); //displayValues.put(CV1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),label_CV1current); displayValues.put(CV1.getChannel(VDipoleCorr.FIELD_RB_HANDLE),label_CV1fieldRB); setValues.put(CV1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),textField_CV1current); textField_CV1current.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ if(MainFunctions.mainDocument.getModel().get().matches("LIVE")){ try { double val = Double.parseDouble(textField_CV1current.getText()); if(val<120 && val>-120){ CV1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE).putVal(val); } else { textField_CV1current.setText(Double.toString(CV1.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE).getValDbl())); } } catch (ConnectionException | GetException | PutException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { textField_CV1current.fireEvent(new RunEvent(runNow.get())); } } }); textField_CV1field.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ textField_CV1field.fireEvent(new RunEvent(runNow.get())); } }); label_CV1fieldRB.textProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal.equals(oldVal)){ label_CV1fieldRB.fireEvent(new RunEvent(runNow.get())); } }); AcceleratorNode CV2 = sequence.getNodesOfType("DCV").get(1); displayValues.put(CV2.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE),label_CV2currentRB); //displayValues.put(CV2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),label_CV2current); displayValues.put(CV2.getChannel(VDipoleCorr.FIELD_RB_HANDLE),label_CV2fieldRB); setValues.put(CV2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),textField_CV2current); textField_CV2current.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ if(MainFunctions.mainDocument.getModel().get().matches("LIVE")){ try { double val = Double.parseDouble(textField_CV2current.getText()); if(val<120 && val>-120){ CV2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE).putVal(val); } else { textField_CV2current.setText(Double.toString(CV2.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE).getValDbl())); } } catch (ConnectionException | GetException | PutException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { textField_CV2current.fireEvent(new RunEvent(runNow.get())); } } }); textField_CV2field.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ textField_CV2field.fireEvent(new RunEvent(runNow.get())); } }); label_CV2fieldRB.textProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal.equals(oldVal)){ label_CV2fieldRB.fireEvent(new RunEvent(runNow.get())); } }); } else { label_CV1currentRB.setDisable(true); label_CV1fieldRB.setDisable(true); textField_CV1current.setDisable(true); label_CV2currentRB.setDisable(true); label_CV2fieldRB.setDisable(true); textField_CV2current.setDisable(true); } if(sequence.getNodesOfType("DCH").size()>1){ AcceleratorNode CH1 = sequence.getNodesOfType("DCH").get(0); displayValues.put(CH1.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE),label_CH1currentRB); //displayValues.put(CH1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),label_CH1current); displayValues.put(CH1.getChannel(HDipoleCorr.FIELD_RB_HANDLE),label_CH1fieldRB); setValues.put(CH1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),textField_CH1current); textField_CH1current.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ if(MainFunctions.mainDocument.getModel().get().matches("LIVE")){ try { double val = Double.parseDouble(textField_CH1current.getText()); if(val<120 && val>-120){ CH1.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE).putVal(val); } else { textField_CH1current.setText(Double.toString(CH1.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE).getValDbl())); } } catch (ConnectionException | GetException | PutException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { textField_CH1current.fireEvent(new RunEvent(runNow.get())); } } }); textField_CH1field.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ textField_CH1field.fireEvent(new RunEvent(runNow.get())); } }); label_CH1fieldRB.textProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal.equals(oldVal)){ label_CH1fieldRB.fireEvent(new RunEvent(runNow.get())); } }); AcceleratorNode CH2 = sequence.getNodesOfType("DCH").get(1); displayValues.put(CH2.getChannel(MagnetPowerSupply.CURRENT_RB_HANDLE),label_CH2currentRB); //displayValues.put(CH2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),label_CH2current); displayValues.put(CH2.getChannel(HDipoleCorr.FIELD_RB_HANDLE),label_CH2fieldRB); setValues.put(CH2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE),textField_CH2current); textField_CH2field.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ if(MainFunctions.mainDocument.getModel().get().matches("LIVE")){ try { double val = Double.parseDouble(textField_CH2current.getText()); if(val<120 && val>-120){ CH2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE).putVal(val); } else { textField_CH2current.setText(Double.toString(CH2.getChannel(MagnetPowerSupply.CURRENT_SET_HANDLE).getValDbl())); } } catch (ConnectionException | GetException | PutException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { textField_CH2current.fireEvent(new RunEvent(runNow.get())); } } }); textField_CH2field.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ textField_CH2field.fireEvent(new RunEvent(runNow.get())); } }); label_CH2fieldRB.textProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal.equals(oldVal)){ label_CH2fieldRB.fireEvent(new RunEvent(runNow.get())); } }); } else { label_CH1currentRB.setDisable(true); label_CH1fieldRB.setDisable(true); textField_CH1current.setDisable(true); label_CH2currentRB.setDisable(true); label_CH2fieldRB.setDisable(true); textField_CH2current.setDisable(true); } if(sequence.getNodesOfType("IRIS").size()>0){ AcceleratorNode IrisEquip = sequence.getNodesOfType("IRIS").get(0); displayValues.put(IrisEquip.getChannel(Iris.APERTURE_RB_HANDLE),label_irisApertureRB); setValues.put(IrisEquip.getChannel(Iris.APERTURE_SET_HANDLE),textField_irisAperture); textField_irisAperture.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_irisAperture.getText()); if(val>=0){ IrisEquip.getChannel(Iris.APERTURE_SET_HANDLE).putVal(val); } else { textField_irisAperture.setText(Double.toString(IrisEquip.getChannel(Iris.APERTURE_RB_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); displayValues.put(IrisEquip.getChannel(Iris.OFFSET_X_RB_HANDLE),label_irisXRB); setValues.put(IrisEquip.getChannel(Iris.OFFSET_X_SET_HANDLE),textField_irisX); textField_irisX.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_irisX.getText()); if(val>=-50 && val<=50){ IrisEquip.getChannel(Iris.APERTURE_SET_HANDLE).putVal(val); } else { textField_irisX.setText(Double.toString(IrisEquip.getChannel(Iris.OFFSET_X_RB_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); displayValues.put(IrisEquip.getChannel(Iris.OFFSET_Y_RB_HANDLE),label_irisYRB); setValues.put(IrisEquip.getChannel(Iris.OFFSET_Y_SET_HANDLE),textField_irisY); textField_irisY.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_irisY.getText()); if(val>=-50 && val<=50){ IrisEquip.getChannel(Iris.OFFSET_Y_SET_HANDLE).putVal(val); } else { textField_irisY.setText(Double.toString(IrisEquip.getChannel(Iris.OFFSET_Y_RB_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_irisApertureRB.setDisable(true); textField_irisAperture.setDisable(true); label_irisXRB.setDisable(true); textField_irisX.setDisable(true); label_irisYRB.setDisable(true); textField_irisY.setDisable(true); } if(sequence.getNodesOfType("CHP").size()>0){ AcceleratorNode Chop = sequence.getNodesOfType("CHP").get(0); displayValues.put(Chop.getChannel(Chopper.DELAY_RB_HANDLE),label_chopperDelayRB); setValues.put(Chop.getChannel(Chopper.DELAY_SET_HANDLE),textField_chopperDelay); displayValues.put(Chop.getChannel(Chopper.LENGTH_RB_HANDLE),label_chopperLengthRB); setValues.put(Chop.getChannel(Chopper.LENGTH_SET_HANDLE),textField_chopperLength); displayValues.put(Chop.getChannel(Chopper.STATUS_RB_HANDLE),chopperStatus); textField_chopperDelay.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_chopperDelay.getText()); if(val > 0){ Chop.getChannel(Chopper.DELAY_SET_HANDLE).putVal(val); } else { textField_chopperDelay.setText(Double.toString(Chop.getChannel(Chopper.DELAY_RB_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); textField_chopperLength.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_chopperLength.getText()); if(val > 0){ Chop.getChannel(Chopper.LENGTH_SET_HANDLE).putVal(val); } else { textField_chopperLength.setText(Double.toString(Chop.getChannel(Chopper.LENGTH_RB_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_chopperDelayRB.setDisable(true); textField_chopperDelay.setDisable(true); label_chopperLengthRB.setDisable(true); textField_chopperLength.setDisable(true); chopperStatus.setFill(Color.GRAY); } if(sequence.getNodesOfType("REP").size()>0){ AcceleratorNode Electrode = sequence.getNodesOfType("REP").get(0); displayValues.put(Electrode.getChannel(RepellerElectrode.STATUS_RB_HANDLE),electrodeStatus); electrodeStatus.setFill(Color.GRAY); } if(sequence.getNodesOfType("SCC").size()>0){ AcceleratorNode n2FlowSCC = sequence.getNodesOfType("SCC").get(0); displayValues.put(n2FlowSCC.getChannel(SpaceChargeCompensation.N2FLOW_RB_HANDLE),label_N2flowRB); setValues.put(n2FlowSCC.getChannel(SpaceChargeCompensation.N2FLOW_SET_HANDLE),textField_N2flow); textField_N2flow.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_N2flow.getText()); if(val > 0){ n2FlowSCC.getChannel(SpaceChargeCompensation.N2FLOW_SET_HANDLE).putVal(val); } else { textField_N2flow.setText(Double.toString(n2FlowSCC.getChannel(SpaceChargeCompensation.N2FLOW_SET_HANDLE).getValDbl())); } } catch (ConnectionException | PutException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } else { label_N2flowRB.setDisable(true); textField_N2flow.setDisable(true); } //define electrode properties checkBox_electrode.setTooltip(new Tooltip("Turns RFQ reppeler electrode On and OFF in the simulation only.")); checkBox_electrode.selectedProperty().addListener((obs, oldVal, newVal) ->{ if(newVal){ checkBox_electrode.setText("ON"); textField_sccelectrode.setDisable(false); textField_sccelectrode.setText(Double.toString(spaceChargeCompElectrode)); } else { checkBox_electrode.setText("OFF"); textField_sccelectrode.setDisable(true); textField_sccelectrode.setText(Double.toString(spaceChargeComp)); } checkBox_electrode.fireEvent(new RunEvent(runNow.get())); }); if(sequence.getNodesOfType("DPL").size()>0){ AcceleratorNode DopplerElem = sequence.getNodesOfType("DPL").get(0); displayValues.put(DopplerElem.getChannel(Doppler.FRACTION_H_R_HANDLE),label_Doppler); } else { label_Doppler.setDisable(true); } //Disgnostics equipment if(accl.getAllNodesOfType("BCM").size()>0){ List<AcceleratorNode> BCM = accl.getAllNodesOfType("BCM"); displayValues.put(BCM.get(0).getChannel(CurrentMonitor.I_AVG_HANDLE),label_CurrentMeasurement1); rb_CurrentMeasurement1.setText(BCM.get(0).toString()); if(BCM.size()>1){ displayValues.put(BCM.get(1).getChannel(CurrentMonitor.I_AVG_HANDLE),label_CurrentMeasurement2); rb_CurrentMeasurement2.setText(BCM.get(1).toString()); } else { label_CurrentMeasurement2.setDisable(true); rb_CurrentMeasurement2.setDisable(true); } } else { label_CurrentMeasurement1.setDisable(true); rb_CurrentMeasurement1.setDisable(true); label_CurrentMeasurement2.setDisable(true); rb_CurrentMeasurement2.setDisable(true); } } } private void setupInitialConditions(){ //Set scale text Field textFieldSigmaScale.setText(Double.toString(scale)); //Create listener for intial parameters textField_x.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { comboBox_inputSimul.getSelectionModel().getSelectedItem().setX(Double.parseDouble(textField_x.getText().trim())*1e-3); } catch(NumberFormatException ex) { textField_x.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getX())); } textField_x.fireEvent(new RunEvent(runNow.get())); } }); textField_xp.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { comboBox_inputSimul.getSelectionModel().getSelectedItem().setXP(Double.parseDouble(textField_xp.getText().trim())*1e-3); } catch(NumberFormatException ex) { textField_xp.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getXP())); } textField_xp.fireEvent(new RunEvent(runNow.get())); } }); textField_y.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { comboBox_inputSimul.getSelectionModel().getSelectedItem().setY(Double.parseDouble(textField_y.getText().trim())*1e-3); } catch(NumberFormatException ex) { textField_y.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getY())); } textField_y.fireEvent(new RunEvent(runNow.get())); } }); textField_yp.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { comboBox_inputSimul.getSelectionModel().getSelectedItem().setYP(Double.parseDouble(textField_yp.getText().trim())*1e-3); } catch(NumberFormatException ex) { textField_yp.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getYP())); } textField_yp.fireEvent(new RunEvent(runNow.get())); } }); textField_betax.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_betax.getText().trim()); if(val>=0){ comboBox_inputSimul.getSelectionModel().getSelectedItem().setBETAX(val); } else { textField_betax.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getBETAX())); } } catch(NumberFormatException ex) { textField_betax.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getBETAX())); } textField_betax.fireEvent(new RunEvent(runNow.get())); } }); textField_alphax.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_alphax.getText().trim()); comboBox_inputSimul.getSelectionModel().getSelectedItem().setALPHAX(val); } catch(NumberFormatException ex) { textField_alphax.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getALPHAX())); } textField_alphax.fireEvent(new RunEvent(runNow.get())); } }); textField_emittx.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_emittx.getText().trim()); if(val>=0){ comboBox_inputSimul.getSelectionModel().getSelectedItem().setEMITTX(val*1e-6); } else { textField_emittx.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getEMITTX()*1e6)); } } catch(NumberFormatException ex) { textField_emittx.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getEMITTX()*1e6)); } textField_emittx.fireEvent(new RunEvent(runNow.get())); } }); textField_betay.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_betay.getText().trim()); if(val>=0){ comboBox_inputSimul.getSelectionModel().getSelectedItem().setBETAY(val); } else { textField_betay.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getBETAY())); } } catch(NumberFormatException ex) { textField_betay.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getBETAY())); } textField_betay.fireEvent(new RunEvent(runNow.get())); } }); textField_alphay.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_alphay.getText().trim()); comboBox_inputSimul.getSelectionModel().getSelectedItem().setALPHAY(val); } catch(NumberFormatException ex) { textField_alphay.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getALPHAY())); } textField_alphax.fireEvent(new RunEvent(runNow.get())); } }); textField_emitty.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_emitty.getText().trim()); if(val>=0){ comboBox_inputSimul.getSelectionModel().getSelectedItem().setEMITTY(val*1e-6); } else { textField_emitty.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getEMITTY()*1e6)); } } catch(NumberFormatException ex) { textField_emitty.setText(Double.toString(comboBox_inputSimul.getSelectionModel().getSelectedItem().getEMITTY()*1e6)); } textField_emitty.fireEvent(new RunEvent(runNow.get())); } }); textField_bc.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_bc.getText().trim()); if(val>=0){ beamCurrent=val; } else { textField_bc.setText(Double.toString(beamCurrent)); } } catch(NumberFormatException ex) { textField_bc.setText(Double.toString(beamCurrent)); } textField_bc.fireEvent(new RunEvent(runNow.get())); } }); textField_scc.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_scc.getText().trim()); if(val>=0 && val<=1.0){ spaceChargeComp=Double.parseDouble(textField_scc.getText().trim()); } else { textField_scc.setText(Double.toString(spaceChargeComp)); } } catch(NumberFormatException ex) { textField_scc.setText(Double.toString(spaceChargeComp)); } textField_scc.fireEvent(new RunEvent(runNow.get())); } }); textField_sccelectrode.focusedProperty().addListener((obs, oldVal, newVal) ->{ if(!newVal){ try { double val = Double.parseDouble(textField_sccelectrode.getText().trim()); if(val>=0 && val<=1.0){ spaceChargeCompElectrode=Double.parseDouble(textField_sccelectrode.getText().trim()); } else { textField_sccelectrode.setText(Double.toString(spaceChargeCompElectrode)); } } catch(NumberFormatException ex) { textField_sccelectrode.setText(Double.toString(spaceChargeCompElectrode)); } textField_sccelectrode.fireEvent(new RunEvent(runNow.get())); } }); } /** * Initializes the values in the displayFields and TextFields */ private void initDisplayFields(){ setValues.keySet().forEach(channel ->{ if (setValues.get(channel)!=null){ if (channel.isConnected()){ try { setValues.get(channel).setText(String.format("%.3f",channel.getValDbl())); setValues.get(channel).setStyle("-fx-background-color: white;"); setValues.get(channel).setDisable(false); } catch (ConnectionException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { setValues.get(channel).setStyle("-fx-background-color: magenta;"); setValues.get(channel).setDisable(true); } } }); displayValues.keySet().forEach(channel ->{ if (displayValues.get(channel) instanceof Label){ if (channel.isConnected()){ try { ((Label) displayValues.get(channel)).setText(String.format("%.3f",channel.getValDbl())); ((Label) displayValues.get(channel)).setStyle("-fx-background-color: white;"); ((Label) displayValues.get(channel)).setDisable(false); } catch (ConnectionException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } else { ((Label) displayValues.get(channel)).setStyle("-fx-background-color: magenta;"); ((Label) displayValues.get(channel)).setDisable(true); } } if (displayValues.get(channel) instanceof Circle){ try { int val = (int) Math.round(channel.getValDbl()); switch (val) { case 1: ((Circle) displayValues.get(channel)).setFill(Color.GREEN); break; case 0: ((Circle) displayValues.get(channel)).setFill(Color.RED); break; default: ((Circle) displayValues.get(channel)).setFill(Color.GRAY); break; } } catch (ConnectionException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } /** * Initializes diagnostics elements */ private void initBIElements(){ //Creates a batch of channels to request when updating GUI List<Channel> channels = new ArrayList<>(); //Add NPM channels List<NPM> npms = new ArrayList<>(); List<EMU> emus = new ArrayList<>(); npms = MainFunctions.mainDocument.getAccelerator().getAllNodesOfType("NPM"); npms.forEach(mon->{ channels.add(mon.getChannel(NPM.X_AVG_HANDLE)); channels.add(mon.getChannel(NPM.Y_AVG_HANDLE)); channels.add(mon.getChannel(NPM.X_P_AVG_HANDLE)); channels.add(mon.getChannel(NPM.Y_P_AVG_HANDLE)); channels.add(mon.getChannel(NPM.SIGMA_X_AVG_HANDLE)); channels.add(mon.getChannel(NPM.SIGMA_Y_AVG_HANDLE)); channels.add(mon.getChannel(NPM.ALPHA_X_TWISS_HANDLE)); channels.add(mon.getChannel(NPM.ALPHA_Y_TWISS_HANDLE)); channels.add(mon.getChannel(NPM.BETA_X_TWISS_HANDLE)); channels.add(mon.getChannel(NPM.BETA_Y_TWISS_HANDLE)); }); emus = MainFunctions.mainDocument.getAccelerator().getAllNodesOfType("EMU"); emus.forEach(mon->{ channels.add(mon.getChannel(EMU.EMITT_X_HANDLE)); channels.add(mon.getChannel(EMU.EMITT_Y_HANDLE)); channels.add(mon.getChannel(EMU.ALPHA_X_TWISS_HANDLE)); channels.add(mon.getChannel(EMU.ALPHA_Y_TWISS_HANDLE)); channels.add(mon.getChannel(EMU.BETA_X_TWISS_HANDLE)); channels.add(mon.getChannel(EMU.BETA_Y_TWISS_HANDLE)); }); request = new BatchConnectionRequest( channels ); request.submitAndWait(5.0); comboBox_currentFC.selectedProperty().addListener((obs, oldVal, newVal) ->{ if(comboBox_currentFC.isSelected()){ RadioButton currentBI = (RadioButton) toggleGroup_currentBI.getSelectedToggle(); String nodeBI = currentBI.getText(); Channel currentMonitor = MainFunctions.mainDocument.getAccelerator().getNode(nodeBI).getChannel(CurrentMonitor.I_AVG_HANDLE); textField_bc.textProperty().bind(((Label)displayValues.get(currentMonitor)).textProperty()); textField_bc.setDisable(true); } else { textField_bc.textProperty().unbind(); textField_bc.setDisable(false); } }); } /** * Update the GUI values from the Live machine */ private void updateGUI(){ //Add NPM data to the chart series String sequenceName = MainFunctions.mainDocument.getSequence(); String Sequence = MainFunctions.mainDocument.getAccelerator().getSequences().toString(); String ComboSequence = MainFunctions.mainDocument.getAccelerator().getComboSequences().toString(); if(sequenceName!=null){ List<NPM> npms = new ArrayList<>(); if (Sequence.contains(sequenceName)) { npms = MainFunctions.mainDocument.getAccelerator().getSequence(sequenceName).getAllNodesOfType("NPM"); } else if (ComboSequence.contains(sequenceName)) { npms = MainFunctions.mainDocument.getAccelerator().getComboSequence(sequenceName).getAllNodesOfType("NPM"); } //Cartesian seriesNPMpos[0].getData().clear(); seriesNPMpos[1].getData().clear(); seriesNPMsigma[0].getData().clear(); seriesNPMsigma[1].getData().clear(); //Cylindrical seriesNPMposCyl[0].getData().clear(); seriesNPMposCyl[1].getData().clear(); seriesNPMsigmaCyl.getData().clear(); npms.forEach((mon) -> { if(mon.getChannel(NPM.X_AVG_HANDLE).isConnected() && mon.getChannel(NPM.Y_AVG_HANDLE).isConnected()){ try { seriesNPMpos[0].getData().add(new XYChart.Data(mon.getSDisplay(),mon.getXAvg())); seriesNPMpos[1].getData().add(new XYChart.Data(mon.getSDisplay(),mon.getYAvg())); Complex phi = new Complex(mon.getXAvg(),mon.getYAvg()); long scale2 = getScaleAxis(posPhi,posR); seriesNPMposCyl[0].getData().add(new XYChart.Data(mon.getSDisplay(),phi.modulus())); seriesNPMposCyl[1].getData().add(new XYChart.Data(mon.getSDisplay(),scale2*phi.phase()/Math.PI)); } catch (ConnectionException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); if(radioButtonOffsetOff.isSelected()){ npms.forEach((NPM mon) -> { if(mon.getChannel(NPM.SIGMA_X_AVG_HANDLE).isConnected() && mon.getChannel(NPM.SIGMA_Y_AVG_HANDLE).isConnected()){ try { seriesNPMsigma[0].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getXSigmaAvg()*1.0e+3)); seriesNPMsigma[0].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getXSigmaAvg()*-1.0e+3)); seriesNPMsigma[1].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getYSigmaAvg()*1.0e+3)); seriesNPMsigma[1].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getYSigmaAvg()*-1.0e+3)); seriesNPMsigmaCyl.getData().add(new XYChart.Data(mon.getSDisplay(),scale*Math.max(mon.getXSigmaAvg(), mon.getYSigmaAvg())*1.0e+3)); seriesNPMsigmaCyl.getData().add(new XYChart.Data(mon.getSDisplay(),scale*Math.min(mon.getXSigmaAvg(), mon.getYSigmaAvg())*-1.0e+3)); } catch (ConnectionException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } if(radioButtonOffsetOn.isSelected()){ npms.forEach((NPM mon) -> { if (mon.getChannel(NPM.SIGMA_X_AVG_HANDLE).isConnected() && mon.getChannel(NPM.SIGMA_Y_AVG_HANDLE).isConnected()) { try { seriesNPMsigma[0].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getXSigmaAvg()*1.0e+3+mon.getXAvg())); seriesNPMsigma[0].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getXSigmaAvg()*-1.0e+3+mon.getXAvg())); seriesNPMsigma[1].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getYSigmaAvg()*1.0e+3+mon.getYAvg())); seriesNPMsigma[1].getData().add(new XYChart.Data(mon.getSDisplay(),scale*mon.getYSigmaAvg()*-1.0e+3+mon.getYAvg())); double posR1 = new Complex(mon.getXAvg(),mon.getYAvg()).modulus(); seriesNPMsigmaCyl.getData().add(new XYChart.Data(mon.getSDisplay(), scale*Math.max(mon.getXSigmaAvg(), mon.getYSigmaAvg())*1.0e+3 + posR1)); seriesNPMsigmaCyl.getData().add(new XYChart.Data(mon.getSDisplay(), scale*Math.max(mon.getXSigmaAvg(), mon.getYSigmaAvg())*-1.0e+3 + posR1)); }catch (ConnectionException | GetException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } } }); } } } private void UpdateSimulation(){ setParameters(); try { newRun.runSimulation(); } catch (ModelException | InstantiationException ex) { Logger.getLogger(FXMLController.class.getName()).log(Level.SEVERE, null, ex); } //Display if successful run if(newRun.hasRun()) { retrieveData(newRun); updateGUI(); displayPlots(); } } @FXML private void handleGetCurrentfromFC(ActionEvent event) { if(comboBox_currentFC.isSelected() && !comboBox_currentFC.isDisabled()){ textField_bc.setDisable(true); } else { textField_bc.setDisable(false); } } @FXML private void coordinateHandler(ActionEvent event) { if (newRun.hasRun()){ addTrajectorySeriesToPlot(); npmPosHandler(new ActionEvent()); addEnvelopeSeriesToPlot(); npmSigHandler(new ActionEvent()); } else { setLabels(); setBounds(); } displayPlots(); } @FXML private void offsetHandler(ActionEvent event) { if (newRun.hasRun()){ addEnvelopeSeriesToPlot(); npmSigHandler(new ActionEvent()); label_transmission.setText(String.format("%.3f",newRun.getTransmission(radioButtonOffsetOn.isSelected())*100)); } else { setLabels(); setBounds(); } displayPlots(); } @FXML private void scaleButtonHandler(InputMethodEvent event) { try{ scale = Double.parseDouble(textFieldSigmaScale.getText().trim()); } catch(NumberFormatException e){ Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Error!"); alert.setHeaderText("All inputs must be numbers"); alert.setContentText("Check inputs and try again"); alert.showAndWait(); } if (newRun.hasRun()){ displayEnvelope(); } } @FXML private void npmPosHandler(ActionEvent event) { if(radioButtonCart.isSelected()){ if(comboBox_posNPM.isSelected()){ plot1.getData().add(seriesNPMpos[0]); plot1.getData().add(seriesNPMpos[1]); //Legend legend = (Legend)plot1.lookup(".chart-legend"); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #ff0000, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #006ddb, white;"); //legend.getItems().get(2).getSymbol().setStyle("-fx-background-color: #ff9999, white;"); //legend.getItems().get(3).getSymbol().setStyle("-fx-background-color: #99ccff, white;"); } else { plot1.getData().remove(seriesNPMpos[0]); plot1.getData().remove(seriesNPMpos[1]); //Legend legend = (Legend)plot1.lookup(".chart-legend"); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #ff0000, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #006ddb, white;"); } } if(radioButtonCyl.isSelected()){ if(comboBox_posNPM.isSelected()){ plot1.getData().add(seriesNPMposCyl[0]); plot1.getData().add(seriesNPMposCyl[1]); //Legend legend = (Legend)plot1.lookup(".chart-legend"); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #006400, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #DAA520, white;"); //legend.getItems().get(2).getSymbol().setStyle("-fx-background-color: #99ff99, white;"); //legend.getItems().get(3).getSymbol().setStyle("-fx-background-color: #f2dca6, white;"); } else { plot1.getData().remove(seriesNPMposCyl[0]); plot1.getData().remove(seriesNPMposCyl[1]); //Legend legend = (Legend)plot1.lookup(".chart-legend"); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #006400, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #DAA520, white;"); } } } @FXML private void npmSigHandler(ActionEvent event) { if(radioButtonCart.isSelected()){ if(comboBox_sigmaNPM.isSelected()){ plot2.getData().add(seriesNPMsigma[0]); plot2.getData().add(seriesNPMsigma[1]); //Legend legend = (Legend)plot2.lookup(".chart-legend"); //legend.getItems().remove(0, 4); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #ff0000, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #006ddb, white;"); //legend.getItems().get(2).getSymbol().setStyle("-fx-background-color: #ff9999, white;"); //legend.getItems().get(3).getSymbol().setStyle("-fx-background-color: #99ccff, white;"); } else { plot2.getData().remove(seriesNPMsigma[0]); plot2.getData().remove(seriesNPMsigma[1]); //Legend legend = (Legend)plot2.lookup(".chart-legend"); //int leg_size = legend.getItems().size(); //legend.getItems().remove(0, leg_size-2); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #ff0000, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #006ddb, white;"); } } if(radioButtonCyl.isSelected()){ if(comboBox_sigmaNPM.isSelected()){ plot2.getData().add(seriesNPMsigmaCyl); //Legend legend = (Legend)plot2.lookup(".chart-legend"); //legend.getItems().remove(0, 3); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #006400, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #99ff99, white;"); } else { plot2.getData().remove(seriesNPMsigmaCyl); //Legend legend = (Legend)plot2.lookup(".chart-legend"); //int leg_size = legend.getItems().size(); //legend.getItems().remove(0, leg_size-1); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #006400, white;"); } } } @FXML private void handleMatchParameters(ActionEvent event) { Task<Void> task; task = new Task<Void>(){ @Override protected Void call() throws Exception { //get Sequence String sequenceName = MainFunctions.mainDocument.getSequence(); String Sequence = MainFunctions.mainDocument.getAccelerator().getSequences().toString(); String ComboSequence = MainFunctions.mainDocument.getAccelerator().getComboSequences().toString(); MatchingSolver doMatch = null; //initializing simulation if(Sequence.contains(sequenceName)){ AcceleratorSeq seq = MainFunctions.mainDocument.getAccelerator().getSequence(sequenceName); doMatch = new MatchingSolver(comboBox_inputSimul.getItems().get(0),comboBox_inputSimul.getSelectionModel().getSelectedItem(), seq, 0.00001); } else if(ComboSequence.contains(sequenceName)){ AcceleratorSeqCombo seq = MainFunctions.mainDocument.getAccelerator().getComboSequence(sequenceName); doMatch = new MatchingSolver(comboBox_inputSimul.getItems().get(0),comboBox_inputSimul.getSelectionModel().getSelectedItem(), seq, 0.00001); } if(doMatch !=null){ doMatch.initSimulation(beamCurrent,spaceChargeComp,spaceChargeCompElectrode,checkBox_electrode.isSelected()); doMatch.solve(); InputParameters finalResult = doMatch.newInputValues(); Platform.runLater( () -> { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Matching Dialog"); alert.setHeaderText("Matching result summary."); // Create expandable Exception. String resultText; resultText = "Positions: \n"+ "(x, xp) = "+String.format("%.3f",finalResult.getX()*1e3)+","+String.format("%.3f",finalResult.getXP()*1e3)+"\n"+ "(y, yp) = "+String.format("%.3f",finalResult.getY()*1e3)+","+String.format("%.3f",finalResult.getYP()*1e3)+"\n"+ "Twiss Parameters: \n"+ "(alphax, betax) = "+String.format("%.3f",finalResult.getALPHAX())+","+String.format("%.3f",finalResult.getBETAX())+"\n"+ "(alphay, betay) = "+String.format("%.3f",finalResult.getALPHAY())+","+String.format("%.3f",finalResult.getBETAY())+"\n"+ "Initial emittances: \n"+ "(emittx, emitty) = "+String.format("%.3f",finalResult.getEMITTX()*1e6)+","+String.format("%.3f",finalResult.getEMITTY()*1e6); Label label = new Label("New Input parameters:"); TextArea textArea = new TextArea(resultText); textArea.setEditable(false); textArea.setWrapText(true); textArea.setMaxWidth(Double.MAX_VALUE); textArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(textArea, Priority.ALWAYS); GridPane.setHgrow(textArea, Priority.ALWAYS); GridPane resultContent = new GridPane(); resultContent.setMaxWidth(Double.MAX_VALUE); resultContent.add(label, 0, 0); resultContent.add(textArea, 0, 1); // Set expandable Exception into the dialog pane. alert.getDialogPane().setExpandableContent(resultContent); ButtonType buttonTypeUse = new ButtonType("Use matching result"); ButtonType buttonTypeCancel = new ButtonType("Cancel"); alert.getButtonTypes().setAll(buttonTypeUse, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeUse){ comboBox_inputSimul.getItems().get(0).setX(finalResult.getX()); comboBox_inputSimul.getItems().get(0).setXP(finalResult.getXP()); comboBox_inputSimul.getItems().get(0).setY(finalResult.getY()); comboBox_inputSimul.getItems().get(0).setYP(finalResult.getYP()); comboBox_inputSimul.getItems().get(0).setALPHAX(finalResult.getALPHAX()); comboBox_inputSimul.getItems().get(0).setBETAX(finalResult.getBETAX()); comboBox_inputSimul.getItems().get(0).setEMITTX(finalResult.getEMITTX()); comboBox_inputSimul.getItems().get(0).setALPHAY(finalResult.getALPHAY()); comboBox_inputSimul.getItems().get(0).setBETAY(finalResult.getBETAY()); comboBox_inputSimul.getItems().get(0).setEMITTY(finalResult.getEMITTY()); comboBox_inputSimul.getSelectionModel().select(0); } }); //MODEL_SYNC_TIMER.resume(); } return null; } ; }; Thread calibrate = new Thread(task); calibrate.setDaemon(true); // thread will not prevent application shutdown //MODEL_SYNC_TIMER.suspend(); calibrate.start(); } /** * Gets parameters from simulation objects and assigns to text fields */ private void getParameters(){ double[] initPos = new double[4]; double[] TwissX = new double[3]; double[] TwissY = new double[3]; initPos = comboBox_inputSimul.getSelectionModel().getSelectedItem().getInit(); TwissX = comboBox_inputSimul.getSelectionModel().getSelectedItem().getTwissX(); TwissY = comboBox_inputSimul.getSelectionModel().getSelectedItem().getTwissY(); textField_x.setText(String.format("%.4f",initPos[0]*1e03)); textField_xp.setText(String.format("%.4f",initPos[1]*1e03)); textField_y.setText(String.format("%.4f",initPos[2]*1e03)); textField_yp.setText(String.format("%.4f",initPos[3]*1e03)); textField_alphax.setText(String.format("%.3f",TwissX[0])); textField_betax.setText(String.format("%.3f",TwissX[1])); textField_emittx.setText(String.format("%.3f",TwissX[2]*1e06)); textField_alphay.setText(String.format("%.3f",TwissY[0])); textField_betay.setText(String.format("%.3f",TwissY[1])); textField_emitty.setText(String.format("%.3f",TwissY[2]*1e06)); beamCurrent = newRun.getBeamCurrent(); textField_bc.setText(Double.toString(beamCurrent)); spaceChargeComp = newRun.getSpaceChargeCompensation(); spaceChargeCompElectrode = newRun.getSpaceChargeCompensationElectrode(); textField_scc.setText(Double.toString(spaceChargeComp)); textField_sccelectrode.setText(Double.toString(spaceChargeCompElectrode)); } /** * Sets simulation parameters from text fields. */ private void setParameters(){ double[] initPos = {0.0,0.0,0.0,0.0}; double[] TwissX = {0.0,0.0,0.0}; double[] TwissY = {0.0,0.0,0.0}; if(comboBox_inputSimul.getSelectionModel().getSelectedItem() != null){ initPos = comboBox_inputSimul.getSelectionModel().getSelectedItem().getInit(); TwissX = comboBox_inputSimul.getSelectionModel().getSelectedItem().getTwissX(); TwissY = comboBox_inputSimul.getSelectionModel().getSelectedItem().getTwissY(); } try{ newRun.setInitialBeamParameters(initPos[0],initPos[1],initPos[2],initPos[3]); newRun.setBeamCurrent(Double.parseDouble(textField_bc.getText())); newRun.setBeamTwissX(TwissX[0],TwissX[1],TwissX[2]); newRun.setBeamTwissY(TwissY[0],TwissY[1],TwissY[2]); newRun.setInitSimulPos(comboBox_inputSimul.getSelectionModel().getSelectedItem().getName()); newRun.setSpaceChargeCompensation(spaceChargeComp,spaceChargeCompElectrode); newRun.setElectrode(checkBox_electrode.isSelected()); newRun.setModelSync(MainFunctions.mainDocument.getModel().get()); //Set fields: if model changes from Live to DESIGN the defaults fileds will be up-to-date newRun.setSolenoid1Field(Double.parseDouble(textField_sol1field.getText())); newRun.setSolenoid2Field(Double.parseDouble(textField_sol2field.getText())); newRun.setVsteerer1Field(Double.parseDouble(textField_CV1field.getText())); newRun.setVsteerer2Field(Double.parseDouble(textField_CV2field.getText())); newRun.setHsteerer1Field(Double.parseDouble(textField_CH1field.getText())); newRun.setHsteerer2Field(Double.parseDouble(textField_CH2field.getText())); } catch(NumberFormatException e){ Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Error!"); alert.setHeaderText("All inputs must be numbers"); alert.setContentText("Check inputs and try again"); alert.showAndWait(); } } /** * Retrieves and displays trajectory plots * @param newRun the simulation */ private void retrieveData(SimulationRunner newRun){ //get Sequence String sequenceName = MainFunctions.mainDocument.getSequence(); String Sequence = MainFunctions.mainDocument.getAccelerator().getSequences().toString(); String ComboSequence = MainFunctions.mainDocument.getAccelerator().getComboSequences().toString(); double pos_ini = 0.0; if (Sequence.contains(sequenceName)) { pos_ini = MainFunctions.mainDocument.getAccelerator().getSequence(sequenceName).getPosition(); } else if (ComboSequence.contains(sequenceName)) { pos_ini = MainFunctions.mainDocument.getAccelerator().getComboSequence(sequenceName).getPosition(); } //retrieves data sigmaX = newRun.getSigmaX(); sigmaY = newRun.getSigmaY(); sigmaR = newRun.getSigmaR(); positions = newRun.getPositions(); posX = newRun.getPosX(); posY = newRun.getPosY(); posR = newRun.getPosR(); posPhi = newRun.getPosPhi(); for(int i = 0; i < positions.size() ; i++) { positions.set(i, (Double) positions.get(i) + pos_ini); } label_transmission.setText(String.format("%.3f",newRun.getTransmission(radioButtonOffsetOn.isSelected())*100)); } /** * Retrieves and displays vaccum chamber apertures */ private void getVacuumChamber(Object Sequence){ double[][] vacuumChamber; seriesSurroundings[0].getData().clear(); seriesSurroundings[1].getData().clear(); if(Sequence != null){ if(Sequence instanceof AcceleratorSeqCombo){ vacuumChamber = ((AcceleratorSeqCombo) Sequence).getAperProfile().getProfileXArray(); for (int i = 0; i < vacuumChamber[0].length ; i++) { seriesSurroundings[0].getData().add(new XYChart.Data(vacuumChamber[0][i], vacuumChamber[1][i]*1e3)); seriesSurroundings[1].getData().add(new XYChart.Data(vacuumChamber[0][i], -1*vacuumChamber[1][i]*1e3)); } } else if(Sequence instanceof AcceleratorSeq){ vacuumChamber = ((AcceleratorSeq) Sequence).getAperProfile().getProfileXArray(); for (int i = 0; i < vacuumChamber[0].length ; i++) { seriesSurroundings[0].getData().add(new XYChart.Data(vacuumChamber[0][i], vacuumChamber[1][i]*1e3)); seriesSurroundings[1].getData().add(new XYChart.Data(vacuumChamber[0][i], -1*vacuumChamber[1][i]*1e3)); } } } else { seriesSurroundings[0].getData().add(new XYChart.Data(0.0, 0.0)); seriesSurroundings[1].getData().add(new XYChart.Data(0.0, 0.0)); } } /** * Checks which coordinate system radio button is selected and displays plots accordingly */ private void displayPlots(){ yAxis.setAutoRanging(true); if (radioButtonCart.isSelected()){ displayCartTrajectory(); } else if (radioButtonCyl.isSelected()){ displayCylTrajectory(); } displayEnvelope(); } /** * Checks which coordinate system radio button is selected and displays envelope accordingly */ private void displayEnvelope(){ if (radioButtonCart.isSelected()){ displayCartEnvelope(); } else if (radioButtonCyl.isSelected()){ displayCylEnvelope(); } } /** * Displays the trajectory in Cartesian coordinates */ private void displayCartTrajectory(){ clearTrajectorySeries(); for (int i = 0; i < posX.size() ; i++) { seriesX.getData().add(new XYChart.Data(positions.get(i), posX.get(i))); seriesY.getData().add(new XYChart.Data(positions.get(i), posY.get(i))); } yAxis.setLabel("Trajectory (mm)"); } /** * Displays the trajectory in cylindrical coordinates */ private void displayCylTrajectory(){ clearTrajectorySeries(); long scale2 = getScaleAxis(posPhi,posR); for (int i = 0; i < posX.size() ; i++) { seriesR.getData().add(new XYChart.Data(positions.get(i), posR.get(i))); seriesPhi.getData().add(new XYChart.Data(positions.get(i), new Double(posPhi.get(i).toString())*scale2)); } if (scale2 != 1){ yAxis.setLabel("Offset (mm) \nAngle (" + Double.toString((double) 1/scale2) + " * π rad)"); //System.out.print(scale2); } else{ yAxis.setLabel("Offset (mm) \nAngle (π rad)"); } } /** * Checks which offset radio button is selected and displays envelope accordingly in Cartesian coordinates */ private void displayCartEnvelope(){ clearEnvelopeSeries(); setCartBounds(); if (radioButtonOffsetOff.isSelected()){ for (int i = 0; i < sigmaX[0].size(); i++){ seriesSigmaX[0].getData().add(new XYChart.Data(positions.get(i), ((double) sigmaX[0].get(i))*scale)); seriesSigmaY[0].getData().add(new XYChart.Data(positions.get(i), ((double) sigmaY[0].get(i))*scale)); seriesSigmaX[1].getData().add(new XYChart.Data(positions.get(i), ((double) sigmaX[1].get(i))*scale)); seriesSigmaY[1].getData().add(new XYChart.Data(positions.get(i), ((double) sigmaY[1].get(i))*scale)); } } else if (radioButtonOffsetOn.isSelected()){ for (int i = 0; i < sigmaX[0].size(); i++){ seriesSigmaOffsetX[0].getData().add(new XYChart.Data(positions.get(i), scaleAndOffset(sigmaX[0],posX,scale,i))); seriesSigmaOffsetY[0].getData().add(new XYChart.Data(positions.get(i), scaleAndOffset(sigmaY[0],posY,scale,i))); seriesSigmaOffsetX[1].getData().add(new XYChart.Data(positions.get(i), scaleAndOffset(sigmaX[1],posX,scale,i))); seriesSigmaOffsetY[1].getData().add(new XYChart.Data(positions.get(i), scaleAndOffset(sigmaY[1],posY,scale,i))); } } } /** * Checks which offset radio button is selected and displays envelope accordingly in cylindrical coordinates */ private void displayCylEnvelope(){ clearEnvelopeSeries(); setCylBounds(); if (radioButtonOffsetOff.isSelected()){ for (int i = 0; i < sigmaX[0].size(); i++){ seriesSigmaR[0].getData().add(new XYChart.Data(positions.get(i), ((double) sigmaR[0].get(i))*scale)); seriesSigmaR[1].getData().add(new XYChart.Data(positions.get(i), ((double) sigmaR[1].get(i))*scale)); } if (Collections.max(sigmaR[0]) > 100){ yAxis1.setUpperBound(Collections.max(sigmaR[0])+10); } //seriesSigmaR[0].getNode().setStyle("-fx-stroke: #006400;"); //seriesSigmaR[1].getNode().setStyle("-fx-stroke: #006400;"); } else if (radioButtonOffsetOn.isSelected()){ for (int i = 0; i < sigmaR[0].size(); i++){ seriesSigmaOffsetR[0].getData().add(new XYChart.Data(positions.get(i), scaleAndOffset(sigmaR[0],posR,scale,i))); seriesSigmaOffsetR[1].getData().add(new XYChart.Data(positions.get(i), scaleAndOffset(sigmaR[1],posR,scale,i))); } yAxis1.setLowerBound(-90); yAxis1.setUpperBound(90); } } /** * Determines which surrounding to show */ private void setBounds(){ if (radioButtonCart.isSelected()){ setCartBounds(); } else if (radioButtonCyl.isSelected()){ setCylBounds(); } } /** * Displays the surroundings in both positive and negative range. */ private void setCartBounds(){ yAxis1.setAutoRanging(false); yAxis1.setLowerBound(-90); yAxis1.setUpperBound(90); } /** * Displays the surroundings in only positive range. */ private void setCylBounds(){ yAxis1.setAutoRanging(false); yAxis1.setLowerBound(0.0); yAxis1.setUpperBound(90); } private void setLabels(){ if (radioButtonCart.isSelected()){ yAxis.setLabel("Offset (mm)"); } else if (radioButtonCyl.isSelected()){ yAxis.setLabel("Offset (mm) \n Angle (π rad)"); } } private long getScaleAxis(ArrayList<Double> posphi, ArrayList<Double> posr){ int i = 1; double maxphi = Collections.max(posphi); double minphi = Collections.min(posphi); double maxr = Collections.max(posr); double minr = Collections.min(posr); double scalephi = Math.max(Math.abs(maxphi),Math.abs(minphi)); double scaler = Math.max(Math.abs(maxr),Math.abs(minr)); if(scalephi>scaler){ return Math.round(scaler/scalephi)==0 ? 1 : Math.round(scaler/scalephi); } else { return Math.round(scalephi/scaler)==0 ? 1 : Math.round(scalephi/scaler); } } private double scaleAndOffset(ArrayList<Double> sigma, ArrayList<Double> pos, double scale, int i){ return ((double) sigma.get(i)*scale+(double) pos.get(i)); } /** * Removes the series from plot and adds the relevant series. */ private void addTrajectorySeriesToPlot(){ plot1.getData().removeAll(seriesX,seriesY,seriesR,seriesPhi,seriesNPMpos[0],seriesNPMpos[1],seriesNPMposCyl[0],seriesNPMposCyl[1]); if(radioButtonCart.isSelected()){ plot1.getData().add(seriesX); plot1.getData().add(seriesY); //Set Style plot1.getStylesheets().remove(0); plot1.getStylesheets().add(this.getClass().getResource("/styles/TrajectoryPlot.css").toExternalForm()); //set colors //Legend legend = (Legend)plot1.lookup(".chart-legend"); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #ff0000, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #006ddb, white;"); } else if (radioButtonCyl.isSelected()){ plot1.getData().add(seriesR); plot1.getData().add(seriesPhi); //set Style plot1.getStylesheets().remove(0); plot1.getStylesheets().add(this.getClass().getResource("/styles/TrajectoryPlotCyl.css").toExternalForm()); //set colors //Legend legend = (Legend)plot1.lookup(".chart-legend"); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #006400, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #DAA520, white;"); } } /** * Removes series from plot and adds the relevant series. */ private void addEnvelopeSeriesToPlot(){ plot2.getData().removeAll(seriesSigmaX[0],seriesSigmaX[1], seriesSigmaY[0],seriesSigmaY[1], seriesSigmaR[0],seriesSigmaR[1], seriesSigmaOffsetX[0],seriesSigmaOffsetX[1], seriesSigmaOffsetY[0],seriesSigmaOffsetY[1], seriesSigmaOffsetR[0],seriesSigmaOffsetR[1], seriesNPMsigma[0],seriesNPMsigma[1],seriesNPMsigmaCyl); if(radioButtonCart.isSelected()){ if(radioButtonOffsetOn.isSelected()){ for(int i = 0; i < seriesSigmaX.length; i++){ plot2.getData().add(seriesSigmaOffsetX[i]); plot2.getData().add(seriesSigmaOffsetY[i]); } } else if (radioButtonOffsetOff.isSelected()){ for(int i = 0; i < seriesSigmaX.length; i++){ plot2.getData().add(seriesSigmaX[i]); plot2.getData().add(seriesSigmaY[i]); } } //set Style plot2.getStylesheets().remove(0); plot2.getStylesheets().add(this.getClass().getResource("/styles/EnvelopePlot.css").toExternalForm()); //set legend colors //Legend legend = (Legend)plot2.lookup(".chart-legend"); //legend.getItems().remove(0, 4); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #ff0000, white;"); //legend.getItems().get(1).getSymbol().setStyle("-fx-background-color: #006ddb, white;"); } else if (radioButtonCyl.isSelected()){ if(radioButtonOffsetOn.isSelected()){ for(int i = 0; i < seriesSigmaX.length; i++){ plot2.getData().add(seriesSigmaOffsetR[i]); } } else if (radioButtonOffsetOff.isSelected()){ for(int i = 0; i < seriesSigmaX.length; i++){ plot2.getData().add(seriesSigmaR[i]); } } //set Style plot2.getStylesheets().remove(0); plot2.getStylesheets().add(this.getClass().getResource("/styles/EnvelopePlotCyl.css").toExternalForm()); //set legend colors //Legend legend = (Legend)plot2.lookup(".chart-legend"); //legend.getItems().remove(0, 3); //legend.getItems().get(0).getSymbol().setStyle("-fx-background-color: #006400, white;"); } } /** * Clears plot1 of all data */ private void clearTrajectorySeries(){ seriesX.getData().clear(); seriesY.getData().clear(); seriesR.getData().clear(); seriesPhi.getData().clear(); } /** * Clears plot2 of all data */ private void clearEnvelopeSeries(){ for (int i = 0; i < seriesSigmaX.length; i++){ seriesSigmaX[i].getData().clear(); seriesSigmaY[i].getData().clear(); seriesSigmaR[i].getData().clear(); seriesSigmaOffsetX[i].getData().clear(); seriesSigmaOffsetY[i].getData().clear(); seriesSigmaOffsetR[i].getData().clear(); } } public class Magnet{ private String magnetName; private String newField; private String oldField; private final BooleanProperty selected = new SimpleBooleanProperty(); public Magnet(String magnetName, String newField, String oldField, boolean selected) { this.magnetName = magnetName; this.newField = newField; this.oldField = oldField; this.selected.set(selected); } public BooleanProperty selectedProperty() { return selected; } public String getMagnetName() { return magnetName; } public void setMagnetName(String magnetName) { this.magnetName = magnetName; } public String getNewField() { return newField; } public void setNewField(String newField) { this.newField = newField; } public String getOldField() { return oldField; } public void setOldField(String oldField) { this.oldField = oldField; } } }
package net.hyperic.sigar.test; import java.io.File; import java.io.FileInputStream; import net.hyperic.sigar.Sigar; import net.hyperic.sigar.SigarException; import net.hyperic.sigar.SigarLoader; import net.hyperic.sigar.SigarNotImplementedException; public class TestProcFd extends SigarTestCase { public TestProcFd(String name) { super(name); } public void testCreate() throws Exception { Sigar sigar = getSigar(); try { sigar.getProcFd(getInvalidPid()); } catch (SigarException e) { } try { long pid = sigar.getPid(); long total = sigar.getProcFd(pid).getTotal(); File file = new File(SigarLoader.getLocation(), "sigar.jar"); traceln("Opening " + file); FileInputStream is = new FileInputStream(file); assertEqualsTrace("Total", total + 1, sigar.getProcFd(pid).getTotal()); is.close(); assertEqualsTrace("Total", total, sigar.getProcFd(pid).getTotal()); } catch (SigarNotImplementedException e) { } } }
package net.i2p.syndie; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; import com.sun.syndication.feed.synd.SyndCategory; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import net.i2p.I2PAppContext; import net.i2p.data.Base64; import net.i2p.data.DataFormatException; import net.i2p.data.DataHelper; import net.i2p.data.Hash; import net.i2p.syndie.data.BlogURI; import net.i2p.util.EepGet; import net.i2p.util.Log; public class Sucker { private static final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(Sucker.class); private String urlToLoad; private String outputDir="./sucker_out"; private String historyPath="./sucker.history"; private String feedTag="feed"; private File historyFile; private String proxyPort; private String proxyHost; private String pushScript; private int attachmentCounter=0; private String messagePath; private String baseUrl; private boolean importEnclosures=true; private boolean importRefs=true; private boolean pendingEndLink; private boolean shouldProxy; private int proxyPortNum; private String blog; private boolean pushToSyndie; private long messageNumber=0; private BlogManager bm; private User user; private List fileNames; private List fileStreams; private List fileTypes; private List tempFiles; // deleted after finished push private boolean stripNewlines; public Sucker() { } /** * Constructor for BlogManager. */ public Sucker(String[] strings) throws IllegalArgumentException { pushToSyndie=true; urlToLoad = strings[0]; blog = strings[1]; feedTag = strings[2]; outputDir = "blog-"+blog; try { historyPath=BlogManager.instance().getRootDir().getCanonicalPath()+"/rss.history"; } catch (IOException e) { e.printStackTrace(); } proxyPort="4444"; proxyHost="localhost"; bm = BlogManager.instance(); Hash blogHash = new Hash(); try { blogHash.fromBase64(blog); } catch (DataFormatException e1) { throw new IllegalArgumentException("ooh, bad $blog"); } user = bm.getUser(blogHash); if(user==null) throw new IllegalArgumentException("wtf, user==null? hash:"+blogHash); } public boolean parseArgs(String args[]) { for (int i = 0; i < args.length; i++) { if ("--load".equals(args[i])) urlToLoad = args[++i]; if ("--outputdir".equals(args[i])) outputDir = args[++i]; if ("--history".equals(args[i])) historyPath = args[++i]; if ("--tag".equals(args[i])) feedTag = args[++i]; if ("--proxyhost".equals(args[i])) proxyHost = args[++i]; if ("--proxyport".equals(args[i])) proxyPort = args[++i]; if ("--exec".equals(args[i])) pushScript = args[++i]; if ("--importenclosures".equals(args[i])) importEnclosures= args[++i].equals("true"); if ("--importenrefs".equals(args[i])) importRefs= args[++i].equals("true"); } // Cut ending '/' from outputDir if (outputDir.endsWith("/")) outputDir = outputDir.substring(0, outputDir.length() - 1); if (urlToLoad == null) return false; return true; } /** * Fetch urlToLoad and call convertToHtml() on any new entries. */ public void suck() { SyndFeed feed; File fetched=null; tempFiles = new ArrayList(); // Find base url int idx=urlToLoad.lastIndexOf('/'); if(idx>0) baseUrl=urlToLoad.substring(0,idx); else baseUrl=urlToLoad; infoLog("Processing: "+urlToLoad); debugLog("Base url: "+baseUrl); try { File lastIdFile=null; // Get next message number to use (for messageId in history only) if(!pushToSyndie) { lastIdFile = new File(historyPath + ".lastId"); if (!lastIdFile.exists()) lastIdFile.createNewFile(); FileInputStream fis = new FileInputStream(lastIdFile); String number = readLine(fis); try { messageNumber = Integer.parseInt(number); } catch (NumberFormatException e) { messageNumber = 0; } // Create outputDir if missing File f = new File(outputDir); f.mkdirs(); } else { messageNumber=bm.getNextBlogEntry(user); } // Create historyFile if missing historyFile = new File(historyPath); if (!historyFile.exists()) historyFile.createNewFile(); shouldProxy = false; proxyPortNum = -1; if ( (proxyHost != null) && (proxyPort != null) ) { try { proxyPortNum = Integer.parseInt(proxyPort); if (proxyPortNum > 0) shouldProxy = true; } catch (NumberFormatException nfe) { nfe.printStackTrace(); } } // fetch int numRetries = 2; fetched = File.createTempFile("sucker", ".fetch"); EepGet get = new EepGet(I2PAppContext.getGlobalContext(), shouldProxy, proxyHost, proxyPortNum, numRetries, fetched.getAbsolutePath(), urlToLoad); SuckerFetchListener lsnr = new SuckerFetchListener(); get.addStatusListener(lsnr); get.fetch(); boolean ok = lsnr.waitForSuccess(); if (!ok) { System.err.println("Unable to retrieve the url after " + numRetries + " tries."); fetched.delete(); return; } if(get.getNotModified()) { debugLog("not modified, saving network bytes from useless fetch"); fetched.delete(); return; } // Build entry list from fetched rss file SyndFeedInput input = new SyndFeedInput(); feed = input.build(new XmlReader(fetched)); List entries = feed.getEntries(); FileOutputStream hos = new FileOutputStream(historyFile, true); // Process list backwards to get syndie to display the // entries in the right order. (most recent at top) for (int i = entries.size()-1; i >= 0; i SyndEntry e = (SyndEntry) entries.get(i); attachmentCounter=0; String messageId = convertToSml(e); if (messageId!=null) { hos.write(messageId.getBytes()); hos.write("\n".getBytes()); } } if(!pushToSyndie) { FileOutputStream fos = new FileOutputStream(lastIdFile); fos.write(("" + messageNumber).getBytes()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (FeedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(fetched!=null) fetched.delete(); debugLog("Done."); } public static void main(String[] args) { Sucker sucker = new Sucker(); boolean ok = sucker.parseArgs(args); if (!ok) { System.out.println("sucker --load $urlToFeed \n" + "--proxyhost <host> \n" + "--proxyport <port> \n" + "--importenclosures true \n" + "--importrefs true \n" + "--tag feed \n" + "--outputdir ./sucker_out \n" + "--exec pushscript.sh OUTPUTDIR UNIQUEID ENTRYTIMESTAMP \n" + "--history ./sucker.history"); System.exit(1); } sucker.suck(); } /** * Call the specified script with "$outputDir $id and $time". */ private boolean execPushScript(String id, String time) { try { String ls_str; String cli = pushScript + " " + outputDir + " " + id + " " + time; Process pushScript_proc = Runtime.getRuntime().exec(cli); // get its output (your input) stream DataInputStream ls_in = new DataInputStream(pushScript_proc.getInputStream()); try { while ((ls_str = ls_in.readLine()) != null) { infoLog(pushScript + ": " + ls_str); } } catch (IOException e) { return false; } try { pushScript_proc.waitFor(); if(pushScript_proc.exitValue()==0) return true; } catch (InterruptedException e) { e.printStackTrace(); } return false; } catch (IOException e1) { System.err.println(e1); return false; } } /** * Converts the SyndEntry e to sml and fetches any images as attachments */ private String convertToSml(SyndEntry e) { String subject; stripNewlines=false; // Calculate messageId, and check if we have got the message already String feedHash = sha1(urlToLoad); String itemHash = sha1(e.getTitle() + e.getDescription()); Date d = e.getPublishedDate(); String time; if(d!=null) time = "" + d.getTime(); else time = "" + new Date().getTime(); String outputFileName = outputDir + "/" + messageNumber; String messageId = feedHash + ":" + itemHash + ":" + time + ":" + outputFileName; // Check if we already have this if (existsInHistory(messageId)) return null; infoLog("new: " + messageId); try { String sml=""; subject=e.getTitle(); List cats = e.getCategories(); Iterator iter = cats.iterator(); String tags = feedTag; while (iter.hasNext()) { SyndCategory c = (SyndCategory) iter.next(); debugLog("Name: "+c.getName()); debugLog("uri:"+c.getTaxonomyUri()); String tag=c.getName(); tag=tag.replaceAll("[^a-zA-z.-_:]","_"); tags += "\t" + feedTag + "." + tag; } SyndContent content; List l = e.getContents(); if(l!=null) { debugLog("There is content"); iter = l.iterator(); while(iter.hasNext()) { content = (SyndContent)iter.next(); String c = content.getValue(); debugLog("Content: "+c); sml += htmlToSml(c); sml += "\n"; } } String source=e.getUri(); if(source.indexOf("http")<0) source=baseUrl+source; sml += "[link schema=\"web\" location=\""+source+"\"]source[/link]\n"; if(pushToSyndie) { debugLog("user.blog: "+user.getBlogStr()); debugLog("user.id: "+bm.getNextBlogEntry(user)); debugLog("subject: "+subject); debugLog("tags: "+tags); debugLog("sml: "+sml); debugLog(""); BlogURI uri = bm.createBlogEntry( user, false, subject, tags, null, sml, fileNames, fileStreams, fileTypes); if(uri==null) { errorLog("pushToSyndie failure."); return null; } else infoLog("pushToSyndie success, uri: "+uri.toString()); } else { FileOutputStream fos; fos = new FileOutputStream(messagePath); sml=subject + "\nTags: " + tags + "\n\n" + sml; fos.write(sml.getBytes()); if (pushScript != null) { if (!execPushScript(""+messageNumber, time)) { errorLog("push script failed"); } else { infoLog("push script success: nr "+messageNumber); } } } messageNumber++; deleteTempFiles(); return messageId; } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } deleteTempFiles(); return null; } private void deleteTempFiles() { Iterator iter = tempFiles.iterator(); while(iter.hasNext()) { File tempFile = (File)iter.next(); tempFile.delete(); } } private String htmlToSml(String html) { String sml=""; int i; pendingEndLink=false; for(i=0;i<html.length();) { char c=html.charAt(i); if(c=='<') { //log("html: "+html.substring(i)); int tagLen = findTagLen(html.substring(i)); if(tagLen<=0) { // did not find anything that looks like tag, treat it like text sml+="&lt;"; i++; continue; } String htmlTag = html.substring(i,i+tagLen); //log("htmlTag: "+htmlTag); String smlTag = htmlTagToSmlTag(htmlTag); if(smlTag!=null) { sml+=smlTag; i+=tagLen; sml+=" "; } else { // Unrecognized tag, treat it as text sml+="&lt;"; i++; continue; } } else { if( !stripNewlines || (c!='\r' && c!='\n')) { sml+=c; if(c=='[' || c==']') sml+=c; } i++; } } return sml; } private String htmlTagToSmlTag(String htmlTag) { final String ignoreTags[] = { "span", "tr", "td", "th", "div", "input" }; String ret=""; String htmlTagLowerCase=htmlTag.toLowerCase(); if(htmlTagLowerCase.startsWith("<img")) { debugLog("Found image tag: "+htmlTag); int a,b; a=htmlTagLowerCase.indexOf("src=\"")+5; b=a+1; while(htmlTagLowerCase.charAt(b)!='\"') b++; String imageLink=htmlTag.substring(a,b); if(pendingEndLink) { // <a href="..."><img src="..."></a> -> [link][/link][img][/img] ret="[/link]"; pendingEndLink=false; } ret += "[img attachment=\""+""+ attachmentCounter +"\"]"; a=htmlTagLowerCase.indexOf("alt=\"")+5; if(a>=5) { b=a; if(htmlTagLowerCase.charAt(b)!='\"') { while(htmlTagLowerCase.charAt(b)!='\"') b++; String altText=htmlTag.substring(a,b); ret+=altText; } } ret+="[/img]"; if(imageLink.indexOf("http")<0) imageLink=baseUrl+"/"+imageLink; fetchAttachment(imageLink); debugLog("Converted to: "+ret); return ret; } if(htmlTagLowerCase.startsWith("<a ")) { debugLog("Found link tag: "+htmlTag); int a,b; a=htmlTagLowerCase.indexOf("href=\"")+6; b=a+1; while(htmlTagLowerCase.charAt(b)!='\"') b++; String link=htmlTag.substring(a,b); if(link.indexOf("http")<0) link=baseUrl+"/"+link; String schema="web"; ret += "[link schema=\""+schema+"\" location=\""+link+"\"]"; if(htmlTagLowerCase.endsWith("/>")) ret += "[/link]"; else pendingEndLink=true; debugLog("Converted to: "+ret); return ret; } if ("</a>".equals(htmlTagLowerCase)) { if (pendingEndLink) { pendingEndLink=false; return "[/link]"; } } if("<b>".equals(htmlTagLowerCase)) return "[b]"; if("</b>".equals(htmlTagLowerCase)) return "[/b]"; if("<i>".equals(htmlTagLowerCase)) return "[i]"; if("</i>".equals(htmlTagLowerCase)) return "[/i]"; if("<em>".equals(htmlTagLowerCase)) return "[i]"; if("</em>".equals(htmlTagLowerCase)) return "[/i]"; if(htmlTagLowerCase.startsWith("<br")) { stripNewlines=true; return "\n"; } if("</br>".equals(htmlTagLowerCase)) return ""; if(htmlTagLowerCase.startsWith("<table") || "</table>".equals(htmlTagLowerCase)) // emulate table with hr return "[hr][/hr]"; for(int i=0;i<ignoreTags.length;i++) { String openTag = "<"+ignoreTags[i]; String closeTag = "</"+ignoreTags[i]; if(htmlTagLowerCase.startsWith(openTag)) return ""; if(htmlTagLowerCase.startsWith(closeTag)) return ""; } return null; } private void fetchAttachment(String link) { link=link.replaceAll("&amp;","&"); infoLog("Fetch attachment from: "+link); File fetched; if(pushToSyndie) { try { // perhaps specify a temp dir? fetched = File.createTempFile("sucker",".attachment"); fetched.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); return; } tempFiles.add(fetched); } else { String attachmentPath = messagePath+"."+attachmentCounter; fetched = new File(attachmentPath); } int numRetries = 2; // we use eepGet, since it retries and doesn't leak DNS requests like URL does EepGet get = new EepGet(I2PAppContext.getGlobalContext(), shouldProxy, proxyHost, proxyPortNum, numRetries, fetched.getAbsolutePath(), link); SuckerFetchListener lsnr = new SuckerFetchListener(); get.addStatusListener(lsnr); get.fetch(); boolean ok = lsnr.waitForSuccess(); if (!ok) { System.err.println("Unable to retrieve the url after " + numRetries + " tries."); fetched.delete(); return; } tempFiles.add(fetched); String filename=EepGet.suggestName(link); String contentType = get.getContentType(); if(contentType==null) contentType="text/plain"; debugLog("successful fetch of filename "+filename); if(fileNames==null) fileNames = new ArrayList(); if(fileTypes==null) fileTypes = new ArrayList(); if(fileStreams==null) fileStreams = new ArrayList(); fileNames.add(filename); fileTypes.add(contentType); try { fileStreams.add(new FileInputStream(fetched)); } catch (FileNotFoundException e) { e.printStackTrace(); } attachmentCounter++; } private void errorLog(String string) { if (_log.shouldLog(Log.ERROR)) _log.error(string); if(!pushToSyndie) System.out.println(string); } private void infoLog(String string) { if (_log.shouldLog(Log.INFO)) _log.info(string); if(!pushToSyndie) System.out.println(string); } private void debugLog(String string) { if (_log.shouldLog(Log.DEBUG)) _log.debug(string); if(!pushToSyndie) System.out.println(string); } private static int findTagLen(String s) { int i; for(i=0;i<s.length();i++) { if(s.charAt(i)=='>') return i+1; if(s.charAt(i)=='"') { i++; while(i<s.length() && s.charAt(i)!='"') i++; } } return -1; } private boolean existsInHistory(String messageId) { int idx; idx = messageId.lastIndexOf(":"); String lineToCompare = messageId.substring(0, idx-1); idx = lineToCompare.lastIndexOf(":"); lineToCompare = lineToCompare.substring(0, idx-1); try { FileInputStream his = new FileInputStream(historyFile); String line; while ((line = readLine(his)) != null) { idx = line.lastIndexOf(":"); if (idx < 0) return false; line = line.substring(0, idx-1); idx = line.lastIndexOf(":"); if (idx < 0) return false; line = line.substring(0, idx-1); if (line.equals(lineToCompare)) return true; } } catch (FileNotFoundException e) { e.printStackTrace(); } return false; } private static String sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(s.getBytes()); byte[] buf = md.digest(); String ret = Base64.encode(buf); return ret; } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return null; } private static String readLine(FileInputStream in) { StringBuffer sb = new StringBuffer(); int c = 0; while (true) { try { c = in.read(); } catch (IOException e) { e.printStackTrace(); break; } if (c < 0) break; if (c == '\n') break; sb.append((char) c); } return sb.toString(); } } /** * Simple blocking listener for eepget. block in waitForSuccess(). */ class SuckerFetchListener implements EepGet.StatusListener { private volatile boolean _complete; private volatile boolean _successful; public SuckerFetchListener() { _complete = false; _successful = false; } public void transferComplete(long alreadyTransferred, long bytesTransferred, long bytesRemaining, String url, String outputFile, boolean notModified) { notifyComplete(true); } public void transferFailed(String url, long bytesTransferred, long bytesRemaining, int currentAttempt) { notifyComplete(false); } private void notifyComplete(boolean ok) { synchronized (this) { _complete = true; _successful = ok; notifyAll(); } } /** * Block until the fetch is successful, returning true if it did fetch completely, * false if it didn't. * */ public boolean waitForSuccess() { while (!_complete) { try { synchronized (this) { wait(); } } catch (InterruptedException ie) {} } return _successful; } public void attemptFailed(String url, long bytesTransferred, long bytesRemaining, int currentAttempt, int numRetries, Exception cause) { // noop, it may retry } public void bytesTransferred(long alreadyTransferred, int currentWrite, long bytesTransferred, long bytesRemaining, String url) { // ignore this status update } public void headerReceived(String url, int currentAttempt, String key, String val) { // ignore } }
package comments.user; import static com.dyuproject.protostuffdb.EntityMetadata.ZERO_KEY; import static com.dyuproject.protostuffdb.SerializedValueUtil.readByteArrayOffsetWithTypeAsSize; import java.io.IOException; import java.util.Arrays; import com.dyuproject.protostuff.KeyBuilder; import com.dyuproject.protostuff.Pipe; import com.dyuproject.protostuff.RpcHeader; import com.dyuproject.protostuff.RpcResponse; import com.dyuproject.protostuffdb.DSRuntimeExceptions; import com.dyuproject.protostuffdb.Datastore; import com.dyuproject.protostuffdb.OpChain; import com.dyuproject.protostuffdb.ProtostuffPipe; import com.dyuproject.protostuffdb.RangeV; import com.dyuproject.protostuffdb.ValueUtil; import com.dyuproject.protostuffdb.WriteContext; /** * Comment ops. */ public final class CommentOps { private CommentOps() {} static byte[] append(byte[] data, int offset, int len, byte[] suffix) { byte[] buf = new byte[len+suffix.length]; System.arraycopy(data, offset, buf, 0, len); System.arraycopy(suffix, 0, buf, len, suffix.length); return buf; } static Comment validateAndProvide(Comment param, long now, OpChain chain) { byte[] parentKey = param.parentKey; if (parentKey.length == 0 || Arrays.equals(parentKey, ZERO_KEY)) { param.parentKey = ZERO_KEY; return param.provide(now, ZERO_KEY, 0); } final WriteContext context = chain.context; final byte[] parentValue = chain.vs().get(parentKey, Comment.EM, null); if (parentValue == null) throw DSRuntimeExceptions.operationFailure("Parent comment does not exist!"); int offset = readByteArrayOffsetWithTypeAsSize(Comment.FN_KEY_CHAIN, parentValue, context), size = context.type, depth = size / 9; if (depth > 127) throw DSRuntimeExceptions.operationFailure("The nested replies are too deep and have exceeded the limit."); return param.provide(now, append(parentValue, offset, size, parentKey), depth); } static boolean create(Comment req, Datastore store, RpcResponse res, Pipe.Schema<Comment.PList> resPipeSchema, RpcHeader header) throws IOException { final byte[] lastSeenKey = req.key, key = new byte[9]; if (!store.chain(null, XCommentOps.OP_NEW, req, 0, res.context, key)) return res.fail("Could not create."); req.key = key; if (req.parentKey != ZERO_KEY) { // user posted a reply final byte[] startKey; if (lastSeenKey == null) { startKey = ValueUtil.copy(req.keyChain, 0, req.keyChain.length - 8); } else { startKey = ValueUtil.copy(req.keyChain, 0, req.keyChain.length); // visit starting the entry after the last seen one lastSeenKey[lastSeenKey.length - 1] |= 0x02; System.arraycopy(lastSeenKey, 0, startKey, startKey.length - 9, 9); } KeyBuilder kb = res.context.kb() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append(startKey) .$push() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$push() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append8(0xFF) .$push(); final ProtostuffPipe pipe = res.context.pipe.init( Comment.EM, Comment.getPipeSchema(), Comment.PList.FN_P, true); try { store.visitRange(false, -1, false, kb.copy(-2), res.context, RangeV.RES_PV, res, kb.buf(), kb.offset(-1), kb.len(-1), kb.buf(), kb.offset(), kb.len()); } finally { pipe.clear(); } } else if (lastSeenKey != null) { // visit starting the entry after the last seen one lastSeenKey[lastSeenKey.length - 1] |= 0x02; KeyBuilder kb = res.context.kb() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append(ZERO_KEY) .$append(lastSeenKey) .$push() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$push() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append8(0xFF) .$push(); final ProtostuffPipe pipe = res.context.pipe.init( Comment.EM, Comment.getPipeSchema(), Comment.PList.FN_P, true); try { store.visitRange(false, -1, false, kb.copy(-2), res.context, RangeV.RES_PV, res, kb.buf(), kb.offset(-1), kb.len(-1), kb.buf(), kb.offset(), kb.len()); } finally { pipe.clear(); } } else { CommentViews.visitByPostId(req.postId, store, res.context, RangeV.Store.ENTITY_PV, RangeV.RES_PV, res); } return true; } }
package net.saick.android.calcapp.core; import java.text.DecimalFormat; import java.util.ArrayList; //enum CalcAction { // NONE, // - // PLUS, // // MINUS, // // MULI, // // DIVIDE, // // EQUAL, // // PERSENT, // // PLUSMINUS // /** * @author Eric * */ public class CalcCore { private double lastValue = 0.0; private double currentValue = 0.0; private CalcAction lastAction = CalcAction.NONE; // TODO: private ArrayList history; private CalcCore() { } /** * * @param v1 * @param v2 * @param action * @return */ private double calculateWithTwoValue(double v1, double v2, CalcAction action) { double result = v2; switch (action) { case DIVIDE: result = v1 / v2; break; case EQUAL: result = v2; break; case MINUS: result = v1 - v2; break; case MULI: result = v1 * v2; break; case NONE: result = v2; break; case PERSENT: result = v2 * 0.01; break; case PLUS: result = v1 + v2; break; case PLUSMINUS: { if (v2 > 0) { result = 0 - v2; } else { result = v2 * -1; } } break; default: break; } return result; } private static class CalcSingletonHolder { private final static CalcCore instance = new CalcCore(); } /** * * @return */ public static CalcCore getInstance() { return CalcSingletonHolder.instance; } /** * @param type * @return */ public static String calculate(CalcAction action) { CalcCore calc = CalcCore.getInstance(); CalcAction doAction; if (action == CalcAction.EQUAL) { doAction = calc.lastAction; } else { doAction = action; } double result = calc.calculateWithTwoValue(calc.lastValue, calc.currentValue, doAction); calc.lastValue = calc.currentValue; calc.currentValue = result; calc.lastAction = action; return CalcCore.currentOutput(); } /** * @param value */ public static String input(String value) { CalcCore calc = CalcCore.getInstance(); String origin = Double.toString(calc.currentValue); if (calc.currentValue <= 0.0) { origin = ""; } else { // contiune } StringBuffer sb = new StringBuffer(); sb.append(origin); value = Double.toString(Double.valueOf(value)); if (Double.valueOf(value) <= 0.0) { // continue } else { sb.append(value); } String current = sb.toString(); try { calc.currentValue = Double.valueOf(current); } catch (Exception e) { } finally { } return CalcCore.currentOutput(); } /** * @return */ public static String currentOutput() { DecimalFormat decimalFormat = new DecimalFormat(" return decimalFormat.format(CalcCore.getInstance().currentValue); } /** * AC * @return */ public static Boolean isNeedDelete() { CalcCore calc = CalcCore.getInstance(); if (calc.currentValue != 0.0) { return true; } else { return false; } } public static String clear() { CalcCore calc = CalcCore.getInstance(); calc.currentValue = 0.0; return CalcCore.currentOutput(); } public static String allclear() { CalcCore calc = CalcCore.getInstance(); calc.currentValue = 0.0; calc.lastValue = 0.0; calc.lastAction = CalcAction.NONE; calc.history.clear(); return CalcCore.currentOutput(); } }
package cx2x.translator.language; import cx2x.translator.language.helper.accelerator.AcceleratorDirective; import cx2x.translator.language.helper.accelerator.AcceleratorGenerator; import cx2x.translator.language.helper.target.Target; import cx2x.xcodeml.exception.IllegalDirectiveException; import cx2x.xcodeml.language.AnalyzedPragma; import cx2x.xcodeml.xelement.Xpragma; import exc.object.Xcode; import exc.object.Xobject; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * ClawLanguage class represent an analyzed pragma statement. * * @author clementval */ public class ClawLanguage extends AnalyzedPragma { private static final String PREFIX_CLAW = "claw"; private AcceleratorGenerator _generator; private Target _target; private ClawDirective _directive; // Clauses values private String _accClausesValue; private String _arrayName; private int _collapseClauseValue; private List<String> _dataValues; private String _groupClauseValue; private List<String> _fctCallParameters; private String _fctName; private List<String> _hoistInductionValues; private List<String> _indexesValues; private List<String> _inductionClauseValues; private List<ClawMapping> _mappingValues; private List<Integer> _offsetValues; private ClawRange _rangeValue; private List<ClawReshapeInfo> _reshapeInfos; private List<ClawDimension> _dimensions; private List<String> _overValues; // Clauses flags private boolean _hasAccClause, _hasCollapseClause, _hasDataClause; private boolean _hasDimensionClause, _hasFusionClause, _hasGroupClause; private boolean _hasIndexesValue, _hasInductionClause, _hasInitClause; private boolean _hasInterchangeClause, _hasOverClause, _hasParallelClause; private boolean _hasPrivateClause, _hasReshapeClause; /** * Constructs an empty ClawLanguage section. * WARNING: This ctor should only be used by the parser. */ protected ClawLanguage(){ resetVariables(); } /** * Constructs an empty ClawLanguage object with an attached pragma. Used only * for transformation that are not CLAW related. * @param pragma The pragma that is attached to the ClawLanguage object. */ public ClawLanguage(Xpragma pragma){ super(pragma); resetVariables(); } private void resetVariables(){ // Clauses values members _accClausesValue = null; _arrayName = null; _collapseClauseValue = 0; _dataValues = null; _dimensions = null; _fctCallParameters = null; _fctName = null; _groupClauseValue = null; _hoistInductionValues = null; _indexesValues = null; _inductionClauseValues = null; _mappingValues = null; _offsetValues = null; _overValues = null; _rangeValue = null; _reshapeInfos = null; // Clauses flags members _hasAccClause = false; _hasCollapseClause = false; _hasDimensionClause = false; _hasFusionClause = false; _hasGroupClause = false; _hasIndexesValue = false; _hasInductionClause = false; _hasInitClause = false; _hasInterchangeClause = false; _hasOverClause = false; _hasParallelClause = false; _hasPrivateClause = false; _hasReshapeClause = false; // General members _directive = null; _generator = null; // super class members _pragma = null; } /** * Check if the pragma statement starts with the claw keyword. * @param pragma The Xpragma object to check. * @return True if the statement starts with claw keyword. False otherwise. */ public static boolean startsWithClaw(Xpragma pragma) { return !(pragma == null || pragma.getValue() == null) && pragma.getValue().startsWith(PREFIX_CLAW); } public static ClawLanguage analyze(Xpragma pragma, AcceleratorGenerator generator, Target target) throws IllegalDirectiveException { ClawLanguage l = analyze(pragma.getValue(), pragma.getLineNo(), generator, target); if(l != null){ l.attachPragma(pragma); } return l; } public static ClawLanguage analyze(Xobject pragma, AcceleratorGenerator generator, Target target) throws IllegalDirectiveException { if(pragma.Opcode() != Xcode.PRAGMA_LINE){ throw new IllegalDirectiveException("Not a pragma statement", "", pragma.getLineNo().lineNo()); } ClawLanguage l = analyze(pragma.getArg(0).getString(), pragma.getLineNo().lineNo(), generator, target); if(l != null){ l.attachPragma(pragma); } return l; } /** * Produce a "naked" pragma. * OMNI compiler keeps the claw prefix when a pragma is defined on several * lines using the continuation symbol '&'. In order to have a simpler * grammar, these multiple occurences of the prefix are not taken into * account. Therefore, this method remove all the prefix and keeps only the * first one. * @param rawPragma The original raw pragma statement straight from OMNI * compiler resprestentation. * @return A naked pragma statement able to be analyzed by the CLAW parser. */ private static String nakenize(String rawPragma){ return PREFIX_CLAW + " " + rawPragma.toLowerCase().replaceAll(PREFIX_CLAW, ""); } private static ClawLanguage analyze(String rawPragma, int lineno, AcceleratorGenerator generator, Target target) throws IllegalDirectiveException { // Remove additional claw keyword rawPragma = nakenize(rawPragma); // Instantiate the lexer with the raw string input ClawLexer lexer = new ClawLexer(new ANTLRInputStream(rawPragma)); // Get a list of matched tokens CommonTokenStream tokens = new CommonTokenStream(lexer); // Pass the tokens to the parser ClawParser parser = new ClawParser(tokens); parser.setErrorHandler(new BailErrorStrategy()); parser.removeErrorListeners(); ClawErrorListener cel = new ClawErrorListener(); parser.addErrorListener(cel); try { // Start the parser analysis from the "analyze" entry point ClawParser.AnalyzeContext ctx = parser.analyze(); // Get the ClawLanguage object return by the parser after analysis. ctx.l.setAcceleratorGenerator(generator); ctx.l.setTarget(target); return ctx.l; } catch(ParseCancellationException pcex){ IllegalDirectiveException ex = cel.getLastError(); if(ex != null){ throw ex; } else { throw new IllegalDirectiveException(rawPragma, "Unsupported construct", lineno, 0); } } } /** * Check whether a group clause was specified. * @return True if group clause was specified. */ public boolean hasGroupClause(){ return _hasGroupClause; } /** * Set the group name and hasGroupClause to true * @param groupName The group name defined in the group clause. */ void setGroupClause(String groupName){ if(groupName != null) { _hasGroupClause = true; _groupClauseValue = groupName; } } /** * Get the group name defined in the group clause. * @return The group name as a String value. */ public String getGroupValue(){ return _groupClauseValue; } /** * Check whether the collapse clause is used. * @return True if the collapse clause if used. */ public boolean hasCollapseClause(){ return _hasCollapseClause; } /** * Set the collapse number and boolean flag. * @param n Number of loop to be collapsed. Will be converted to integer. */ void setCollapseClause(String n){ setCollapseClause(Integer.parseInt(n)); } /** * Set the collapse number and boolean flag. Flag is enable if n is greater * than 1. Otherwise, collapse clause has no impact. * @param n Number of loops to be collapsed. */ void setCollapseClause(int n){ if(n > 1) { _hasCollapseClause = true; _collapseClauseValue = n; } } /** * Get the collapse clause extracted value. * @return An interger value. */ public int getCollapseValue(){ return _collapseClauseValue; } // Loop interchange specific methods /** * Set the list of interhcnage indexes. * @param indexes List of indexes as string. */ void setIndexes(List<String> indexes){ _hasIndexesValue = true; _indexesValues = indexes; } /** * Get the loop index list * @return List of loop index */ public List<String> getIndexes(){ return _indexesValues; } /** * Check whether the interchange directive has indexes values. * @return True if the directive has interchange value. */ public boolean hasIndexes(){ return _hasIndexesValue; } // Loop extract specific methods /** * Set the range value. * @param range A ClawRange object. */ protected void setRange(ClawRange range){ _rangeValue = range; } /** * Get the range extracted value. * @return A ClawRange object. */ public ClawRange getRange(){ return _rangeValue; } /** * Set the ClawMapping list * @param mappings A list of ClawMapping objects. */ void setMappings(List<ClawMapping> mappings){ _mappingValues = mappings; } /** * Get the list of extracted ClawMapping objects. * @return List of ClawMapping objects. */ public List<ClawMapping> getMappings(){ return _mappingValues; } /** * Enable the fusion clause for the current directive. */ void setFusionClause(){ _hasFusionClause = true; } /** * Check whether the current directive has the fusion clause enabled. * @return True if the fusion clause is enabled. */ public boolean hasFusionClause(){ return _hasFusionClause; } /** * Enable the parallel clause for the current directive. */ void setParallelClause(){ _hasParallelClause = true; } /** * Check whether the current directive has the parallel clause enabled. * @return True if the parallel clause is enabled. */ public boolean hasParallelClause(){ return _hasParallelClause; } /** * Enable the accelerator clause for the current directive and set the * extracted clauses. * @param clauses Accelerator clauses extracted from the accelerator clause. */ void setAcceleratorClauses(String clauses){ _hasAccClause = true; _accClausesValue = clauses; } /** * Check whether the current directive has the accelerator clause enabled. * @return True if the accelerator clause is enabled. */ public boolean hasAcceleratorClause(){ return _hasAccClause; } /** * Get the accelerator clauses extracted from the accelerator clause. * @return Accelerator clauses as a String. */ public String getAcceleratorClauses(){ return _accClausesValue; } /** * Set the offsets list extracted from the kcache directive. * @param offsets A list of offsets. */ void setOffsets(List<Integer> offsets){ _offsetValues = offsets; } /** * Get the list of offsets. * @return List of offsets. */ public List<Integer> getOffsets(){ return _offsetValues; } // loop hoist clauses /** * Check whether the interchange clause is used. * @return True if the interchange clause if used. */ public boolean hasInterchangeClause(){ return _hasInterchangeClause; } /** * Set the interchange clause as used. */ void setInterchangeClause(){ _hasInterchangeClause = true; } /** * Set the list of induction variables used in the loop-hoist directive. * @param vars List of induction variable. */ void setHoistInductionVars(List<String> vars){ _hoistInductionValues = vars; } /** * Get the list of induction variables used in the hoist directive. * @return A list of induction variable. */ public List<String> getHoistInductionVars(){ return _hoistInductionValues; } // Directive generic method /** * Define the current directive of the language section. * @param directive A value of the ClawDirective enumeration. */ public void setDirective(ClawDirective directive){ _directive = directive; } /** * Get the current directive of the language section. * @return Value of the current directive. */ public ClawDirective getDirective(){ return _directive; } /** * Enable the induction clause for the current directive and set the extracted * name value. * @param names List of induction name extracted from the clause. */ void setInductionClause(List<String> names){ _hasInductionClause = true; _inductionClauseValues = names; } /** * Check whether the current directive has the induction clause enabled. * @return True if the induction clause is enabled. */ public boolean hasInductionClause(){ return _hasInductionClause; } /** * Get the name value extracted from the induction clause. * @return Induction name as a String. */ public List<String> getInductionValues(){ return _inductionClauseValues; } /** * Enable the data clause for the current directive and set the extracted * identifiers value. * @param data List of identifiers extracted from the clause. */ void setDataClause(List<String> data){ _hasDataClause = true; _dataValues = data; } /** * Check whether the current directive has the induction clause enabled. * @return True if the data clause is enabled. */ public boolean hasDataClause(){ return _hasDataClause; } /** * Get the identifier values extracted from the data clause. * @return Identifier as a String. */ public List<String> getDataClauseValues(){ return _dataValues; } /** * Enable the over clause for the current directive and set the extracted * dimensions value. * @param data List of dimension extracted from the clause. */ void setOverClause(List<String> data){ _hasOverClause = true; _overValues = data; } /** * Check whether the current directive has the over clause enabled. * @return True if the over clause is enabled. */ public boolean hasOverClause(){ return _hasOverClause; } /** * Get the dimensions values extracted from the over clause. * @return Dimensions identifier or : as a String. */ public List<String> getOverClauseValues(){ return _overValues; } /** * Check whether the init clause is used. * @return True if the init clause is used. */ public boolean hasInitClause(){ return _hasInitClause; } /** * Set the init clause flag. */ void setInitClause(){ _hasInitClause = true; } /** * Check whether the private clause is used. * @return True if the private clause is used. */ public boolean hasPrivateClause(){ return _hasPrivateClause; } /** * Set the private clause flag. */ void setPrivateClause(){ _hasPrivateClause = true; } /** * Set the list of parameters for the fct call of the "call" directive * @param data List of identifiers extracted from the clause. */ void setFctParams(List<String> data){ _fctCallParameters = data; } /** * Get the list of parameters extracted from the call directive. * @return List of parameters identifier as String value. */ public List<String> getFctParams(){ return _fctCallParameters; } /** * Set the array name value. * @param value String value for the array name. */ void setArrayName(String value){ _arrayName = value; } /** * Get the array name extracted from the call directive. * @return Array name from the call directive. */ public String getArrayName(){ return _arrayName; } /** * Set the function name value. * @param value String value for the function name. */ void setFctName(String value){ _fctName = value; } /** * Get the fct name extracted from the call directive. * @return Fct name from the call directive. */ public String getFctName(){ return _fctName; } /** * Set the reshape clause extracted information. * @param infos List of ClawReshapeInfo objects containing the extracted * information from the reshape clause. */ void setReshapeClauseValues(List<ClawReshapeInfo> infos){ _hasReshapeClause = true; _reshapeInfos = infos; } /** * Get the reshape extracted information. * @return List of ClawReshapeInfo objects containing the extracted * information from the reshape clause. */ public List<ClawReshapeInfo> getReshapeClauseValues(){ return _reshapeInfos; } /** * Check whether the reshape clause is used. * @return True if the reshape clause is used. */ public boolean hasReshapeClause(){ return _hasReshapeClause; } /** * Check whether the dimesion clause is used. * @return True if the dimesion clause is used. */ public boolean hasDimensionClause(){ return _hasDimensionClause; } /** * Add a new dimension extracted from the directive. * @param dimension ClawDimension object constructed from the value extracted * in the clause. */ void addDimension(ClawDimension dimension){ _hasDimensionClause = true; if(_dimensions == null){ _dimensions = new ArrayList<>(); } _dimensions.add(dimension); } /** * Get the dimensions extracted information. * @return All dimensions extracted from the directive. */ public List<ClawDimension> getDimesionValues(){ return _dimensions; } /** * Get the dimensions extracted information in reverse order. * @return All dimensions extracted from the directive in reverse order. */ public List<ClawDimension> getDimensionValuesReversed(){ List<ClawDimension> tmp = new ArrayList<>(_dimensions); Collections.reverse(tmp); return tmp; } /** * Attach the pragma related to this CLAW language analysis. * @param pragma Xpragma object. */ private void attachPragma(Xpragma pragma){ _pragma = pragma; } /** * Attach the pragma related to this CLAW language analysis. * @param pragma Xobject associated with the pragma statement. */ private void attachPragma(Xobject pragma){ } /** * Set the accelerator directive generator for pragma generation * @param generator The current accelerator directive generator. */ private void setAcceleratorGenerator(AcceleratorGenerator generator){ _generator = generator; } /** * Get the accelerator generator for the current accelerator directive * language associated with the program. * @return Associated accelerator directive generator. */ public AcceleratorGenerator getAcceleratorGenerator(){ return _generator; } /** * Set the target for code transformation. * @param target A target value from the enumeration. */ private void setTarget(Target target){ _target = target; } /** * Get the associated target. * @return Target. */ public Target getTarget(){ return _target; } /** * Get the current accelerator directive language target. * @return Value of the AcceleratorDirective enumeration. */ public AcceleratorDirective getDirectiveLanguage(){ return (_generator != null) ? _generator.getDirectiveLanguage() : AcceleratorDirective.NONE; } /** * Create an instance of ClawLanguage that correspond to a loop-fusion * directive. Used for dynamically created transformation. * @param master Base object which initiate the creation of this instance. * @return An instance of ClawLanguage describing a loop-fusion with the * group, collapse clauses and the pragma from the master object. */ public static ClawLanguage createLoopFusionLanguage(ClawLanguage master){ ClawLanguage l = new ClawLanguage(); l.setDirective(ClawDirective.LOOP_FUSION); l.setGroupClause(master.getGroupValue()); l.setCollapseClause(master.getCollapseValue()); l.attachPragma(master.getPragma()); return l; } /** * Create an instance of ClawLanguage that correspond to a loop-fusion * directive. Used for dynamically created transformation. * @param base Pragma that triggered the transformation. * @param group Group clause value. * @param collapse Collapse clause value. * @return An instance of ClawLanguage describing a loop-fusion with the * group, collapse clauses and the pragma from the master object. */ public static ClawLanguage createLoopFusionLanguage(Xpragma base, String group, int collapse) { ClawLanguage l = new ClawLanguage(); l.setDirective(ClawDirective.LOOP_FUSION); l.setGroupClause(group); l.setCollapseClause(collapse); l.attachPragma(base); return l; } /** * Create an instance of ClawLanguage that correspond to a loop-interchange * directive. Used for dynamically created transformation. * @param master Base object which initiate the creation of this instance. * @param pragma Pragma statement located just before the first do stmt. * @return An instance of ClawLanguage describing a loop-interchange with the * indexes from the master object. */ public static ClawLanguage createLoopInterchangeLanguage(ClawLanguage master, Xpragma pragma) { ClawLanguage l = new ClawLanguage(); l.setDirective(ClawDirective.LOOP_INTERCHANGE); l.setIndexes(master.getIndexes()); l.attachPragma(pragma); return l; } }
package ui; import static businessLogic.GameEngine.checkCommand; import data.Player; import data.Round; import java.util.Scanner; public class UI { private static final Scanner IN = new Scanner(System.in); private static String inputUI; private static final String COMMANDS = "\n" + "Type <Exit> at any time to exit \n" + "Type <Info> to know about this project\n" + "Type <Help> if you need some help\n" + "Type <Hands> to print Hands"; public static final String[] RANKS = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}; public static final String[] SUITS = {"\u2660", "\u2663", "\u2764", "\u2666"}; static final String DECORATOR = "********/*/"; public static final String DEALER = "D"; public static final String BIGBLIND = "\u0E4F"; public static final String LITTLEBLIND = "\u263B"; public static void printTest() { System.out.println(DEALER); System.out.println(BIGBLIND); System.out.println(LITTLEBLIND); } public static void printWelcome() { System.out.println("\nWelcome to UN Hold' em"); String ascci = ". + "|U.--. ||N.--. ||H.--. ||O.--. ||L.--. ||D.--. ||'.--. ||E.--. ||M.--. |\n" + "| (\\/) || :(): || :/\\: || :/\\: || :/\\: || :/\\: || :/\\: || (\\/) || (\\/) |\n" + "| :\\/: || ()() || (__) || :\\/: || (__) || (__) || :\\/: || :\\/: || :\\/: |\n" + "| '--'U|| '--'N|| '--'H|| '--'O|| '--'L|| '--'D|| '--''|| '--'E|| '--'M|\n" + "` + " "; System.out.print(ascci); printCommands(); } public static void printError(Exception ex) { if ("Command".equals(ex.getMessage())) { return; } System.out.print("Error: "); System.out.println(ex.getMessage()); } public static String askMsg(String question) throws Exception { System.out.print(question); inputUI = IN.nextLine(); if (checkCommand(inputUI, true)) { throw new Exception("Command"); } return inputUI; } public static int askInt(String question) throws Exception { askMsg(question); try { return Integer.parseInt(inputUI); } catch (Exception e) { throw new Exception("Not a number"); } } public static void printHelp() { System.out.println(DECORATOR); System.out.println("Poker Hold'em is a game of bets in which each player has two cards and the goal is to assemble the \n best set of five cards between yours and the five comunitary cards."); System.out.println("The comunitary cards are showed to all the players in this way: After each round of bets, a card \n of the deck is 'burned'(discarded)"); System.out.println("and three cards(first round) or one card(other rounds) are showed until five cards were at sight."); System.out.println("You can match the bet, backing out, or check (pass) on your turn"); System.out.println("bet more if you have a good hand in the game and win more points "); System.out.println(DECORATOR); printHands(); } public static void printHands() { System.out.println("These are the hands you can form on the game, they are sorted upward by value (1 = higher value):"); System.out.println("1) Royal Flush: 10" + "\u2660 " + "J" + "\u2660 " + "Q" + "\u2660 " + "K" + "\u2660 " + "A" + "\u2660 " + "(five higher cards from the same suit )"); System.out.println("2) Straight Flush: 4\u2663 5\u2663 6\u2663 7\u2663 8\u2663 (Five cards consecutive from the same suit)"); System.out.println("3) Four of a Kind: A\u2660 A\u2663 A\u2764 A\u2666 8\u2663 (Four A's and a kicker*, )"); System.out.println("4) Full House: 10\u2666 10\u2764 10\u2663 J\u2660 J\u2663 (A pair and a Three of a Kind, in tie case wins the one who has the higher Three of a Kind)"); System.out.println("5) Flush: 5\u2660 7\u2660 2\u2660 9\u2660 Q\u2660 (Five cards in disorder of the same suit)"); System.out.println("6) Straight: 3\u2764 4\u2663 5\u2764 6\u2666 7\u2660 (Five consecutive card from different suits)"); System.out.println("7) Three of a Kind: 7\u2666 7\u2663 7\u2764 A\u2666 (Three card of the same value, the last two have to be different between them)"); System.out.println("8) Double Pair: Q\u2764 Q\u2663 J\u2663 J\u2666 4\u2764 (two pairs of cards , in case of tie wins the one who has the higher pair and so on)"); System.out.println("9) Pair: 8\u2666 8\u2660 K\u2663 7\u2666 3\u2764"); System.out.println("10) High Card: A\u2764 J\u2663 10\u2666 5\u2764 6\u2666 (When anybody have some of the previous hands, wins the one who has the higher kicker*)"); System.out.println("* \nA kicker is the highest card on that doesn't determine the type of the hand, it decides who wins in case of tie"); System.out.println("P.S.: If two or more player have the same hand, wins the higher one, if the hands are completely the same \n the prize is divided among the winners. Also, if two or more player have hands that are composed of other hands like \n double pair(two pairs) or full house(Three of a kind and a pair) and there is a tie, the sub-hand are compared until \n the kicker if it's necessary and wins the higher of them."); System.out.println("We hope you enjoy it! :D"); System.out.println(DECORATOR); } public static void printCommands() { System.out.println(COMMANDS); } public static void printMainMenu() { System.out.println("ººººººººMenuºººººººº "); System.out.println("(1) - Start a round? \t (2) - Never played poker before? \t (3) - Command List\n(4) - Exit"); System.out.print("Your option here:"); } public static void printRoundMenu() { System.out.println("(1) - Check \t (2) - Raise \t (3) - Fold \t (4) - All in \t (5)- Retire"); System.out.println("Note: currently only option (5) is functional\n(Type any from 1 to 4 to check the progress of a poker round)"); } public static void printExit() { System.out.println("\nThanks, see you later"); } public static void printInfo() { System.out.print("Developer Team :"); System.out.println("One Poker"); } /** * Prints the round players and their hands used to test at the start and * end of round * * @param ronda */ public static void printStandings(Round ronda) { //System.out.println("PLAYERS SIZE: " + ronda.getPlayersSize()); System.out.println("At the end of a round a winner is choosen, if there is a tie the pot is splitted"); System.out.println("Each player can form a \"Best hand\" combining his cards with the comunitary hand"); System.out.println("The player(s) with the best hand wins"); System.out.println("\nStandings(from best to worst):"); for (Player plyr : ronda.getPlayers()) { System.out.print("Player "); System.out.print(plyr); System.out.println(""); } if (ronda.getPlayer(0).getId() % 5 == 0) { System.out.println("You win"); } else if (ronda.getPlayer(1).compareTo(ronda.getPlayer(0)) == 0) { System.out.println("Tie"); } else { System.out.println("You lose"); } System.out.println("Type <Hands> to check how Hand are ranked"); } /** * Prints the board with the bottoms * * @param pos rank of between 0 to 7 * @param players length is always 8 * */ public static void printBoard(int pos, Round ronda) { Player[] players = new Player[8]; for (int i = 0; i < ronda.getPlayersSize(); i++) { players[i] = ronda.getPlayer(i); } String[] botones = new String[8]; /*boolean bigBlind = false; boolean littleBlind = false; for (int i = pos; i > pos - botones.length; i--) { if (!(players[(i + 8) % 8] == (null))) { if (i == pos) { System.out.println("HERE: " + i); botones[(i + 8) % 8] = BIGBLIND; bigBlind = true; } else if (bigBlind) { System.out.println("HERE: >" + i); botones[(i + 8) % 8] = LITTLEBLIND; bigBlind = false; littleBlind = true; } else if (littleBlind) { System.out.println("HERE:>> " + i); botones[(i + 8) % 8] = DEALER; littleBlind = false; } else { botones[(i + 8) % 8] = " "; } } else { botones[(i + 8) % 8] = " "; } }*/ switch (pos) { case 0: { System.out.println("YOU ARE PLAYER #" + ronda.getPlayer(0).getId()); System.out.println("2 cards are dealt to each player"); System.out.println("The flop: "); break; } case 1: { System.out.println("The turn: "); break; } case 2: { System.out.println("The river: "); break; } } botones[0] = BIGBLIND; botones[1] = LITTLEBLIND; botones[2] = DEALER; for (int i = 3; i < 8; i++) { botones[i] = ""; } String handTableStr = ""; int count = 5; for (int i = 0; i < ronda.getTableHand().getSize(); i++, count handTableStr += ronda.getTableHand().getCard(i).toString(); } for (int i = 0; i < count; i++) { handTableStr += " "; } String foo = handTableStr.length() > 16 ? "\t" : "\t\t"; System.out.println(" System.out.println(" #\t " + printPlayer(players[0]) + "\t" + printPlayer(players[1]) + "\t" + printPlayer(players[2]) + "\t\t#"); System.out.println("# \t\t" + botones[0] + " \t" + botones[1] + "\t" + botones[2] + "\t\t #"); System.out.println("#" + printPlayer(players[7]) + " " + botones[7] + "\t " + handTableStr + " " + botones[3] + foo + printPlayer(players[3]) + "\t #" ); System.out.println("# \t" + botones[6] + "\t" + botones[5] + "\t " + botones[4] + "\t\t\t #"); System.out.println(" #\t" + printPlayer(players[6]) + "\t" + printPlayer(players[5]) + "\t\t" + printPlayer(players[4]) + "\t\t# "); System.out.println(" } public static String printPlayer(Player player) { if (player == null) { return " "; } else if (player.isHumanPlayer()) { return player.toString(); } else { return "#" + player.getId(); } } }
package ui; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import org.eclipse.egit.github.core.client.GitHubRequest; import util.GitHubClientExtended; import util.ModelUpdater; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.PasswordField; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.input.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.stage.Modality; import javafx.stage.Stage; import model.Model; import model.TurboIssue; public class UI extends Application { public static final String STYLE_YELLOW_BORDERS = "-fx-background-color: #FFFA73; -fx-border-color: #000000; -fx-border-width: 1px;"; public static final String STYLE_BORDERS_FADED = "-fx-border-color: #B2B1AE; -fx-border-width: 1px; -fx-border-radius: 3;"; public static final String STYLE_BORDERS = "-fx-border-color: #000000; -fx-border-width: 1px;"; public static final String STYLE_FADED = "-fx-text-fill: #B2B1AE;"; private Stage mainStage; private ColumnControl columns; private Model model; private GitHubClientExtended client; private String repoOwner, repoName; private ModelUpdater modelUpdater; public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { client = new GitHubClientExtended(); model = new Model(client); mainStage = stage; Scene scene = new Scene(createRoot(), 800, 600); // setUpHotkeys(scene); setupStage(stage, scene); } private void setupStage(Stage stage, Scene scene) { stage.setTitle("HubTurbo"); stage.setMinWidth(800); stage.setMinHeight(600); stage.setScene(scene); stage.show(); stage.setOnCloseRequest(e -> { if (modelUpdater != null) { modelUpdater.stopModelUpdate(); } }); } // Node definitions private Parent createRoot() { columns = new ColumnControl(mainStage, model); BorderPane root = new BorderPane(); root.setCenter(columns); root.setTop(createMenuBar()); return root; } private void initLoginForm(MenuItem login) { login.setOnAction((e) -> { Stage stage = new Stage(); stage.setTitle("GitHub Login"); GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); Label repoNameLabel = new Label("Repository:"); grid.add(repoNameLabel, 0, 0); TextField repoOwnerField = new TextField("HubTurbo"); grid.add(repoOwnerField, 1, 0); Label slash = new Label("/"); grid.add(slash, 2, 0); TextField repoNameField = new TextField("HubTurbo"); grid.add(repoNameField, 3, 0); Label usernameLabel = new Label("Username:"); grid.add(usernameLabel, 0, 1); TextField usernameField = new TextField(); grid.add(usernameField, 1, 1, 3, 1); Label passwordLabel = new Label("Password:"); grid.add(passwordLabel, 0, 2); PasswordField passwordField = new PasswordField(); grid.add(passwordField, 1, 2, 3, 1); repoOwnerField.setMaxWidth(80); repoNameField.setMaxWidth(80); Button loginButton = new Button("Sign in"); loginButton.setOnAction((ev) -> { String username = usernameField.getText(); String password = passwordField.getText(); if (username.isEmpty() && password.isEmpty()) { BufferedReader reader; try { reader = new BufferedReader(new FileReader( "credentials.txt")); String line = null; while ((line = reader.readLine()) != null) { if (username.isEmpty()) username = line; else password = line; } System.out.println("Logged in using credentials.txt"); } catch (Exception e1) { System.out .println("Failed to find or open credentials.txt"); } } login(username, password); repoOwner = repoOwnerField.getText(); repoName = repoNameField.getText(); loadDataIntoModel(); columns.loadIssues(); setupModelUpdate(); mainStage.setTitle("HubTurbo (" + client.getRemainingRequests() + " requests remaining out of " + client.getRequestLimit() + ")"); stage.hide(); }); HBox buttons = new HBox(10); buttons.setAlignment(Pos.BOTTOM_RIGHT); buttons.getChildren().add(loginButton); grid.add(buttons, 3, 3); Scene scene = new Scene(grid, 320, 200); stage.setScene(scene); stage.initOwner(mainStage); stage.initModality(Modality.APPLICATION_MODAL); stage.setX(mainStage.getX()); stage.setY(mainStage.getY()); stage.show(); }); } private void loadDataIntoModel() { model.setRepoId(repoOwner, repoName); } private void setupModelUpdate() { modelUpdater = new ModelUpdater(client, model); modelUpdater.startModelUpdate(); } // private void setUpHotkeys(Scene scene) { // scene.getAccelerators().put( // new KeyCodeCombination(KeyCode.DIGIT1, // KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), // (Runnable) () -> changePanelCount(1)); private MenuBar createMenuBar() { MenuBar menuBar = new MenuBar(); Menu projects = new Menu("Projects"); MenuItem login = new MenuItem("Login"); initLoginForm(login); projects.getItems().addAll(login); Menu milestones = new Menu("Milestones"); MenuItem manageMilestones = new MenuItem("Manage milestones..."); milestones.getItems().addAll(manageMilestones); manageMilestones.setOnAction(e -> { (new ManageMilestonesDialog(mainStage, model)).show().thenApply( response -> { return true; }); }); Menu issues = new Menu("Issues"); MenuItem newIssue = new MenuItem("New Issue"); newIssue.setOnAction(e -> { TurboIssue issue = new TurboIssue("New issue", ""); (new IssueDialog(mainStage, model, issue)).show().thenApply( response -> { if (response.equals("ok")) { model.createIssue(issue); } // Required for some reason columns.refresh(); return true; }); }); issues.getItems().addAll(newIssue); Menu labels = new Menu("Labels"); MenuItem manageLabels = new MenuItem("Manage labels..."); manageLabels.setOnAction(e -> { (new ManageLabelsDialog(mainStage, model)).show().thenApply( response -> { return true; }); }); labels.getItems().addAll(manageLabels); Menu view = new Menu("View"); MenuItem refresh = new MenuItem("Refresh"); refresh.setOnAction((e) -> { modelUpdater.stopModelUpdate(); loadDataIntoModel(); columns.refresh(); // In case modelUpdater.startModelUpdate(); }); refresh.setAccelerator(new KeyCodeCombination(KeyCode.F5)); Menu columnsMenu = new Menu("Change number of columns...."); view.getItems().addAll(refresh, columnsMenu); final ToggleGroup numberOfCols = new ToggleGroup(); for (int i = 1; i <= 9; i++) { RadioMenuItem item = new RadioMenuItem(Integer.toString(i)); item.setToggleGroup(numberOfCols); columnsMenu.getItems().add(item); final int j = i; item.setOnAction((e) -> columns.setColumnCount(j)); item.setAccelerator(new KeyCodeCombination(KeyCode.valueOf("DIGIT" + Integer.toString(j)), KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN)); if (i == 1) item.setSelected(true); } menuBar.getMenus().addAll(projects, milestones, issues, labels, view); return menuBar; } public boolean login(String userId, String password) { client.setCredentials(userId, password); try { GitHubRequest request = new GitHubRequest(); request.setUri("/"); client.get(request); } catch (IOException e) { // Login failed return false; } return true; } }
package com.example.my.project; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button login,signup; EditText username,password; String s1,s2,s3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); login=(Button)findViewById(R.id.login); signup=(Button)findViewById(R.id.signup); username=(EditText)findViewById(R.id.username); password=(EditText)findViewById(R.id.password); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { s1=username.getText().toString(); s2=password.getText().toString(); if(s1.isEmpty()==true || s2.isEmpty()==true) { Toast.makeText(MainActivity.this,"Fill all Fields",Toast.LENGTH_SHORT).show(); } else { SQLiteDatabase data = openOrCreateDatabase("magic", MODE_PRIVATE, null); data.execSQL("create table if not exists user (name varchar, password varchar, email varchar)"); String x = "select * from user where name='" + s1 + "' and password='" + s2 + "'"; Cursor cursor = data.rawQuery(x,null); if(cursor.getCount()>0) { cursor.close(); Toast.makeText(MainActivity.this, "Logging in...", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, Third.class); Intent j = i.putExtra("data",s1 ); startActivity(j); } else { cursor.close(); Toast.makeText(MainActivity.this, "Wrong Username and/or Password", Toast.LENGTH_SHORT).show(); } } } }); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent k=new Intent(MainActivity.this,Third.class); startActivity(k); } }); } }
package picoded.servlet; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertArrayEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import picoded.conv.ConvertJSON; import picoded.enums.EmptyArray; import picoded.enums.HttpRequestType; public class CorePage_test { private CorePage corePage; private CorePage corePageMock; // = mock(CorePage.class); @Before public void setUp() { corePage = new CorePage(); corePageMock = mock(CorePage.class); } @After public void tearDown() { corePage = null; } @Test public void constructor() { assertNotNull(corePage); } @Test public void requestTypeSetTest() { assertNotNull(CorePage.RequestTypeSet.GET); } @Test public void getHttpServletRequestTest() { assertNull(corePage.getHttpServletRequest()); } @Test public void requestHeaderMapInvalidTest() { assertNull(corePage.requestHeaderMap()); } @Test public void requestHeaderMapValidTest() throws ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); List<String> headerList = new ArrayList<String>(); headerList.add("header_1"); headerList.add("header_2"); when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerList)); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); assertNotNull(corePageLocal.requestHeaderMap()); } @Test public void requestHeaderMapAlternatePathTest() { Map<String, String[]> map = new HashMap<>(); map.put("arg", new String[] { "a", "b" }); corePage._requestHeaderMap = map; assertNotNull(corePage.requestHeaderMap()); } @Test public void processChainTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.GET; corePage.responseOutputStream = mockStream; assertTrue(corePage.processChain()); } @Test public void processChainJSONPathTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.GET; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); assertTrue(corePage.processChain()); } @Test public void processChainJSONPathRequestTypeOtherTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.HEAD; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); assertTrue(corePage.processChain()); } @Test public void processChainJSONPOSTTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); assertTrue(corePage.processChain()); } @Test public void processChainJSONPOSTDoAuthTest() throws Exception { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); Map<String, Object> templateDataObj = new HashMap<String, Object>(); corePage.templateDataObj = templateDataObj; CorePage corePageLocal = spy(corePage); when(corePageLocal.doAuth(templateDataObj)).thenReturn(false); assertFalse(corePageLocal.processChain()); } @Test public void processChainJSONPOSTDoJSONTest() throws Exception { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); Map<String, Object> templateDataObj = new HashMap<String, Object>(); corePage.templateDataObj = templateDataObj; corePage.jsonDataObj = templateDataObj; CorePage corePageLocal = spy(corePage); when(corePageLocal.doJSON(templateDataObj, templateDataObj)).thenReturn(false); assertFalse(corePageLocal.processChain()); } @Test public void processChainJSONPUTTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.PUT; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); assertTrue(corePage.processChain()); } @Test public void processChainJSONDELETETest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.DELETE; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); assertTrue(corePage.processChain()); } @Test public void processChainJSONPOSTExceptionTest() throws Exception { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; corePage.setJsonRequestFlag("*"); Map<String, Object> templateDataObj = new HashMap<String, Object>(); corePage.templateDataObj = templateDataObj; corePage.jsonDataObj = templateDataObj; CorePage corePageLocal = spy(corePage); when(corePageLocal.doPostJSON(templateDataObj, templateDataObj)).thenThrow(Exception.class); assertFalse(corePageLocal.processChain()); } @Test public void processChainNormalPathTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.GET; corePage.responseOutputStream = mockStream; assertTrue(corePage.processChain()); } @Test public void processChainNormalPathRequestTypeOtherTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.HEAD; corePage.responseOutputStream = mockStream; assertTrue(corePage.processChain()); } @Test public void processChainNormalPathRequestTypePUTFalseTest() throws Exception { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.PUT; Map<String, Object> templateDataObj = new HashMap<String, Object>(); corePage.templateDataObj = templateDataObj; corePage.jsonDataObj = templateDataObj; CorePage corePageLocal = spy(corePage); when(corePageLocal.doPutRequest(templateDataObj)).thenReturn(false); corePageLocal.responseOutputStream = mockStream; assertFalse(corePageLocal.processChain()); } @Test public void processChainNormalPOSTTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; assertTrue(corePage.processChain()); } @Test public void processChainNormalPOSTDoAuthTest() throws Exception { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; Map<String, Object> templateDataObj = new HashMap<String, Object>(); corePage.templateDataObj = templateDataObj; CorePage corePageLocal = spy(corePage); when(corePageLocal.doAuth(templateDataObj)).thenReturn(false); assertFalse(corePageLocal.processChain()); } @Test public void processChainNormalPOSTDoJSONTest() throws Exception { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; Map<String, Object> templateDataObj = new HashMap<String, Object>(); corePage.templateDataObj = templateDataObj; CorePage corePageLocal = spy(corePage); when(corePageLocal.doRequest(templateDataObj)).thenReturn(false); assertFalse(corePageLocal.processChain()); } @Test public void processChainNormalPUTTest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.PUT; corePage.responseOutputStream = mockStream; assertTrue(corePage.processChain()); } @Test public void processChainNormalDELETETest() throws ServletException { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.DELETE; corePage.responseOutputStream = mockStream; assertTrue(corePage.processChain()); } @Test(expected = ServletException.class) public void processChainExceptionTest() throws Exception { assertFalse(corePage.processChain()); } @Test(expected = ServletException.class) public void processChainNormalPOSTExceptionTest() throws Exception { ServletOutputStream mockStream = mock(ServletOutputStream.class); corePage.requestType = HttpRequestType.POST; corePage.responseOutputStream = mockStream; Map<String, Object> templateDataObj = new HashMap<String, Object>(); corePage.templateDataObj = templateDataObj; CorePage corePageLocal = spy(corePage); when(corePageLocal.doPostRequest(templateDataObj)).thenThrow(Exception.class); assertFalse(corePageLocal.processChain()); } @Test public void isJsonRequestTest() { assertNotNull(corePage.setJsonRequestFlag("*")); assertTrue(corePage.isJsonRequest()); } @Test public void isJsonRequestAlternatePathTest() throws IOException, ServletException { CorePage corePageLocal; corePage.setJsonRequestFlag("in"); HttpServletRequest httpRequest = mock(HttpServletRequest.class); Map<String, String[]> map = new HashMap<String, String[]>(); map.put("in", new String[] { "json" }); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); when(httpRequest.getParameterMap()).thenReturn(map); corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, httpRequest, response)); assertTrue(corePageLocal.isJsonRequest()); } @Test public void isJsonRequestAlternatePathEmptyStringTest() throws IOException, ServletException { CorePage corePageLocal; corePage.setJsonRequestFlag("in"); HttpServletRequest httpRequest = mock(HttpServletRequest.class); Map<String, String[]> map = new HashMap<String, String[]>(); map.put("in", new String[] { "" }); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); when(httpRequest.getParameterMap()).thenReturn(map); corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, httpRequest, response)); assertFalse(corePageLocal.isJsonRequest()); } @Test public void getJsonRequestFlagTest() { corePage.setJsonRequestFlag("in"); assertEquals("in", corePage.getJsonRequestFlag()); } @Test public void requestHeaderMapTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); corePage.doGet(request, response); assertNull(corePage.requestHeaderMap()); } @Test public void isGET() { corePage.requestType = HttpRequestType.GET; assertTrue(corePage.isGET()); } @Test public void isOPTIONTest() { corePage.requestType = HttpRequestType.OPTION; assertTrue(corePage.isOPTION()); } @Test public void isPOSTTest() { corePage.requestType = HttpRequestType.POST; assertTrue(corePage.isPOST()); } @Test public void isPUTTest() { corePage.requestType = HttpRequestType.PUT; assertTrue(corePage.isPUT()); } @Test public void isDELETETest() { corePage.requestType = HttpRequestType.DELETE; assertTrue(corePage.isDELETE()); } @Test public void isGETTest() { corePage.requestType = HttpRequestType.PUT; assertFalse(corePage.isGET()); } @Test public void isOPTIONFalseTest() { corePage.requestType = HttpRequestType.PUT; assertFalse(corePage.isOPTION()); } @Test public void isPOSTFalseTest() { corePage.requestType = HttpRequestType.PUT; assertFalse(corePage.isPOST()); } @Test public void isPUTFalseTest() { corePage.requestType = HttpRequestType.GET; assertFalse(corePage.isPUT()); } @Test public void isDELETEFalseTest() { corePage.requestType = HttpRequestType.PUT; assertFalse(corePage.isDELETE()); } @Test public void spawnInstanceTest() throws ServletException { assertNotNull(corePage.spawnInstance()); } @Test public void initSetupTest() { ServletConfig servletConfig = mock(ServletConfig.class); corePage.initSetup(corePage, servletConfig); } @Test(expected = RuntimeException.class) public void initSetupexceptionTest() throws ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletConfig servletConfig = mock(ServletConfig.class); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); doThrow(Exception.class).when(corePageLocal).init(servletConfig); corePageLocal.initSetup(corePageLocal, servletConfig); } @Test public void getWriterTest() throws IOException, ServletException { HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); HttpServletRequest request = mock(HttpServletRequest.class); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); assertNotNull(corePageLocal.getWriter()); } @Test public void getWriterNullTest() { ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(corePageMock.getOutputStream()).thenReturn(mockOutput); assertNull(corePageMock.getWriter()); } @Test public void getOutputStreamInvalidTest() { assertNull(corePage.getOutputStream()); } @Test public void getOutputStreamValidTest() throws IOException, ServletException { HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); HttpServletRequest request = mock(HttpServletRequest.class); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); assertNotNull(corePageLocal.getOutputStream()); } @Test public void getOutputStreamNullTest() throws IOException, ServletException { HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); HttpServletRequest request = mock(HttpServletRequest.class); corePageMock.doGet(request, response); assertNull(corePageMock.getOutputStream()); } @Test public void getContextPathTest() { corePage._contextPath = "/root"; assertEquals("/root", corePage.getContextPath()); } @Test public void getContextPathRequestObjectNotNullTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletContext()).thenReturn(mock(ServletContext.class)); when(request.getServletContext().getRealPath("/")).thenReturn("/root"); corePage.httpRequest = request; assertEquals("/root/", corePage.getContextPath()); } @Test public void getContextPathThroughServletContextEventTest() { ServletContextEvent servletContextEvent = mock(ServletContextEvent.class); ServletContext servletContext = mock(ServletContext.class); when(servletContextEvent.getServletContext()).thenReturn(servletContext); when(servletContext.getRealPath("/")).thenReturn("/home"); corePage._servletContextEvent = servletContextEvent; assertEquals("/home/", corePage.getContextPath()); } //@Test //testing inside try block public void getContextPathDefaultTest() throws ServletException { HttpServletResponse response = mock(HttpServletResponse.class); HttpServletRequest request = mock(HttpServletRequest.class); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); when(corePageLocal.getServletContext()).thenReturn(request.getServletContext()); when(corePageLocal.getServletContext().getRealPath("/")).thenReturn("/home"); assertEquals("/home/", corePageLocal.getContextPath()); } @Test public void getContextPathExceptionTest() { assertNotNull(corePage.getContextPath()); } @Test public void getContextURITest() { assertEquals("/", corePage.getContextURI()); } @Test public void getContextURIThroughContextPathTest() { corePage._contextURI = "/root"; assertEquals("/root", corePage.getContextURI()); } @Test public void getContextURIThroughHTTPRequestTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getContextPath()).thenReturn("/root"); corePage.httpRequest = request; assertEquals("/root", corePage.getContextURI()); } @Test public void getContextURIThroughServletContextEventTest() { ServletContextEvent servletContextEvent = mock(ServletContextEvent.class); ServletContext servletContext = mock(ServletContext.class); when(servletContextEvent.getServletContext()).thenReturn(servletContext); when(servletContext.getContextPath()).thenReturn("/home"); corePage._servletContextEvent = servletContextEvent; assertEquals("/home/", corePage.getContextURI()); } @Test public void getServletContextURITest() throws ServletException { HttpServletRequest request = mock(HttpServletRequest.class); when(corePageMock.getHttpServletRequest()).thenReturn(request); when(request.getServletPath()).thenReturn("/"); HttpServletResponse response = mock(HttpServletResponse.class); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); assertNotNull(corePageLocal.getServletContextURI()); } @Test public void getServletContextURIInvalidTest() { assertNull(corePageMock.getServletContextURI()); } @Test(expected = RuntimeException.class) public void getServletContextURIExceptionTest() { assertNull(corePage.getServletContextURI()); } //@Test public void getContextURIExceptionTest() { doThrow(UnsupportedEncodingException.class).when(mock(URLDecoder.class, "decode")); assertEquals("../", corePage.getContextURI()); } public void getParameterTest() { HttpServletRequest httpRequest = mock(HttpServletRequest.class); Map<String, String[]> map = new HashMap<String, String[]>(); map.put("user", new String[] { "me" }); when(httpRequest.getParameterMap()).thenReturn(map); assertEquals("me", corePageMock.getParameter("user")); } @Test public void getParameterNULLTest() { HttpServletRequest httpRequest = mock(HttpServletRequest.class); Map<String, String[]> map = new HashMap<String, String[]>(); when(httpRequest.getParameterMap()).thenReturn(map); corePage.httpRequest = httpRequest; assertNull(corePage.getParameter("")); } @Test public void sendRedirectTest() throws ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); CorePage corePageLocal = corePage.setupInstance(HttpRequestType.GET, request, response); corePageLocal.sendRedirect("/home"); } @Test(expected = RuntimeException.class) public void sendRedirectExceptionTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); CorePage corePageLocal = corePage.setupInstance(HttpRequestType.GET, request, response); doThrow(IOException.class).when(response).sendRedirect("/home"); corePageLocal.sendRedirect("/home"); } @Test public void doAuthTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doAuth(map)); } @Test public void doRequestTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doRequest(map)); } @Test public void doGetRequestTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doGetRequest(map)); } @Test public void doPostRequesTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doPostRequest(map)); } @Test public void doPutRequestTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doPutRequest(map)); } @Test public void doDeleteRequestTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doDeleteRequest(map)); } @Test public void outputRequestTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); File file = new File("me.txt"); PrintWriter printWriter = new PrintWriter(file); assertTrue(corePage.outputRequest(map, printWriter)); printWriter.close(); } @Test(expected = Exception.class) public void outputRequestExceptionTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); File file = new File("me.txt"); PrintWriter printWriter = new PrintWriter(file); assertTrue(corePage.outputRequestException(map, printWriter, new Exception())); printWriter.close(); } @Test public void doJSONTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doJSON(map, map)); } @Test public void doGetJSONTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doGetJSON(map, map)); } @Test public void doPostJSONTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doPostJSON(map, map)); } @Test public void doPutJSONTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doPutJSON(map, map)); } @Test public void doDeleteJSONTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); assertTrue(corePage.doDeleteJSON(map, map)); } @Test public void outputJSONTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> template = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); File file = new File("me.txt"); PrintWriter printWriter = new PrintWriter(file); assertTrue(corePage.outputJSON(map, template, printWriter)); printWriter.flush(); printWriter.close(); File rFile = new File("me.txt"); BufferedReader expected = new BufferedReader(new FileReader(rFile)); String line; while ((line = expected.readLine()) != null) { assertEquals(ConvertJSON.fromObject(map), line); } expected.close(); rFile.delete(); } @Test public void outputJSONHTTPResponseNotNullTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> template = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); File file = new File("me.txt"); PrintWriter printWriter = new PrintWriter(file); HttpServletResponse response = mock(HttpServletResponse.class); corePage.httpResponse = response; assertTrue(corePage.outputJSON(map, template, printWriter)); printWriter.flush(); printWriter.close(); File rFile = new File("me.txt"); BufferedReader expected = new BufferedReader(new FileReader(rFile)); String line; while ((line = expected.readLine()) != null) { assertEquals(ConvertJSON.fromObject(map), line); } expected.close(); rFile.delete(); } @Test public void outputJSONExceptionTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> template = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); File file = new File("me.txt"); PrintWriter printWriter = new PrintWriter(file); assertFalse(corePage.outputJSONException(map, template, printWriter, new Exception("There is an error"))); printWriter.flush(); printWriter.close(); File rFile = new File("me.txt"); BufferedReader expected = new BufferedReader(new FileReader(rFile)); String line; Map<String, String> ret = new HashMap<String, String>(); ret.put("error", org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(new Exception("There is an error"))); while ((line = expected.readLine()) != null) { assertNotNull(line); } expected.close(); rFile.delete(); } @Test public void outputJSONExceptionHTTPResponseNotNullTest() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> template = new HashMap<String, Object>(); map.put("user", new String[] { "me" }); File file = new File("me.txt"); PrintWriter printWriter = new PrintWriter(file); HttpServletResponse response = mock(HttpServletResponse.class); corePage.httpResponse = response; assertFalse(corePage.outputJSONException(map, template, printWriter, new Exception("There is an error"))); printWriter.flush(); printWriter.close(); File rFile = new File("me.txt"); BufferedReader expected = new BufferedReader(new FileReader(rFile)); String line; Map<String, String> ret = new HashMap<String, String>(); ret.put("error", org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(new Exception("There is an error"))); while ((line = expected.readLine()) != null) { assertNotNull(line); } expected.close(); rFile.delete(); } @Test public void doGetTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); corePageMock.doGet(request, response); } @Test public void doPostTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); corePageMock.doPost(request, response); } @Test public void doPutTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); corePageMock.doPut(request, response); } @Test public void doDeleteTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); corePageMock.doDelete(request, response); } @Test public void doOptionsTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream mockOutput = mock(ServletOutputStream.class); when(response.getOutputStream()).thenReturn(mockOutput); corePageMock.doOptions(request, response); } @Test(expected = ServletException.class) public void doOptionsExceptionTest() throws ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); corePageMock.doOptions(request, response); } @Test public void contextInitializedTest() { ServletContextEvent servletContextEvent = new ServletContextEvent(mock(ServletContext.class)); corePage.contextInitialized(servletContextEvent); } @Test(expected = RuntimeException.class) public void contextInitializedExceptionTest() throws Exception { ServletContextEvent servletContextEvent = new ServletContextEvent(mock(ServletContext.class)); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); doThrow(Exception.class).when(corePageLocal).doSharedSetup(); corePageLocal.contextInitialized(servletContextEvent); } @Test public void contextDestroyedTest() { ServletContextEvent servletContextEvent = new ServletContextEvent(mock(ServletContext.class)); corePage.contextDestroyed(servletContextEvent); } @Test(expected = RuntimeException.class) public void contextDestroyedExceptionTest() throws Exception { ServletContextEvent servletContextEvent = new ServletContextEvent(mock(ServletContext.class)); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); CorePage corePageLocal = spy(corePage.setupInstance(HttpRequestType.GET, request, response)); doThrow(Exception.class).when(corePageLocal).destroyContext(); corePageLocal.contextDestroyed(servletContextEvent); } @Test(expected = Exception.class) public void doExceptionTest() throws Exception { corePage.doException(new Exception("CorePage Exception")); } @Test public void getHttpServletResponseTest() { assertNull(corePage.getHttpServletResponse()); } @Test public void requestCookieMapTest() { assertNull(corePage.requestCookieMap()); } @Test public void requestCookieMapCookieNotNullTest() { Map<String, String[]> cookieMap = new HashMap<String, String[]>(); corePage._requestCookieMap = cookieMap; assertNotNull(corePage.requestCookieMap()); } @Test public void requestCookieMapHTTPRequestNotNullTest() { HttpServletRequest request = mock(HttpServletRequest.class); Cookie cookie = mock(Cookie.class); when(request.getCookies()).thenReturn(new Cookie[] { cookie }); corePage.httpRequest = request; assertNotNull(corePage.requestCookieMap()); } @Test public void requestServletPathTest() { HttpServletRequest request = mock(HttpServletRequest.class); corePage.httpRequest = request; assertNull(corePage.requestServletPath()); } @Test public void requestTypeTest() { assertNull(corePage.requestType()); } @Test public void requestTypeNotNullTest() { corePage.requestType = HttpRequestType.GET; assertEquals(HttpRequestType.GET, corePage.requestType()); } @Test public void requestURITest() { HttpServletRequest request = mock(HttpServletRequest.class); corePage.httpRequest = request; assertNull(corePage.requestURI()); } @Test public void requestWildcardUriTest() { HttpServletRequest request = mock(HttpServletRequest.class); corePage.httpRequest = request; assertNull(corePage.requestWildcardUri()); } @Test public void requestWildcardUriPathNotNullTest() { HttpServletRequest request = mock(HttpServletRequest.class); corePage.httpRequest = request; when(request.getPathInfo()).thenReturn("/home"); assertEquals("/home", corePage.requestWildcardUri()); } @Test public void requestWildcardUriExceptionTest() { HttpServletRequest request = mock(HttpServletRequest.class); corePage.httpRequest = request; when(request.getPathInfo()).thenThrow(Exception.class); assertNull(corePage.requestWildcardUri()); } @Test public void requestWildcardUriArrayTest() { HttpServletRequest request = mock(HttpServletRequest.class); corePage.httpRequest = request; assertArrayEquals(EmptyArray.STRING, corePage.requestWildcardUriArray()); } @Test public void requestWildcardUriArrayAlternateTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn(""); corePage.httpRequest = request; assertArrayEquals(EmptyArray.STRING, corePage.requestWildcardUriArray()); } @Test public void requestWildcardUriArrayNotEmptyTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("/"); corePage.httpRequest = request; assertArrayEquals(new String[] { "" }, corePage.requestWildcardUriArray()); } @Test public void requestWildcardUriArrayNotEmptyAlternateTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("\\"); corePage.httpRequest = request; assertArrayEquals(new String[] { "" }, corePage.requestWildcardUriArray()); } @Test public void requestWildcardUriArrayValidPathTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("/home/"); corePage.httpRequest = request; assertArrayEquals(new String[] { "home" }, corePage.requestWildcardUriArray()); } @Test public void requestWildcardUriArrayValidAlternatePathTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("/home\\"); corePage.httpRequest = request; assertArrayEquals(new String[] { "home" }, corePage.requestWildcardUriArray()); } @Test public void requestWildcardUriArrayInvalidPathTest() { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getPathInfo()).thenReturn("home"); corePage.httpRequest = request; assertArrayEquals(new String[] { "home" }, corePage.requestWildcardUriArray()); } @Test(expected = ServletException.class) public void setupInstanceExceptionTest() throws ServletException, IOException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); List<String> headerList = new ArrayList<String>(); headerList.add("header_1"); headerList.add("header_2"); when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerList)); when(response.getOutputStream()).thenThrow(Exception.class); corePage.setupInstance(HttpRequestType.GET, request, response); } @Test public void setupInstance2paramsTest() throws ServletException { Map<String, String[]> reqParam = new HashMap<String, String[]>(); assertNotNull(corePage.setupInstance(HttpRequestType.GET, reqParam)); } @Test public void setupInstance3paramsTest() throws ServletException { Map<String, String[]> reqParam = new HashMap<String, String[]>(); Map<String, Cookie[]> reqCookieMap = new HashMap<String, Cookie[]>(); assertNotNull(corePage.setupInstance(HttpRequestType.GET, reqParam, reqCookieMap)); } }
package distance_calculation; import java.io.PrintWriter; import java.io.*; public class MAIN { public static void main(String args[]) throws Exception { File Mesh2nd = new File("/Users/jiao/Desktop/shortestpath_test/Mesh2nd_test.csv"); File srcfilepath = new File("/Users/jiao/Desktop/split_map/.shp"); File shelter = new File("/Users/jiao/Desktop/shortestpath_test/shelter_lat_lon_mesh.csv");//5th )location2 File hospital = new File("/Users/jiao/Desktop/shortestpath_test/hospital_lat_lon_mesh.csv");//5th )location2 File out = new File("/Users/jiao/Desktop/shortestpath_test/output.csv"); //if(!out.exists()) { // out.createNewFile(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(out, false), "SHIFT_JIS")); pw.write("scode"+","+"ecode"+","+"distance"); pw.close(); BufferedReader distance_info = new BufferedReader(new InputStreamReader(new FileInputStream(Mesh2nd), "SHIFT_JIS")); String value; String line; line = distance_info.readLine(); while ((line = distance_info.readLine()) != null) { String pair[] = line.split(","); value=pair[0]; File destfilepath= new File("/Users/jiao/Desktop/split_map/test.shp"); File shelter_temp = new File("/Users/jiao/Desktop/shortestpath_test/shelter_lat_lon_mesh_temp.csv"); File hospital_temp = new File("/Users/jiao/Desktop/shortestpath_test/hospital_lat_lon_mesh_temp.csv"); File out_temp = new File("/Users/jiao/Desktop/shortestpath_test/output_temp.csv"); File out_temp2 = new File("/Users/jiao/Desktop/shortestpath_test/output_temp2.csv"); new transShape(srcfilepath, destfilepath,value); refile.select(shelter, shelter_temp, value); refile.select(hospital, hospital_temp, value); new find_nearest_top3(destfilepath, shelter_temp,hospital_temp,out_temp); find_nearest_top3.find_top3(out_temp,out_temp2); refile.add(out_temp2,out);//out } // value="523644"; } }
package org.zaproxy.zap.extension.ascanrules; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.apache.log4j.Logger; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.remote.*; import org.parosproxy.paros.core.scanner.*; import org.parosproxy.paros.core.scanner.Alert; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.zap.model.Vulnerabilities; import org.zaproxy.zap.model.Vulnerability; public class TestSelenium extends AbstractAppParamPlugin { public final String DRIVER_PATH = "/Users/mzamith/Downloads/chromedriver"; private Logger log = Logger.getLogger(this.getClass()); private static Vulnerability vuln = Vulnerabilities.getVulnerability("wasc_8"); private WebDriver driver; private String site; public void setUp(HttpMessage msg) throws Exception { this.site = msg.getRequestHeader().getURI().toString(); Proxy proxy = new Proxy(); proxy.setHttpProxy("localhost:8090"); proxy.setFtpProxy("localhost:8090"); proxy.setSslProxy("localhost:8090"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(CapabilityType.PROXY, proxy); System.setProperty("webdriver.chrome.driver", DRIVER_PATH); driver = new ChromeDriver(); this.setDriver(driver); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } public void tearDown() throws Exception { driver.close(); } public void tstLoginUser() { this.loginUser("tom", "' OR '1' = '1"); if (driver.getPageSource().indexOf("Succesfully logged in.") > 0) { System.out.println("LOGIN: PASS"); bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_LOW, null, null, null, null, null); }else System.out.println("LOGIN: FAIL"); } public void loginUser(String user, String password) { driver.get(site); WebElement link = driver.findElement(By.name("username")); link.sendKeys(user); link = driver.findElement(By.name("passwd")); link.sendKeys(password); link = driver.findElement(By.id("submit")); link.click(); //sleep(); } protected WebDriver getDriver() { return driver; } protected void setDriver(WebDriver driver) { this.driver = driver; } protected String getSite() { return site; } protected void setSite(String site) { this.site = site; } private void sleep() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.getMessage(); } } public void testAll() { tstLoginUser(); } @Override public int getId() { return 0; } @Override public String getName() { return "SeleniumTest"; } @Override public String[] getDependency() { return null; } @Override public String getDescription() { if (vuln != null) { return vuln.getDescription(); } return "Failed to load vulnerability description from file"; } @Override public int getCategory() { return Category.INJECTION; } @Override public String getSolution() { if (vuln != null) { return vuln.getSolution(); } return "Failed to load vulnerability solution from file"; } @Override public String getReference() { if (vuln != null) { StringBuilder sb = new StringBuilder(); for (String ref : vuln.getReferences()) { if (sb.length() > 0) { sb.append('\n'); } sb.append(ref); } return sb.toString(); } return "Failed to load vulnerability reference from file"; } @Override public void init() { } @Override public void scan(HttpMessage msg, String param, String value) { TestSelenium test = new TestSelenium(); try{ test.setUp(msg); test.testAll(); test.tearDown(); }catch (Exception e){ log.error(e.getMessage()); } } }
package com.lue.client; import java.rmi.NoSuchObjectException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import com.lue.client.tests.Test; import com.lue.client.tests.TestIF; import com.lue.client.tests.TestParameters; import com.lue.common.Schedule; import com.lue.common.Schedule.ScheduleElement; import com.lue.common.SupportedTests; import com.lue.common.UnitTestException; import com.lue.server.Scheduler; import com.lue.server.SchedulerRmiIF; public class ScheduleRunner extends UnicastRemoteObject implements ScheduleRunnerIF { private static final long serialVersionUID = 1L; public Logger logger; protected SchedulerRmiIF schedulerIF; protected int scheduleRunnerId; protected SupportedTests supportedTests; protected Schedule schedule; protected List<TestIF> testQueue; protected Settings settings; protected Registry registry; public ScheduleRunner(int scheduleRunnerId) throws Exception { this.scheduleRunnerId = scheduleRunnerId; logger = Logger.getLogger(ScheduleRunner.class.getName()); testQueue = new ArrayList<TestIF>(); supportedTests = getSupportedTests(); } public void connectToScheduler(String host, int port) throws Exception { logger.log(Level.INFO, "Connecting to server " + host + " on port " + port + "..."); Registry registry = LocateRegistry.getRegistry(host, port); schedulerIF = (SchedulerRmiIF) registry.lookup(Scheduler.SCHEDULER_RMI_NAME); schedulerIF.registerScheduleRunner(this); logger.log(Level.INFO, "Connected. Client ID is: " + scheduleRunnerId); } public void disconnectFromScheduler() { try { UnicastRemoteObject.unexportObject(this, true); } catch (NoSuchObjectException e) { e.printStackTrace(); } } @Override public SupportedTests getSupportedTests() { if(supportedTests == null) { supportedTests = Settings.fromXML().getSupportedTests(); } return supportedTests; } @Override public void pushSchedule(Schedule schedule) throws RemoteException, UnitTestException { while(scheduleRunnerId == -1) { // waiting until scheduleRunnerId is set correctly ... otherwise the server starts its tests before the client even got its id back from registerclient... TODO quite dirty... try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } // checking if all tests are supported logger.log(Level.INFO, "Receiving schedule..." + " client id is: " + scheduleRunnerId); for(ScheduleElement t : schedule) { if(!supportedTests.isTestSupported(t.getTestKey())) throw new UnitTestException("Test " + t.getTestKey() + " is NOT supported!"); } // after making sure all tests are supported we store the schedule in a local field this.schedule = schedule; // when generating a new testQueue we need to empty the old one. testQueue.clear(); int testId = 0; for(ScheduleElement t : schedule) { String testClass = t.getTestKey(); TestParameters params = t.getParameters(); Test<? extends TestParameters> test = TestBuilder.build(testClass, testId, params); test.addObserver(new TestCompletedObserver(scheduleRunnerId, test, schedulerIF)); testQueue.add(test); testId++; } logger.log(Level.INFO, "received"); } @Override public void resetSchedule() throws RemoteException { schedule = null; } @Override public void runSchedule() throws RemoteException { new Thread(){ public void run() { for(TestIF t : testQueue) { t.execute(); // executes test and sends result automatically to server } } }.start(); } public static void main(String[] args) throws Exception { System.out.println("ScheduleRunner is about to start. Please set an id (Integer) such that the server can distinguish between multiple scheduleRunners: "); Scanner in = new Scanner(System.in); int id = in.nextInt(); in.close(); System.out.println("Accepted input."); ScheduleRunner scheduleRunner = new ScheduleRunner(id); scheduleRunner.logger.log(Level.INFO, "logger works!"); try{ scheduleRunner.connectToScheduler("127.0.0.1", 1099); }catch(Exception e){ scheduleRunner.disconnectFromScheduler(); throw e; } do { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } while (true); } @Override public String getName() { return "HardCoded Name"; } /** * This method gets called by the server. It always returns true so the server can check * if the scheduleRunner is still connected. */ @Override public boolean isAlive() throws RemoteException { return false; } @Override public int getId() throws RemoteException { return scheduleRunnerId; } }
package com.sii.rental.ui.views; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.di.UIEventTopic; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; import com.opcoach.training.rental.Customer; import com.opcoach.training.rental.RentalAgency; import com.sii.rental.core.RentalCoreActivator; import com.sii.rental.ui.RentalUIConstants; public class RentalAddOn implements RentalUIConstants{ @PostConstruct public void initContext(IEclipseContext ctx) { ctx.set(RentalAgency.class, RentalCoreActivator.getAgency()); ctx.set(RENTAL_UI_IMG_REGISTRY, getLocalImageRegistry()); } ImageRegistry getLocalImageRegistry() { Bundle b = FrameworkUtil.getBundle(getClass()); ImageRegistry reg = new ImageRegistry(); reg.put(IMG_CUSTOMER, ImageDescriptor.createFromURL(b.getEntry(IMG_CUSTOMER))); reg.put(IMG_RENTAL, ImageDescriptor.createFromURL(b.getEntry(IMG_RENTAL))); reg.put(IMG_RENTAL_OBJECT, ImageDescriptor.createFromURL(b.getEntry(IMG_RENTAL_OBJECT))); reg.put(IMG_AGENCY, ImageDescriptor.createFromURL(b.getEntry(IMG_AGENCY))); return reg; } @Inject @Optional void reactOnCustomEvent(@UIEventTopic("copyCustomer") Customer custom) { System.out.println(custom.getDisplayName()); } @Inject public void getExtensions(IExtensionRegistry reg) { for(IConfigurationElement elt : reg.getConfigurationElementsFor("org.eclipse.e4.workbench.model")) { if(elt.getName().equals("fragment")) { String frg = elt.getAttribute("uri"); System.out.println("fragment:" + frg); System.out.println("fragment.plugin:" + elt.getNamespaceIdentifier()); } else if(elt.getName().equals("processor")) { String prc = elt.getAttribute("class"); System.out.println("processor:" + prc); } } } }
package org.spine3.base; import com.google.common.base.Converter; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.escape.Escaper; import java.util.Map; import java.util.regex.Pattern; import static com.google.common.collect.Maps.newHashMap; import static org.spine3.base.ItemQuoter.converter; import static org.spine3.base.StringifierRegistry.getStringifier; import static org.spine3.util.Exceptions.newIllegalArgumentException; /** * The stringifier for the {@code Map} classes. * * <p>The stringifier for the type of the elements in the map * should be registered in the {@code StringifierRegistry} class * for the correct usage of {@code MapStringifier}. * * <h3>Example</h3> * * {@code * // The registration of the stringifier. * final Type type = Types.mapTypeOf(String.class, Long.class); * StringifierRegistry.getInstance().register(stringifier, type); * * // Obtain already registered `MapStringifier`. * final Stringifier<Map<String, Long>> mapStringifier = StringifierRegistry.getInstance() * .getStringifier(type); * * // Convert to string. * final Map<String, Long> mapToConvert = newHashMap(); * mapToConvert.put("first", 1); * mapToConvert.put("second", 2); * * // The result is: \"first\":\"1\",\"second\":\"2\". * final String convertedString = mapStringifier.toString(mapToConvert); * * * // Convert from string. * final String stringToConvert = ... * final Map<String, Long> convertedMap = mapStringifier.fromString(stringToConvert); * } * * @param <K> the type of the keys in the map * @param <V> the type of the values in the map */ class MapStringifier<K, V> extends Stringifier<Map<K, V>> { private static final char DEFAULT_ELEMENT_DELIMITER = ','; private static final char KEY_VALUE_DELIMITER = ':'; /** * The delimiter for the passed elements in the {@code String} representation, * {@code DEFAULT_ELEMENT_DELIMITER} by default. */ private final char delimiter; private final Escaper escaper; private final Splitter.MapSplitter splitter; private final Stringifier<K> keyStringifier; private final Stringifier<V> valueStringifier; /** * Creates a {@code MapStringifier}. * * <p>The {@code DEFAULT_ELEMENT_DELIMITER} is used for key-value * separation in {@code String} representation of the {@code Map}. * * @param keyClass the class of the key elements * @param valueClass the class of the value elements */ MapStringifier(Class<K> keyClass, Class<V> valueClass) { super(); this.keyStringifier = getStringifier(keyClass); this.valueStringifier = getStringifier(valueClass); this.delimiter = DEFAULT_ELEMENT_DELIMITER; this.escaper = Stringifiers.createEscaper(delimiter); this.splitter = getMapSplitter(createBucketPattern(delimiter), createKeyValuePattern()); } /** * Creates a {@code MapStringifier}. * * <p>The specified delimiter is used for key-value separation * in {@code String} representation of the {@code Map}. * * @param keyClass the class of the key elements * @param valueClass the class of the value elements * @param delimiter the delimiter for the passed elements via string */ MapStringifier(Class<K> keyClass, Class<V> valueClass, char delimiter) { super(); this.keyStringifier = getStringifier(keyClass); this.valueStringifier = getStringifier(valueClass); this.delimiter = delimiter; this.escaper = Stringifiers.createEscaper(delimiter); this.splitter = getMapSplitter(createBucketPattern(delimiter), createKeyValuePattern()); } private static Splitter.MapSplitter getMapSplitter(String bucketPattern, String keyValuePattern) { final Splitter.MapSplitter result = Splitter.onPattern(bucketPattern) .withKeyValueSeparator(Splitter.onPattern(keyValuePattern)); return result; } private static String createBucketPattern(char delimiter) { return Pattern.compile("(?<!\\\\)\\\\\\" + delimiter) .pattern(); } private static String createKeyValuePattern() { return Pattern.compile("(?<!\\\\)" + KEY_VALUE_DELIMITER) .pattern(); } @Override protected String toString(Map<K, V> obj) { final Converter<String, String> quoteConverter = converter(); final Map<String, String> resultMap = newHashMap(); for (Map.Entry<K, V> entry : obj.entrySet()) { final String convertedKey = keyStringifier.andThen(quoteConverter) .convert(entry.getKey()); final String convertedValue = valueStringifier.andThen(quoteConverter) .convert(entry.getValue()); resultMap.put(convertedKey, convertedValue); } final String result = Joiner.on(delimiter) .withKeyValueSeparator(KEY_VALUE_DELIMITER) .join(resultMap); return result; } @Override protected Map<K, V> fromString(String s) { final String escapedString = escaper.escape(s); final Map<String, String> buckets = splitter.split(escapedString); final Map<K, V> resultMap = convert(buckets); return resultMap; } private Map<K, V> convert(Map<String, String> buckets) { final Converter<String, String> quoteConverter = converter(); final Map<K, V> resultMap = newHashMap(); try { for (Map.Entry<String, String> bucket : buckets.entrySet()) { final K convertedKey = quoteConverter.reverse() .andThen(keyStringifier.reverse()) .convert(bucket.getKey()); final V convertedValue = quoteConverter.reverse() .andThen(valueStringifier.reverse()) .convert(bucket.getValue()); resultMap.put(convertedKey, convertedValue); } return resultMap; } catch (Throwable e) { throw newIllegalArgumentException("The exception occurred during the conversion", e); } } }
package continuum.rest.client; import continuum.Continuum; import continuum.atom.Atom; import continuum.atom.AtomID; import continuum.control.Controller; import continuum.slab.Iterator; import continuum.slab.Slab; import continuum.slab.Translator; import continuum.slice.Scan; import continuum.slice.Scanner; import continuum.slice.Slice; import continuum.rest.http.HTTP; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import static continuum.Continuum.*; public class Client implements Controller, Translator<Atom> { private final String baseUrl; public Client() { this("localhost"); } public Client(String host) { this(host, 1337); } //TODO: HttpSlab? public Client(String host, int port) { baseUrl = "http://" + host + ":" + port + "/api/1.0"; } /** * {@inheritDoc} */ @Override public Continuum.AtomBuilder atom() { return new AtomBuilder(); } /** * {@inheritDoc} */ @Override public Continuum.AtomBuilder atom(String name) { return atom().name(name); } /** * {@inheritDoc} */ @Override public ScanBuilder scan(String name) { return Continuum.scan().name(name); } /** * {@inheritDoc} */ @Override public Translator<Atom> translator() { return this; } /** * {@inheritDoc} */ @Override public void write(Atom atom) throws Exception { Map<String, Object> data = new HashMap<>(); Map<String, Object> fields = new HashMap<>(); data.put("name", atom.name()); data.put("value", atom.values().value()); data.put("timestamp", atom.timestamp()); if (atom.particles() != null) for (String key : atom.particles().keySet()) data.put(key, atom.particles().get(key)); if (atom.fields() != null) for (String key : atom.fields().keySet()) fields.put(key, atom.fields().get(key)); if (fields.size() > 0) data.put("fields", fields); HTTP.postJSON(baseUrl + "/write", data); } /** * {@inheritDoc} */ @Override public Atom get(AtomID atomID) throws Exception { return read(atomID); } /** * {@inheritDoc} */ @Override public Atom read(AtomID atomID) throws Exception { throw new UnsupportedOperationException("Mer"); } /** * {@inheritDoc} */ @Override public Slice slice(Scan scan) throws Exception { String url = baseUrl + "/read?name=" + scan.name(); url += "&start=" + scan.start(); url += "&end=" + scan.end(); if (scan.particles() != null) { for (String name : scan.particles().keySet()) { Object value = scan.particles().get(name); url += "&" + name + "=" + value; } } return HTTP.getJSONObject(url, CSlice.class); } @Override public Stream<Slice> stream(Scan scan) throws Exception { throw new Exception("HTTP Streaming not yet supported"); } /** * {@inheritDoc} */ @Override public Scanner scanner() { System.err.println("Client.scanner() not implemented!!!"); return null; } /** * {@inheritDoc} */ @Override public Iterator<Atom> iterator() { throw new UnsupportedOperationException("Can not iterate via HTTP"); } @Override public Iterator<Atom> iterator(boolean b) { return null; } /** * {@inheritDoc} */ @Override public Slab slab() { return null; } public class AtomBuilder extends Continuum.AtomBuilder { private AtomBuilder() { } public AtomBuilder name(String name) { super.name(name); return this; } @Override public Atom build() { return new CAtom(name, particles, timestamp, fields, values); } } }
package replicant; import arez.testng.ActionWrapper; import arez.testng.ArezTestSupport; import java.lang.reflect.Field; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import static org.mockito.Mockito.*; import static org.testng.Assert.*; @Listeners( MessageCollector.class ) @ActionWrapper( enable = false ) public abstract class AbstractReplicantTest implements ArezTestSupport { @BeforeMethod public void beforeMethod() throws Exception { ArezTestSupport.super.beforeMethod(); ReplicantTestUtil.resetConfig( false ); getProxyLogger().setLogger( new TestLogger() ); } @AfterMethod public void afterMethod() { ReplicantTestUtil.resetConfig( true ); ArezTestSupport.super.afterMethod(); } @Nonnull protected final Connection newConnection( @Nonnull final Connector connector ) { connector.onConnection( ValueUtil.randomString() ); final Connection connection = connector.ensureConnection(); connection.setConnectionId( ValueUtil.randomString() ); return connection; } @Nonnull final Entity findOrCreateEntity( @Nonnull final Class<?> type, final int id ) { return safeAction( () -> Replicant .context() .getEntityService() .findOrCreateEntity( Replicant.areNamesEnabled() ? type.getSimpleName() + "/" + id : null, type, id ) ); } @Nonnull protected final Subscription createSubscription( @Nonnull final ChannelAddress address, @Nullable final Object filter, final boolean explicitSubscription ) { return safeAction( () -> Replicant.context() .getSubscriptionService() .createSubscription( address, filter, explicitSubscription ) ); } @Nonnull final TestLogger getTestLogger() { return (TestLogger) getProxyLogger().getLogger(); } @Nonnull private ReplicantLogger.ProxyLogger getProxyLogger() { return (ReplicantLogger.ProxyLogger) ReplicantLogger.getLogger(); } @SuppressWarnings( "NonJREEmulationClassesInClientCode" ) @Nonnull private Field toField( @Nonnull final Class<?> type, @Nonnull final String fieldName ) { Class<?> clazz = type; while ( null != clazz && Object.class != clazz ) { try { final Field field = clazz.getDeclaredField( fieldName ); field.setAccessible( true ); return field; } catch ( final Throwable t ) { clazz = clazz.getSuperclass(); } } fail(); return null; } @SuppressWarnings( "SameParameterValue" ) @Nullable final Object getFieldValue( @Nonnull final Object object, @Nonnull final String fieldName ) { try { return toField( object.getClass(), fieldName ).get( object ); } catch ( final Throwable t ) { throw new AssertionError( t ); } } @Nonnull protected final TestApplicationEventHandler registerTestApplicationEventHandler() { final TestApplicationEventHandler handler = new TestApplicationEventHandler(); Replicant.context().getEventBroker().addApplicationEventHandler( handler ); return handler; } @Nonnull protected final TestSpyEventHandler registerTestSpyEventHandler() { final TestSpyEventHandler handler = new TestSpyEventHandler(); Replicant.context().getSpy().addSpyEventHandler( handler ); return handler; } @Nonnull protected final SystemSchema newSchema() { return newSchema( ValueUtil.randomInt() ); } @Nonnull final SystemSchema newSchema( final int schemaId ) { final ChannelSchema[] channels = new ChannelSchema[ 0 ]; final EntitySchema[] entities = new EntitySchema[ 0 ]; return new SystemSchema( schemaId, replicant.Replicant.areNamesEnabled() ? ValueUtil.randomString() : null, channels, entities ); } @Nonnull protected final Connector createConnector() { return createConnector( newSchema( 1 ) ); } @Nonnull protected final Connector createConnector( @Nonnull final SystemSchema schema ) { return (Connector) Replicant.context().registerConnector( schema, mock( Transport.class ) ); } @Nonnull final Connection createConnection() { final Connection connection = Connection.create( createConnector() ); connection.setConnectionId( ValueUtil.randomString() ); return connection; } }
package io.spine.client; import com.google.common.testing.NullPointerTester; import com.google.protobuf.Any; import com.google.protobuf.DoubleValue; import com.google.protobuf.StringValue; import com.google.protobuf.Timestamp; import io.spine.base.EntityColumn; import io.spine.base.EntityStateField; import io.spine.base.EventMessageField; import io.spine.base.Field; import io.spine.base.FieldPath; import io.spine.client.Filter.Operator; import io.spine.core.EventContext; import io.spine.core.EventContextField; import io.spine.core.Version; import io.spine.core.Versions; import io.spine.test.client.ClProjectCreated; import io.spine.test.client.TestEntity; import io.spine.test.client.TestEntityOwner; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.Calendar; import java.util.concurrent.atomic.AtomicInteger; import static com.google.common.truth.Truth.assertThat; import static io.spine.base.Time.currentTime; import static io.spine.client.CompositeFilter.CompositeOperator; import static io.spine.client.CompositeFilter.CompositeOperator.ALL; import static io.spine.client.CompositeFilter.CompositeOperator.EITHER; import static io.spine.client.Filter.Operator.EQUAL; import static io.spine.client.Filter.Operator.GREATER_OR_EQUAL; import static io.spine.client.Filter.Operator.GREATER_THAN; import static io.spine.client.Filter.Operator.LESS_OR_EQUAL; import static io.spine.client.Filter.Operator.LESS_THAN; import static io.spine.client.Filters.eq; import static io.spine.client.Filters.ge; import static io.spine.client.Filters.gt; import static io.spine.client.Filters.le; import static io.spine.client.Filters.lt; import static io.spine.protobuf.AnyPacker.pack; import static io.spine.protobuf.AnyPacker.unpack; import static io.spine.protobuf.TypeConverter.toAny; import static io.spine.test.client.TestEntityOwner.Role.ADMIN; import static io.spine.testing.DisplayNames.HAVE_PARAMETERLESS_CTOR; import static io.spine.testing.DisplayNames.NOT_ACCEPT_NULLS; import static io.spine.testing.Tests.assertHasPrivateParameterlessCtor; import static java.lang.String.format; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @DisplayName("`Filters` utility should") class FiltersTest { private static final String FIELD = "owner.when_last_visited"; private static final Timestamp REQUESTED_VALUE = currentTime(); private static final String ENUM_FIELD = "owner.role"; private static final TestEntityOwner.Role ENUM_VALUE = ADMIN; @Test @DisplayName(HAVE_PARAMETERLESS_CTOR) void haveUtilityConstructor() { assertHasPrivateParameterlessCtor(TargetFilters.class); } @Test @DisplayName(NOT_ACCEPT_NULLS) void passNullToleranceCheck() { new NullPointerTester() .setDefault(Filter.class, Filter.getDefaultInstance()) .setDefault(EntityColumn.class, TestEntity.Column.firstField()) .setDefault(EntityStateField.class, TestEntity.Field.owner()) .setDefault(EventMessageField.class, ClProjectCreated.Field.name()) .setDefault(EventContextField.class, EventContext.Field.pastMessage()) .testAllPublicStaticMethods(Filters.class); } @Nested @DisplayName("create filter of type") class CreateFilterOfType { @Test @DisplayName("`equals`") void equals() { checkCreatesInstance(eq(FIELD, REQUESTED_VALUE), EQUAL); } @Test @DisplayName("`greater than`") void greaterThan() { checkCreatesInstance(gt(FIELD, REQUESTED_VALUE), GREATER_THAN); } @Test @DisplayName("`greater than or equals`") void greaterOrEqual() { checkCreatesInstance(ge(FIELD, REQUESTED_VALUE), GREATER_OR_EQUAL); } @Test @DisplayName("`less than`") void lessThan() { checkCreatesInstance(lt(FIELD, REQUESTED_VALUE), LESS_THAN); } @Test @DisplayName("`less than or equals`") void lessOrEqual() { checkCreatesInstance(le(FIELD, REQUESTED_VALUE), LESS_OR_EQUAL); } @Test @DisplayName("`equals` for enumerated types") void equalsForEnum() { Filter filter = eq(ENUM_FIELD, ENUM_VALUE); FieldPath fieldPath = filter.getFieldPath(); String actual = Field.withPath(fieldPath) .toString(); assertEquals(ENUM_FIELD, actual); assertEquals(toAny(ENUM_VALUE), filter.getValue()); assertEquals(EQUAL, filter.getOperator()); } private void checkCreatesInstance(Filter filter, Operator operator) { String actual = Field.withPath(filter.getFieldPath()) .toString(); assertEquals(FIELD, actual); assertEquals(pack(REQUESTED_VALUE), filter.getValue()); assertEquals(operator, filter.getOperator()); } } @Nested @DisplayName("create filter based on a typed") class CreateFilterByTyped { @Test @DisplayName("column") void column() { EntityColumn column = TestEntity.Column.firstField(); String value = "expected-filter-value"; String expectedPath = column.name() .value(); checkCreates(eq(column, value), expectedPath, value, EQUAL); } @Test @DisplayName("entity state field") void entityStateField() { EntityStateField field = TestEntity.Field.thirdField(); int value = 142; String expectedPath = field.getField() .toString(); checkCreates(gt(field, value), expectedPath, value, GREATER_THAN); } @Test @DisplayName("event message field") void eventMessageField() { EventMessageField field = ClProjectCreated.Field.name().value(); String value = "expected-project-name"; String expectedPath = field.getField() .toString(); checkCreates(eq(field, value), expectedPath, value, EQUAL); } @Test @DisplayName("event context field") void eventContextField() { EventContextField field = EventContext.Field.external(); boolean value = true; String expectedPath = format("context.%s", field.getField()); checkCreates(eq(field, value), expectedPath, value, EQUAL); } private void checkCreates(Filter filter, String expectedPath, Object expectedValue, Operator expectedOperator) { String fieldPath = Field.withPath(filter.getFieldPath()) .toString(); assertThat(fieldPath).isEqualTo(expectedPath); Any value = filter.getValue(); Any packedExpectedValue = toAny(expectedValue); assertThat(value).isEqualTo(packedExpectedValue); Operator operator = filter.getOperator(); assertThat(operator).isEqualTo(expectedOperator); } } @Nested @DisplayName("create composite filter of type") class CreateCompositeFilterOfType { @Test @DisplayName("`all`") void all() { Filter[] filters = { le(FIELD, REQUESTED_VALUE), ge(FIELD, REQUESTED_VALUE) }; checkCreatesInstance(Filters.all(filters[0], filters[1]), ALL, filters); } @Test @DisplayName("`either`") void either() { Filter[] filters = { lt(FIELD, REQUESTED_VALUE), gt(FIELD, REQUESTED_VALUE) }; checkCreatesInstance(Filters.either(filters[0], filters[1]), EITHER, filters); } private void checkCreatesInstance(CompositeFilter filter, CompositeOperator operator, Filter[] groupedFilters) { assertEquals(operator, filter.getOperator()); assertThat(filter.getFilterList()) .containsExactlyElementsIn(groupedFilters); } } @Nested @DisplayName("create ordering filter") class CreateOrderingFilter { @Test @DisplayName("for numbers") void forNumbers() { double number = 3.14; Filter filter = le("third_field", number); assertThat(filter.getOperator()).isEqualTo(LESS_OR_EQUAL); DoubleValue value = unpack(filter.getValue(), DoubleValue.class); assertThat(value.getValue()).isWithin(0.01).of(number); } @Test @DisplayName("for strings") void forStrings() { String theString = "abc"; Filter filter = gt("first_field", theString); assertThat(filter.getOperator()).isEqualTo(GREATER_THAN); StringValue value = unpack(filter.getValue(), StringValue.class); assertThat(value.getValue()).isEqualTo(theString); } @Test @DisplayName("for timestamps") void forTimestamps() { Timestamp timestamp = currentTime(); Filter filter = gt(FIELD, timestamp); assertThat(filter.getOperator()).isEqualTo(GREATER_THAN); Timestamp value = unpack(filter.getValue(), Timestamp.class); assertThat(value).isEqualTo(timestamp); } @Test @DisplayName("for versions") void forVersions() { Version version = Versions.zero(); Filter filter = ge("some_version_field", version); assertThat(filter).isNotNull(); assertThat(filter.getOperator()).isEqualTo(GREATER_OR_EQUAL); Version value = unpack(filter.getValue(), Version.class); assertThat(value).isEqualTo(version); } } @Nested @DisplayName("fail to create ordering filter") class FailToCreateOrderingFilter { @Test @DisplayName("for enumerated types") void forEnums() { assertThrows(IllegalArgumentException.class, () -> ge(ENUM_FIELD, ENUM_VALUE)); } @Test @DisplayName("for non-primitive number types") void forNonPrimitiveNumbers() { AtomicInteger number = new AtomicInteger(42); assertThrows(IllegalArgumentException.class, () -> ge("atomicField", number)); } @Test @DisplayName("for not supported types") void forUnsupportedTypes() { Comparable<?> value = Calendar.getInstance(); // Comparable but not supported assertThrows(IllegalArgumentException.class, () -> le("invalidField", value)); } } }
package org.jenetics; import static org.jenetics.util.object.eq; import static org.jenetics.util.object.hashCodeOf; import static org.jenetics.util.object.nonNull; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; import javolution.context.ConcurrentContext; import javolution.xml.XMLFormat; import javolution.xml.XMLSerializable; import javolution.xml.stream.XMLStreamException; import org.jenetics.util.Concurrency; import org.jenetics.util.Copyable; import org.jenetics.util.Factory; import org.jenetics.util.arrays; public class Population<G extends Gene<?, G>, C extends Comparable<? super C>> implements List<Phenotype<G, C>>, Copyable<Population<G, C>>, RandomAccess, XMLSerializable { private static final long serialVersionUID = 1L; private final List<Phenotype<G, C>> _population; private Population(final List<Phenotype<G, C>> population) { _population = population; } /** * Constructs a population containing the elements of the specified collection, * in the order they are returned by the collection's iterator. * * @param population the collection whose elements are to be placed into * this list. * @throws NullPointerException if the specified population is {@code null}. */ public Population(final Collection<? extends Phenotype<G, C>> population) { this(new ArrayList<>(population)); } public Population(final int size) { this(new ArrayList<Phenotype<G, C>>(size + 1)); } /** * Creating a new <code>Population</code>. */ public Population() { this(new ArrayList<Phenotype<G, C>>()); } public Population<G, C> fill( final Factory<? extends Phenotype<G, C>> factory, final int count ) { // Serial version. if (ConcurrentContext.getConcurrency() == 0) { for (int i = 0; i < count; ++i) { _population.add(factory.newInstance()); } // Parallel version. } else { final PhenotypeArray<G, C> array = new PhenotypeArray<>(count); fill(factory, array._array); _population.addAll(array); } return this; } private static < G extends Gene<?, G>, C extends Comparable<? super C> > void fill( final Factory<? extends Phenotype<G, C>> factory, final Object[] array ) { try (final Concurrency c = Concurrency.start()) { final int threads = ConcurrentContext.getConcurrency() + 1; final int[] parts = arrays.partition(array.length, threads); for (int i = 0; i < parts.length - 1; ++i) { final int part = i; c.execute(new Runnable() { @Override public void run() { for (int j = parts[part + 1]; --j >= parts[part];) { array[j] = factory.newInstance(); } }}); } } } /** * Add <code>Phenotype</code> to the <code>Population</code>. * * @param phenotype <code>Phenotype</code> to be add. * @throws NullPointerException if the given {@code phenotype} is {@code null}. */ @Override public boolean add(final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); return _population.add(phenotype); } /** * Add <code>Phenotype</code> to the <code>Population</code>. * * @param index Index of the * @param phenotype <code>Phenotype</code> to be add. * @throws NullPointerException if the given {@code phenotype} is {@code null}. */ @Override public void add(final int index, final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); _population.add(index, phenotype); } @Override public boolean addAll(final Collection<? extends Phenotype<G, C>> c) { return _population.addAll(c); } @Override public boolean addAll(int index, Collection<? extends Phenotype<G, C>> c) { return _population.addAll(index, c); } @Override public Phenotype<G, C> get(final int index) { return _population.get(index); } @Override public Phenotype<G, C> set(final int index, final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); return _population.set(index, phenotype); } public void remove(final Phenotype<G, C> phenotype) { nonNull(phenotype, "Phenotype"); _population.remove(phenotype); } @Override public boolean remove(final Object o) { return _population.remove(o); } @Override public boolean removeAll(final Collection<?> c) { return _population.removeAll(c); } @Override public Phenotype<G, C> remove(final int index) { return _population.remove(index); } @Override public void clear() { _population.clear(); } /** * Sorting the phenotypes in this population according to its fitness * value in descending order. */ public void sort() { sort(Optimize.MAXIMUM.<C>descending()); } public void sort(final Comparator<? super C> comparator) { quicksort(0, size() - 1, comparator); } private void quicksort( final int left, final int right, final Comparator<? super C> comparator ) { if (right > left) { final int j = partition(left, right, comparator); quicksort(left, j - 1, comparator); quicksort(j + 1, right, comparator); } } private int partition( final int left, final int right, final Comparator<? super C> comparator ) { final C pivot = _population.get(left).getFitness(); int i = left; int j = right + 1; while (true) { do { ++i; } while ( i < right && comparator.compare(_population.get(i).getFitness(), pivot) < 0 ); do { --j; } while ( j > left && comparator.compare(_population.get(j).getFitness(), pivot) > 0 ); if (j <= i) { break; } swap(i, j); } swap(left, j); return j; } private void swap(final int i, final int j) { _population.set(i, _population.set(j, _population.get(i))); } /** * Reverse the order of the population. */ public void reverse() { Collections.reverse(_population); } @Override public Iterator<Phenotype<G, C>> iterator() { return _population.iterator(); } @Override public ListIterator<Phenotype<G, C>> listIterator() { return _population.listIterator(); } @Override public ListIterator<Phenotype<G, C>> listIterator(final int index) { return _population.listIterator(index); } @Override public int size() { return _population.size(); } @Override public boolean isEmpty() { return _population.isEmpty(); } @Override public boolean contains(final Object o) { return _population.contains(o); } @Override public boolean containsAll(final Collection<?> c) { return _population.containsAll(c); } @Override public int indexOf(final Object o) { return _population.indexOf(o); } @Override public int lastIndexOf(final Object o) { return _population.lastIndexOf(o); } @Override public boolean retainAll(final Collection<?> c) { return _population.retainAll(c); } @Override public List<Phenotype<G, C>> subList(final int fromIndex, final int toIndex) { return _population.subList(fromIndex, toIndex); } @Override public Object[] toArray() { return _population.toArray(); } @Override public <A> A[] toArray(final A[] a) { return _population.toArray(a); } public List<Genotype<G>> getGenotypes() { final List<Genotype<G>> genotypes = new ArrayList<>(_population.size()); for (Phenotype<G, C> phenotype : _population) { genotypes.add(phenotype.getGenotype()); } return genotypes; } @Override public Population<G, C> copy() { return new Population<>(new ArrayList<>(_population)); } @Override public int hashCode() { return hashCodeOf(getClass()).and(_population).value(); } @Override public boolean equals(final Object object) { if (object == this) { return true; } if (!(object instanceof Population<?, ?>)) { return false; } final Population<?, ?> population = (Population<?, ?>)object; return eq(_population, population._population); } @Override public String toString() { StringBuilder out = new StringBuilder(); for (Phenotype<?, ?> pt : this) { out.append(pt.toString()).append("\n"); } return out.toString(); } @SuppressWarnings({ "unchecked", "rawtypes" }) static final XMLFormat<Population> XML = new XMLFormat<Population>(Population.class) { private static final String SIZE = "size"; @Override public Population newInstance( final Class<Population> cls, final InputElement xml ) throws XMLStreamException { final int size = xml.getAttribute(SIZE, 10); final Population p = new Population(size); for (int i = 0; i < size; ++i) { p.add(xml.<Phenotype>getNext()); } return p; } @Override public void write(final Population p, final OutputElement xml) throws XMLStreamException { xml.setAttribute(SIZE, p.size()); for (Object phenotype : p) { xml.add(phenotype); } } @Override public void read(final InputElement xml, final Population p) { } }; private static final class PhenotypeArray< G extends Gene<?, G>, C extends Comparable<? super C> > extends AbstractCollection<Phenotype<G, C>> { final Object[] _array; PhenotypeArray(final int size) { _array = new Object[size]; } @SuppressWarnings("unchecked") @Override public Iterator<Phenotype<G, C>> iterator() { return Arrays.asList((Phenotype<G, C>[])_array).iterator(); } @Override public int size() { return _array.length; } @Override public Object[] toArray() { return _array; } } }
package org.egordorichev.lasttry.world.spawn; import com.badlogic.gdx.Gdx; import org.egordorichev.lasttry.LastTry; import org.egordorichev.lasttry.entity.enemy.Enemy; import org.egordorichev.lasttry.item.block.Block; import org.egordorichev.lasttry.util.AdvancedRectangle; import org.egordorichev.lasttry.util.Camera; import org.egordorichev.lasttry.util.GenericContainer; import org.egordorichev.lasttry.util.Log; import org.egordorichev.lasttry.world.biome.Biome; import org.egordorichev.lasttry.world.spawn.logic.EnemySpawn; import org.egordorichev.lasttry.world.spawn.logic.SpawnRate; import java.util.ArrayList; import java.util.List; public class SpawnSystem { private Biome biome; private int spawnRate, maxSpawns; private int minXGrid, minYGRID, maxXGRID, maxYGrid, maxXGridForActiveZone; private int diffBetweenSpawnedAndMaxSpawns; private List<Enemy> activeEnemyEntities = new ArrayList<>(); public void update() { if(LastTry.environment.currentBiome.get() == null){ return; } //Get user biome this.biome = LastTry.environment.currentBiome.get(); this.spawnTriggered(); } //TODO Split method private void spawnTriggered() { //Retrieve max spawns of biome final int maxSpawns = biome.getSpawnMax(); final int origSpawnRate = biome.getSpawnRate(); //Spawn rate is modified based on different factors such as time, events occurring. int spawnRate = SpawnRate.calculateSpawnRate(origSpawnRate); //Spawn rate refers to 1 in 'Spawn Rate' chance of a monster spawning. float percentChanceSpawnRate = 1/(float)spawnRate; ArrayList<Enemy> enemiesInActiveArea = this.generateEnemiesInActiveArea(); //TODO Expensive calculation //TODO Reached 49 and got stuck as there is no monster with spawn weight of 1, wasting calculations. int spawnWeightOfActiveEnemies = EnemySpawn.calcSpawnWeightOfActiveEnemies(enemiesInActiveArea); //If spawn weight of active enemies is greater than max spawns of biome we quit if(spawnWeightOfActiveEnemies>maxSpawns){ return; } //TODO Split percentage calc into another method float percentageOfSpawnRateAndActiveMonsters; int diffBetweenSpawnedAndMaxSpawns = maxSpawns - spawnWeightOfActiveEnemies; if(spawnWeightOfActiveEnemies==0){ percentageOfSpawnRateAndActiveMonsters = 1; }else { percentageOfSpawnRateAndActiveMonsters = ((float)spawnWeightOfActiveEnemies / (float)maxSpawns) * 100; } float spawnRateFloat = SpawnRate.applyMultiplierToSpawnRate(percentChanceSpawnRate, percentageOfSpawnRateAndActiveMonsters); if(!EnemySpawn.shouldEnemySpawn(spawnRateFloat)){ return; } Log.debug("Monster probability successful"); //TODO Can branch here if 0 enemies ArrayList<Enemy> eligibleEnemiesForSpawn = EnemySpawn.retrieveEligibleSpawnEnemies(diffBetweenSpawnedAndMaxSpawns); if(eligibleEnemiesForSpawn.size()==0){ return; } Enemy enemyToBeSpawned = retrieveRandomEnemy(eligibleEnemiesForSpawn); Log.debug("Enemy to be spawned is: "+enemyToBeSpawned); spawnEnemy(enemyToBeSpawned); } private void spawnEnemy(Enemy enemy) { GenericContainer.Pair<Integer> suitableXySpawnPoint = generateEligibleSpawnPoint(); Log.debug("Monster about to be spawned"); Log.debug("Monster is being spawned with block x point of: "+suitableXySpawnPoint.getFirst()/Block.SIZE+ " block y point of: "+suitableXySpawnPoint.getSecond()/Block.SIZE); Log.debug("Monster is being spawned with x point of: "+suitableXySpawnPoint.getFirst()+ "y point of: "+suitableXySpawnPoint.getSecond()); LastTry.entityManager.spawnEnemy((short)enemy.getID(), suitableXySpawnPoint.getFirst(), suitableXySpawnPoint.getSecond()); } //MOVE OUT private GenericContainer.Pair<Integer> generateEligibleSpawnPoint() { Log.debug("Generating eligible spawn point"); //Generate inside the active zone int xGridSpawnPoint = maxXGridForActiveZone-30; int yGridSpawnPoint = minYGRID; int xPixelSpawnPoint = xGridSpawnPoint* Block.SIZE; int yPixelSpawnPoint = yGridSpawnPoint * Block.SIZE; GenericContainer.Pair<Integer> xyPoint = new GenericContainer.Pair<>(); xyPoint.set(xPixelSpawnPoint, yPixelSpawnPoint); return xyPoint; } private Enemy retrieveRandomEnemy(ArrayList<Enemy> eligibleEnemiesForSpawning){ int randomIndex = LastTry.random.nextInt(eligibleEnemiesForSpawning.size()); return eligibleEnemiesForSpawning.get(randomIndex); } //TODO Move out /** * Generates the max and minimum x,y values of the current screen the user is viewing. */ private void generateMinMaxGridBlockValues() { int windowWidth = Gdx.graphics.getWidth(); int windowHeight = Gdx.graphics.getHeight(); int tww = windowWidth / Block.SIZE; int twh = windowHeight / Block.SIZE; //We want to get the further most position of x on the screen, camera is always in the middle so we //divide total window width by 2 and divide by blcok size to get grid position int tcx = (int) (Camera.game.position.x - windowWidth/2) / Block.SIZE; //TODO Change on inversion of y axis //We are subtracting because of the inverted y axis otherwise it would be LastTry.camera.position.y+windowheight/2 int tcy = (int) (LastTry.world.getHeight() - (Camera.game.position.y + windowHeight/2) / Block.SIZE); //Checking to make sure y value is not less than 0 - World generated will always start from 0,0 top left. this.minYGRID = Math.max(0, tcy - 2); this.maxYGrid = Math.min(LastTry.world.getHeight() - 1, tcy + twh + 3); //Checking to make y values is not less than 0 this.minXGrid = Math.max(0, tcx - 2); this.maxXGRID = Math.min(LastTry.world.getWidth() - 1, tcx + tww + 2); //Active zone is 6 greater //TODO Must check that it is not out of bounds. this.maxXGridForActiveZone = this.maxXGRID + 25; } /** * Retrieves enemies in the active area. * * @return A list of enemies int he active area. */ private ArrayList<Enemy> generateEnemiesInActiveArea() { //Must clear the list each time, as it has no way of knowing if an entity has died so we must rebuild //each time to ensure we have an up to date list ArrayList<Enemy> enemiesInActiveArea = new ArrayList<>(); this.generateMinMaxGridBlockValues(); List<Enemy> enemyEntities = LastTry.entityManager.retrieveEnemyEntities(); enemyEntities.stream().forEach(enemy -> { //TODO Rethink //Checks if the enemy is in the active area and if the enemy is not already in the list, it adds to the list if(this.isEnemyInActiveArea(enemy)){ enemiesInActiveArea.add(enemy); //LastTry.debug("Enemy in active area of: "+enemy.getName()); } }); return enemiesInActiveArea; } /** * Checks grid x and y of enemy, comparing with min x,y grid values calculated above. * If enemy grid x and y, is within the specified area returns true else false. * * @param enemy Enemy entity * @return boolean indicating whether enemy is in grid area */ private boolean isEnemyInActiveArea(Enemy enemy) { //Get block co ordinates of enemy int enemyBlockGridX = enemy.physics.getGridX(); int enemyBlockGridY = enemy.physics.getGridY(); //TODO Change on inversion of y axis //Due to inverted y axis /** * If enemy block grid x is greater than minimum screen x and enemy block grid x less than max screen x * True * If enemy block grid y is less than max y grid and enemy block grid y greater than min y grid */ if(enemyBlockGridX>=this.minXGrid&&enemyBlockGridX<=this.maxXGridForActiveZone){ if(enemyBlockGridY<=this.maxYGrid&&enemyBlockGridY>=this.minYGRID){ return true; } } Log.debug("Limits maxXGrid: "+this.maxXGridForActiveZone+" and limits min X grid: "+this.minXGrid); Log.debug("Pixels max X Grid: "+this.maxXGridForActiveZone*Block.SIZE+" and pixel limits X grid: "+this.minXGrid*Block.SIZE); Log.debug("Limits maxYGrid: "+this.maxYGrid+" and limits min Y grid: "+this.minYGRID); Log.debug("Pixels max Y Grid: "+this.maxYGrid*Block.SIZE+" and pixel limits Y grid: "+this.minYGRID*Block.SIZE); Log.debug("Enemy found out of active area with x of: "+enemyBlockGridX+" and y of: "+enemyBlockGridY); Log.debug("In pixels x is: "+enemyBlockGridX*Block.SIZE+" and y pixels is: "+enemyBlockGridY*Block.SIZE); return false; } /** * Generate rectangle with co ordinates where the player is in the center and a boundary between sides and player * is 6 blocks. */ public void calcArea(){ float xOfPLayer = LastTry.player.physics.getCenterX(); float yOfPlayer = LastTry.player.physics.getCenterY(); AdvancedRectangle advancedRectangle = new AdvancedRectangle(xOfPLayer, yOfPlayer, 6); if(advancedRectangle.allSidesInBoundary()){ Log.debug("All sides in boundary"); //advancedRectangle.debugSetItemsOnPoints(); } } public void calculateNonSpawnSafePlayerArea(){ //TODO Implement } }
package ch.zhaw.photoflow.core; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import ch.zhaw.photoflow.core.domain.Photo; import ch.zhaw.photoflow.core.domain.Project; public class FileHandlerTest { private static File TEST_DIR; private FileHandler fileHandler; private Project project; private Photo photo1, photo2, photo3, photo4; private List<Photo> photos; private File file1, file2, file3, file4; @BeforeClass public static void beforeClass() throws IOException { TEST_DIR = Files.createTempDirectory("FileHandlerTest").toFile(); TEST_DIR.deleteOnExit(); FileHandler.USER_HOME_DIR = TEST_DIR; } @Before public void before() throws IOException, FileHandlerException { // Prepare Test with dummy Testdata project = Project.newProject(); project.setId(1234); fileHandler = new FileHandler(project.getId().get()); file1 = new File(TEST_DIR, "test1.jpg"); file2 = new File(TEST_DIR, "test2.jpg"); file3 = new File(TEST_DIR, "test3.jpg"); file4 = new File(TEST_DIR, "test4.jpg"); file1.createNewFile(); file2.createNewFile(); file3.createNewFile(); file4.createNewFile(); photo1 = Photo.newPhoto(p -> p.setFilePath(file1.getName())); photo2 = Photo.newPhoto(p -> p.setFilePath(file2.getName())); photo3 = Photo.newPhoto(p -> p.setFilePath(file3.getName())); photo4 = Photo.newPhoto(p -> p.setFilePath("testNotExist.jpg")); photos = Arrays.asList(photo1, photo2, photo3); } @After public void after () throws FileHandlerException { fileHandler.deleteProject(); } /** * Checks that after the FileHandler is created, the corresponding Working Directories are created. * @throws FileHandlerException */ @Test public void checkDirectoriesCreated() throws FileHandlerException { assertTrue(fileHandler.projectDir().isDirectory()); } /** * Checks that the Zip File could be generated. * @throws FileNotFoundException If one of the Photo's in the List cannot be found (physically). * @throws IOException */ @Test public void checkExportZip() throws FileHandlerException { fileHandler.importPhoto(photo1, file1); fileHandler.importPhoto(photo2, file2); fileHandler.importPhoto(photo3, file3); assertTrue(fileHandler.exportZip(TEST_DIR + "test.zip", photos).isFile()); } /** * Loads a Photo-File according the Photo-Object. Checks that exception is thrown if File cannot be found. * @throws FileNotFoundException */ @Test(expected=FileHandlerException.class) public void checkLoadPhoto() throws FileHandlerException { fileHandler.importPhoto(photo3, file3); assertTrue(fileHandler.getPhotoFile(photo3).isFile()); fileHandler.loadPhoto(photo4); } /** * Checks the archive functionality. * Project Folder is moved to Archive Folder and should not be existing in old Directory anymore. * @throws IOException * @throws FileHandlerException */ @SuppressWarnings("static-access") @Test public void checkArchiveProject() throws IOException, FileHandlerException { fileHandler.importPhoto(photo1, file1); fileHandler.importPhoto(photo2, file2); fileHandler.archiveProject(); assertFalse(new File(fileHandler.workingDir().getAbsolutePath()+"/"+project.getId().get()).isDirectory()); assertTrue(fileHandler.projectDir().exists()); if (file1.exists()&&file2.exists()) { file1.delete(); file2.delete(); } } }
package imagej.updater.core; import imagej.updater.util.Util; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import java.util.regex.Matcher; import org.scijava.util.FileUtils; /** * This class represents a file handled by the updater. * <p> * The ImageJ updater knows about certain files (see * {@link Checksummer#directories} for details). These files can be local-only, * up-to-date, updateable, etc. * </p> * * @author Johannes Schindelin */ public class FileObject { public static class Version implements Comparable<Version> { public String checksum; // This timestamp is not a Unix epoch! // Instead, it is Long.parseLong(Util.timestamp(epoch)) public long timestamp; // optional (can differ from FileObject.filename if the version differs) public String filename; Version(final String checksum, final long timestamp) { this.checksum = checksum; this.timestamp = timestamp; } @Override public int compareTo(final Version other) { final long diff = timestamp - other.timestamp; if (diff != 0) return diff < 0 ? -1 : +1; return checksum.compareTo(other.checksum); } @Override public boolean equals(final Object other) { return other instanceof Version ? equals((Version) other) : false; } public boolean equals(final Version other) { return timestamp == other.timestamp && checksum.equals(other.checksum); } @Override public int hashCode() { return (checksum == null ? 0 : checksum.hashCode()) ^ new Long(timestamp).hashCode(); } @Override public String toString() { return "Version(" + checksum + ";" + timestamp + ")"; } } public static enum Action { // no changes LOCAL_ONLY("Local-only"), NOT_INSTALLED("Not installed"), INSTALLED( "Up-to-date"), UPDATEABLE("Update available"), MODIFIED( "Locally modified"), NEW("New file"), OBSOLETE("Obsolete"), // changes UNINSTALL("Uninstall it"), INSTALL("Install it"), UPDATE("Update it"), // developer-only changes UPLOAD("Upload it"), REMOVE("Remove it"); private String label; Action(final String label) { this.label = label; } @Override public String toString() { return label; } } public static enum Status { NOT_INSTALLED(Action.NOT_INSTALLED, Action.INSTALL, Action.REMOVE), INSTALLED(Action.INSTALLED, Action.UNINSTALL), UPDATEABLE(Action.UPDATEABLE, Action.UNINSTALL, Action.UPDATE, Action.UPLOAD), MODIFIED(Action.MODIFIED, Action.UNINSTALL, Action.UPDATE, Action.UPLOAD), LOCAL_ONLY(Action.LOCAL_ONLY, Action.UNINSTALL, Action.UPLOAD), NEW(Action.NEW, Action.INSTALL, Action.REMOVE), OBSOLETE_UNINSTALLED( Action.NOT_INSTALLED), OBSOLETE(Action.OBSOLETE, Action.UNINSTALL, Action.UPLOAD), OBSOLETE_MODIFIED( Action.MODIFIED, Action.UNINSTALL, Action.UPLOAD); private final Action[] actions; private final boolean[] validActions; Status(final Action... actions) { this.actions = actions; validActions = new boolean[Action.values().length]; for (final Action action : actions) validActions[action.ordinal()] = true; } @Deprecated public Action[] getActions() { return actions; } public Action[] getDeveloperActions() { return actions; } public boolean isValid(final Action action) { return validActions[action.ordinal()]; } public Action getNoAction() { return actions[0]; } } protected Map<String, FileObject> overriddenUpdateSites = new HashMap<String, FileObject>(); private Status status; private Action action; public String updateSite, originalUpdateSite, filename, description; public boolean executable; public Version current; public Set<Version> previous; public long filesize; public boolean metadataChanged; public boolean descriptionFromPOM; public String localFilename, localChecksum; public long localTimestamp; // These are LinkedHashMaps to retain the order of the entries protected Map<String, Dependency> dependencies; private Set<String> links; protected Set<String> authors; private Set<String> platforms; private Set<String> categories; public FileObject(final String updateSite, final String filename, final long filesize, final String checksum, final long timestamp, final Status status) { this.updateSite = updateSite; this.filename = filename; if (checksum != null) current = new Version(checksum, timestamp); previous = new LinkedHashSet<Version>(); this.status = status; dependencies = new LinkedHashMap<String, Dependency>(); authors = new LinkedHashSet<String>(); platforms = new LinkedHashSet<String>(); categories = new LinkedHashSet<String>(); links = new LinkedHashSet<String>(); this.filesize = filesize; setNoAction(); } public void merge(final FileObject upstream) { for (final Version previous : upstream.previous) addPreviousVersion(previous.checksum, previous.timestamp, previous.filename); if (updateSite == null || updateSite.equals(upstream.updateSite)) { updateSite = upstream.updateSite; description = upstream.description; dependencies = upstream.dependencies; authors = upstream.authors; platforms = upstream.platforms; categories = upstream.categories; links = upstream.links; filesize = upstream.filesize; executable = upstream.executable; if (current != null && !upstream.hasPreviousVersion(current.checksum)) addPreviousVersion( current.checksum, current.timestamp, current.filename); current = upstream.current; status = upstream.status; action = upstream.action; } else { final Version other = upstream.current; if (other != null && !hasPreviousVersion(other.checksum)) addPreviousVersion( other.checksum, other.timestamp, other.filename); } } /** * Fill unset metadata with metadata from another object * * @param other the metadata source */ public void completeMetadataFrom(final FileObject other) { if (description == null || description.length() == 0) description = other.description; if (links == null || links.size() == 0) links = other.links; if (authors == null || authors.size() == 0) authors = other.authors; if (platforms == null || platforms.size() == 0) platforms = other.platforms; if (categories == null || categories.size() == 0) categories = other.categories; } public boolean hasPreviousVersion(final String checksum) { if (current != null && current.checksum.equals(checksum)) return true; for (final Version version : previous) if (version.checksum.equals(checksum)) return true; for (Entry<String, FileObject> overridden : overriddenUpdateSites.entrySet()) if (overridden.getValue().hasPreviousVersion(checksum)) return true; return false; } public boolean overridesOtherUpdateSite() { return !overriddenUpdateSites.isEmpty(); } public boolean isNewerThan(final long timestamp) { if (current != null && current.timestamp <= timestamp) return false; for (final Version version : previous) if (version.timestamp <= timestamp) return false; return true; } void setVersion(final String checksum, final long timestamp) { if (current != null) previous.add(current); current = new Version(checksum, timestamp); current.filename = filename; } public void setLocalVersion(final String filename, final String checksum, final long timestamp) { localFilename = filename; localChecksum = checksum; localTimestamp = timestamp; if (current != null && checksum.equals(current.checksum)) { if (status != Status.LOCAL_ONLY) status = Status.INSTALLED; setNoAction(); return; } status = hasPreviousVersion(checksum) ? (current == null ? Status.OBSOLETE : Status.UPDATEABLE) : (current == null ? Status.OBSOLETE_MODIFIED : Status.MODIFIED); setNoAction(); } public String getDescription() { return description; } public void addDependency(final FilesCollection files, final FileObject dependency) { final String filename = dependency.getFilename(); addDependency(filename, files.prefix(filename)); } public void addDependency(final String filename, final File file) { addDependency(filename, Util.getTimestamp(file), false); } public void addDependency(final String filename, final long timestamp, final boolean overrides) { addDependency(new Dependency(filename, timestamp, overrides)); } public void addDependency(final Dependency dependency) { if (dependency.filename == null || "".equals(dependency.filename.trim())) return; // the timestamp should not be changed unnecessarily final String key = getFilename(dependency.filename, true); if (dependencies.containsKey(key)) { final Dependency other = dependencies.get(key); if (other.filename.equals(dependency.filename) || other.timestamp >= dependency.timestamp) return; } dependencies.put(key, dependency); } public void removeDependency(final String other) { dependencies.remove(getFilename(other, true)); } public boolean hasDependency(final String filename) { return dependencies.containsKey(getFilename(filename, true)); } public void addLink(final String link) { links.add(link); } public Iterable<String> getLinks() { return links; } public void addAuthor(final String author) { authors.add(author); } public Iterable<String> getAuthors() { return authors; } public void addPlatform(String platform) { if ("linux".equals(platform)) platforms.add("linux32"); else if (platform != null && !platform.trim().equals("")) platforms.add(platform .trim()); } public Iterable<String> getPlatforms() { return platforms; } public void addCategory(final String category) { categories.add(category); } public void replaceList(final String tag, final String... list) { if (tag.equals("Dependency")) { final long now = Long.parseLong(Util.timestamp(new Date().getTime())); final Dependency[] newList = new Dependency[list.length]; for (int i = 0; i < list.length; i++) { boolean obsoleted = false; String item = list[i].trim(); if (item.startsWith("obsoletes ")) { item = item.substring(10); obsoleted = true; } Dependency dep = dependencies.get(item); if (dep == null) dep = new Dependency(item, now, obsoleted); else if (dep.overrides != obsoleted) { dep.timestamp = now; dep.overrides = obsoleted; } newList[i] = dep; } dependencies.clear(); for (final Dependency dep : newList) addDependency(dep); return; } final Set<String> map = tag.equals("Link") ? links : tag.equals("Author") ? authors : tag .equals("Platform") ? platforms : tag.equals("Category") ? categories : null; if (map == null) return; map.clear(); for (final String string : list) map.add(string.trim()); } public Iterable<String> getCategories() { return categories; } public Iterable<Version> getPrevious() { return previous; } public void addPreviousVersion(final String checksum, final long timestamp, final String filename) { final Version version = new Version(checksum, timestamp); if (filename != null && !"".equals(filename)) version.filename = filename; if (!previous.contains(version)) previous.add(version); } public void setNoAction() { action = status.getNoAction(); } public void setAction(final FilesCollection files, final Action action) { if (!status.isValid(action)) throw new Error( "Invalid action requested for file " + filename + "(" + action + ", " + status + ")"); if (action == Action.UPLOAD) { if (current == null) { current = new Version(localChecksum, localTimestamp); } if (localFilename != null) { current.filename = filename; filename = localFilename; } if (updateSite == null) { Collection<String> sites = files.getSiteNamesToUpload(); if (sites == null || sites.size() != 1) { throw new Error("Need an update site to upload to!"); } updateSite = sites.iterator().next(); } files.updateDependencies(this); } else if (originalUpdateSite != null && action != Action.REMOVE) { updateSite = originalUpdateSite; originalUpdateSite = null; } this.action = action; } public boolean setFirstValidAction(final FilesCollection files, final Action... actions) { for (final Action action : actions) if (status.isValid(action)) { setAction(files, action); return true; } return false; } public void setStatus(final Status status) { this.status = status; setNoAction(); } public void markUploaded() { if (isLocalOnly()) { status = Status.INSTALLED; localChecksum = current.checksum; localTimestamp = current.timestamp; } else if (isObsolete() || status == Status.UPDATEABLE) { /* force re-upload */ status = Status.INSTALLED; setVersion(localChecksum, localTimestamp); } else { if (localChecksum == null || localChecksum.equals(current.checksum)) throw new Error( filename + " is already uploaded"); setVersion(localChecksum, localTimestamp); } } @Deprecated public void markRemoved() { throw new UnsupportedOperationException("Use #markRemoved(FilesCollection) instead!"); } public void markRemoved(final FilesCollection files) { FileObject overriding = null; int overridingRank = -1; for (final Map.Entry<String, FileObject> entry : overriddenUpdateSites.entrySet()) { final FileObject file = entry.getValue(); if (file.isObsolete()) continue; final UpdateSite site = files.getUpdateSite(entry.getKey()); if (overridingRank < site.getRank()) { overriding = file; overridingRank = site.getRank(); } } addPreviousVersion(current.checksum, current.timestamp, current.filename); setStatus(Status.OBSOLETE_UNINSTALLED); current = null; if (overriding != null) { for (final Map.Entry<String, FileObject> entry : overriddenUpdateSites.entrySet()) { final FileObject file = entry.getValue(); if (file == overriding) continue; overriding.overriddenUpdateSites.put(entry.getKey(), file); } overriding.overriddenUpdateSites.put(updateSite, this); files.add(overriding); } } public String getLocalFilename(boolean forDisplay) { if (localFilename == null || localFilename.equals(filename)) return filename; if (!forDisplay) return localFilename; return filename + " (local: " + localFilename + ")"; } private static Matcher matchVersion(final String filename) { if (!filename.endsWith(".jar")) return null; final Matcher matcher = FileUtils.matchVersionedFilename(filename); return matcher.matches() ? matcher : null; } public String getFilename() { return getFilename(false); } public String getFilename(boolean stripVersion) { return getFilename(filename, stripVersion); } public static String getFilename(final String filename, boolean stripVersion) { final Matcher matcher; if (stripVersion && (matcher = matchVersion(filename)) != null) { return matcher.group(1) + matcher.group(5); } return filename; } public String getBaseName() { final Matcher matcher = matchVersion(filename); if (matcher != null) return matcher.group(1); final String extension = FileUtils.getExtension(filename); return filename.substring(0, filename.length() - extension.length() - 1); } public String getFileVersion() { final Matcher matcher = matchVersion(filename); if (matcher != null) return matcher.group(2); return ""; } public String getChecksum() { return action == Action.UPLOAD ? localChecksum : action == Action.REMOVE || current == null ? null : current.checksum; } public long getTimestamp() { return action == Action.UPLOAD ? (status == Status.LOCAL_ONLY && current != null ? current.timestamp : localTimestamp) : (action == Action.REMOVE || current == null ? 0 : current.timestamp); } public Iterable<Dependency> getDependencies() { return dependencies.values(); } public Iterable<FileObject> getFileDependencies( final FilesCollection files, final boolean recursive) { final Set<FileObject> result = new LinkedHashSet<FileObject>(); if (recursive) result.add(this); final Stack<FileObject> stack = new Stack<FileObject>(); stack.push(this); while (!stack.empty()) { final FileObject file = stack.pop(); for (final Dependency dependency : file.getDependencies()) { final FileObject file2 = files.get(dependency.filename); if (file2 == null || file2.isObsolete()) continue; if (recursive && !result.contains(file2)) stack.push(file2); result.add(file2); } } return result; } public Status getStatus() { return status; } public Action getAction() { return action; } public boolean isInstallable() { return status.isValid(Action.INSTALL); } public boolean isUpdateable() { return status.isValid(Action.UPDATE); } public boolean isUninstallable() { return status.isValid(Action.UNINSTALL); } public boolean isLocallyModified() { return status.getNoAction() == Action.MODIFIED; } /** * Tell whether this file can be uploaded to its update site Note: this does * not check whether the file is locally modified. */ public boolean isUploadable(final FilesCollection files) { switch (status) { case INSTALLED: return false; default: } if (updateSite == null) return files.hasUploadableSites(); final UpdateSite updateSite = files.getUpdateSite(this.updateSite); return updateSite != null && updateSite.isUploadable(); } public boolean actionSpecified() { return action != status.getNoAction(); } public boolean toUpdate() { return action == Action.UPDATE; } public boolean toUninstall() { return action == Action.UNINSTALL; } public boolean toInstall() { return action == Action.INSTALL; } public boolean toUpload() { return action == Action.UPLOAD; } public boolean isObsolete() { switch (status) { case OBSOLETE: case OBSOLETE_MODIFIED: case OBSOLETE_UNINSTALLED: return true; default: return false; } } public boolean isForPlatform(final String platform) { return platforms.contains(platform); } public boolean isForThisPlatform(final FilesCollection files) { return platforms.size() == 0 || isForPlatform(files.util.platform); } public boolean isUpdateablePlatform(final FilesCollection files) { if (platforms.size() == 0) return true; for (final String platform : platforms) if (files.util.isUpdateablePlatform(platform)) return true; return false; } public boolean isLocalOnly() { return status == Status.LOCAL_ONLY; } /* This returns true if the user marked the file for uninstall, too */ public boolean willNotBeInstalled() { switch (action) { case NOT_INSTALLED: case NEW: case UNINSTALL: case REMOVE: return true; case LOCAL_ONLY: case INSTALLED: case UPDATEABLE: case MODIFIED: case OBSOLETE: case INSTALL: case UPDATE: case UPLOAD: return false; default: throw new RuntimeException("Unhandled action: " + action); } } /* This returns true if the user marked the file for uninstall, too */ public boolean willBeUpToDate() { switch (action) { case OBSOLETE: case REMOVE: case NOT_INSTALLED: case NEW: case UPDATEABLE: case MODIFIED: case UNINSTALL: return false; case INSTALLED: case INSTALL: case UPDATE: case UPLOAD: case LOCAL_ONLY: return true; default: throw new RuntimeException("Unhandled action: " + action); } } // TODO: this needs a better name; something like wantsAction() public boolean isUpdateable(final boolean evenForcedUpdates) { return action == Action.UPDATE || action == Action.INSTALL || status == Status.UPDATEABLE || status == Status.OBSOLETE || (evenForcedUpdates && (status.isValid(Action.UPDATE) || status == Status.OBSOLETE_MODIFIED)); } public boolean stageForUpdate(final FilesCollection files, boolean evenForcedOnes) { if (!evenForcedOnes && status == Status.MODIFIED) return false; if (!setFirstValidAction(files, Action.UPDATE, Action.INSTALL)) return false; for (final FileObject file : getFileDependencies(files, true)) { if (!evenForcedOnes && (file.status == Status.MODIFIED || file.status == Status.OBSOLETE_MODIFIED)) continue; file.setFirstValidAction(files, Action.UPDATE, Action.INSTALL); } return true; } public void stageForUpload(final FilesCollection files, final String updateSite) { if (status == Status.LOCAL_ONLY) { localChecksum = current.checksum; localTimestamp = current.timestamp; } this.updateSite = updateSite; if (status == Status.NOT_INSTALLED) { setAction(files, Action.REMOVE); } else { setAction(files, Action.UPLOAD); } String baseName = getBaseName(); String withoutVersion = getFilename(true); List<Dependency> fixup = new ArrayList<Dependency>(); for (final FileObject file : files.forUpdateSite(updateSite)) { if (file.isObsolete()) continue; fixup.clear(); for (final Dependency dependency : file.getDependencies()) { if (dependency.overrides) continue; if (dependency.filename.startsWith(baseName) && withoutVersion.equals(getFilename(dependency.filename, true)) && !dependency.filename.equals(filename)) { fixup.add(dependency); } } for (final Dependency dependency : fixup) { file.dependencies.remove(dependency.filename); dependency.filename = filename; file.dependencies.put(filename, dependency); } } } public void stageForUninstall(final FilesCollection files) throws IOException { final String filename = getLocalFilename(false); if (action != Action.UNINSTALL) setAction(files, Action.UNINSTALL); if (filename.endsWith(".jar")) touch(files.prefixUpdate(filename)); else { String old = filename + ".old"; if (old.endsWith(".exe.old")) old = old.substring(0, old.length() - 8) + ".old.exe"; files.prefix(filename).renameTo(files.prefix(old)); touch(files.prefixUpdate(old)); } if (status != Status.LOCAL_ONLY) setStatus(isObsolete() ? Status.OBSOLETE_UNINSTALLED : Status.NOT_INSTALLED); } public static void touch(final File file) throws IOException { if (file.exists()) { final long now = new Date().getTime(); file.setLastModified(now); } else { final File parent = file.getParentFile(); if (!parent.exists()) parent.mkdirs(); file.createNewFile(); } } public String toDebug() { return filename + "(" + status + ", " + action + ")"; } @Override public String toString() { return filename; } }
package com.notlob.jgrid.model; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import com.notlob.jgrid.Grid; import com.notlob.jgrid.styles.CellStyle; /** * Tracks what's visible in the Grid. * * @author Stef * */ public class Viewport<T> { // BUG: Pretty certain there's inconsistent use of cell padding / spacing (or lack of) throughout the methods in here.... private int firstRowIndex; private int lastRowIndex; private int firstColumnIndex; private int lastColumnIndex; private final Grid<T> grid; private final GridModel<T> gridModel; private final Rectangle viewportArea; // There number of horizontal pixels tolerance to trigger a column resize with the mouse. private final int RESIZE_DEADZONE = 3; public Viewport(final Grid<T> grid) { this.grid = grid; this.gridModel = grid.getGridModel(); this.viewportArea = new Rectangle(-1, -1, -1, -1); invalidate(); } public void invalidate() { firstRowIndex = -1; lastRowIndex = -1; firstColumnIndex = -1; lastColumnIndex = -1; viewportArea.x = -1; viewportArea.y = -1; viewportArea.width = -1; viewportArea.height = -1; } /** * Calculates the first and last visible column and row indexes in the viewport. */ public void calculateVisibleCellRange(final GC gc) { // If they haven't been invalidated, then just return and let the cached values be used. if (firstRowIndex != -1 && lastRowIndex != -1 && firstColumnIndex != -1 && lastColumnIndex != -1) { return; } final Rectangle viewportArea = getViewportArea(gc); final int originX = grid.getHorizontalBar().getSelection(); final int originY = grid.getVerticalBar().getSelection(); if (!grid.getRows().isEmpty()) { setFirstRowIndex(originY); // Get the first and last visible rows. int y = 0; for (int rowIndex=originY; rowIndex<gridModel.getRows().size(); rowIndex++) { final Row<T> row = gridModel.getRows().get(rowIndex); y += (grid.getRowHeight(row) + gridModel.getStyleRegistry().getCellSpacingVertical()); if ((y > viewportArea.height) && (getLastRowIndex() == -1)) { setLastRowIndex(rowIndex); break; } } } // If all rows fit in the screen, cap it. if (getLastRowIndex() == -1 && !gridModel.getRows().isEmpty()) { setLastRowIndex(gridModel.getRows().size()); } if (!grid.getColumns().isEmpty()) { setFirstColumnIndex(originX); // Get the first and last visible columns. int x = 0; for (int columnIndex=originX; columnIndex<gridModel.getColumns().size(); columnIndex++) { final Column column = gridModel.getColumns().get(columnIndex); x += (column.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal()); if ((x > viewportArea.width) && (getLastColumnIndex() == -1)) { setLastColumnIndex(columnIndex); break; } } } // If all columns fit in the screen, cap it. if (getLastColumnIndex() == -1 && !gridModel.getColumns().isEmpty()) { setLastColumnIndex(gridModel.getColumns().size()); } // If we're showing a mega-wide column that's wider than the grid. if ((getFirstColumnIndex() == -1) && (getLastColumnIndex() != -1)) { setFirstColumnIndex(getLastColumnIndex()); } // If we're showing a mega-tall row that's taller than the grid. if ((getFirstRowIndex() == -1) && (getLastRowIndex() != -1)) { setFirstRowIndex(getLastRowIndex()); } } /** * Calculates the bounds of the viewport (the area without column headers and row numbers). */ public Rectangle getViewportArea(final GC gc) { // Use the cached size if it's not been invalidated. if (viewportArea.x != -1 && viewportArea.y != -1 && viewportArea.width != -1 && viewportArea.height != -1) { return viewportArea; } viewportArea.x = grid.getClientArea().x; viewportArea.y = grid.getClientArea().y; viewportArea.width = grid.getClientArea().width; viewportArea.height = grid.getClientArea().height; // Shift the viewport down to make room for column header row(s). for (final Row<T> row : gridModel.getColumnHeaderRows()) { viewportArea.y += (grid.getRowHeight(row) + gridModel.getStyleRegistry().getCellSpacingVertical()); viewportArea.height -= viewportArea.y; } // Shift the viewport right enough to show the longest row number. if (gridModel.isShowRowNumbers()) { final CellStyle cellStyle = gridModel.getStyleRegistry().getRowNumberStyle(); final Point extent = grid.getTextExtent(String.valueOf(gridModel.getRows().size() + 1), gc, cellStyle.getFontData()); final Column rowNumberColumn = gridModel.getRowNumberColumn(); rowNumberColumn.setWidth(cellStyle.getPaddingLeft() + extent.x + cellStyle.getPaddingRight() + (cellStyle.getBorderOuterLeft() == null ? 0 : cellStyle.getBorderOuterLeft().getWidth())); viewportArea.x += (rowNumberColumn.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal()); viewportArea.width -= (rowNumberColumn.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal()); } // Shift the viewport right enough if there's a group selector column. if (gridModel.isShowGroupSelector()) { final Column groupSelectorColumn = gridModel.getGroupSelectorColumn(); viewportArea.x += (groupSelectorColumn.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal()); viewportArea.width -= (groupSelectorColumn.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal()); } // Shift the viewport right for every pinned column. for (Column pinnedColumn : gridModel.getPinnedColumns()) { final int width = pinnedColumn.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal(); viewportArea.x += width; viewportArea.width -= width; } return viewportArea; } /** * If the right-edge of a row is currently visible this return the x position (minus the viewport's x). * * Otherwise it returns the width of the viewport. */ public int getVisibleRowWidth(final GC gc) { final Rectangle viewportArea = getViewportArea(gc); int x = viewportArea.x; for (int columnIndex=getFirstColumnIndex(); columnIndex<getLastVisibleColumnIndex(); columnIndex++) { final Column column = gridModel.getColumns().get(columnIndex); x += (column.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal()); } return Math.min(viewportArea.width, x - viewportArea.x); // Can't currently explain this substract. It's TOO early in the morning!!! } /** * Visual trick - we actually paint the visible columns and then the next TWO columns (although they are clipped). * This stops flickering on the right-most column when horizontally scrolling. */ public int getLastVisibleColumnIndex() { return (lastColumnIndex == -1) ? -1 : Math.min(lastColumnIndex + 2, gridModel.getColumns().size()); } public int getLastVisibleRowIndex() { return (lastRowIndex == -1) ? -1 : Math.min(lastRowIndex + 2, gridModel.getRows().size()); } public int getFirstRowIndex() { return firstRowIndex; } /** * Last (wholey visible - uncropped) row index. */ public int getLastRowIndex() { return lastRowIndex; } public int getFirstColumnIndex() { return firstColumnIndex; } /** * Last (wholey visible - uncropped) column index. */ public int getLastColumnIndex() { return lastColumnIndex; } private void setFirstRowIndex(final int firstRowIndex) { this.firstRowIndex = firstRowIndex; } private void setLastRowIndex(final int lastRowIndex) { this.lastRowIndex = lastRowIndex; } private void setFirstColumnIndex(final int firstColumnIndex) { this.firstColumnIndex = firstColumnIndex; } private void setLastColumnIndex(final int lastColumnIndex) { this.lastColumnIndex = lastColumnIndex; } /** * Return how many columns are currently visible. */ public int getWidthInColumns() { if ((getFirstColumnIndex() == -1) || (getLastColumnIndex() == -1)) { return 0; } final int columns = getLastColumnIndex() - getFirstColumnIndex(); if (columns == 0 && (getFirstColumnIndex() != -1 || getLastColumnIndex() != -1)) { // Edge case where there's a single column that's wider than the grid. return 1; } return columns; } /** * Return how many rows are currently visible. */ public int getHeightInRows() { if ((getFirstRowIndex() == -1) || (getLastRowIndex() == -1)) { return 0; } final int rows = getLastRowIndex() - getFirstRowIndex(); if (rows == 0 && (getFirstRowIndex() != -1 || getLastRowIndex() != -1)) { // An edge case where there's a single row that's taller than the grid. return 1; } return rows; } /** * Return how many rows fit on the last page of the viewport. */ public int getRowCountLastPage(final GC gc) { if (!grid.getRows().isEmpty()) { return getRowsToFitAbove(gc, (gridModel.getRows().size()-1)); } return 0; } /** * Return the number of rows that will fit in the viewport if the specified row is to be the last shown row. */ private int getRowsToFitAbove(final GC gc, final int startingRowIndex) { final Rectangle viewportArea = getViewportArea(gc); int rowCount = 0; if (!grid.getRows().isEmpty()) { // Work from the last row - towards the first, trying to fit them into the viewport. int y = 0; for (int rowIndex=startingRowIndex; rowIndex>=0; rowIndex final Row<T> row = gridModel.getRows().get(rowIndex); y += (grid.getRowHeight(row) + gridModel.getStyleRegistry().getCellSpacingVertical()); if ((y <= viewportArea.height)) { rowCount++; } else { break; } } } return rowCount; } /** * Return how many column fit on the last page of the viewport. */ public int getColumnCountLastPage(final GC gc) { if (!grid.getColumns().isEmpty()) { return getColumnsToFitToTheLeftOf(gc, gridModel.getColumns().get(gridModel.getColumns().size()-1)); } return 0; } /** * Return how many columns will fit to the left of the specified column. */ private int getColumnsToFitToTheLeftOf(final GC gc, final Column startingColumn) { final Rectangle viewportArea = getViewportArea(gc); int columnCount = 0; if (!grid.getColumns().isEmpty()) { // Work from the last column - towards the first, trying to fit them into the viewport. int x = 0; for (int columnIndex=(gridModel.getColumns().indexOf(startingColumn)); columnIndex>=0; columnIndex final Column column = gridModel.getColumns().get(columnIndex); x += (column.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal()); if ((x <= viewportArea.width)) { columnCount++; } else { break; } } } return columnCount; } /** * Find the column at the pixel coordinates specified. */ public int getColumnIndexByX(final int x, final GC gc) { int currentX = getViewportArea(gc).x; if (x >= currentX) { // Look at viewport columns. for (int columnIndex=getFirstColumnIndex(); columnIndex<getLastVisibleColumnIndex(); columnIndex++) { final Column column = gridModel.getColumns().get(columnIndex); currentX += getColumnWidth(currentX, column) + gridModel.getStyleRegistry().getCellSpacingHorizontal(); if (x <= currentX) { return columnIndex; } } } else { // Compensate for the row number and group selector columns. currentX = gridModel.isShowRowNumbers() ? gridModel.getRowNumberColumn().getWidth() : 0; currentX += gridModel.isShowGroupSelector() ? gridModel.getGroupSelectorColumn().getWidth() : 0; // Look at pinned columns. for (Column column : gridModel.getPinnedColumns()) { if ((x > currentX) && (x <= (currentX + column.getWidth()))) { return gridModel.getColumns().indexOf(column); } currentX += column.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal(); } } return -1; } public int getColumnX(final Column column) { int x = 0; for (final Column current : gridModel.getColumns()) { if (current == column) { return x; } x += current.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal(); } return -1; } /** * Returns the x position of the column in the viewport. */ public int getColumnViewportX(final GC gc, final Column column) { int currentX = getViewportArea(gc).x; for (int columnIndex=getFirstColumnIndex(); columnIndex<getLastVisibleColumnIndex(); columnIndex++) { final Column current = gridModel.getColumns().get(columnIndex); if (current == column) { return currentX; } currentX += current.getWidth() + gridModel.getStyleRegistry().getCellSpacingHorizontal(); } return -1; } /** * Determines if there's a column at the specified mouse location which is eligible for the operation * (RESIZE | REPOSITION) specified. * * For RESIZE - if the location is near the edge of a column, return that column. * * For REPOSITION - if the location is in the middle of the column (but not in the RESIZE bounds, then * return that column); */ public Column getColumnForMouseOperation(final GC gc, final int x, final int y, final ColumnMouseOperation operation) { final int height = grid.getRowHeight(gridModel.getColumnHeaderRow()); // Only proceed if the mouse is in the mouse header region. if ((y >= 0) && (y <= height)) { final Rectangle viewportArea = getViewportArea(gc); int columnHeaderX = viewportArea.x + gridModel.getStyleRegistry().getCellSpacingHorizontal(); for (int columnIndex=firstColumnIndex; columnIndex<lastColumnIndex; columnIndex++) { final Column column = gridModel.getColumns().get(columnIndex); final int columnWidth = getColumnWidth(columnHeaderX, column); // Note: We bump the columnHeaderX before the check for a resize and after for a reposition. switch (operation) { case RESIZE: columnHeaderX += (columnWidth + gridModel.getStyleRegistry().getCellSpacingHorizontal()); if ((x > (columnHeaderX - RESIZE_DEADZONE)) && (x < (columnHeaderX + RESIZE_DEADZONE))) { return column; } break; case REPOSITION: if ((x >= (columnHeaderX + RESIZE_DEADZONE)) && (x <= (columnHeaderX + column.getWidth() - RESIZE_DEADZONE))) { return column; } columnHeaderX += (columnWidth + gridModel.getStyleRegistry().getCellSpacingHorizontal()); break; } } } return null; } /** * Find the row at the pixel coordinates specified. */ public int getRowIndexByY(final int y, final GC gc) { final Rectangle viewportArea = getViewportArea(gc); int currentY = viewportArea.y; if ((y >= 0) && (y < currentY)) { // A column header row has been clicked. for (final Row<T> row : gridModel.getColumnHeaderRows()) { currentY += grid.getRowHeight(row); if (y <= currentY) { return -1; } } } else { // A data row (or row number) has been clicked. for (int rowIndex=getFirstRowIndex(); rowIndex<getLastVisibleRowIndex(); rowIndex++) { if (rowIndex == -1) { return -1; } if (rowIndex < gridModel.getRows().size()) { final Row<T> row = gridModel.getRows().get(rowIndex); currentY += grid.getRowHeight(row); if (y <= currentY) { return rowIndex; } } } } return -1; } /** * Locate the y pixel co-ordinate of the row in the viewport's coordinates. */ public int getRowViewportY(final GC gc, final Row<T> row) { final Rectangle viewportArea = getViewportArea(gc); int currentY = viewportArea.y; for (int rowIndex=getFirstRowIndex(); rowIndex<=getLastRowIndex(); rowIndex++) { if ((rowIndex < 0) || (rowIndex >= gridModel.getRows().size())) { return -1; } final Row<T> currentRow = gridModel.getRows().get(rowIndex); if (currentRow == row) { return currentY; } currentY += (grid.getRowHeight(currentRow) + gridModel.getStyleRegistry().getCellSpacingVertical()); } return -1; } /** * Locate the y pixel co-ordinate of the row regardless of whether its on screen or not. */ public int getRowY(final GC gc, final Row<T> row) { int currentY = 0; for (final Row<T> current : gridModel.getRows()) { if (current == row) { return currentY; } currentY += grid.getRowHeight(current); } return -1; } private boolean isRowAboveViewport(final Row<T> row) { return (row.getRowIndex() > 0) && (row.getRowIndex() < getFirstRowIndex()); } private boolean isColumnLeftOfViewport(final Column column) { final int columnIndex = grid.getColumns().indexOf(column); return (columnIndex > 0) && (columnIndex < getFirstColumnIndex()); } /** * Ensures the cell specified is visible in the viewport. */ public void reveal(final GC gc, final Column column, final Row<T> row) { final int rowIndex = gridModel.getRows().indexOf(row); final int columnIndex = gridModel.getColumns().indexOf(column); final int max = grid.getVerticalBar().getMaximum(); final int capped = Math.min(rowIndex, max); boolean selectionChanged = false; if (!isRowVisible(row)) { if (isRowAboveViewport(row)) { grid.getVerticalBar().setSelection(capped); } else { // Scrolling down to make the row visible requires us to get the row to be the last row in the viewport. To do this, // we have to do a little walk up from the row - calculating how many rows will fit into the page. grid.getVerticalBar().setSelection(row.getRowIndex() - (getRowsToFitAbove(gc, rowIndex) - 1)); } selectionChanged = true; } if (!isColumnVisible(column)) { if (isColumnLeftOfViewport(column)) { grid.getHorizontalBar().setSelection(columnIndex); } else { // Scrolling right to make the column visible requires us to get the column to be the last column in the viewport. To do this, // we have to do a little walk left from the column - calculating how many columns will fit into the page. grid.getHorizontalBar().setSelection(columnIndex - (getColumnsToFitToTheLeftOf(gc, column) - 1)); } selectionChanged = true; } if (selectionChanged) { invalidate(); grid.redraw(); grid.update(); } } public boolean isRowVisible(final Row<T> row) { return (row.getRowIndex() >= getFirstRowIndex() && row.getRowIndex() < getLastRowIndex()); } public boolean isColumnVisible(final Column column) { final int columnIndex = grid.getColumns().indexOf(column); return (columnIndex >= getFirstColumnIndex() && columnIndex < getLastColumnIndex()); } /** * The last column is 'stretchy' and runs to the end of the grid. */ public int getColumnWidth(final int columnX, final Column column) { return (column.isLastColumn()) ? (grid.getClientArea().width - columnX) : column.getWidth(); } @Override public String toString() { return String.format("Row [%s -> %s] Col [%s -> %s]", firstRowIndex, lastRowIndex, firstColumnIndex, lastColumnIndex); } }
package net.sf.mmm.util.data.api.id; import java.util.Objects; import java.util.UUID; import net.sf.mmm.util.exception.api.ObjectMismatchException; /** * This is the abstract base implementation of {@link Id}. * * @param <E> the generic type of the identified entity. * * @author hohwille * @since 8.4.0 */ public abstract class AbstractId<E> implements Id<E> { private static final long serialVersionUID = 1L; private final Class<E> type; private final long version; /** * The constructor. */ protected AbstractId() { super(); this.type = null; this.version = VERSION_LATEST; } /** * The constructor. * * @param type - see {@link #getType()}. */ public AbstractId(Class<E> type) { this(type, VERSION_LATEST); } /** * The constructor. * * @param type - see {@link #getType()}. * @param version - see {@link #getVersion()}. */ public AbstractId(Class<E> type, long version) { super(); this.type = type; this.version = version; } @Override public Class<E> getType() { return this.type; } @Override public long getVersion() { return this.version; } @Override public Id<E> withVersion(long newVersion) { if (this.version == newVersion) { return this; } return newId(this.type, newVersion); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public final Id<E> withType(Class<?> newType) { if (this.type == null) { return (Id) newId(newType, this.version); } else if (this.type != newType) { throw new ObjectMismatchException(newType, this.type, this); } return this; } /** * Internal method called from {@link #withType(Class)} or {@link #withType(Class)} to create a new instance. * * @param <T> the generic type of {@code newType}. * @param newType the new {@link #getType() type}. * @param newVersion the new {@link #getVersion() version}. * @return the new instance of the {@link Id} implementation. */ protected abstract <T> AbstractId<T> newId(Class<T> newType, long newVersion); @Override public final int hashCode() { return ~getId().hashCode(); } @Override public final boolean equals(Object obj) { if (obj == this) { return true; } if ((obj == null) || !(obj instanceof AbstractId)) { return false; } AbstractId<?> other = (AbstractId<?>) obj; if (!Objects.equals(getId(), other.getId())) { return false; } if (!Objects.equals(this.type, other.type)) { return false; } if (this.version != other.version) { return false; } return true; } @Override public String toString() { StringBuilder buffer = new StringBuilder(32); toString(buffer); return buffer.toString(); } /** * @see #toString() * @param buffer the {@link StringBuilder} where to {@link StringBuilder#append(CharSequence) append} the string * representation to. */ protected void toString(StringBuilder buffer) { buffer.append(getId()); if (this.version != VERSION_LATEST) { buffer.append(VERSION_SEPARATOR); buffer.append(this.version); } } /** * @param idString the id (without version) as {@link String}. * @return the {@code idString} as {@link UUID} or {@code null} if not a {@link UUID}. */ protected static UUID parseUuid(String idString) { if ((idString.length() > 29) && (idString.indexOf('-') > 0)) { return UUID.fromString(idString); } else { return null; } } }
package org.wikipedia; import android.app.Application; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.Window; import android.webkit.WebView; import com.squareup.otto.Bus; import org.acra.ACRA; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import org.mediawiki.api.json.Api; import org.wikipedia.analytics.FunnelManager; import org.wikipedia.analytics.SessionFunnel; import org.wikipedia.bridge.StyleLoader; import org.wikipedia.data.ContentPersister; import org.wikipedia.data.DBOpenHelper; import org.wikipedia.editing.EditTokenStorage; import org.wikipedia.editing.summaries.EditSummary; import org.wikipedia.editing.summaries.EditSummaryPersister; import org.wikipedia.events.ChangeTextSizeEvent; import org.wikipedia.events.ThemeChangeEvent; import org.wikipedia.history.HistoryEntry; import org.wikipedia.history.HistoryEntryPersister; import org.wikipedia.login.UserInfoStorage; import org.wikipedia.migration.PerformMigrationsTask; import org.wikipedia.networking.MccMncStateHandler; import org.wikipedia.pageimages.PageImage; import org.wikipedia.pageimages.PageImagePersister; import org.wikipedia.savedpages.SavedPage; import org.wikipedia.savedpages.SavedPagePersister; import org.wikipedia.search.RecentSearch; import org.wikipedia.search.RecentSearchPersister; import org.wikipedia.settings.PrefKeys; import org.wikipedia.wikidata.WikidataCache; import org.wikipedia.zero.WikipediaZeroHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.UUID; @ReportsCrashes( formKey = "", mode = ReportingInteractionMode.DIALOG, resDialogTitle = R.string.acra_report_dialog_title, resDialogText = R.string.acra_report_dialog_text, resDialogCommentPrompt = R.string.acra_report_dialog_comment, mailTo = "mobile-android-wikipedia-crashes@wikimedia.org") public class WikipediaApp extends Application { private float screenDensity; public float getScreenDensity() { return screenDensity; } // Reload in onCreate to override private String networkProtocol = "https"; public String getNetworkProtocol() { return networkProtocol; } private boolean sslFallback = false; public boolean getSslFallback() { return sslFallback; } public void setSslFallback(boolean fallback) { sslFallback = fallback; } private int sslFailCount = 0; public int getSslFailCount() { return sslFailCount; } public int incSslFailCount() { return ++sslFailCount; } private String appVersionString; public String getAppVersionString() { return appVersionString; } public static final int THEME_LIGHT = R.style.Theme_WikiLight; public static final int THEME_DARK = R.style.Theme_WikiDark; public static final int FONT_SIZE_MULTIPLIER_MIN = -5; public static final int FONT_SIZE_MULTIPLIER_MAX = 8; private static final float FONT_SIZE_FACTOR = 0.1f; public static final int RELEASE_PROD = 0; public static final int RELEASE_BETA = 1; public static final int RELEASE_ALPHA = 2; private int releaseType = RELEASE_PROD; public static final int PREFERRED_THUMB_SIZE = 96; /** * Returns a constant that tells whether this app is a production release, * a beta release, or an alpha (continuous integration) release. * @return Release type of the app. */ public int getReleaseType() { return releaseType; } private List<String> languageMruList; private SessionFunnel sessionFunnel; public SessionFunnel getSessionFunnel() { return sessionFunnel; } /** * Singleton instance of WikipediaApp */ private static WikipediaApp INSTANCE; private Bus bus; private int currentTheme = 0; private WikipediaZeroHandler zeroHandler; public WikipediaZeroHandler getWikipediaZeroHandler() { return zeroHandler; } private WikidataCache wikidataCache; public WikidataCache getWikidataCache() { return wikidataCache; } /** * Preference manager for storing things like the app's install IDs for EventLogging, theme, * font size, etc. */ private SharedPreferences prefs; public WikipediaApp() { INSTANCE = this; } /** * Returns the singleton instance of the WikipediaApp * * This is ok, since android treats it as a singleton anyway. */ public static WikipediaApp getInstance() { return INSTANCE; } @Override public void onCreate() { super.onCreate(); ACRA.init(this); if (getPackageName().contains("beta")) { releaseType = RELEASE_BETA; } else if (getPackageName().contains("alpha")) { releaseType = RELEASE_ALPHA; } bus = new Bus(); final Resources resources = getResources(); ViewAnimations.init(resources); screenDensity = resources.getDisplayMetrics().density; this.prefs = PreferenceManager.getDefaultSharedPreferences(this); PrefKeys.initPreferenceKeys(resources); sessionFunnel = new SessionFunnel(this); // Enable debugging on the webview if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } Api.setConnectionFactory(new OkHttpConnectionFactory(this)); try { appVersionString = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { // This will never happen! throw new RuntimeException(e); } zeroHandler = new WikipediaZeroHandler(this); wikidataCache = new WikidataCache(this); new PerformMigrationsTask().execute(); } public Bus getBus() { return bus; } private String userAgent; public String getUserAgent() { if (userAgent == null) { String channel = Utils.getChannel(this); channel = channel.equals("") ? channel : " ".concat(channel); userAgent = String.format("WikipediaApp/%s (Android %s; %s)%s", getAppVersionString(), Build.VERSION.RELEASE, getString(R.string.device_type), channel ); } return userAgent; } /** * @return the value that should go in the Accept-Language header. */ public String getAcceptLanguage() { String primaryAppLanguage = getPrimaryLanguage(); String acceptLanguage = primaryAppLanguage; Locale defaultLocale = Locale.getDefault(); String wikiLanguage = Utils.langCodeToWikiLang(defaultLocale.getLanguage()); // For now, let's only modify Accept-Language for Chinese languages. // Chinese language users have been reporting that the wrong language // is being displayed. In case the app setting is not Chinese (e.g., // it's English), yet the user navigates to a page in Chinese, or a // page containing Chinese dialect templates, we want to show the // correct dialect there, too. if (primaryAppLanguage.equals("zh") || wikiLanguage.equals("zh")) { // The next two lines are inside the if() guard just for speed. In the future when we remove the if // guard, they will always get called. String country = defaultLocale.getCountry(); String langWithCountryCode = TextUtils.isEmpty(country) ? wikiLanguage : wikiLanguage + "-" + country.toLowerCase(Locale.ROOT); if (primaryAppLanguage.equals(langWithCountryCode)) { // The app setting agrees with the system locale, so: // -If the system locale was overly simplistic (just the language, no country), use the app setting // -If the system locale (and app setting) was specific, use the specific value followed by the general // This should help to ensure that the correct dialect is displayed on pages that have templating. acceptLanguage = langWithCountryCode.equals(wikiLanguage) ? primaryAppLanguage : primaryAppLanguage + "," + wikiLanguage + ";q=0.9"; } else if (primaryAppLanguage.equals(wikiLanguage)) { // The app setting does not agree with the system locale, but the base language (e.g., zh) matches, so // use the specific value followed by the general. This way the user will get the more specific // dialect displayed on pages that have templating. acceptLanguage = langWithCountryCode + "," + primaryAppLanguage + ";q=0.9"; } else { // In the case that the app setting doesn't map up at all to the system locale, express to the server // that the first preference is the app setting's language, followed by the specific system locale // followed by the general system locale. In principle, this should result in correct templating in // the case that the article is in the non-system locale, yet contains templated glyphs in the // system locale. acceptLanguage = primaryAppLanguage + "," + langWithCountryCode + ";q=0.9"; if (!langWithCountryCode.equals(wikiLanguage)) { acceptLanguage = acceptLanguage + "," + wikiLanguage + ";q=0.8"; } } } return acceptLanguage; } private HashMap<String, Api> apis = new HashMap<String, Api>(); private MccMncStateHandler mccMncStateHandler = new MccMncStateHandler(); public Api getAPIForSite(Site site) { HashMap<String, String> customHeaders = new HashMap<String, String>(); customHeaders.put("User-Agent", getUserAgent()); customHeaders.put("X-WMF-UUID", getAppInstallID()); String acceptLanguage = getAcceptLanguage(); // TODO: once we're not constraining this to just Chinese, add the header unconditionally. // Note: the Accept-Language header is unconditionally added based on device locale with a // a single value (e.g., en-us or zh-cn) *by the platform* on the other app platform. Contrast // that with *this* platform, which does not do this for some reason (possibly on side effect free // method invocation theory. But given that up until now we haven't been adding the Accept-Language // header manually on this platform, we don't want to just arbitrarily start doing so for *all* requests. if (!acceptLanguage.equals(getPrimaryLanguage())) { customHeaders.put("Accept-Language", acceptLanguage); } // Because the mccMnc enrichment is a one-time thing, we don't need to have a complex hash key // for the apis HashMap<String, Api> like we do below. It naturally gets the correct // Accept-Language header from above, when applicable. Api api = mccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, customHeaders); if (api == null) { String domainAndApiAndVariantKey = site.getDomain() + "-" + site.getApiDomain() + "-" + acceptLanguage; if (!apis.containsKey(domainAndApiAndVariantKey)) { apis.put(domainAndApiAndVariantKey, new Api(site.getApiDomain(), site.getUseSecure(), site.getScriptPath("api.php"), customHeaders)); } api = apis.get(domainAndApiAndVariantKey); } api.setHeaderCheckListener(zeroHandler); return api; } private Site primarySite; /** * Default site of the application * You should use PageTitle.getSite() to get the currently browsed site */ public Site getPrimarySite() { if (primarySite == null) { primarySite = Site.forLang(getPrimaryLanguage()); } return primarySite; } /** * Convenience method to get an API object for the primary site. * * @return An API object that is equivalent to calling getAPIForSite(getPrimarySite) */ public Api getPrimarySiteApi() { return getAPIForSite(getPrimarySite()); } private String primaryLanguage; public String getPrimaryLanguage() { if (primaryLanguage == null) { primaryLanguage = prefs.getString(PrefKeys.getContentLanguageKey(), null); if (primaryLanguage == null) { // No preference set! String wikiCode = Utils.langCodeToWikiLang(Locale.getDefault().getLanguage()); if (!isWikiLanguage(wikiCode)) { wikiCode = "en"; // fallback, see comments in #findWikiIndex } return wikiCode; } } return primaryLanguage; } public void setPrimaryLanguage(String language) { primaryLanguage = language; prefs.edit().putString(PrefKeys.getContentLanguageKey(), language).apply(); primarySite = null; } private DBOpenHelper dbOpenHelper; public DBOpenHelper getDbOpenHelper() { if (dbOpenHelper == null) { dbOpenHelper = new DBOpenHelper(this); } return dbOpenHelper; } private HashMap<String, ContentPersister> persisters = new HashMap<String, ContentPersister>(); public ContentPersister getPersister(Class cls) { if (!persisters.containsKey(cls.getCanonicalName())) { ContentPersister persister; if (cls.equals(HistoryEntry.class)) { persister = new HistoryEntryPersister(this); } else if (cls.equals(PageImage.class)) { persister = new PageImagePersister(this); } else if (cls.equals(RecentSearch.class)) { persister = new RecentSearchPersister(this); } else if (cls.equals(SavedPage.class)) { persister = new SavedPagePersister(this); } else if (cls.equals(EditSummary.class)) { persister = new EditSummaryPersister(this); } else { throw new RuntimeException("No persister found for class " + cls.getCanonicalName()); } persisters.put(cls.getCanonicalName(), persister); } return persisters.get(cls.getCanonicalName()); } private String[] wikiCodes; public int findWikiIndex(String wikiCode) { if (wikiCodes == null) { wikiCodes = getResources().getStringArray(R.array.preference_language_keys); } for (int i = 0; i < wikiCodes.length; i++) { if (wikiCodes[i].equals(wikiCode)) { return i; } } // FIXME: Instrument this with EL to find out what is happening on places where there is a lang we can't find return findWikiIndex("en"); } private boolean isWikiLanguage(String lang) { if (wikiCodes == null) { wikiCodes = getResources().getStringArray(R.array.preference_language_keys); } for (String wikiCode : wikiCodes) { if (wikiCode.equals(lang)) { return true; } } return false; } private RemoteConfig remoteConfig; public RemoteConfig getRemoteConfig() { if (remoteConfig == null) { remoteConfig = new RemoteConfig(prefs); } return remoteConfig; } private String[] canonicalNames; public String canonicalNameFor(int index) { if (canonicalNames == null) { canonicalNames = getResources().getStringArray(R.array.preference_language_canonical_names); } return canonicalNames[index]; } private String[] localNames; public String localNameFor(int index) { if (localNames == null) { localNames = getResources().getStringArray(R.array.preference_language_local_names); } return localNames[index]; } private EditTokenStorage editTokenStorage; public EditTokenStorage getEditTokenStorage() { if (editTokenStorage == null) { editTokenStorage = new EditTokenStorage(this); } return editTokenStorage; } private SharedPreferenceCookieManager cookieManager; public SharedPreferenceCookieManager getCookieManager() { if (cookieManager == null) { cookieManager = new SharedPreferenceCookieManager(prefs); } return cookieManager; } private UserInfoStorage userInfoStorage; public UserInfoStorage getUserInfoStorage() { if (userInfoStorage == null) { userInfoStorage = new UserInfoStorage(prefs); } return userInfoStorage; } private FunnelManager funnelManager; public FunnelManager getFunnelManager() { if (funnelManager == null) { funnelManager = new FunnelManager(this); } return funnelManager; } private StyleLoader styleLoader; public StyleLoader getStyleLoader() { if (styleLoader == null) { styleLoader = new StyleLoader(this); } return styleLoader; } private String appInstallID; public String getAppInstallID() { appInstallID = getAppInstallIDForFeature(PrefKeys.getAppInstallId()); Log.d("Wikipedia", "appInstallID is" + appInstallID); return appInstallID; } /** * Returns the unique app install ID for a feature. The app install ID is used to track unique * users of each feature for the purpose of improving the app's user experience. * @param prefKey a key from PrefKeys for a feature with a unique app install ID * @return the unique app install ID of the specified feature */ private String getAppInstallIDForFeature(String prefKey) { String installID; if (prefs.contains(prefKey)) { installID = prefs.getString(prefKey, null); } else { installID = UUID.randomUUID().toString(); prefs.edit().putString(prefKey, installID).apply(); } return installID; } /** * Gets the currently-selected theme for the app. * @return Theme that is currently selected, which is the actual theme ID that can * be passed to setTheme() when creating an activity. */ public int getCurrentTheme() { if (currentTheme == 0) { currentTheme = prefs.getInt(PrefKeys.getColorTheme(), THEME_LIGHT); if (currentTheme != THEME_LIGHT && currentTheme != THEME_DARK) { currentTheme = THEME_LIGHT; } } return currentTheme; } /** * Sets the theme of the app. If the new theme is the same as the current theme, nothing happens. * Otherwise, an event is sent to notify of the theme change. * @param newTheme */ public void setCurrentTheme(int newTheme) { if (newTheme == currentTheme) { return; } currentTheme = newTheme; prefs.edit().putInt(PrefKeys.getColorTheme(), currentTheme).apply(); bus.post(new ThemeChangeEvent()); } /** * Make adjustments to a Drawable object to look better in the current theme. * (e.g. apply a white color filter for night mode) * @param d Drawable to be adjusted. */ public void adjustDrawableToTheme(Drawable d) { if (getCurrentTheme() == THEME_DARK) { d.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP); } else { d.clearColorFilter(); } } /** * Make adjustments to a link or button Drawable object to look better in the current theme. * (e.g. apply a blue color filter for night mode, ) * @param d Drawable to be adjusted. */ public void adjustLinkDrawableToTheme(Drawable d) { if (getCurrentTheme() == THEME_DARK) { d.setColorFilter(getResources().getColor(R.color.button_dark), PorterDuff.Mode.SRC_ATOP); } else { d.setColorFilter(getResources().getColor(R.color.button_light), PorterDuff.Mode.SRC_ATOP); } } public int getFontSizeMultiplier() { return prefs.getInt(PrefKeys.getTextSizeMultiplier(), 0); } public void setFontSizeMultiplier(int multiplier) { if (multiplier < FONT_SIZE_MULTIPLIER_MIN) { multiplier = FONT_SIZE_MULTIPLIER_MIN; } else if (multiplier > FONT_SIZE_MULTIPLIER_MAX) { multiplier = FONT_SIZE_MULTIPLIER_MAX; } prefs.edit().putInt(PrefKeys.getTextSizeMultiplier(), multiplier).apply(); bus.post(new ChangeTextSizeEvent()); } /** * Gets the current size of the app's font. This is given as a device-specific size (not "sp"), * and can be passed directly to setTextSize() functions. * @param window The window on which the font will be displayed. * @return Actual current size of the font. */ public float getFontSize(Window window) { int multiplier = prefs.getInt(PrefKeys.getTextSizeMultiplier(), 0); return Utils.getFontSizeFromSp(window, getResources().getDimension(R.dimen.textSize)) * (1.0f + multiplier * FONT_SIZE_FACTOR); } /** * Gets whether EventLogging is currently enabled or disabled. * * @return A boolean that is true if EventLogging is enabled, and false if it is not. */ public boolean isEventLoggingEnabled() { return prefs.getBoolean(PrefKeys.getEventLoggingEnabled(), true); } public List<String> getLanguageMruList() { if (languageMruList == null) { languageMruList = new ArrayList<String>(); String mruString = prefs.getString(PrefKeys.getLanguageMru(), getPrimaryLanguage()); languageMruList.addAll(Arrays.asList(mruString.split(","))); } return languageMruList; } public void addLanguageToMruList(String langCode) { if (languageMruList != null) { languageMruList.remove(langCode); languageMruList.add(0, langCode); prefs.edit().putString(PrefKeys.getLanguageMru(), TextUtils.join(",", languageMruList)).apply(); } } public boolean showImages() { return prefs.getBoolean(PrefKeys.getShowImages(), true); } }
package net.silentchaos512.lib.registry; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.google.common.collect.MapMaker; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.crafting.IRecipe; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionType; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; import net.minecraft.world.biome.Biome; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.client.registry.IRenderFactory; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.ForgeRegistries; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.registries.IForgeRegistryEntry; import net.silentchaos512.lib.item.ItemBlockSL; import net.silentchaos512.lib.util.LogHelper; public class SRegistry { // Internal use only! private final Set<IRegistryObject> registryObjects = new HashSet<>(); protected IRegistrationHandler handlerBlocks; protected IRegistrationHandler handlerItems; protected IRegistrationHandler handlerEnchantments; protected IRegistrationHandler handlerRecipes; /** A reference to the mod's instance object. */ protected Object mod; /** The LogHelper for the mod, if any. May be used to log error messages. */ protected LogHelper logHelper; /** The mod ID for the mod this SRegistry instance belongs to. */ public final String modId; /** The resource prefix for the mod. This is set in the constructor based on the modId. */ public final String resourcePrefix; public RecipeMaker recipes; protected boolean listModelsInPost = false; public SRegistry(String modId) { this.modId = modId; this.resourcePrefix = modId.toLowerCase() + ":"; this.recipes = new RecipeMaker(modId); MinecraftForge.EVENT_BUS.register(new EventHandler(this)); } public SRegistry(String modId, LogHelper logHelper) { this(modId); this.logHelper = logHelper; } /** * The mod object should be set automatically in preInit, but it can be done manually if that fails. */ public void setMod(Object mod) { this.mod = mod; } public <T> IRegistrationHandler<T> addRegistrationHandler(IRegistrationHandler<T> handler, Class<T> clazz) { if (clazz == Block.class) handlerBlocks = handler; else if (clazz == Item.class) handlerItems = handler; else if (clazz == Enchantment.class) handlerEnchantments = handler; else if (clazz == IRecipe.class) handlerRecipes = handler; // TODO return handler; } // Block /** * Register an IRegistryObject Block (BlockSL, etc.) Uses getName for its key. */ public <T extends Block & IRegistryObject> T registerBlock(T block) { return registerBlock(block, block.getName()); } /** * Register a Block. Its name (registry key/name) must be provided. Uses a new ItemBlockSL. */ public <T extends Block> T registerBlock(T block, String key) { return registerBlock(block, key, new ItemBlockSL(block)); } /** * Register an IRegistryObject Block (BlockSL, etc.) with a custom ItemBlock. Uses getName for its key. */ public <T extends Block & IRegistryObject> T registerBlock(T block, ItemBlock itemBlock) { return registerBlock(block, block.getName(), itemBlock); } /** * Register a Block. Its name (registry key/name) and ItemBlock must be provided. */ public <T extends Block> T registerBlock(T block, String key, ItemBlock itemBlock) { if (block instanceof IRegistryObject) { registryObjects.add((IRegistryObject) block); } ResourceLocation name = new ResourceLocation(resourcePrefix + key); safeSetRegistryName(block, name); ForgeRegistries.BLOCKS.register(block); if (itemBlock != null) { safeSetRegistryName(itemBlock, name); ForgeRegistries.ITEMS.register(itemBlock); } return block; } // Item /** * Register an IRegistryObject Item (ItemSL, etc.) Uses getName for its key. */ public <T extends Item & IRegistryObject> T registerItem(T item) { return registerItem(item, item.getName()); } /** * Register an Item. Its name (registry key/name) must be provided. */ public <T extends Item> T registerItem(T item, String key) { if (item instanceof IRegistryObject) { registryObjects.add((IRegistryObject) item); } ResourceLocation name = new ResourceLocation(resourcePrefix + key); safeSetRegistryName(item, name); ForgeRegistries.ITEMS.register(item); return item; } // Enchantment public void registerEnchantment(Enchantment ench, String key) { ResourceLocation name = new ResourceLocation(resourcePrefix + key); safeSetRegistryName(ench, name); ForgeRegistries.ENCHANTMENTS.register(ench); } // Entity /** Automatically incrementing ID number for registering entities. */ protected int lastEntityId = -1; public void registerEntity(Class<? extends Entity> entityClass, String key) { registerEntity(entityClass, key, ++lastEntityId, mod, 64, 20, true); } public void registerEntity(Class<? extends Entity> entityClass, String key, int trackingRange, int updateFrequency, boolean sendsVelocityUpdates) { registerEntity(entityClass, key, ++lastEntityId, mod, trackingRange, updateFrequency, sendsVelocityUpdates); } public void registerEntity(Class<? extends Entity> entityClass, String key, int id, Object mod, int trackingRange, int updateFrequency, boolean sendsVelocityUpdates) { ResourceLocation resource = new ResourceLocation(modId, key); EntityRegistry.registerModEntity(resource, entityClass, key, id, mod, trackingRange, updateFrequency, sendsVelocityUpdates); } @SideOnly(Side.CLIENT) public <T extends Entity> void registerEntityRenderer(Class<T> entityClass, IRenderFactory<T> renderFactory) { RenderingRegistry.registerEntityRenderingHandler(entityClass, renderFactory); } public void safeSetRegistryName(IForgeRegistryEntry entry, ResourceLocation name) { if (entry.getRegistryName() == null) { entry.setRegistryName(name); } } /** * Register a TileEntity. "tile." + resourcePrefix is automatically prepended to the key. */ public void registerTileEntity(Class<? extends TileEntity> tileClass, String key) { String fullKey = "tile." + resourcePrefix + key; GameRegistry.registerTileEntity(tileClass, fullKey); } /** * Registers a renderer for a TileEntity. * * @param tileClass * @param renderer */ @SideOnly(Side.CLIENT) public <T extends TileEntity> void registerTileEntitySpecialRenderer(Class<T> tileClass, TileEntitySpecialRenderer<T> renderer) { ClientRegistry.bindTileEntitySpecialRenderer(tileClass, renderer); } /** * Call in the "preInit" phase in your common proxy. */ public void preInit() { if (mod == null) { ModContainer container = Loader.instance().getIndexedModList().get(modId); if (container != null) mod = container.getMod(); else if (logHelper != null) logHelper.warning("SRegistry for this mod failed to get the mod instance! This could be because the provided mod ID is incorrect."); } } /** * Call in the "init" phase in your common proxy. */ public void init() { } /** * Call in the "postInit" phase in your common proxy. */ public void postInit() { } /** * Call in the "preInit" phase in your client proxy. */ public void clientPreInit() { } /** * Call in the "init" phase in your client proxy. */ public void clientInit() { } /** * Call in the "postInit" phase in your client proxy. */ public void clientPostInit() { if (listModelsInPost) { Map<Integer, ModelResourceLocation> models = new MapMaker().makeMap(); for (IRegistryObject obj : registryObjects) { models.clear(); obj.getModels(models); for (ModelResourceLocation model : models.values()) { if (model != null) { System.out.println(model); } } } } } @Deprecated protected void addRecipes() { for (IRegistryObject obj : registryObjects) obj.addRecipes(recipes); } protected void addOreDictEntries() { for (IRegistryObject obj : registryObjects) obj.addOreDict(); } @SideOnly(Side.CLIENT) protected void registerModels() { ModelResourceLocation model; Map<Integer, ModelResourceLocation> models = new MapMaker().initialCapacity(16).makeMap(); for (IRegistryObject obj : registryObjects) { if (!obj.registerModels()) { Item item = obj instanceof Block ? Item.getItemFromBlock((Block) obj) : (Item) obj; models.clear(); obj.getModels(models); models.entrySet().forEach(entry -> ModelLoader.setCustomModelResourceLocation(item, entry.getKey(), entry.getValue())); } } } /** * Handles the new Forge RegistryEvents. An instance will automatically be registered when an SRegistry is * constructed. * * @author SilentChaos512 * @since 2.2.2 */ public static class EventHandler { protected SRegistry sregistry; public EventHandler(SRegistry sregistry) { this.sregistry = sregistry; } @SubscribeEvent public void registerBlocks(RegistryEvent.Register<Block> event) { if (sregistry.handlerBlocks != null) { sregistry.handlerBlocks.registerAll(sregistry); } } @SubscribeEvent public void registerItems(RegistryEvent.Register<Item> event) { if (sregistry.handlerItems != null) { sregistry.handlerItems.registerAll(sregistry); } sregistry.addOreDictEntries(); } @SubscribeEvent public void registerPotions(RegistryEvent.Register<Potion> event) { // TODO } @SubscribeEvent public void registerBiomes(RegistryEvent.Register<Biome> event) { // TODO } @SubscribeEvent public void registerSoundEvents(RegistryEvent.Register<SoundEvent> event) { // TODO } @SubscribeEvent public void registerPotionTypes(RegistryEvent.Register<PotionType> event) { // TODO } @SubscribeEvent public void registerEnchantments(RegistryEvent.Register<Enchantment> event) { if (sregistry.handlerEnchantments != null) { sregistry.handlerEnchantments.registerAll(sregistry); } } @SubscribeEvent public void registerVillagerProfessions(RegistryEvent.Register<VillagerProfession> event) { // TODO } @SubscribeEvent public void registerEntities(RegistryEvent.Register<EntityEntry> event) { // TODO } @SubscribeEvent public void registerRecipes(RegistryEvent.Register<IRecipe> event) { if (sregistry.handlerRecipes != null) { sregistry.handlerRecipes.registerAll(sregistry); } sregistry.addRecipes(); } @SubscribeEvent public void registerModels(ModelRegistryEvent event) { sregistry.registerModels(); } } }
package git4idea.history; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CharArrayUtil; import git4idea.GitFormatException; import git4idea.GitVcs; import git4idea.config.GitVersionSpecialty; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Parser for git log output. * <p> * Commit records have the following format: * <pre> * RECORD_START (commit information, separated by ITEMS_SEPARATOR) RECORD_END \n (changed paths with statuses)?</pre> * Example: * <pre> * 2c815939f45fbcfda9583f84b14fe9d393ada790&lt;ITEMS_SEPARATOR&gt;sample commit&lt;RECORD_END&gt; * D a.txt</pre> */ public class GitLogParser { private static final Logger LOG = Logger.getInstance(GitLogParser.class); // Single records begin with %x01, end with %03. Items of commit information (hash, committer, subject, etc.) are separated by %x02. // each character is declared twice - for Git pattern format and for actual character in the output. public static final String RECORD_START = "\u0001\u0001"; public static final char ITEMS_SEPARATOR = '\u0002'; public static final String RECORD_END = "\u0003\u0003"; public static final String RECORD_START_GIT = "%x01%x01"; private static final String ITEMS_SEPARATOR_GIT = "%x02"; private static final String RECORD_END_GIT = "%x03%x03"; private static final int INPUT_ERROR_MESSAGE_HEAD_LIMIT = 1000000; // limit the string by ~2mb private static final int INPUT_ERROR_MESSAGE_TAIL_LIMIT = 100; private final boolean mySupportsRawBody; @NotNull private final String myPretty; @NotNull private OptionsParser myOptionsParser; @NotNull private PathsParser myPathsParser; private boolean myIsInBody = true; private GitLogParser(boolean supportsRawBody, @NotNull NameStatus nameStatusOption, @NotNull GitLogOption... options) { myPretty = "--pretty=format:" + makeFormatFromOptions(options); mySupportsRawBody = supportsRawBody; myOptionsParser = new OptionsParser(options); myPathsParser = new PathsParser(nameStatusOption); } public GitLogParser(@NotNull Project project, @NotNull NameStatus nameStatus, @NotNull GitLogOption... options) { this(GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(GitVcs.getInstance(project).getVersion()), nameStatus, options); } public GitLogParser(@NotNull Project project, @NotNull GitLogOption... options) { this(project, NameStatus.NONE, options); } @NotNull public List<GitLogRecord> parse(@NotNull CharSequence output) { List<GitLogRecord> result = ContainerUtil.newArrayList(); List<CharSequence> lines = StringUtil.split(output, "\n", true, false); for (CharSequence line : lines) { try { GitLogRecord record = parseLine(line); if (record != null) { result.add(record); } } catch (GitFormatException e) { clear(); LOG.error(e); } } GitLogRecord record = finish(); if (record != null) result.add(record); return result; } @Nullable public GitLogRecord parseOneRecord(@NotNull CharSequence output) { List<GitLogRecord> records = parse(output); clear(); if (records.isEmpty()) return null; return ContainerUtil.getFirstItem(records); } /** * Expects a line without separator. */ @Nullable public GitLogRecord parseLine(@NotNull CharSequence line) { if (myPathsParser.expectsPaths()) { return parseLineWithPaths(line); } return parseLineWithoutPaths(line); } @Nullable private GitLogRecord parseLineWithPaths(@NotNull CharSequence line) { if (myIsInBody) { myIsInBody = !myOptionsParser.parseLine(line); } else { if (CharArrayUtil.regionMatches(line, 0, RECORD_START)) { GitLogRecord record = createRecord(); myIsInBody = !myOptionsParser.parseLine(line); return record; } myPathsParser.parseLine(line); } return null; } @Nullable private GitLogRecord parseLineWithoutPaths(@NotNull CharSequence line) { if (myOptionsParser.parseLine(line)) { return createRecord(); } return null; } @Nullable public GitLogRecord finish() { if (myOptionsParser.isEmpty()) return null; return createRecord(); } @NotNull private GitLogRecord createRecord() { Map<GitLogOption, String> options = myOptionsParser.getResult(); myOptionsParser.clear(); List<GitLogStatusInfo> result = myPathsParser.getResult(); myPathsParser.clear(); myIsInBody = true; return new GitLogRecord(options, result, mySupportsRawBody); } public void clear() { myOptionsParser.clear(); myPathsParser.clear(); myIsInBody = true; } @NotNull public String getPretty() { return myPretty; } @NotNull private static String makeFormatFromOptions(@NotNull GitLogOption[] options) { Function<GitLogOption, String> function = option -> "%" + option.getPlaceholder(); return RECORD_START_GIT + StringUtil.join(options, function, ITEMS_SEPARATOR_GIT) + RECORD_END_GIT; } private static void throwGFE(@NotNull String message, @NotNull CharSequence line) { throw new GitFormatException(message + " [" + getTruncatedEscapedOutput(line) + "]"); } @NotNull private static String getTruncatedEscapedOutput(@NotNull CharSequence line) { String lineString; String formatString = "%s...(%d more characters)...%s"; if (line.length() > INPUT_ERROR_MESSAGE_HEAD_LIMIT + INPUT_ERROR_MESSAGE_TAIL_LIMIT + formatString.length()) { lineString = String.format(formatString, line.subSequence(0, INPUT_ERROR_MESSAGE_HEAD_LIMIT), (line.length() - INPUT_ERROR_MESSAGE_HEAD_LIMIT - INPUT_ERROR_MESSAGE_TAIL_LIMIT), line.subSequence(line.length() - INPUT_ERROR_MESSAGE_TAIL_LIMIT, line.length())); } else { lineString = line.toString(); } return StringUtil.escapeStringCharacters(lineString); } // --name-status or no flag enum NameStatus { /** * No flag. */ NONE, /** * --name-status */ STATUS } /** * Options which may be passed to 'git log --pretty=format:' as placeholders and then parsed from the result. * These are the pieces of information about a commit which we want to get from 'git log'. */ enum GitLogOption { HASH("H"), TREE("T"), COMMIT_TIME("ct"), AUTHOR_NAME("an"), AUTHOR_TIME("at"), AUTHOR_EMAIL("ae"), COMMITTER_NAME("cn"), COMMITTER_EMAIL("ce"), SUBJECT("s"), BODY("b"), PARENTS("P"), REF_NAMES("d"), SHORT_REF_LOG_SELECTOR("gd"), RAW_BODY("B"); private String myPlaceholder; GitLogOption(String placeholder) { myPlaceholder = placeholder; } private String getPlaceholder() { return myPlaceholder; } } private static class OptionsParser { @NotNull private final GitLogOption[] myOptions; @NotNull private final PartialResult myResult = new PartialResult(); public OptionsParser(@NotNull GitLogOption[] options) { myOptions = options; } public boolean parseLine(@NotNull CharSequence line) { int offset = 0; if (myResult.isEmpty()) { if (!CharArrayUtil.regionMatches(line, offset, RECORD_START)) { return false; } offset += RECORD_START.length(); } while (offset < line.length()) { if (atRecordEnd(line, offset)) { myResult.finishItem(); if (myResult.getResult().size() != myOptions.length) { throwGFE("Parsed incorrect options " + myResult.getResult() + " for " + Arrays.toString(myOptions), line); } return true; } char c = line.charAt(offset); if (c == ITEMS_SEPARATOR) { myResult.finishItem(); } else { myResult.append(c); } offset++; } myResult.append('\n'); return false; } private static boolean atRecordEnd(@NotNull CharSequence line, int offset) { return (offset == line.length() - RECORD_END.length() && CharArrayUtil.regionMatches(line, offset, RECORD_END)); } @NotNull public Map<GitLogOption, String> getResult() { return createOptions(myResult.getResult()); } @NotNull private Map<GitLogOption, String> createOptions(@NotNull List<String> options) { Map<GitLogOption, String> optionsMap = new HashMap<>(options.size()); for (int index = 0; index < options.size(); index++) { optionsMap.put(myOptions[index], options.get(index)); } return optionsMap; } public void clear() { myResult.clear(); } public boolean isEmpty() { return myResult.isEmpty(); } } private static class PathsParser { @NotNull private final NameStatus myNameStatusOption; @NotNull private List<GitLogStatusInfo> myStatuses = ContainerUtil.newArrayList(); public PathsParser(@NotNull NameStatus nameStatusOption) { myNameStatusOption = nameStatusOption; } public void parseLine(@NotNull CharSequence line) { if (line.length() == 0) return; List<String> match = parsePathsLine(line); if (match.isEmpty()) { // ignore } else { if (myNameStatusOption != NameStatus.STATUS) throwGFE("Status list not expected", line); if (match.size() == 2) { myStatuses.add(new GitLogStatusInfo(GitChangeType.fromString(match.get(0)), match.get(1), null)); } else { myStatuses.add(new GitLogStatusInfo(GitChangeType.fromString(match.get(0)), match.get(1), match.get(2))); } } } @NotNull private static List<String> parsePathsLine(@NotNull CharSequence line) { int offset = 0; PartialResult result = new PartialResult(); while (offset < line.length()) { if (atLineEnd(line, offset)) { break; } char charAt = line.charAt(offset); if (charAt == '\t') { result.finishItem(); } else { result.append(charAt); } offset++; } result.finishItem(); return result.getResult(); } private static boolean atLineEnd(@NotNull CharSequence line, int offset) { while (offset < line.length() && (line.charAt(offset) == '\t' || line.charAt(offset) == ' ')) offset++; if (offset == line.length() || (line.charAt(offset) == '\n' || line.charAt(offset) == '\r')) return true; return false; } @NotNull public List<GitLogStatusInfo> getResult() { return myStatuses; } public void clear() { myStatuses = ContainerUtil.newArrayList(); } public boolean expectsPaths() { return myNameStatusOption == NameStatus.STATUS; } } private static class PartialResult { @NotNull private List<String> myResult = ContainerUtil.newArrayList(); @NotNull private final StringBuilder myCurrentItem = new StringBuilder(); public void append(char c) { myCurrentItem.append(c); } public void finishItem() { myResult.add(myCurrentItem.toString()); myCurrentItem.setLength(0); } @NotNull public List<String> getResult() { return myResult; } public void clear() { myCurrentItem.setLength(0); myResult = ContainerUtil.newArrayList(); } public boolean isEmpty() { return myResult.isEmpty() && myCurrentItem.length() == 0; } } }
// FormatWriter.java package loci.formats; import java.awt.Image; import java.awt.image.*; import java.io.IOException; import loci.common.*; import loci.formats.meta.DummyMetadata; import loci.formats.meta.MetadataRetrieve; public abstract class FormatWriter extends FormatHandler implements IFormatWriter { // -- Fields -- /** Frame rate to use when writing in frames per second, if applicable. */ protected int fps = 10; /** Default color model. */ protected ColorModel cm; /** Available compression types. */ protected String[] compressionTypes; /** Current compression type. */ protected String compression; /** Whether the current file has been prepped for writing. */ protected boolean initialized; /** * Current metadata retrieval object. Should <b>never</b> be accessed * directly as the semantics of {@link #getMetadataRetrieve()} * prevent "null" access. */ protected MetadataRetrieve metadataRetrieve = new DummyMetadata(); // -- Constructors -- /** Constructs a format writer with the given name and default suffix. */ public FormatWriter(String format, String suffix) { super(format, suffix); } /** Constructs a format writer with the given name and default suffixes. */ public FormatWriter(String format, String[] suffixes) { super(format, suffixes); } // -- IFormatWriter API methods -- /* @see IFormatWriter#saveBytes(byte[], boolean) */ public void saveBytes(byte[] bytes, boolean last) throws FormatException, IOException { saveBytes(bytes, 0, last, last); } /* @see IFormatWriter#saveBytes(byte[], int, boolean, boolean) */ public void saveBytes(byte[] bytes, int series, boolean lastInSeries, boolean last) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); MetadataRetrieve r = getMetadataRetrieve(); if (r == null) throw new FormatException("MetadataRetrieve cannot be null"); int width = r.getPixelsSizeX(series, 0).intValue(); int height = r.getPixelsSizeY(series, 0).intValue(); int type = FormatTools.pixelTypeFromString(r.getPixelsPixelType(series, 0)); boolean littleEndian = !r.getPixelsBigEndian(series, 0).booleanValue(); int bpp = FormatTools.getBytesPerPixel(type); int planeSize = width * height * bpp; // calculate the number of channels per plane int channels = bytes.length / planeSize; BufferedImage img = AWTImageTools.makeImage(bytes, width, height, channels, true, bpp, FormatTools.isFloatingPoint(type), littleEndian, FormatTools.isSigned(type)); saveImage(img, series, lastInSeries, last); } /* @see IFormatWriter#saveImage(Image, boolean) */ public void saveImage(Image image, boolean last) throws FormatException, IOException { saveImage(image, 0, last, last); } /* @see IFormatWriter#canDoStacks() */ public boolean canDoStacks() { return false; } /* @see IFormatWriter#setMetadataRetrieve(MetadataRetrieve) */ public void setMetadataRetrieve(MetadataRetrieve retrieve) { FormatTools.assertId(currentId, false, 1); if (retrieve == null) { throw new IllegalArgumentException("Metadata object is null"); } metadataRetrieve = retrieve; } /* @see IFormatWriter#getMetadataRetrieve() */ public MetadataRetrieve getMetadataRetrieve() { return metadataRetrieve; } /* @see IFormatWriter#setColorModel(ColorModel) */ public void setColorModel(ColorModel model) { cm = model; } /* @see IFormatWriter#getColorModel() */ public ColorModel getColorModel() { return cm; } /* @see IFormatWriter#setFramesPerSecond(int) */ public void setFramesPerSecond(int rate) { fps = rate; } /* @see IFormatWriter#getFramesPerSecond() */ public int getFramesPerSecond() { return fps; } /* @see IFormatWriter#getCompressionTypes() */ public String[] getCompressionTypes() { return compressionTypes; } /* @see IFormatWriter#setCompression(compress) */ public void setCompression(String compress) throws FormatException { // check that this is a valid type for (int i=0; i<compressionTypes.length; i++) { if (compressionTypes[i].equals(compress)) { compression = compress; return; } } throw new FormatException("Invalid compression type: " + compress); } /* @see IFormatWriter#getCompression() */ public String getCompression() { return compression; } /* @see IFormatWriter#getPixelTypes() */ public int[] getPixelTypes() { return new int[] {FormatTools.INT8, FormatTools.UINT8, FormatTools.INT16, FormatTools.UINT16, FormatTools.INT32, FormatTools.UINT32, FormatTools.FLOAT}; } /* @see IFormatWriter#isSupportedType(int) */ public boolean isSupportedType(int type) { int[] types = getPixelTypes(); for (int i=0; i<types.length; i++) { if (type == types[i]) return true; } return false; } // -- IFormatHandler API methods -- /* @see IFormatHandler#setId(String) */ public void setId(String id) throws FormatException, IOException { if (id.equals(currentId)) return; close(); currentId = id; initialized = false; } }
package loci.formats; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import loci.common.DataTools; import loci.common.Region; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TileStitcher extends ReaderWrapper { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(TileStitcher.class); // -- Fields -- private int tileX = 0; private int tileY = 0; private Integer[][] tileMap; // -- Utility methods -- /** Converts the given reader into a TileStitcher, wrapping if needed. */ public static TileStitcher makeTileStitcher(IFormatReader r) { if (r instanceof TileStitcher) return (TileStitcher) r; return new TileStitcher(r); } // -- Constructor -- /** Constructs a TileStitcher around a new image reader. */ public TileStitcher() { super(); } /** Constructs a TileStitcher with the given reader. */ public TileStitcher(IFormatReader r) { super(r); } // -- IFormatReader API methods -- /* @see IFormatReader#getSizeX() */ public int getSizeX() { return reader.getSizeX() * tileX; } /* @see IFormatReader#getSizeY() */ public int getSizeY() { return reader.getSizeY() * tileY; } /* @see IFormatReader#getSeriesCount() */ public int getSeriesCount() { if (tileX == 1 && tileY == 1) { return reader.getSeriesCount(); } return 1; } /* @see IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { return openBytes(no, 0, 0, getSizeX(), getSizeY()); } /* @see IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { return openBytes(no , buf, 0, 0, getSizeX(), getSizeY()); } /* @see IFormatReader#openBytes(int, int, int, int, int) */ public byte[] openBytes(int no, int x, int y, int w, int h) throws FormatException, IOException { int bpp = FormatTools.getBytesPerPixel(getPixelType()); int ch = getRGBChannelCount(); byte[] newBuffer = DataTools.allocate(w, h, ch, bpp); return openBytes(no, newBuffer, x, y, w, h); } /* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(getCurrentFile(), true, 2); if (tileX == 1 && tileY == 1) { return super.openBytes(no, buf, x, y, w, h); } byte[] tileBuf = new byte[buf.length / tileX * tileY]; int tw = reader.getSizeX(); int th = reader.getSizeY(); Region image = new Region(x, y, w, h); int pixelType = getPixelType(); int pixel = getRGBChannelCount() * FormatTools.getBytesPerPixel(pixelType); int outputRowLen = w * pixel; int outputRow = 0, outputCol = 0; Region intersection = null; for (int ty=0; ty<tileY; ty++) { for (int tx=0; tx<tileX; tx++) { Region tile = new Region(tx * tw, ty * th, tw, th); if (!tile.intersects(image)) { continue; } intersection = tile.intersection(image); int rowLen = pixel * (int) Math.min(intersection.width, tw); if (tileMap[ty][tx] == null) { outputCol += rowLen; continue; } reader.setSeries(tileMap[ty][tx]); reader.openBytes(no, tileBuf, 0, 0, tw, th); int outputOffset = outputRowLen * outputRow + outputCol; for (int row=0; row<intersection.height; row++) { int realRow = row + intersection.y - tile.y; int inputOffset = pixel * (realRow * tw + tx); System.arraycopy(tileBuf, inputOffset, buf, outputOffset, rowLen); outputOffset += outputRowLen; } outputCol += rowLen; } if (intersection != null) { outputRow += intersection.height; outputCol = 0; } } return buf; } /* @see IFormatReader#setId(String) */ public void setId(String id) throws FormatException, IOException { super.setId(id); MetadataStore store = getMetadataStore(); if (!(store instanceof IMetadata) || reader.getSeriesCount() == 1) { tileX = 1; tileY = 1; return; } IMetadata meta = (IMetadata) store; // don't even think about stitching HCS data, as it quickly gets complicated // it might be worth improving this in the future so that fields are // stitched, but plates/wells are left alone, but for now it is easy // enough to just ignore HCS data with multiple plates and/or wells if (meta.getPlateCount() > 1 || (meta.getPlateCount() == 1 && meta.getWellCount(0) > 1)) { tileX = 1; tileY = 1; return; } // now make sure that all of the series have the same dimensions boolean equalDimensions = true; for (int i=1; i<meta.getImageCount(); i++) { if (!meta.getPixelsSizeX(i).equals(meta.getPixelsSizeX(0))) { equalDimensions = false; } if (!meta.getPixelsSizeY(i).equals(meta.getPixelsSizeY(0))) { equalDimensions = false; } if (!meta.getPixelsSizeZ(i).equals(meta.getPixelsSizeZ(0))) { equalDimensions = false; } if (!meta.getPixelsSizeC(i).equals(meta.getPixelsSizeC(0))) { equalDimensions = false; } if (!meta.getPixelsSizeT(i).equals(meta.getPixelsSizeT(0))) { equalDimensions = false; } if (!meta.getPixelsType(i).equals(meta.getPixelsType(0))) { equalDimensions = false; } if (!equalDimensions) break; } if (!equalDimensions) { tileX = 1; tileY = 1; return; } ArrayList<TileCoordinate> tiles = new ArrayList<TileCoordinate>(); ArrayList<Double> uniqueX = new ArrayList<Double>(); ArrayList<Double> uniqueY = new ArrayList<Double>(); boolean equalZs = true; Double firstZ = meta.getPlanePositionZ(0, meta.getPlaneCount(0) - 1); for (int i=0; i<reader.getSeriesCount(); i++) { TileCoordinate coord = new TileCoordinate(); coord.x = meta.getPlanePositionX(i, meta.getPlaneCount(i) - 1); coord.y = meta.getPlanePositionY(i, meta.getPlaneCount(i) - 1); tiles.add(coord); if (coord.x != null && !uniqueX.contains(coord.x)) { uniqueX.add(coord.x); } if (coord.y != null && !uniqueY.contains(coord.y)) { uniqueY.add(coord.y); } Double zPos = meta.getPlanePositionZ(i, meta.getPlaneCount(i) - 1); if (firstZ == null) { if (zPos != null) { equalZs = false; } } else { if (!firstZ.equals(zPos)) { equalZs = false; } } } tileX = uniqueX.size(); tileY = uniqueY.size(); if (!equalZs) { LOGGER.warn("Z positions not equal"); } tileMap = new Integer[tileY][tileX]; Double[] xCoordinates = uniqueX.toArray(new Double[tileX]); Arrays.sort(xCoordinates); Double[] yCoordinates = uniqueY.toArray(new Double[tileY]); Arrays.sort(yCoordinates); for (int row=0; row<tileMap.length; row++) { for (int col=0; col<tileMap[row].length; col++) { TileCoordinate coordinate = new TileCoordinate(); coordinate.x = xCoordinates[col]; coordinate.y = yCoordinates[row]; for (int tile=0; tile<tiles.size(); tile++) { if (tiles.get(tile).equals(coordinate)) { tileMap[row][col] = tile; } } } } } // -- IFormatHandler API methods -- /* @see IFormatHandler#getNativeDataType() */ public Class<?> getNativeDataType() { return byte[].class; } // -- Helper classes -- class TileCoordinate { public Double x; public Double y; public boolean equals(Object o) { if (!(o instanceof TileCoordinate)) { return false; } TileCoordinate tile = (TileCoordinate) o; boolean xEqual = x == null ? tile.x == null : x.equals(tile.x); boolean yEqual = y == null ? tile.y == null : y.equals(tile.y); return xEqual && yEqual; } } }
// SEQReader.java package loci.formats.in; import java.io.IOException; import loci.common.RandomAccessInputStream; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.tiff.IFD; import loci.formats.tiff.TiffParser; public class SEQReader extends BaseTiffReader { // -- Constants -- /** * An array of shorts (length 12) with identical values in all of our * samples; assuming this is some sort of format identifier. */ private static final int IMAGE_PRO_TAG_1 = 50288; /** Frame rate. */ private static final int IMAGE_PRO_TAG_2 = 40105; // -- Constructor -- /** Constructs a new Image-Pro SEQ reader. */ public SEQReader() { super("Image-Pro Sequence", "seq"); domains = new String[] {FormatTools.UNKNOWN_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser parser = new TiffParser(stream); parser.setDoCaching(false); IFD ifd = parser.getFirstIFD(); if (ifd == null) return false; Object tag = ifd.get(IMAGE_PRO_TAG_1); return tag != null && (tag instanceof short[]); } // -- Internal BaseTiffReader API methods -- /* @see BaseTiffReader#initStandardMetadata() */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); core[0].sizeZ = 0; core[0].sizeT = 0; MetadataLevel level = getMetadataOptions().getMetadataLevel(); for (IFD ifd : ifds) { if (level != MetadataLevel.MINIMUM) { short[] tag1 = (short[]) ifd.getIFDValue(IMAGE_PRO_TAG_1); if (tag1 != null) { String seqId = ""; for (int i=0; i<tag1.length; i++) seqId = seqId + tag1[i]; addGlobalMeta("Image-Pro SEQ ID", seqId); } } int tag2 = ifds.get(0).getIFDIntValue(IMAGE_PRO_TAG_2); if (tag2 != -1) { // should be one of these for every image plane core[0].sizeZ++; addGlobalMeta("Frame Rate", tag2); } addGlobalMeta("Number of images", getSizeZ()); } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getSizeZ() == 1 && getSizeT() == 1) { core[0].sizeZ = ifds.size(); } // default values addGlobalMeta("frames", getSizeZ()); addGlobalMeta("channels", super.getSizeC()); addGlobalMeta("slices", getSizeT()); // parse the description to get channels, slices and times where applicable String descr = ifds.get(0).getComment(); metadata.remove("Comment"); if (descr != null) { String[] lines = descr.split("\n"); for (String token : lines) { token = token.trim(); int eq = token.indexOf("="); if (eq == -1) eq = token.indexOf(":"); if (eq != -1) { String label = token.substring(0, eq); String data = token.substring(eq + 1); addGlobalMeta(label, data); if (label.equals("channels")) core[0].sizeC = Integer.parseInt(data); else if (label.equals("frames")) { core[0].sizeT = Integer.parseInt(data); } else if (label.equals("slices")) { core[0].sizeZ = Integer.parseInt(data); } } } } if (isRGB() && getSizeC() != 3) core[0].sizeC *= 3; core[0].dimensionOrder = "XY"; int maxNdx = 0, max = 0; int[] dims = {getSizeZ(), getSizeC(), getSizeT()}; String[] axes = {"Z", "C", "T"}; for (int i=0; i<dims.length; i++) { if (dims[i] > max) { max = dims[i]; maxNdx = i; } } core[0].dimensionOrder += axes[maxNdx]; if (maxNdx != 1) { if (getSizeC() > 1) { core[0].dimensionOrder += "C"; core[0].dimensionOrder += (maxNdx == 0 ? axes[2] : axes[0]); } else core[0].dimensionOrder += (maxNdx == 0 ? axes[2] : axes[0]) + "C"; } else { if (getSizeZ() > getSizeT()) core[0].dimensionOrder += "ZT"; else core[0].dimensionOrder += "TZ"; } } }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.tree.DefaultTreeCellRenderer; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.ui.ArbilTree; import nl.mpi.arbil.ui.ArbilTreeRenderer; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; public class EgoSelectionPanel extends JPanel { private ArbilTree egoTree; // DefaultTreeModel egoModel; // DefaultMutableTreeNode egoRootNode; private ArbilTree requiredTree; // DefaultTreeModel requiredModel; // DefaultMutableTreeNode requiredRootNode; private ArbilTree impliedTree; // DefaultTreeModel impliedModel; // DefaultMutableTreeNode impliedRootNode; JPanel labelPanel3; JLabel transientLabel; public EgoSelectionPanel() { DefaultTreeCellRenderer cellRenderer = new DefaultTreeCellRenderer(); // egoRootNode = new DefaultMutableTreeNode(new JLabel("Ego", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); // egoModel = new DefaultTreeModel(egoRootNode); // egoTree = new JTree(egoModel); egoTree = new ArbilTree(); // todo: add trac task to modify the arbil tree such that each tree can have its own preview table // egoTree.getModel(). // egoTree.setRootVisible(false); egoTree.setCellRenderer(new ArbilTreeRenderer()); // requiredRootNode = new DefaultMutableTreeNode(new JLabel("Required", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); // requiredModel = new DefaultTreeModel(requiredRootNode); // requiredTree = new JTree(requiredModel); requiredTree = new ArbilTree(); // requiredTree.setRootVisible(false); requiredTree.setCellRenderer(new ArbilTreeRenderer()); // impliedRootNode = new DefaultMutableTreeNode(new JLabel("Implied", cellRenderer.getDefaultOpenIcon(), JLabel.LEFT)); // impliedModel = new DefaultTreeModel(impliedRootNode); // impliedTree = new JTree(impliedModel); impliedTree = new ArbilTree(); // impliedTree.setRootVisible(false); impliedTree.setCellRenderer(new ArbilTreeRenderer()); // egoTree.setRootVisible(false); this.setLayout(new BorderLayout()); JPanel treePanel1 = new JPanel(new BorderLayout()); JPanel treePanel2 = new JPanel(new BorderLayout()); // treePanel.setLayout(new BoxLayout(treePanel, BoxLayout.PAGE_AXIS)); JScrollPane outerScrolPane = new JScrollPane(treePanel1); // this.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected Ego")); JPanel labelPanel1 = new JPanel(new BorderLayout()); JPanel labelPanel2 = new JPanel(new BorderLayout()); labelPanel3 = new JPanel(new BorderLayout()); // JPanel labelPanel4 = new JPanel(new BorderLayout()); labelPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Ego")); labelPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Required")); labelPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Implied")); // labelPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Transient")); labelPanel1.add(egoTree, BorderLayout.CENTER); labelPanel2.add(requiredTree, BorderLayout.CENTER); labelPanel3.add(impliedTree, BorderLayout.CENTER); egoTree.setBackground(labelPanel1.getBackground()); requiredTree.setBackground(labelPanel1.getBackground()); impliedTree.setBackground(labelPanel1.getBackground()); treePanel1.add(labelPanel1, BorderLayout.PAGE_START); treePanel1.add(treePanel2, BorderLayout.CENTER); treePanel2.add(labelPanel2, BorderLayout.PAGE_START); treePanel2.add(labelPanel3, BorderLayout.CENTER); this.add(outerScrolPane, BorderLayout.CENTER); } public void setTreeNodes(HashSet<UniqueIdentifier> egoIdentifiers, HashSet<UniqueIdentifier> requiredEntityIdentifiers, EntityData[] allEntities) { ArrayList<ArbilDataNode> egoNodeArray = new ArrayList<ArbilDataNode>(); ArrayList<ArbilDataNode> requiredNodeArray = new ArrayList<ArbilDataNode>(); ArrayList<ArbilDataNode> remainingNodeArray = new ArrayList<ArbilDataNode>(); for (EntityData entityData : allEntities) { if (entityData.isVisible) { try { ArbilDataNode arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(entityData.getEntityPath())); if (entityData.isEgo || egoIdentifiers.contains(entityData.getUniqueIdentifier())) { egoNodeArray.add(arbilDataNode); } else if (requiredEntityIdentifiers.contains(entityData.getUniqueIdentifier())) { requiredNodeArray.add(arbilDataNode); } else { remainingNodeArray.add(arbilDataNode); } } catch (URISyntaxException exception) { System.err.println(exception.getMessage()); } } } // setEgoNodes(egoNodeArray, egoTree, egoModel, egoRootNode); egoTree.rootNodeChildren = egoNodeArray.toArray(new ArbilDataNode[]{}); egoTree.requestResort(); // setEgoNodes(requiredNodeArray, requiredTree, requiredModel, requiredRootNode); requiredTree.rootNodeChildren = requiredNodeArray.toArray(new ArbilDataNode[]{}); requiredTree.requestResort(); // setEgoNodes(remainingNodeArray, impliedTree, impliedModel, impliedRootNode); impliedTree.rootNodeChildren = remainingNodeArray.toArray(new ArbilDataNode[]{}); impliedTree.requestResort(); if (transientLabel != null) { labelPanel3.remove(transientLabel); } } public void setTransientNodes(EntityData[] allEntities) { egoTree.rootNodeChildren = new ArbilDataNode[]{}; egoTree.requestResort(); // setEgoNodes(requiredNodeArray, requiredTree, requiredModel, requiredRootNode); requiredTree.rootNodeChildren = new ArbilDataNode[]{}; requiredTree.requestResort(); // setEgoNodes(remainingNodeArray, impliedTree, impliedModel, impliedRootNode); impliedTree.rootNodeChildren = new ArbilDataNode[]{}; impliedTree.requestResort(); transientLabel = new JLabel(allEntities.length + " transient entities have been generated"); labelPanel3.add(transientLabel, BorderLayout.PAGE_START); } // private void setEgoNodes(ArrayList<ArbilDataNode> selectedNodes, JTree currentTree, DefaultTreeModel currentModel, DefaultMutableTreeNode currentRootNode) { // currentRootNode.removeAllChildren(); // currentModel.nodeStructureChanged(currentRootNode); // if (selectedNodes != null) { // for (ArbilDataNode imdiTreeObject : selectedNodes) { //// System.out.println("adding node: " + imdiTreeObject.toString()); // currentModel.insertNodeInto(new DefaultMutableTreeNode(imdiTreeObject), currentRootNode, 0); // currentTree.expandPath(new TreePath(currentRootNode.getPath())); }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.util.BugCatcher; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.data.KinTreeNode; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.svg.GraphPanel; public class EntitySearchPanel extends JPanel { private EntityCollection entityCollection; private KinTree resultsTree; private JTextArea resultsArea = new JTextArea(); private JTextField searchField; private JProgressBar progressBar; private JButton searchButton; private JPanel searchPanel; private GraphPanel graphPanel; private MessageDialogHandler dialogHandler; private BugCatcher bugCatcher; private ArbilDataNodeLoader dataNodeLoader; public EntitySearchPanel(EntityCollection entityCollection, KinDiagramPanel kinDiagramPanel, GraphPanel graphPanel, MessageDialogHandler dialogHandler, BugCatcher bugCatcher, ArbilDataNodeLoader dataNodeLoader) { this.entityCollection = entityCollection; this.graphPanel = graphPanel; this.dialogHandler = dialogHandler; this.bugCatcher = bugCatcher; this.dataNodeLoader = dataNodeLoader; this.setLayout(new BorderLayout()); resultsTree = new KinTree(kinDiagramPanel, graphPanel); resultsTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Test Tree"), true)); resultsTree.setRootVisible(false); // resultsTree.requestResort();// this resort is unrequred JLabel searchLabel = new JLabel("Search Entity Names"); searchField = new JTextField(); searchField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { EntitySearchPanel.this.performSearch(); } super.keyReleased(e); } }); progressBar = new JProgressBar(); searchButton = new JButton("Search"); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EntitySearchPanel.this.performSearch(); } }); searchPanel = new JPanel(); searchPanel.setLayout(new BorderLayout()); searchPanel.add(searchLabel, BorderLayout.PAGE_START); searchPanel.add(searchField, BorderLayout.CENTER); searchPanel.add(searchButton, BorderLayout.PAGE_END); this.add(searchPanel, BorderLayout.PAGE_START); this.add(new JScrollPane(resultsTree), BorderLayout.CENTER); this.add(resultsArea, BorderLayout.PAGE_END); } public void setTransferHandler(KinDragTransferHandler dragTransferHandler) { resultsTree.setTransferHandler(dragTransferHandler); resultsTree.setDragEnabled(true); } protected void performSearch() { searchPanel.remove(searchButton); progressBar.setIndeterminate(true); searchPanel.add(progressBar, BorderLayout.PAGE_END); searchPanel.revalidate(); new Thread() { @Override public void run() { ArrayList<ArbilNode> resultsArray = new ArrayList<ArbilNode>(); EntityData[] searchResults = entityCollection.getEntityByKeyWord(searchField.getText(), graphPanel.getIndexParameters()); resultsArea.setText("Found " + searchResults.length + " entities\n"); for (EntityData entityData : searchResults) { // if (resultsArray.size() < 1000) { resultsArray.add(new KinTreeNode(entityData, graphPanel.getIndexParameters(), dialogHandler, bugCatcher, entityCollection, dataNodeLoader)); // } else { // resultsArea.append("results limited to 1000\n"); // break; } resultsTree.rootNodeChildren = resultsArray.toArray(new KinTreeNode[]{}); resultsTree.requestResort(); searchPanel.remove(progressBar); searchPanel.add(searchButton, BorderLayout.PAGE_END); searchPanel.revalidate(); } }.start(); } }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.ui.ArbilTable; import nl.mpi.kinnate.data.KinTreeNode; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.IndexerParameters; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.svg.GraphPanel; public class EntitySearchPanel extends JPanel { private EntityCollection entityCollection; private KinTree resultsTree; private JTextArea resultsArea = new JTextArea(); private JTextField searchField; IndexerParameters indexParameters; public EntitySearchPanel(EntityCollection entityCollection, GraphPanel graphPanel, ArbilTable arbilTable) { this.entityCollection = entityCollection; this.setLayout(new BorderLayout()); resultsTree = new KinTree(graphPanel); resultsTree.setCustomPreviewTable(arbilTable); resultsTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Test Tree"), true)); resultsTree.setRootVisible(false); resultsTree.requestResort(); JLabel searchLabel = new JLabel("Search Entity Names"); searchField = new JTextField(); searchField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { EntitySearchPanel.this.performSearch(); } super.keyReleased(e); } }); JButton searchButton = new JButton("Search"); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EntitySearchPanel.this.performSearch(); } }); JPanel searchPanel = new JPanel(); searchPanel.setLayout(new BorderLayout()); searchPanel.add(searchLabel, BorderLayout.PAGE_START); searchPanel.add(searchField, BorderLayout.CENTER); searchPanel.add(searchButton, BorderLayout.PAGE_END); this.add(searchPanel, BorderLayout.PAGE_START); this.add(new JScrollPane(resultsTree), BorderLayout.CENTER); this.add(resultsArea, BorderLayout.PAGE_END); } public void setTransferHandler(DragTransferHandler dragTransferHandler) { resultsTree.setTransferHandler(dragTransferHandler); } protected void performSearch() { ArrayList<ArbilNode> resultsArray = new ArrayList<ArbilNode>(); EntityData[] searchResults = entityCollection.getEntityByKeyWord(searchField.getText(), indexParameters); resultsArea.setText("Found " + searchResults.length + " entities\n"); for (EntityData entityData : searchResults) { // if (resultsArray.size() < 1000) { resultsArray.add(new KinTreeNode(entityData)); // } else { // resultsArea.append("results limited to 1000\n"); // break; } resultsTree.rootNodeChildren = resultsArray.toArray(new KinTreeNode[]{}); resultsTree.requestResort(); } }
package no.nordicsemi.android.dfu; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.content.Intent; import android.os.Build; import android.os.SystemClock; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import java.util.UUID; import java.util.zip.CRC32; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import no.nordicsemi.android.dfu.internal.ArchiveInputStream; import no.nordicsemi.android.dfu.internal.exception.DeviceDisconnectedException; import no.nordicsemi.android.dfu.internal.exception.DfuException; import no.nordicsemi.android.dfu.internal.exception.RemoteDfuException; import no.nordicsemi.android.dfu.internal.exception.RemoteDfuExtendedErrorException; import no.nordicsemi.android.dfu.internal.exception.UnknownResponseException; import no.nordicsemi.android.dfu.internal.exception.UploadAbortedException; import no.nordicsemi.android.error.SecureDfuError; /* package */ @SuppressWarnings("JavaDoc") class SecureDfuImpl extends BaseCustomDfuImpl { // UUIDs used by the DFU static final UUID DEFAULT_DFU_SERVICE_UUID = new UUID(0x0000FE5900001000L, 0x800000805F9B34FBL); // 16-bit UUID assigned by Bluetooth SIG static final UUID DEFAULT_DFU_CONTROL_POINT_UUID = new UUID(0x8EC90001F3154F60L, 0x9FB8838830DAEA50L); static final UUID DEFAULT_DFU_PACKET_UUID = new UUID(0x8EC90002F3154F60L, 0x9FB8838830DAEA50L); static UUID DFU_SERVICE_UUID = DEFAULT_DFU_SERVICE_UUID; static UUID DFU_CONTROL_POINT_UUID = DEFAULT_DFU_CONTROL_POINT_UUID; static UUID DFU_PACKET_UUID = DEFAULT_DFU_PACKET_UUID; private static final int DFU_STATUS_SUCCESS = 1; private static final int MAX_ATTEMPTS = 3; // Object types private static final int OBJECT_COMMAND = 0x01; private static final int OBJECT_DATA = 0x02; // Operation codes and packets private static final int OP_CODE_CREATE_KEY = 0x01; private static final int OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY = 0x02; private static final int OP_CODE_CALCULATE_CHECKSUM_KEY = 0x03; private static final int OP_CODE_EXECUTE_KEY = 0x04; private static final int OP_CODE_SELECT_OBJECT_KEY = 0x06; private static final int OP_CODE_RESPONSE_CODE_KEY = 0x60; private static final byte[] OP_CODE_CREATE_COMMAND = new byte[]{OP_CODE_CREATE_KEY, OBJECT_COMMAND, 0x00, 0x00, 0x00, 0x00 }; private static final byte[] OP_CODE_CREATE_DATA = new byte[]{OP_CODE_CREATE_KEY, OBJECT_DATA, 0x00, 0x00, 0x00, 0x00}; private static final byte[] OP_CODE_PACKET_RECEIPT_NOTIF_REQ = new byte[]{OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY, 0x00, 0x00 /* param PRN uint16 in Little Endian */}; private static final byte[] OP_CODE_CALCULATE_CHECKSUM = new byte[]{OP_CODE_CALCULATE_CHECKSUM_KEY}; private static final byte[] OP_CODE_EXECUTE = new byte[]{OP_CODE_EXECUTE_KEY}; private static final byte[] OP_CODE_SELECT_OBJECT = new byte[]{OP_CODE_SELECT_OBJECT_KEY, 0x00 /* type */}; private BluetoothGattCharacteristic mControlPointCharacteristic; private BluetoothGattCharacteristic mPacketCharacteristic; private long prepareObjectDelay; private final SecureBluetoothCallback mBluetoothCallback = new SecureBluetoothCallback(); protected class SecureBluetoothCallback extends BaseCustomBluetoothCallback { @Override public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { if (characteristic.getValue() == null || characteristic.getValue().length < 3) { loge("Empty response: " + parse(characteristic)); mError = DfuBaseService.ERROR_INVALID_RESPONSE; notifyLock(); return; } final int responseType = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0); // The first byte should always be the response code if (responseType == OP_CODE_RESPONSE_CODE_KEY) { final int requestType = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1); //noinspection SwitchStatementWithTooFewBranches switch (requestType) { case OP_CODE_CALCULATE_CHECKSUM_KEY: { final int offset = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3); final int remoteCrc = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 3 + 4); final int localCrc = (int) (((ArchiveInputStream) mFirmwareStream).getCrc32() & 0xFFFFFFFFL); // Check whether local and remote CRC match if (localCrc == remoteCrc) { // If so, update the number of bytes received mProgressInfo.setBytesReceived(offset); } else { // Else, and only in case it was a PRN received, not the response for // Calculate Checksum Request, stop sending data if (mFirmwareUploadInProgress) { mFirmwareUploadInProgress = false; notifyLock(); return; } // else will be handled by sendFirmware(gatt) below } handlePacketReceiptNotification(gatt, characteristic); break; } default: { /* * If the DFU target device is in invalid state (e.g. the Init Packet is * required but has not been selected), the target will send * DFU_STATUS_INVALID_STATE error for each firmware packet that was send. * We are interested may ignore all but the first one. */ if (mRemoteErrorOccurred) break; final int status = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 2); if (status != DFU_STATUS_SUCCESS) mRemoteErrorOccurred = true; handleNotification(gatt, characteristic); break; } } } else { loge("Invalid response: " + parse(characteristic)); mError = DfuBaseService.ERROR_INVALID_RESPONSE; } notifyLock(); } } SecureDfuImpl(@NonNull final Intent intent, @NonNull final DfuBaseService service) { super(intent, service); } @Override public boolean isClientCompatible(@NonNull final Intent intent, @NonNull final BluetoothGatt gatt) { final BluetoothGattService dfuService = gatt.getService(DFU_SERVICE_UUID); if (dfuService == null) return false; final BluetoothGattCharacteristic characteristic = dfuService.getCharacteristic(DFU_CONTROL_POINT_UUID); if (characteristic == null || characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG) == null) return false; mControlPointCharacteristic = characteristic; mPacketCharacteristic = dfuService.getCharacteristic(DFU_PACKET_UUID); return mPacketCharacteristic != null; } @Override public boolean initialize(@NonNull final Intent intent, @NonNull final BluetoothGatt gatt, @FileType final int fileType, @NonNull final InputStream firmwareStream, @Nullable final InputStream initPacketStream) throws DfuException, DeviceDisconnectedException, UploadAbortedException { if (initPacketStream == null) { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, "The Init packet is required by this version DFU Bootloader"); mService.terminateConnection(gatt, DfuBaseService.ERROR_INIT_PACKET_REQUIRED); return false; } return super.initialize(intent, gatt, fileType, firmwareStream, initPacketStream); } @Override public BaseBluetoothGattCallback getGattCallback() { return mBluetoothCallback; } @Override protected UUID getControlPointCharacteristicUUID() { return DFU_CONTROL_POINT_UUID; } @Override protected UUID getPacketCharacteristicUUID() { return DFU_PACKET_UUID; } @Override protected UUID getDfuServiceUUID() { return DFU_SERVICE_UUID; } @Override public void performDfu(@NonNull final Intent intent) throws DfuException, DeviceDisconnectedException, UploadAbortedException { logw("Secure DFU bootloader found"); mProgressInfo.setProgress(DfuBaseService.PROGRESS_STARTING); // Add one second delay to avoid the traffic jam before the DFU mode is enabled // Related: mService.waitFor(1000); // End final BluetoothGatt gatt = mGatt; // Secure DFU since SDK 15 supports higher MTUs. // Let's request the MTU requested by the user. It may be that a lower MTU will be used. if (intent.hasExtra(DfuBaseService.EXTRA_MTU) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { final int requiredMtu = intent.getIntExtra(DfuBaseService.EXTRA_MTU, 517); logi("Requesting MTU = " + requiredMtu); requestMtu(requiredMtu); } prepareObjectDelay = intent.getLongExtra(DfuBaseService.EXTRA_DATA_OBJECT_DELAY, 0); try { // Enable notifications enableCCCD(mControlPointCharacteristic, NOTIFICATIONS); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Notifications enabled"); // Wait a second here before going further // Related: mService.waitFor(1000); // End final boolean allowResume = !intent.hasExtra(DfuBaseService.EXTRA_DISABLE_RESUME) || !intent.getBooleanExtra(DfuBaseService.EXTRA_DISABLE_RESUME, false); if (!allowResume) logi("Resume feature disabled. Performing fresh DFU"); try { sendInitPacket(gatt, allowResume); } catch (final RemoteDfuException e) { // If the SD+BL upload failed, we may still be able to upload the App. // The SD+BL might have been updated before. if (!mProgressInfo.isLastPart()) { mRemoteErrorOccurred = false; logw("Sending SD+BL failed. Trying to send App only"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "Invalid system components. Trying to send application"); mFileType = DfuBaseService.TYPE_APPLICATION; // Set new content type in the ZIP Input Stream and update sizes of images final ArchiveInputStream zhis = (ArchiveInputStream) mFirmwareStream; zhis.setContentType(mFileType); final byte[] applicationInit = zhis.getApplicationInit(); mInitPacketStream = new ByteArrayInputStream(applicationInit); mInitPacketSizeInBytes = applicationInit.length; mImageSizeInBytes = zhis.applicationImageSize(); mProgressInfo.init(mImageSizeInBytes, 2, 2); sendInitPacket(gatt, false); } else { // There's noting we could do about it. throw e; } } sendFirmware(gatt); // The device will reset so we don't have to send Disconnect signal. mProgressInfo.setProgress(DfuBaseService.PROGRESS_DISCONNECTING); mService.waitUntilDisconnected(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_INFO, "Disconnected by the remote device"); // We are ready with DFU, the device is disconnected, let's close it and finalize the operation. finalize(intent, false); } catch (@SuppressWarnings("CaughtExceptionImmediatelyRethrown") final UploadAbortedException e) { // In secure DFU there is currently not possible to reset the device to application mode, so... do nothing // The connection will be terminated in the DfuBaseService throw e; } catch (final UnknownResponseException e) { final int error = DfuBaseService.ERROR_INVALID_RESPONSE; loge(e.getMessage()); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, e.getMessage()); mService.terminateConnection(gatt, error); } catch (final RemoteDfuException e) { final int error = DfuBaseService.ERROR_REMOTE_TYPE_SECURE | e.getErrorNumber(); loge(e.getMessage() + ": " + SecureDfuError.parse(error)); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, String.format(Locale.US, "Remote DFU error: %s", SecureDfuError.parse(error))); // For the Extended Error more details can be obtained on some devices. if (e instanceof RemoteDfuExtendedErrorException) { final RemoteDfuExtendedErrorException ee = (RemoteDfuExtendedErrorException) e; final int extendedError = DfuBaseService.ERROR_REMOTE_TYPE_SECURE_EXTENDED | ee.getExtendedErrorNumber(); loge("Extended Error details: " + SecureDfuError.parseExtendedError(extendedError)); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, "Details: " + SecureDfuError.parseExtendedError(extendedError) + " (Code = " + ee.getExtendedErrorNumber() + ")"); mService.terminateConnection(gatt, extendedError | DfuBaseService.ERROR_REMOTE_MASK); } else { mService.terminateConnection(gatt, error | DfuBaseService.ERROR_REMOTE_MASK); } } } /** * This method does the following: * <ol> * <li>Selects the Command object - this Op Code returns the maximum acceptable size of a * command object, and the offset and CRC32 of the command that is already stored in the * device (in case the DFU was started in a previous connection and disconnected before * it has finished).</li> * <li>If the offset received is greater than 0 and less or equal to the size of the * Init file that is to be sent, it will compare the * received CRC with the local one and, if they match: * <ul> * <li>If offset < init file size - it will continue sending the Init file from the * point it stopped before,</li> * <li>If offset == init file size - it will send Execute command to execute the * Init file, as it may have not been executed before.</li> * </ul> * </li> * <li>If the CRC don't match, or the received offset is greater then init file size, * it creates the Command Object and sends the whole Init file as the previous one was * different.</li> * </ol> * Sending of the Init packet is done without using PRNs (Packet Receipt Notifications), * so they are disabled prior to sending the data. * * @param gatt the target GATT device. * @param allowResume true to allow resuming sending Init Packet. If false, it will be started * again. * @throws RemoteDfuException * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException * @throws UnknownResponseException */ private void sendInitPacket(@NonNull final BluetoothGatt gatt, final boolean allowResume) throws RemoteDfuException, DeviceDisconnectedException, DfuException, UploadAbortedException, UnknownResponseException { final CRC32 crc32 = new CRC32(); // Used to calculate CRC32 of the Init packet ObjectChecksum checksum; // First, select the Command Object. As a response the maximum command size and information whether there is already // a command saved from a previous connection is returned. logi("Setting object to Command (Op Code = 6, Type = 1)"); final ObjectInfo info = selectObject(OBJECT_COMMAND); logi(String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); //noinspection StatementWithEmptyBody if (mInitPacketSizeInBytes > info.maxSize) { // Ignore this here. Later, after sending the 'Create object' command, DFU target will send an error if init packet is too large } // Can we resume? If the offset obtained from the device is greater then zero we can compare it with the local init packet CRC // and resume sending the init packet, or even skip sending it if the whole file was sent before. boolean skipSendingInitPacket = false; boolean resumeSendingInitPacket = false; if (allowResume && info.offset > 0 && info.offset <= mInitPacketSizeInBytes) { try { // Read the same number of bytes from the current init packet to calculate local CRC32 final byte[] buffer = new byte[info.offset]; mInitPacketStream.read(buffer); // Calculate the CRC32 crc32.update(buffer); final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL); if (info.CRC32 == crc) { logi("Init packet CRC is the same"); if (info.offset == mInitPacketSizeInBytes) { // The whole init packet was sent and it is equal to one we try to send now. // There is no need to send it again. We may try to resume sending data. logi("-> Whole Init packet was sent before"); skipSendingInitPacket = true; mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Received CRC match Init packet"); } else { logi("-> " + info.offset + " bytes of Init packet were sent before"); resumeSendingInitPacket = true; mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Resuming sending Init packet..."); } } else { // A different Init packet was sent before, or the error occurred while sending. // We have to send the whole Init packet again. mInitPacketStream.reset(); crc32.reset(); info.offset = 0; } } catch (final IOException e) { loge("Error while reading " + info.offset + " bytes from the init packet stream", e); try { // Go back to the beginning of the stream, we will send the whole init packet mInitPacketStream.reset(); crc32.reset(); info.offset = 0; } catch (final IOException e1) { loge("Error while resetting the init packet stream", e1); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } } if (!skipSendingInitPacket) { // The Init packet is sent different way in this implementation than the firmware, and receiving PRNs is not implemented. // This value might have been stored on the device, so we have to explicitly disable PRNs. setPacketReceiptNotifications(0); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Packet Receipt Notif disabled (Op Code = 2, Value = 0)"); for (int attempt = 1; attempt <= MAX_ATTEMPTS;) { if (!resumeSendingInitPacket) { // Create the Init object logi("Creating Init packet object (Op Code = 1, Type = 1, Size = " + mInitPacketSizeInBytes + ")"); writeCreateRequest(OBJECT_COMMAND, mInitPacketSizeInBytes); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object created"); } // Write Init data to the Packet Characteristic try { logi("Sending " + (mInitPacketSizeInBytes - info.offset) + " bytes of init packet..."); writeInitData(mPacketCharacteristic, crc32); } catch (final DeviceDisconnectedException e) { loge("Disconnected while sending init packet"); throw e; } final int crc = (int) (crc32.getValue() & 0xFFFFFFFFL); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Command object sent (CRC = %08X)", crc)); // Calculate Checksum logi("Sending Calculate Checksum command (Op Code = 3)"); checksum = readChecksum(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); logi(String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); if (crc == checksum.CRC32) { // Everything is OK, we can proceed break; } else { if (attempt < MAX_ATTEMPTS) { attempt++; logi("CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, "CRC does not match! Retrying...(" + attempt + "/" + MAX_ATTEMPTS + ")"); try { // Go back to the beginning, we will send the whole Init packet again resumeSendingInitPacket = false; info.offset = 0; info.CRC32 = 0; mInitPacketStream.reset(); crc32.reset(); } catch (final IOException e) { loge("Error while resetting the init packet stream", e); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } else { loge("CRC does not match!"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, "CRC does not match!"); mService.terminateConnection(gatt, DfuBaseService.ERROR_CRC_ERROR); return; } } } } // Execute Init packet. It's better to execute it twice than not execute at all... logi("Executing init packet (Op Code = 4)"); writeExecute(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Command object executed"); } /** * This method does the following: * <ol> * <li>Sets the Packet Receipt Notification to a value specified in the settings.</li> * <li>Selects the Data object - this returns maximum single object size and the offset * and CRC of the data already saved.</li> * <li>If the offset received is greater than 0 it will calculate the CRC of the same * number of bytes of the firmware to be sent. If the CRC match it will continue sending data. * Otherwise, it will go back to the beginning of the last chunk, or to the beginning * of the previous chunk assuming the last one was not executed before, and continue * sending data from there.</li> * <li>If the CRC and offset received match and the offset is equal to the firmware size, * it will only send the Execute command.</li> * </ol> * @param gatt the target GATT device. * @throws RemoteDfuException * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException * @throws UnknownResponseException */ private void sendFirmware(final BluetoothGatt gatt) throws RemoteDfuException, DeviceDisconnectedException, DfuException, UploadAbortedException, UnknownResponseException { // Send the number of packets of firmware before receiving a receipt notification int numberOfPacketsBeforeNotification = mPacketsBeforeNotification; if (numberOfPacketsBeforeNotification > 0) { setPacketReceiptNotifications(numberOfPacketsBeforeNotification); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Packet Receipt Notif Req (Op Code = 2) sent (Value = " + numberOfPacketsBeforeNotification + ")"); } // We are ready to start sending the new firmware. logi("Setting object to Data (Op Code = 6, Type = 2)"); final ObjectInfo info = selectObject(OBJECT_DATA); logi(String.format(Locale.US, "Data object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Data object info received (Max size = %d, Offset = %d, CRC = %08X)", info.maxSize, info.offset, info.CRC32)); mProgressInfo.setMaxObjectSizeInBytes(info.maxSize); // Number of chunks in which the data will be sent final int chunkCount = (mImageSizeInBytes + info.maxSize - 1) / info.maxSize; int currentChunk = 0; boolean resumeSendingData = false; // Can we resume? If the offset obtained from the device is greater then zero we can compare it with the local CRC // and resume sending the data. if (info.offset > 0) { try { currentChunk = info.offset / info.maxSize; int bytesSentAndExecuted = info.maxSize * currentChunk; int bytesSentNotExecuted = info.offset - bytesSentAndExecuted; // If the offset is dividable by maxSize, assume that the last page was not executed if (bytesSentNotExecuted == 0) { bytesSentAndExecuted -= info.maxSize; bytesSentNotExecuted = info.maxSize; } // Read the same number of bytes from the current init packet to calculate local CRC32 if (bytesSentAndExecuted > 0) { mFirmwareStream.read(new byte[bytesSentAndExecuted]); // Read executed bytes mFirmwareStream.mark(info.maxSize); // Mark here } // Here the bytesSentNotExecuted is for sure greater then 0 mFirmwareStream.read(new byte[bytesSentNotExecuted]); // Read the rest // Calculate the CRC32 final int crc = (int) (((ArchiveInputStream) mFirmwareStream).getCrc32() & 0xFFFFFFFFL); if (crc == info.CRC32) { logi(info.offset + " bytes of data sent before, CRC match"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, info.offset + " bytes of data sent before, CRC match"); mProgressInfo.setBytesSent(info.offset); mProgressInfo.setBytesReceived(info.offset); // If the whole page was sent and CRC match, we have to make sure it was executed if (bytesSentNotExecuted == info.maxSize && info.offset < mImageSizeInBytes) { logi("Executing data object (Op Code = 4)"); try { writeExecute(); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object executed"); } catch (final RemoteDfuException e) { // In DFU bootloader from SDK 15.x, 16 and 17 there's a bug, which // prevents executing an object that has already been executed. if (e.getErrorNumber() != SecureDfuError.OPERATION_NOT_PERMITTED) { throw e; } mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object already executed"); } } else { resumeSendingData = true; } } else { logi(info.offset + " bytes sent before, CRC does not match"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, info.offset + " bytes sent before, CRC does not match"); // The CRC of the current object is not correct. If there was another Data object sent before, its CRC must have been correct, // as it has been executed. Either way, we have to create the current object again. mProgressInfo.setBytesSent(bytesSentAndExecuted); mProgressInfo.setBytesReceived(bytesSentAndExecuted); info.offset -= bytesSentNotExecuted; info.CRC32 = 0; // invalidate mFirmwareStream.reset(); logi("Resuming from byte " + info.offset + "..."); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Resuming from byte " + info.offset + "..."); } } catch (final IOException e) { loge("Error while reading firmware stream", e); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } else { // Initialize the timer used to calculate the transfer speed mProgressInfo.setBytesSent(0); } final long startTime = SystemClock.elapsedRealtime(); if (info.offset < mImageSizeInBytes) { int attempt = 1; // Each page will be sent in MAX_ATTEMPTS while (mProgressInfo.getAvailableObjectSizeIsBytes() > 0) { if (!resumeSendingData) { // Create the Data object final int availableObjectSizeInBytes = mProgressInfo.getAvailableObjectSizeIsBytes(); logi("Creating Data object (Op Code = 1, Type = 2, Size = " + availableObjectSizeInBytes + ") (" + (currentChunk + 1) + "/" + chunkCount + ")"); writeCreateRequest(OBJECT_DATA, availableObjectSizeInBytes); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object (" + (currentChunk + 1) + "/" + chunkCount + ") created"); // Waiting until the device is ready to receive the data object. // If prepare data object delay was set in the initiator, the delay will be used // for all data objects. if (prepareObjectDelay > 0 || chunkCount == 0) { mService.waitFor(prepareObjectDelay > 0 ? prepareObjectDelay : 400); } mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Uploading firmware..."); } else { mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Resuming uploading firmware..."); resumeSendingData = false; } // Send the current object part try { logi("Uploading firmware..."); uploadFirmwareImage(mPacketCharacteristic); } catch (final DeviceDisconnectedException e) { loge("Disconnected while sending data"); throw e; } // Calculate Checksum logi("Sending Calculate Checksum command (Op Code = 3)"); final ObjectChecksum checksum = readChecksum(); logi(String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, String.format(Locale.US, "Checksum received (Offset = %d, CRC = %08X)", checksum.offset, checksum.CRC32)); // It may happen, that not all bytes that were sent were received by the remote device final int bytesLost = mProgressInfo.getBytesSent() - checksum.offset; if (bytesLost > 0) { logw(bytesLost + " bytes were lost!"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, bytesLost + " bytes were lost"); try { // We have to reset the stream and read 'offset' number of bytes to recalculate the CRC mFirmwareStream.reset(); // Resets to the beginning of current object mFirmwareStream.read(new byte[info.maxSize - bytesLost]); // Reads additional bytes that were sent and received in this object mProgressInfo.setBytesSent(checksum.offset); } catch (final IOException e) { loge("Error while reading firmware stream", e); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } // To decrease the chance of loosing data next time let's set PRN to 1. // This will make the update very long, but perhaps it will succeed. final int newPrn = 1; if (mPacketsBeforeNotification == 0 || mPacketsBeforeNotification > newPrn) { numberOfPacketsBeforeNotification = mPacketsBeforeNotification = newPrn; setPacketReceiptNotifications(numberOfPacketsBeforeNotification); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Packet Receipt Notif Req (Op Code = 2) sent (Value = " + newPrn + ")"); } } // Calculate the CRC32 final int crc = (int) (((ArchiveInputStream) mFirmwareStream).getCrc32() & 0xFFFFFFFFL); if (crc == checksum.CRC32) { if (bytesLost > 0) { resumeSendingData = true; continue; } // Execute Init packet logi("Executing data object (Op Code = 4)"); writeExecute(mProgressInfo.isComplete()); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object executed"); // Increment iterator currentChunk++; attempt = 1; //Mark this location after completion of successful transfer. In the event of a CRC retry on the next packet we will restart from this point. mFirmwareStream.mark(0); } else { String crcFailMessage = String.format(Locale.US, "CRC does not match! Expected %08X but found %08X.", crc, checksum.CRC32); if (attempt < MAX_ATTEMPTS) { attempt++; crcFailMessage += String.format(Locale.US, " Retrying...(%d/%d)", attempt, MAX_ATTEMPTS); logi(crcFailMessage); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, crcFailMessage); try { // Reset the CRC and file pointer back to the previous mark() point after completion of the last successful packet. mFirmwareStream.reset(); mProgressInfo.setBytesSent(((ArchiveInputStream) mFirmwareStream).getBytesRead()); } catch (final IOException e) { loge("Error while resetting the firmware stream", e); mService.terminateConnection(gatt, DfuBaseService.ERROR_FILE_IO_EXCEPTION); return; } } else { loge(crcFailMessage); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_ERROR, crcFailMessage); mService.terminateConnection(gatt, DfuBaseService.ERROR_CRC_ERROR); return; } } } } else { // Looks as if the whole file was sent correctly but has not been executed logi("Executing data object (Op Code = 4)"); writeExecute(true); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Data object executed"); } final long endTime = SystemClock.elapsedRealtime(); logi("Transfer of " + (mProgressInfo.getBytesSent() - info.offset) + " bytes has taken " + (endTime - startTime) + " ms"); mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_APPLICATION, "Upload completed in " + (endTime - startTime) + " ms"); } /** * Checks whether the response received is valid and returns the status code. * * @param response the response received from the DFU device. * @param request the expected Op Code * @return the status code * @throws UnknownResponseException if response was not valid */ private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException { if (response == null || response.length < 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request || (response[2] != DFU_STATUS_SUCCESS && response[2] != SecureDfuError.OP_CODE_NOT_SUPPORTED && response[2] != SecureDfuError.INVALID_PARAM && response[2] != SecureDfuError.INSUFFICIENT_RESOURCES && response[2] != SecureDfuError.INVALID_OBJECT && response[2] != SecureDfuError.UNSUPPORTED_TYPE && response[2] != SecureDfuError.OPERATION_NOT_PERMITTED && response[2] != SecureDfuError.OPERATION_FAILED && response[2] != SecureDfuError.EXTENDED_ERROR)) throw new UnknownResponseException("Invalid response received", response, OP_CODE_RESPONSE_CODE_KEY, request); return response[2]; } /** * Sets number of data packets that will be send before the notification will be received. * * @param data control point data packet * @param value number of packets before receiving notification. If this value is 0, then the * notification of packet receipt will be disabled by the DFU target. */ private void setNumberOfPackets(@SuppressWarnings("SameParameterValue") @NonNull final byte[] data, final int value) { data[1] = (byte) (value & 0xFF); data[2] = (byte) ((value >> 8) & 0xFF); } /** * Sets the object size in correct position of the data array. * * @param data control point data packet * @param value Object size in bytes. */ private void setObjectSize(@NonNull final byte[] data, final int value) { data[2] = (byte) (value & 0xFF); data[3] = (byte) ((value >> 8) & 0xFF); data[4] = (byte) ((value >> 16) & 0xFF); data[5] = (byte) ((value >> 24) & 0xFF); } /** * Sets the number of packets that needs to be sent to receive the Packet Receipt Notification. * Value 0 disables PRNs. By default this is disabled. The PRNs may be used to send both the * Data and Command object, but this Secure DFU implementation can handle them only during Data transfer. * <p> * The intention of having PRNs is to make sure the outgoing BLE buffer is not getting overflown. * The PRN will be sent after sending all packets from the queue. * * @param number number of packets required before receiving a Packet Receipt Notification. * @throws DfuException * @throws DeviceDisconnectedException * @throws UploadAbortedException * @throws UnknownResponseException * @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS} */ private void setPacketReceiptNotifications(final int number) throws DfuException, DeviceDisconnectedException, UploadAbortedException, UnknownResponseException, RemoteDfuException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); // Send the number of packets of firmware before receiving a receipt notification logi("Sending the number of packets before notifications (Op Code = 2, Value = " + number + ")"); setNumberOfPackets(OP_CODE_PACKET_RECEIPT_NOTIF_REQ, number); writeOpCode(mControlPointCharacteristic, OP_CODE_PACKET_RECEIPT_NOTIF_REQ); // Read response final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Sending the number of packets failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Sending the number of packets failed", status); } /** * Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the * {@link android.bluetooth.BluetoothGattCallback#onCharacteristicWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)} * will be called or the device gets disconnected. * If connection state will change, or an error will occur, an exception will be thrown. * * @param characteristic the characteristic to write to. Should be the DFU CONTROL POINT. * @param value the value to write to the characteristic. * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private void writeOpCode(@NonNull final BluetoothGattCharacteristic characteristic, @NonNull final byte[] value) throws DeviceDisconnectedException, DfuException, UploadAbortedException { writeOpCode(characteristic, value, false); } /** * Writes Create Object request providing the type and size of the object. * * @param type {@link #OBJECT_COMMAND} or {@link #OBJECT_DATA}. * @param size size of the object or current part of the object. * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException * @throws RemoteDfuException thrown when the returned status code is not equal to {@link #DFU_STATUS_SUCCESS} * @throws UnknownResponseException */ private void writeCreateRequest(final int type, final int size) throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException, UnknownResponseException { if (!mConnected) throw new DeviceDisconnectedException("Unable to create object: device disconnected"); final byte[] data = (type == OBJECT_COMMAND) ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA; setObjectSize(data, size); writeOpCode(mControlPointCharacteristic, data); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_CREATE_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Creating Command object failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Creating Command object failed", status); } /** * Selects the current object and reads its metadata. The object info contains the max object * size, and the offset and CRC32 of the whole object until now. * * @return object info. * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException * @throws RemoteDfuException thrown when the returned status code is not equal to * {@link #DFU_STATUS_SUCCESS}. */ private ObjectInfo selectObject(final int type) throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException, UnknownResponseException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read object info: device disconnected"); OP_CODE_SELECT_OBJECT[1] = (byte) type; writeOpCode(mControlPointCharacteristic, OP_CODE_SELECT_OBJECT); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_SELECT_OBJECT_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Selecting object failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Selecting object failed", status); final ObjectInfo info = new ObjectInfo(); info.maxSize = unsignedBytesToInt(response, 3); info.offset = unsignedBytesToInt(response, 3 + 4); info.CRC32 = unsignedBytesToInt(response, 3 + 8); return info; } /** * Sends the Calculate Checksum request. As a response a notification will be sent with current * offset and CRC32 of the current object. * * @return requested object info. * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException * @throws RemoteDfuException thrown when the returned status code is not equal to * {@link #DFU_STATUS_SUCCESS}. */ private ObjectChecksum readChecksum() throws DeviceDisconnectedException, DfuException, UploadAbortedException, RemoteDfuException, UnknownResponseException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_CALCULATE_CHECKSUM); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_CALCULATE_CHECKSUM_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Receiving Checksum failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Receiving Checksum failed", status); final ObjectChecksum checksum = new ObjectChecksum(); checksum.offset = unsignedBytesToInt(response, 3); checksum.CRC32 = unsignedBytesToInt(response, 3 + 4); return checksum; } private int unsignedBytesToInt(@NonNull final byte[] array, final int offset) { return (array[offset] & 0xFF) + ((array[offset + 1] & 0xFF) << 8) + ((array[offset + 2] & 0xFF) << 16) + ((array[offset + 3] & 0xFF) << 24); } /** * Sends the Execute operation code and awaits for a return notification containing status code. * The Execute command will confirm the last chunk of data or the last command that was sent. * Creating the same object again, instead of executing it allows to retransmitting it in case * of a CRC error. * * @throws DfuException * @throws DeviceDisconnectedException * @throws UploadAbortedException * @throws UnknownResponseException * @throws RemoteDfuException thrown when the returned status code is not equal to * {@link #DFU_STATUS_SUCCESS}. */ private void writeExecute() throws DfuException, DeviceDisconnectedException, UploadAbortedException, UnknownResponseException, RemoteDfuException { if (!mConnected) throw new DeviceDisconnectedException("Unable to read Checksum: device disconnected"); writeOpCode(mControlPointCharacteristic, OP_CODE_EXECUTE); final byte[] response = readNotificationResponse(); final int status = getStatusCode(response, OP_CODE_EXECUTE_KEY); if (status == SecureDfuError.EXTENDED_ERROR) throw new RemoteDfuExtendedErrorException("Executing object failed", response[3]); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Executing object failed", status); } private void writeExecute(final boolean allowRetry) throws DfuException, DeviceDisconnectedException, UploadAbortedException, UnknownResponseException, RemoteDfuException { try { writeExecute(); } catch (final RemoteDfuException e) { if (allowRetry && e.getErrorNumber() == SecureDfuError.INVALID_OBJECT) { logw(e.getMessage() + ": " + SecureDfuError.parse(DfuBaseService.ERROR_REMOTE_TYPE_SECURE | SecureDfuError.INVALID_OBJECT)); if (mFileType == DfuBaseService.TYPE_SOFT_DEVICE) { logw("Are you sure your new SoftDevice is API compatible with the updated one? If not, update the bootloader as well"); // API compatible = both SoftDevices have the same Major version } mService.sendLogBroadcast(DfuBaseService.LOG_LEVEL_WARNING, String.format(Locale.US, "Remote DFU error: %s. SD busy? Retrying...", SecureDfuError.parse(DfuBaseService.ERROR_REMOTE_TYPE_SECURE | SecureDfuError.INVALID_OBJECT))); logi("SD busy? Retrying..."); logi("Executing data object (Op Code = 4)"); writeExecute(); } else { throw e; } } } private class ObjectInfo extends ObjectChecksum { int maxSize; } private class ObjectChecksum { int offset; int CRC32; } }
package org.jboss.as.model; import java.io.Serializable; import java.util.Arrays; /** * An identifier for a deployment unit suitable for use as a map key. * * @author Brian Stansberry */ public class DeploymentUnitKey implements Serializable { private static final long serialVersionUID = 8171593872559737006L; private final String name; private final byte[] sha1Hash; private final int hashCode; /** * Creates a new DeploymentUnitKey * * @param name the deployment's name * @param sha1Hash an sha1 hash of the deployment content */ public DeploymentUnitKey(String name, byte[] sha1Hash) { if (name == null) { throw new IllegalArgumentException("name is null"); } if (sha1Hash == null) { throw new IllegalArgumentException("sha1Hash is null"); } this.name = name; this.sha1Hash = sha1Hash; // We assume a hashcode will be wanted, so calculate and cache int result = 17; result += 31 * name.hashCode(); result += 31 * Arrays.hashCode(sha1Hash); this.hashCode = result; } /** * Gets the name of the deployment. * * @return the name */ public String getName() { return name; } /** * Gets a defensive copy of the sha1 hash of the deployment. * * @return the hash */ public byte[] getSha1Hash() { return sha1Hash.clone(); } /** * Gets the sha1 hash of the deployment as a hex string. * * @return the hash */ public String getSha1HashAsHexString() { return AbstractModelElement.bytesToHexString(sha1Hash); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj instanceof DeploymentUnitKey) { DeploymentUnitKey other = (DeploymentUnitKey) obj; return name.equals(other.name) && Arrays.equals(sha1Hash, sha1Hash); } return false; } @Override public int hashCode() { return hashCode; } /** * Computes a hash of the name and sha1 hash. Exposed as a convenience * since {@link #getSha1Hash()} returns a defensive copy of the byte[]. * * @return a hash of the name and the sha1 hash */ long elementHash() { return name.hashCode() & 0xffffffffL ^ AbstractModelElement.calculateElementHashOf(sha1Hash); } }
package logica; import java.util.ArrayList; public class Cancion { private String nombre; private int duracion; private ArrayList<String> letra; private int numeroLineaActual; private String Imagen; public Cancion() { } public Cancion(String nombre, int duracion, ArrayList<String> letra, int numeroLineaActual, String imagen) { super(); this.nombre = nombre; this.duracion = duracion; this.letra = letra; this.numeroLineaActual = numeroLineaActual; Imagen = imagen; } public int getDuracion() { return duracion; } public void setDuracion(int duracion) { this.duracion = duracion; } public ArrayList<String> getLetra() { return letra; } public void setLetra(ArrayList<String> letra) { this.letra = letra; } public int getNumeroLineaActual() { return numeroLineaActual; } public void setNumeroLineaActual(int numeroLineaActual) { this.numeroLineaActual = numeroLineaActual; } public String getImagen() { return Imagen; } public void setImagen(String imagen) { Imagen = imagen; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
package jlibs.xml.sax.dog.sniff; import jlibs.core.lang.NotImplementedException; import jlibs.xml.DefaultNamespaceContext; import jlibs.xml.sax.dog.DataType; import jlibs.xml.sax.dog.NodeItem; import jlibs.xml.sax.dog.NodeType; import jlibs.xml.sax.dog.Scope; import jlibs.xml.sax.dog.expr.*; import jlibs.xml.sax.dog.expr.nodset.NodeSet; import jlibs.xml.sax.dog.expr.nodset.NodeSetListener; import jlibs.xml.sax.dog.expr.nodset.PositionTracker; import jlibs.xml.sax.dog.expr.nodset.StringEvaluation; import jlibs.xml.sax.dog.path.EventID; import jlibs.xml.sax.helpers.MyNamespaceSupport; import org.xml.sax.Attributes; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamReader; import java.util.*; /** * @author Santhosh Kumar T */ public final class Event extends EvaluationListener implements NodeSetListener{ private List<Expression> exprList; private EventID.ConstraintEntry listenersArray[][]; @SuppressWarnings({"unchecked"}) public Event(NamespaceContext givenNSContext, List<Expression> exprList, int noOfConstraints, boolean documentRequired){ this.givenNSContext = givenNSContext; this.exprList = exprList; int noOfXPaths = exprList.size(); results = new Object[noOfXPaths]; pendingInstantResults = new int[noOfXPaths]; listeners = new List[noOfXPaths]; instantListenersCount = new int[noOfXPaths]; finished = new BitSet(noOfXPaths); listenersArray = new EventID.ConstraintEntry[6][noOfConstraints]; if(documentRequired) docNodeItem = nodeItem = new NodeItem(); } public NamespaceContext getNamespaceContext(){ return nsContext; } private long order; private int type; private String namespaceURI; private String localName; private String qualifiedName; private String value; public long order(){ return order; } public int type(){ return type; } public String namespaceURI(){ return namespaceURI; } public String localName(){ return localName; } public String qualifiedName(){ return qualifiedName; } public String value(){ if(type==NodeType.TEXT && value==null) value = buff.length()>0 ? buff.toString() : null; return value; } public String language(){ return tailInfo==null ? "" : tailInfo.lang; } private StringBuilder elementLocation = new StringBuilder(); private Info locationInfo; public String location(){ if(type==NodeType.DOCUMENT) return "/"; StringBuilder elementLocation = this.elementLocation; // update elementLocation Info info = locationInfo.next; while(info!=null){ assert info.slash==-1; info.slash = elementLocation.length(); elementLocation.append('/'); elementLocation.append(info.elem).append('[').append(info.elemntPos).append(']'); info = info.next; } locationInfo = tailInfo; int len; switch(type){ case NodeType.ELEMENT: return elementLocation.toString(); case NodeType.ATTRIBUTE: len = elementLocation.length(); elementLocation.append("/@").append(qname(namespaceURI, localName)); break; case NodeType.NAMESPACE: len = elementLocation.length(); elementLocation.append("/namespace::").append(localName); break; case NodeType.TEXT: len = elementLocation.length(); elementLocation.append("/text()[").append(tailInfo.textCount).append(']'); break; case NodeType.COMMENT: len = elementLocation.length(); elementLocation.append("/comment()[").append(tailInfo.commentCount).append(']'); break; case NodeType.PI: len = elementLocation.length(); elementLocation.append("/processing-instruction('").append(localName).append("')[").append(tailInfo.piMap.get(localName).value).append(']'); break; default: throw new NotImplementedException(); } String location = elementLocation.toString(); elementLocation.setLength(len); return location; } @Override public String toString(){ return location(); } private EventID current; public EventID getID(){ if(current==null){ current = new EventID(type, listenersArray); // current.location = location(); } return current; } private boolean interestedInAttributes; private boolean interestedInNamespaces; private boolean interestedInText; private void fireEvent(){ EventID id = current; current = null; EventID firstID = null; EventID activeID = null; boolean interestedInAttributes = false; boolean interestedInNamespaces = false; boolean interestedInText = false; do{ if(!id.onEvent(this)){ if(firstID==null) firstID = id; else activeID.previous = id; activeID = id; interestedInAttributes |= id.interestedInAttributes; interestedInNamespaces |= id.interestedInNamespaces; interestedInText |= id.interestedInText>0; } id = id.previous; }while(id!=null); if(activeID!=null) activeID.previous = null; EventID current = this.current; if(current!=null && current.axisEntryCount!=0){ current.previous = firstID; current.listenersAdded(); interestedInAttributes |= current.interestedInAttributes; interestedInNamespaces |= current.interestedInNamespaces; interestedInText |= current.interestedInText>0; }else this.current = firstID; this.interestedInAttributes = interestedInAttributes; this.interestedInNamespaces = interestedInNamespaces; this.interestedInText = interestedInText; } private void firePush(){ EventID id = current; EventID firstID = null; EventID activeID = null; boolean interestedInAttributes = false; boolean interestedInNamespaces = false; boolean interestedInText = false; do{ if(!id.push()){ if(firstID==null) firstID = id; else activeID.previous = id; activeID = id; interestedInAttributes |= id.interestedInAttributes; interestedInNamespaces |= id.interestedInNamespaces; interestedInText |= id.interestedInText>0; } id = id.previous; }while(id!=null); if(activeID!=null) activeID.previous = null; current = firstID; this.interestedInAttributes = interestedInAttributes; this.interestedInNamespaces = interestedInNamespaces; this.interestedInText = interestedInText; } private void firePop(){ EventID id = current; EventID firstID = null; EventID activeID = null; boolean interestedInAttributes = false; boolean interestedInNamespaces = false; boolean interestedInText = false; boolean doc = tailInfo==null; do{ if(!id.pop(doc)){ if(firstID==null) firstID = id; else activeID.previous = id; activeID = id; interestedInAttributes |= id.interestedInAttributes; interestedInNamespaces |= id.interestedInNamespaces; interestedInText |= id.interestedInText>0; } id = id.previous; }while(id!=null); if(activeID!=null) activeID.previous = null; current = firstID; this.interestedInAttributes = interestedInAttributes; this.interestedInNamespaces = interestedInNamespaces; this.interestedInText = interestedInText; } private NodeItem nodeItem; public NodeItem nodeItem(){ if(nodeItem==null) nodeItem = new NodeItem(this); return nodeItem; } private XMLBuilder xmlBuilder = null; private NodeItem docNodeItem; public NodeItem documentNodeItem(){ return docNodeItem; } public void setXMLBuilder(XMLBuilder xmlBuilder){ this.xmlBuilder = xmlBuilder; } @SuppressWarnings({"SimplifiableIfStatement"}) private boolean isXMLRequired(){ if(xmlBuilder==null) return false; else if(xmlBuilder.active) return true; else return xmlBuilder.active = nodeItem!=null; } private void notifyXMLBuilder(){ if(xmlBuilder==null) return; else if(!xmlBuilder.active && nodeItem==null) return; Object xml = xmlBuilder.onEvent(this); if(nodeItem!=null){ nodeItem.xml = xml; nodeItem.xmlBuilt = true; finishedXMLBuild(nodeItem); } } @Override public void mayHit(){ nodeItem.refCount++; } @Override public void discard(long order){ xmlBuilder.discard(order); } @Override public void finished(){} private final Object results[]; private final int pendingInstantResults[]; private final BitSet finished; private int pendingExpressions; public static final RuntimeException STOP_PARSING = new RuntimeException("STOP_PARSING"); private boolean stopped; @Override public void finished(Evaluation evaluation){ assert evaluation.expression.scope()==Scope.DOCUMENT; assert hasInstantListener(evaluation.expression) ? evaluation.getResult()==null : evaluation.getResult()!=null; assert pendingExpressions>0; int id = evaluation.expression.id; assert results[id]==null || results[id]==evaluation; // null for StaticEvaluation // store result if this doc expression is used in some predicate boolean needEvaluation = false; finished.set(id); List<EvaluationListener> listeners = this.listeners[id]; if(listeners!=null){ boolean hasPendingInstantResults = pendingInstantResults[id]!=0; boolean clearListeners = true; for(EvaluationListener listener: listeners){ if(!listener.disposed){ if(listener instanceof InstantEvaluationListener && hasPendingInstantResults){ clearListeners = false; continue; } listener.finished(evaluation); } } if(clearListeners) this.listeners[id] = null; else needEvaluation = true; } if(!needEvaluation) results[id] = evaluation.expression.storeResult ? evaluation.getResult() : null; if(--pendingExpressions==0 && tailInfo!=null){ tailInfo = null; if(xmlBuilder==null) throw STOP_PARSING; stopped = true; } } public static final Object DUMMY_VALUE = new Object(); public void onInstantResult(Expression expression, NodeItem nodeItem){ BitSet bitSet = nodeItem.expressions; if(bitSet==null){ nodeItem.expressions = bitSet = new BitSet(); bitSet.set(expression.id); }else if(bitSet.get(expression.id)) return; else bitSet.set(expression.id); if(xmlBuilder==null || nodeItem.xmlBuilt) fireInstantResult(expression, nodeItem); else pendingInstantResults[expression.id]++; } private void fireInstantResult(Expression expression, NodeItem nodeItem){ if(expression.getXPath()==null) // non-user given absolute xpath return; List<EvaluationListener> listeners = this.listeners[expression.id]; for(EvaluationListener listener: listeners){ if(!listener.disposed && listener instanceof InstantEvaluationListener) ((InstantEvaluationListener)listener).onNodeHit(expression, nodeItem); } } public void finishedXMLBuild(NodeItem nodeItem){ nodeItem.xmlBuilt = true; BitSet bitSet = nodeItem.expressions; if(bitSet==null) return; int i=0; while(true){ i = bitSet.nextSetBit(i); if(i==-1) return; fireInstantResult(exprList.get(i), nodeItem); pendingInstantResults[i] if(finished.get(i) && pendingInstantResults[i]==0){ List<EvaluationListener> listeners = this.listeners[i]; if(listeners!=null){ this.listeners[i] = null; for(EvaluationListener listener: listeners){ if(!listener.disposed && listener instanceof InstantEvaluationListener) listener.finished((Evaluation)results[i]); } results[i] = null; } } i++; } } private EvaluationListener listener; public void setListener(EvaluationListener listener){ if(this.listener!=null) throw new IllegalStateException("EvaluationListener can be set only once"); this.listener = listener; for(Expression expr: exprList) addListener(expr, this.listener); } public EvaluationListener getListener(){ return listener; } private final List<EvaluationListener> listeners[]; private final int instantListenersCount[]; public Evaluation addListener(Expression expr, EvaluationListener evaluationListener){ assert expr.scope()==Scope.DOCUMENT; int id = expr.id; List<EvaluationListener> listeners = this.listeners[id]; if(listeners==null) this.listeners[id] = listeners=new ArrayList<EvaluationListener>(); listeners.add(evaluationListener); if(supportsInstantResults(expr) && evaluationListener instanceof InstantEvaluationListener) instantListenersCount[id]++; Object value = results[id]; if(value instanceof Evaluation) return (Evaluation)value; else{ if(value==null) return null; else throw new IllegalStateException(); } } public void removeListener(Expression expr, EvaluationListener evaluationListener){ List<EvaluationListener> listeners = this.listeners[expr.id]; if(listeners!=null){ if(listeners.remove(evaluationListener)){ if(supportsInstantResults(expr) && evaluationListener instanceof InstantEvaluationListener) instantListenersCount[expr.id] } }else evaluationListener.disposed = true; } private boolean supportsInstantResults(Expression expr){ return expr instanceof NodeSet; } public boolean hasInstantListener(Expression expr){ return supportsInstantResults(expr) && instantListenersCount[expr.id]>0; } public Object result(Expression expr){ assert expr.scope()==Scope.DOCUMENT; return results[expr.id]; } void setData(int type, String namespaceURI, String localName, String qualifiedName, String value){ nodeItem = null; this.type = type; this.namespaceURI = namespaceURI; this.localName = localName; this.qualifiedName = qualifiedName; this.value = value; } private void onEvent(int type, String namespaceURI, String localName, String qualifiedName, String value){ nodeItem = null; order++; this.type = type; this.namespaceURI = namespaceURI; this.localName = localName; this.qualifiedName = qualifiedName; this.value = value; if(!stopped && type!=NodeType.ELEMENT) fireEvent(); } public void onStartDocument(){ int noOfXPaths = exprList.size(); pendingExpressions = noOfXPaths; nsContext = new DefaultNamespaceContext(); locationInfo = tailInfo = new Info(); tailInfo.lang = ""; tailInfo.slash = 0; order = 0L; type = NodeType.DOCUMENT; value = namespaceURI = localName = qualifiedName = ""; Object results[] = this.results; for(int i=noOfXPaths-1; i>=0; i Expression expression = exprList.get(i); Object result = expression.getResult(this); if(result instanceof Evaluation){ results[i] = result; Evaluation eval = (Evaluation)result; eval.addListener(this); if(xmlBuilder!=null && expression.resultType==DataType.NODESET && eval instanceof NodeSetListener.Support) ((Support)eval).setNodeSetListener(this); eval.start(); }else{ Evaluation eval; if(expression.resultType==DataType.NODESET && hasInstantListener(expression)){ onInstantResult(expression, nodeItem); results[i] = eval = new StaticEvaluation<Expression>(expression, order, null); }else eval = new StaticEvaluation<Expression>(expression, order, result); finished(eval); } } current.listenersAdded(); firePush(); if(isXMLRequired()) nodeItem.xml = xmlBuilder.doStartDocument(nodeItem); else if(stopped) throw STOP_PARSING; } public void onEndDocument(){ if(!stopped) pop(); assert pendingExpressions==0; assert tailInfo==null; if(xmlBuilder!=null) xmlBuilder.doEndDocument(this); } public void onStartElement(String uri, String localName, String qualifiedName, String lang){ onEvent(NodeType.ELEMENT, uri, localName, qualifiedName, null); if(!stopped){ Info info = new Info(); info.elem = qname(uri, localName); info.elemntPos = tailInfo.updateElementPosition(info.elem); info.lang = lang!=null ? lang : language(); push(info); fireEvent(); } if(!stopped) firePush(); if(isXMLRequired()){ Object xml = xmlBuilder.doStartElement(this, nodeItem); if(nodeItem!=null) nodeItem.xml = xml; }else if(stopped) throw STOP_PARSING; } public void onEndElement(){ if(!stopped) pop(); if(xmlBuilder!=null && xmlBuilder.active){ if(xmlBuilder.doEndElement(this)==null && stopped) throw STOP_PARSING; } } public void onText(){ if(buff.length()>0){ if(!stopped) tailInfo.textCount++; if(xmlBuilder!=null || interestedInText) onEvent(NodeType.TEXT, "", "", "", null); notifyXMLBuilder(); buff.setLength(0); } } public void onComment(char[] ch, int start, int length){ if(!stopped) tailInfo.commentCount++; onEvent(NodeType.COMMENT, "", "", "", new String(ch, start, length)); notifyXMLBuilder(); } public void onPI(String target, String data){ if(!stopped) tailInfo.updatePIPosition(target); onEvent(NodeType.PI, "", target, target, data); notifyXMLBuilder(); } public void onAttributes(Attributes attrs){ if(interestedInAttributes){ int len = attrs.getLength(); for(int i=0; i<len; i++){ onEvent(NodeType.ATTRIBUTE, attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getValue(i)); notifyXMLBuilder(); } }else if(xmlBuilder!=null && xmlBuilder.active) xmlBuilder.onAttributes(this, attrs); } public void onAttributes(XMLStreamReader reader){ if(interestedInAttributes){ int len = reader.getAttributeCount(); for(int i=0; i<len; i++){ String prefix = reader.getAttributePrefix(i); String localName = reader.getAttributeLocalName(i); String qname = prefix.length()==0 ? localName : prefix+':'+localName; String uri = reader.getAttributeNamespace(i); if(uri==null) uri = ""; onEvent(NodeType.ATTRIBUTE, uri, localName, qname, reader.getAttributeValue(i)); notifyXMLBuilder(); } }else if(xmlBuilder!=null && xmlBuilder.active) xmlBuilder.onAttributes(this, reader); } public void onNamespaces(MyNamespaceSupport nsSupport){ if(interestedInNamespaces){ Enumeration<String> prefixes = nsSupport.getPrefixes(); while(prefixes.hasMoreElements()){ String prefix = prefixes.nextElement(); String uri = nsSupport.getURI(prefix); onEvent(NodeType.NAMESPACE, "", prefix, prefix, uri); notifyXMLBuilder(); } }else if(xmlBuilder!=null && xmlBuilder.active) xmlBuilder.onNamespaces(this, nsSupport); } private Info tailInfo; private void push(Info info){ info.prev = tailInfo; tailInfo.next = info; tailInfo = info; } private void pop(){ Info curTailInfo = tailInfo; if(curTailInfo.slash!=-1) elementLocation.setLength(curTailInfo.slash); if(locationInfo==curTailInfo) locationInfo = curTailInfo.prev; tailInfo = curTailInfo.prev; if(tailInfo!=null) tailInfo.next = null; firePop(); } static final class IntWrapper{ int value = 1; } static final class Info{ Info prev; Info next; int slash = -1; String elem; String lang; int elemntPos = 1; private static int updatePosition(Map<String, IntWrapper> map, String key){ IntWrapper position = map.get(key); if(position==null){ map.put(key, new IntWrapper()); return 1; }else return ++position.value; } Map<String, IntWrapper> elemMap; public int updateElementPosition(String qname){ if(elemMap==null) elemMap = new HashMap<String, IntWrapper>(); return updatePosition(elemMap, qname); } Map<String, IntWrapper> piMap; public int updatePIPosition(String target){ if(piMap==null) piMap = new HashMap<String, IntWrapper>(); return updatePosition(piMap, target); } int textCount; int commentCount; } private DefaultNamespaceContext nsContext; public final NamespaceContext givenNSContext; private String qname(String uri, String name){ String prefix = nsContext.getPrefix(uri); if(prefix==null){ prefix = givenNSContext.getPrefix(uri); if(prefix!=null) nsContext.declarePrefix(prefix, uri); else prefix = nsContext.declarePrefix(uri); } if(prefix.length()==0) return name; else{ // doing: // return prefix+';'+name; // manually to avoid StringBuilder creation int prefixLen = prefix.length(); int nameLen = name.length(); char ch[] = new char[prefixLen+1+nameLen]; prefix.getChars(0, prefixLen, ch, 0); ch[prefixLen] = ':'; name.getChars(0, name.length(), ch, prefixLen+1); assert new String(ch).equals(prefix+':'+name); return new String(ch); } } public final StringBuilder buff = new StringBuilder(500); public void appendText(char[] ch, int start, int length){ if(xmlBuilder!=null || interestedInText) buff.append(ch, start, length); else if(buff.length()==0) buff.append('x'); } public Evaluation evaluation; public Object evaluate(Expression expr){ evaluation = null; switch(expr.scope()){ case Scope.GLOBAL: return expr.getResult(); case Scope.DOCUMENT: Object value = results[expr.id]; return value instanceof Evaluation ? null : value; default: assert expr.scope()==Scope.LOCAL; Object result = expr.getResult(this); assert result!=null; if(result instanceof Evaluation){ evaluation = (Evaluation)result; return null; }else return result; } } public ArrayDeque<PositionTracker> positionTrackerStack = new ArrayDeque<PositionTracker>(); public StringEvaluation stringEvaluation; }
package org.neo4j.server; import java.io.File; import org.apache.log4j.BasicConfigurator; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.logging.Logger; import org.neo4j.server.startup.healthcheck.ConfigFileMustBePresentRule; import org.neo4j.server.startup.healthcheck.StartupHealthCheck; import org.neo4j.server.web.Jetty6WebServer; public class BootStrapper { public static final Logger log = Logger.getLogger(BootStrapper.class); public static final Integer OK = 0; public static final Integer WEB_SERVER_STARTUP_ERROR_CODE = 1; public static final Integer GRAPH_DATABASE_STARTUP_ERROR_CODE = 2; private NeoServer server; public void controlEvent(int arg) { // Do nothing, required by the WrapperListener interface } public Integer start() { return start(null); } public Integer start(String[] args) { try { StartupHealthCheck startupHealthCheck = new StartupHealthCheck(new ConfigFileMustBePresentRule()); Jetty6WebServer webServer = new Jetty6WebServer(); server = new NeoServer(new AddressResolver(), startupHealthCheck, getConfigFile(), webServer); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { log.info("Neo4j Server shutdown initiated by kill signal"); if (server != null) { server.stop(); } } }); return OK; } catch (TransactionFailureException tfe) { tfe.printStackTrace(); log.error( String.format( "Failed to start Neo Server on port [%d], because ", server.restApiUri().getPort() ) + tfe + ". Another process may be using database location " + server.getDatabase().getLocation() ); return GRAPH_DATABASE_STARTUP_ERROR_CODE; } catch (Exception e) { e.printStackTrace(); log.error("Failed to start Neo Server on port [%s]", server.getWebServerPort()); return WEB_SERVER_STARTUP_ERROR_CODE; } } public void stop() { stop(0); } public int stop(int stopArg) { String location = "unknown location"; try { log.info("Successfully shutdown Neo Server on port [%d], database [%s]", server.getWebServerPort(), location); return 0; } catch (Exception e) { log.error("Failed to cleanly shutdown Neo Server on port [%d], database [%s]. Reason [%s] ", server.getWebServerPort(), location, e.getMessage()); return 1; } } public NeoServer getServer() { return server; } protected static File getConfigFile() { return new File(System.getProperty(Configurator.NEO_SERVER_CONFIG_FILE_KEY, Configurator.DEFAULT_CONFIG_DIR)); } public static void main(String[] args) { BasicConfigurator.configure(); BootStrapper bootstrapper = new BootStrapper(); bootstrapper.start(args); } }
package com.xxl.rpc.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import java.util.regex.Pattern; /** * get ip * * @author xuxueli 2016-5-22 11:38:05 */ public class IpUtil { private static final Logger logger = LoggerFactory.getLogger(IpUtil.class); private static final String ANYHOST = "0.0.0.0"; private static final String LOCALHOST = "127.0.0.1"; public static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); private static volatile String LOCAL_ADDRESS = null; /** * valid address * @param address * @return boolean */ private static boolean isValidAddress(InetAddress address) { if (address == null || address.isLoopbackAddress() || address.isLinkLocalAddress()) { return false; } String name = address.getHostAddress(); return (name != null && ! ANYHOST.equals(name) && ! LOCALHOST.equals(name) && IP_PATTERN.matcher(name).matches()); } /** * get first valid addredd * * @return InetAddress */ private static InetAddress getFirstValidAddress() { // NetworkInterface address try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces != null) { while (interfaces.hasMoreElements()) { try { NetworkInterface network = interfaces.nextElement(); Enumeration<InetAddress> addresses = network.getInetAddresses(); if (addresses != null) { while (addresses.hasMoreElements()) { try { InetAddress address = addresses.nextElement(); if (isValidAddress(address)) { return address; } } catch (Throwable e) { logger.error("Failed to retriving ip address, " + e.getMessage(), e); } } } } catch (Throwable e) { logger.error("Failed to retriving ip address, " + e.getMessage(), e); } } } } catch (Throwable e) { logger.error("Failed to retriving ip address, " + e.getMessage(), e); } // getLocalHost address try { InetAddress localAddress = InetAddress.getLocalHost(); if (isValidAddress(localAddress)) { return localAddress; } } catch (Throwable e) { logger.error("Failed to retriving ip address, " + e.getMessage(), e); } logger.error("Could not get local host ip address, will use 127.0.0.1 instead."); return null; } /** * get address * * @return String */ private static String getAddress() { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getFirstValidAddress(); LOCAL_ADDRESS = localAddress.getHostAddress(); return LOCAL_ADDRESS; } /** * get ip * * @return String */ public static String getIp(){ return getAddress(); } /** * get ip:port * * @param port * @return String */ public static String getIpPort(int port){ String ip = getIp(); return getIpPort(ip, port); } public static String getIpPort(String ip, int port){ if (ip==null) { return null; } return ip.concat(":").concat(String.valueOf(port)); } public static Object[] parseIpPort(String address){ String[] array = address.split(":"); String host = array[0]; int port = Integer.parseInt(array[1]); return new Object[]{host, port}; } }
import java.util.ArrayList; public class Em08HashTable<K,V> { public Em08HashTable(int input_size){ this.size = nextPrime(input_size); System.out.println(nextPrime(input_size)); table = new Entry[size]; free = size; } public ArrayList<V> search(K searchkey){ // equivalent to contains; if (searchkey == null) throw new NullPointerException(); ArrayList res = new ArrayList<V>(); boolean idontcare = false; for (int i = 0; i < table.length ; i++ ) idontcare = (table[i] != null && searchkey.equals(table[i].getKey())) ? res.add( table[i].getValue()) : false; res.trimToSize(); return res; } // Sucht nen freien Platz in der liste und inserted das element dort public boolean insert(K key, V value){ // equivalent implementation to put(); if(key == null || value == null || free < 1) return false; Entry en = new Entry(key,value); int h1,h2,index,count = 1; h1 = hash1(en); h2 = hash2(en); index = h1; //System.out.println("h: "+h+" table[h]: "+(table[h]==null)); while (table[index] != null){ System.err.println("Index: "+index+" Count: "+count); index = (h1+(count*h2)) % size; count++; //System.out.println("h: "+h+" table[h]: "+table[h]); /*if (count > 5000) { //System.out.println(this); System.exit(1); }*/ } table[index] = en; free return true; } /** * @return String of the Table */ public String toString(){ String res = ""; for (Entry i : table) { if (i == null) res += "Key: null\t" + "\t" + "Value: null\n"; else res += "Key: " + i.getKey() + "\t" + "\t" + "Value: " + i.getValue() + "\n"; } return res; } /** * @return JSON strings in form of KEY:VALUE */ public String toJSON(){ String res = "["; for (Entry i : table) { if (i != null) res +="{\'" +i.getKey() + "\': \'" + i.getValue() + "\'},\n"; } res += "]"; return res; } /** * @return hash value of the Entry obj */ private int hash1(Entry<K,V> e){ return Math.abs(e.getKey().hashCode() % size); } /** * @return hash value of the Entry obj */ private int hash2(Entry<K,V> e){ return Math.abs(1 + e.getKey().hashCode() % (size -2)); } /** * @return next greater prime than start */ private int nextPrime(int start){ if (isPrime(start)) return start; int count = start; boolean prime = false; while(!prime && count < Integer.MAX_VALUE){ count++; prime = isPrime(count); } return count; } /** * @return if primenumber true otherwise false */ private static boolean isPrime(int i){ int factors = 0; int j = 1; while(j <= i) { if(i % j == 0) { factors++; } j++; } return (factors == 2); } public int getSize(){ return size; } public int getFree(){ return free; } /** * Fields * @link Hashtable */ private int free; private int size; /** * Entry array */ private Entry[] table; private static class Entry<K,V> { public Entry(K k, V v, int h, Entry<K,V> n){ key = k; value = v; hash = h; next = n; } public Entry(K k, V v){ this(k,v,0,null); } public int hashCode(){ if (key == null || value == null) throw new NullPointerException(); return key.hashCode() + value.hashCode(); } public K getKey(){ return key; } public V getValue(){ return value; } public V setValue(V value){ if (value == null) throw new NullPointerException(); V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o){ if (!(o instanceof Entry)) return false; Entry e = (Entry)o; return (e.getKey() == null ? false : (e.getKey() == this.key)) && (e.getValue() == null ? false : (e.getValue() == this.value)); } K key; V value; int hash; Entry<K,V> next; } }
package org.drools.server; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.drools.Person; import org.drools.RuleBase; import org.drools.StatefulSession; import org.drools.StatelessSession; import org.drools.common.InternalRuleBase; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; public class RuleService extends HttpServlet { static XStream xmlInstance = configureXStream(false); static XStream jsonInstance = configureXStream(true); @Override protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { String uri = request.getRequestURI(); RuleBase rb = getRuleBaseFromURI(uri); //doService(request.getInputStream(), resp.getOutputStream(), rb); //sample(); } void doService(InputStream inputStream, OutputStream outputStream, RuleBase rb, boolean json) { InternalRuleBase irb = (InternalRuleBase) rb; ClassLoader originalCL = Thread.currentThread().getContextClassLoader(); try { ClassLoader cl = irb.getRootClassLoader(); Thread.currentThread().setContextClassLoader(cl); XStream xs = (json) ? jsonInstance : xmlInstance; ServiceRequestMessage req = (ServiceRequestMessage) xs.fromXML(inputStream); StatelessSession session = rb.newStatelessSession(); if (req.globals != null) { for (NamedFact nf : req.globals) { session.setGlobal(nf.id, nf.fact); } } List<Object> facts = new ArrayList<Object>(); if (req.inFacts != null) { for (AnonFact f : req.inFacts) { facts.add(f.fact); } } if (req.inOutFacts != null) { for (NamedFact nf : req.inOutFacts) { facts.add(nf.fact); } } session.execute(facts); ServiceResponseMessage res = new ServiceResponseMessage(); if (req.globals != null) { res.globals = req.globals; } if (req.inOutFacts != null) { res.inOutFacts = req.inOutFacts; } xs.toXML(res, outputStream); } finally { Thread.currentThread().setContextClassLoader(originalCL); } } private RuleBase getRuleBaseFromURI(String uri) { return null; } private void sample() { XStream xs = configureXStream(true); ServiceRequestMessage req = new ServiceRequestMessage(); req.globals = new NamedFact[1]; req.inFacts = new AnonFact[1]; req.inOutFacts = new NamedFact[1]; req.globals[0] = new NamedFact("jo", new Person("Jo", "Chocolote")); //req.inFacts[0] = new AnonFact(new Person("Mike", "beer")); req.inFacts[0] = new AnonFact(new Person("Mike", "wine")); req.inOutFacts[0] = new NamedFact("mark", new Person("Mark", "Cheese")); String requestMessage = xs.toXML(req); ServiceRequestMessage req_ = (ServiceRequestMessage) xs.fromXML(requestMessage); String requestMessage_ = xs.toXML(req_); System.out.println(requestMessage); if (!requestMessage_.equals(requestMessage)) throw new RuntimeException("fail !"); } static XStream configureXStream(boolean json) { if (json) { XStream xs = new XStream(new JettisonMappedXmlDriver()); alias(xs); return xs; } else { XStream xs = new XStream(); alias(xs); return xs; } } private static void alias(XStream xs) { xs.alias("knowledgebase-request", ServiceRequestMessage.class); xs.alias("knowledgebase-response", ServiceResponseMessage.class); xs.alias("named-fact", NamedFact.class); xs.alias("anon-fact", AnonFact.class); } public static void main(String[] args) throws ServletException, IOException { RuleService rs = new RuleService(); rs.sample(); } }
import java.io.*; import java.net.*; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.KeeperException.Code; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; public class ClientDriver { ZkConnector zkc; Watcher watcher; ZooKeeper theZoo = null; static Socket JobServer = null; static ObjectOutputStream out = null; static ObjectInputStream in = null; public static void main(String[] args) throws IOException, ClassNotFoundException { String zooInfo = null; if(args.length == 1 ) { //get config from command line zooInfo = args[0]; } else { System.err.println("ERROR: Invalid arguments!"); System.exit(-1); } // connect to zookeeper to ClientDriver client = new ClientDriver(zooInfo); // get the jobserver String[] jobServerInfo = client.checkpath().split(":"); String jobHost = jobServerInfo[0]; int jobPort = Integer.parseInt(jobServerInfo[1]); // need to get jobserver connection info JobServer = new Socket(jobHost, jobPort); out = new ObjectOutputStream(JobServer.getOutputStream()); in = new ObjectInputStream(JobServer.getInputStream()); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; System.out.print("Enter queries or x for exit:\n"); System.out.print(">"); while ((userInput = stdIn.readLine()) != null && userInput.toLowerCase().indexOf("x") == -1) { /* make a new request packet */ JobTrackerPacket packetToServer = new JobTrackerPacket(); packetToServer.type = JobTrackerPacket.JOB_REQUEST; out.writeObject(packetToServer); /* print server reply */ JobTrackerPacket packetFromServer; packetFromServer = (JobTrackerPacket) in.readObject(); if (packetFromServer.type == JobTrackerPacket.REPLY_REQUEST) { System.out.println("replied to request"); } else if (packetFromServer.type == JobTrackerPacket.REPLY_QUERRY) { System.out.println("replied to querry"); } /* re-print console prompt */ System.out.print(">"); } /* tell server that i'm quitting */ JobTrackerPacket packetToServer = new JobTrackerPacket(); packetToServer.type = JobTrackerPacket.CLIENT_BYE; //packetToServer.message = "Bye!"; out.writeObject(packetToServer); out.close(); in.close(); stdIn.close(); JobServer.close(); } public ClientDriver(String hosts) { zkc = new ZkConnector(); try { zkc.connect(hosts); } catch(Exception e) { System.out.println("Zookeeper connect "+ e.getMessage()); } theZoo = zkc.getZooKeeper(); watcher = new Watcher() { // Anonymous Watcher @Override public void process(WatchedEvent event) { handleEvent(event); } }; } private String checkpath() { String jobServerInfo = null; // first check that the jobtrack node exists Stat stat = zkc.exists("/jobTrack", watcher); if (stat != null) { // znode exist; try { // get the data jobServerInfo = new String(theZoo.getData("/jobTrack", false, stat)); } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return jobServerInfo; } private void handleEvent(WatchedEvent event) { String path = event.getPath(); EventType type = event.getType(); if(path.equalsIgnoreCase("/jobTrack")) { if (type == EventType.NodeDeleted) { System.out.println("/jobTrack" + " deleted! Let's go!"); checkpath(); // try to become the boss } if (type == EventType.NodeCreated) { System.out.println("/jobTrack" + " created!"); try{ Thread.sleep(5000); } catch (Exception e) {} checkpath(); // re-enable the watch } } } }
package org.yamcs.xtce; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.stream.XMLStreamException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.ConfigurationException; import org.yamcs.YConfiguration; import org.yamcs.xtce.xml.XtceStaxReader; /** * XTCE XML loader * * @author mu * */ public class XtceLoader implements SpaceSystemLoader { private transient XtceStaxReader xtceReader = null; private transient String xtceFileName; /** * Logger */ transient static Logger log = LoggerFactory.getLogger(XtceLoader.class.getName()); Set<String> excludedContainers; /** * Constructor */ public XtceLoader(String xtceFileName) { this.xtceFileName=xtceFileName; initialize(); } public XtceLoader(YConfiguration config) { if(!config.containsKey("file")) { throw new ConfigurationException("the configuration has to contain the keyword 'file' pointing to the XTCE file to be loaded"); } this.xtceFileName = (String) config.get("file"); if(config.containsKey("excludeTmContainers")) { List<String> ec = config.getList("excludeTmContainers"); excludedContainers = new HashSet<String>(ec); } } /** * Common initialization routine for constructors */ private void initialize() { } @Override public boolean needsUpdate(RandomAccessFile consistencyDateFile) throws IOException, ConfigurationException { String line = null; while ((line = consistencyDateFile.readLine()) != null) { if (line.startsWith("XTCE")) { String version = line.substring(5); return (!version.equals(getVersionFromXTCEFile())); } } log.info("Could not find a line starting with 'XTCE' in the consistency date file"); return true; } private String getVersionFromXTCEFile() throws IOException, ConfigurationException { RandomAccessFile xtceFile = new RandomAccessFile(xtceFileName, "r"); File file = new File(xtceFileName); try { String line; while ((line = xtceFile.readLine()) != null) { if (line.trim().startsWith("<SpaceSystem")) { int nameTagPos = line.indexOf("name=\""); if (nameTagPos == -1) { // Space system name is not defined return null; } String xtceFileVersion = line.substring(nameTagPos + 6, line.indexOf('"', nameTagPos + 6)); return xtceFileVersion + Long.toString(file.lastModified()); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { xtceFile.close(); } return null; } @Override public SpaceSystem load() throws ConfigurationException, DatabaseLoadException { try { xtceReader = new XtceStaxReader(); if(excludedContainers!=null) { xtceReader.setExcludedContainers(excludedContainers); } return xtceReader.readXmlDocument(xtceFileName); } catch (FileNotFoundException e) { throw new ConfigurationException("XTCE file not found: " + xtceFileName); } catch (XMLStreamException e) { throw new DatabaseLoadException("Cannot parse file: '"+xtceFileName+": "+e.toString(), e); } catch (Exception e) { throw new DatabaseLoadException(e); } } @Override public String getConfigName() throws ConfigurationException { String xtceFileVersion = null; try { xtceFileVersion = getVersionFromXTCEFile(); } catch (Exception e) { xtceFileVersion = "unknown"; } return xtceFileVersion; } @Override public void writeConsistencyDate(FileWriter consistencyDateFile) throws IOException { String xtceFileVersion = null; try { xtceFileVersion = getVersionFromXTCEFile(); } catch (ConfigurationException e) { xtceFileVersion = "unknown"; } consistencyDateFile.write("XTCE " + xtceFileVersion + "\n"); } }
package de.tobject.findbugs.reporter; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IOpenable; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.internal.core.CompilationUnit; import org.eclipse.jdt.internal.core.NamedMember; import org.eclipse.jdt.internal.core.SourceType; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Shell; import de.tobject.findbugs.FindbugsPlugin; import de.tobject.findbugs.marker.FindBugsMarker; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.DetectorFactoryCollection; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.PackageMemberAnnotation; import edu.umd.cs.findbugs.SortedBugCollection; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.config.ProjectFilterSettings; import edu.umd.cs.findbugs.config.UserPreferences; /** * Utility methods for converting FindBugs BugInstance objects * into Eclipse markers. * * @author Peter Friese * @author David Hovemeyer */ public abstract class MarkerUtil { /** * Create an Eclipse marker for given BugInstance. * * @param bug the BugInstance * @param project the project */ public static void createMarker(BugInstance bug, IProject project) { String className = null; String packageName = null; if (bug.getPrimaryClass() != null) { className = bug.getPrimaryClass().getClassName(); packageName = bug.getPrimaryClass().getPackageName(); } if (Reporter.DEBUG) { System.out.println("BUG in class: " //$NON-NLS-1$ + packageName + "." //$NON-NLS-1$ + className + ": \n\t" //$NON-NLS-1$ + bug.getMessage() + " / Annotation: " //$NON-NLS-1$ + bug.getAnnotationText() + " / Source Line: " //$NON-NLS-1$ + bug.getPrimarySourceLineAnnotation()); } IResource resource = null; try { resource = getUnderlyingResource(bug, project); } catch (JavaModelException e1) { FindbugsPlugin.getDefault().logException( e1, "Could not find class resource for FindBugs warning"); } if (resource != null) { // default - first class line int startLine = 1; if (bug.getPrimarySourceLineAnnotation() != null) { startLine = bug.getPrimarySourceLineAnnotation().getStartLine(); } int fieldLine = -1; if (startLine <= 0 && bug.getPrimaryField() != null && bug.getPrimaryField().getSourceLines() != null) { fieldLine = bug.getPrimaryField().getSourceLines().getStartLine(); } // Eclipse editor starts with 1, otherwise the marker will not be shown in editor at all if(startLine <= 0 && fieldLine > 0) { startLine = fieldLine; } addMarker(bug, project, resource, startLine); if(startLine != fieldLine && fieldLine > 0){ addMarker(bug, project, resource, startLine); } } else { if (Reporter.DEBUG) { System.out.println("NOT found resource for a BUG in class: " //$NON-NLS-1$ + packageName + "." //$NON-NLS-1$ + className + ": \n\t" //$NON-NLS-1$ + bug.getMessage() + " / Annotation: " //$NON-NLS-1$ + bug.getAnnotationText() + " / Source Line: " //$NON-NLS-1$ + bug.getPrimarySourceLineAnnotation()); } } } private static void addMarker(BugInstance bug, IProject project, IResource resource, int startLine) { if (Reporter.DEBUG) { System.out.println("Creating marker for " //$NON-NLS-1$ + resource.getLocation() + ": line " //$NON-NLS-1$ + startLine + bug.getMessage()); } try { project.getWorkspace().run( new MarkerReporter(bug, resource, startLine), // action null, // scheduling rule (null if there are no scheduling restrictions) 0, // flags (could specify IWorkspace.AVOID_UPDATE) null); // progress monitor (null if progress reporting is not desired) } catch (CoreException e) { e.printStackTrace(); } } final static Pattern fullName = Pattern.compile("^(.+?)(([$+][0-9].*)?)"); /** * Get the underlying resource (Java class) for given BugInstance. * * @param bug the BugInstance * @param project the project * @return the IResource representing the Java class * @throws JavaModelException */ public static IResource getUnderlyingResource(BugInstance bug, IProject project) throws JavaModelException { SourceLineAnnotation primarySourceLineAnnotation = bug.getPrimarySourceLineAnnotation(); PackageMemberAnnotation packageAnnotation = null; String packageName = null; String qualifiedClassName = null; if (primarySourceLineAnnotation == null) { packageAnnotation = bug.getPrimaryClass(); if (packageAnnotation != null) { packageName = packageAnnotation.getPackageName(); qualifiedClassName = packageAnnotation.getClassName(); } } else { packageName = primarySourceLineAnnotation.getPackageName(); qualifiedClassName = primarySourceLineAnnotation.getClassName(); } if (qualifiedClassName == null) { return null; } if (Reporter.DEBUG) { System.out.println("Looking up class: " //$NON-NLS-1$ + packageName + ", " //$NON-NLS-1$ + qualifiedClassName); } Matcher m = fullName.matcher(qualifiedClassName); IType type; String innerName = null; if (m.matches() && m.group(2).length() > 0) { String outerQualifiedClassName = m.group(1).replace('$','.'); innerName = m.group(2).substring(1); type = Reporter.getJavaProject(project).findType(outerQualifiedClassName); // dump(type, 0); /* * code below only points to the first line of inner class * even if this is not a class bug but field bug */ completeInnerClassInfo(qualifiedClassName, innerName, type, bug); } else { type = Reporter.getJavaProject(project).findType(qualifiedClassName.replace('$','.')); } // reassign it as it may be changed for inner classes primarySourceLineAnnotation = bug.getPrimarySourceLineAnnotation(); int startLine; /* * Eclipse can help us find the line number for fields => we trying to add line * info for fields here */ if (primarySourceLineAnnotation != null) { startLine = primarySourceLineAnnotation.getStartLine(); if(startLine <= 0 && bug.getPrimaryField() != null){ completeFieldInfo(qualifiedClassName, innerName, type, bug); } } else { if(bug.getPrimaryField() != null){ completeFieldInfo(qualifiedClassName, innerName, type, bug); } } if (type != null) { return type.getUnderlyingResource(); } return null; } private static void completeFieldInfo(String qualifiedClassName, String innerName, IType type, BugInstance bug) throws JavaModelException { FieldAnnotation field = bug.getPrimaryField(); if (field == null || type == null) { return; } IField ifield = type.getField(field.getFieldName()); if (type instanceof SourceType) { IScanner scanner = initScanner(type); ISourceRange sourceRange = ifield.getSourceRange(); int offset = sourceRange.getOffset(); int lineNbr = scanner.getLineNumber(offset); lineNbr = lineNbr <= 0 ? 1 : lineNbr; String sourceFileStr = ""; //$NON-NLS-1$ IResource res = type.getUnderlyingResource(); if (res != null) { sourceFileStr = res.getRawLocation().toOSString(); } field.setSourceLines( new SourceLineAnnotation( qualifiedClassName, sourceFileStr, lineNbr, lineNbr, 0, 0)); } } /** * @param innerName * @param type * @throws JavaModelException */ public static void completeInnerClassInfo(String qualifiedClassName, String innerName, IType type, BugInstance bug) throws JavaModelException { int lineNbr = findChildSourceLine(type, innerName); // should be always first line, if not found lineNbr = lineNbr <= 0 ? 1 : lineNbr; String sourceFileStr = ""; //$NON-NLS-1$ IResource res = type==null ? null : type.getUnderlyingResource(); if (res != null) { sourceFileStr = res.getRawLocation().toOSString(); } bug.addSourceLine( new SourceLineAnnotation( qualifiedClassName, sourceFileStr, lineNbr, lineNbr, 0, 0)); } /** * @param source * @return start line of given type, or 1 if line could not be found * @throws JavaModelException */ public static int getLineStart(SourceType source) throws JavaModelException { IOpenable op = source.getOpenable(); if (op instanceof CompilationUnit) { IScanner scanner = initScanner(source); ISourceRange range = source.getSourceRange(); return scanner.getLineNumber(range.getOffset()); } // start line of enclosing type return 1; } /** * @param source must be not null * @return may return null, otherwise an initialized scanner which may answer which * source offset index belongs to which source line * @throws JavaModelException */ private static IScanner initScanner(IJavaElement source) throws JavaModelException { IOpenable op = source.getOpenable(); if (op instanceof CompilationUnit) { CompilationUnit cu = (CompilationUnit) op; IScanner scanner = ToolFactory.createScanner(false, false, false, true); scanner.setSource(cu.getContents()); try { while (scanner.getNextToken() != ITerminalSymbols.TokenNameEOF) { // do nothing, just wait for the end of stream } } catch (InvalidInputException e) { FindbugsPlugin.getDefault().logException(e, "Could not init scanner for type: " + source); } return scanner; } return null; } public static int findChildSourceLine(IJavaElement javaElement, String name) throws JavaModelException { if (javaElement == null) { //new Exception("trace: javaElement is null").printStackTrace(); return -1; } char firstChar = name.charAt(0); boolean firstIsDigit = Character.isDigit(firstChar); if (!firstIsDigit) { return findInnerClassSourceLine(javaElement, name); } boolean innerFromMember = firstIsDigit && name.length() > 1 && !Character.isDigit(name.charAt(1)); if(innerFromMember){ return findInnerClassSourceLine(javaElement, name.substring(1)); } try { int innerNumber = Integer.parseInt(name); return findInnerAnonymousClassSourceLine(javaElement, innerNumber); } catch (NumberFormatException e) { FindbugsPlugin.getDefault().logException( e, "Could not find source line information for class member"); } return -1; } /** * @param javaElement * @return */ public static int findInnerAnonymousClassSourceLine(IJavaElement javaElement, int innerNumber) { IOpenable op = javaElement.getOpenable(); if (!(op instanceof CompilationUnit)) { return -1; } CompilationUnit cu = (CompilationUnit) op; IScanner scanner = ToolFactory.createScanner(false, false, false, true); scanner.setSource(cu.getContents()); try { int innerCount = 0; int tokenID = scanner.getNextToken(); while (tokenID != ITerminalSymbols.TokenNameEOF) { if (tokenID != ITerminalSymbols.TokenNamenew) { tokenID = scanner.getNextToken(); continue; } int startClassPos = scanner.getCurrentTokenStartPosition(); tokenID = scanner.getNextToken(); if (tokenID != ITerminalSymbols.TokenNameIdentifier) { continue; } tokenID = scanner.getNextToken(); if (tokenID != ITerminalSymbols.TokenNameLPAREN) { continue; } tokenID = scanner.getNextToken(); if (tokenID != ITerminalSymbols.TokenNameRPAREN) { continue; } tokenID = scanner.getNextToken(); if (tokenID != ITerminalSymbols.TokenNameLBRACE) { continue; } tokenID = scanner.getNextToken(); innerCount++; if (innerCount == innerNumber) { return scanner.getLineNumber(startClassPos); } } } catch (InvalidInputException e) { FindbugsPlugin.getDefault().logException(e, "Error scanning for inner class start line"); } return -1; } private static void dump(IJavaElement javaElement, int indentation) { try { for(int i = 0; i < indentation; i++) System.out.print(" "); System.out.println(javaElement.getElementName() + " " + javaElement.getClass().getName()); if (javaElement instanceof SourceType) { for(int i = 0; i < indentation; i++) System.out.print(" "); System.out.println("--> " + ((NamedMember)javaElement).getFullyQualifiedName('.', false)); } if (javaElement instanceof IParent) for(IJavaElement child : ((IParent) javaElement).getChildren()) dump(child, indentation+1); } catch (Exception e) { e.printStackTrace(); } } /** * @param javaElement * @param name * @param elemName * @return * @throws JavaModelException */ public static int findInnerClassSourceLine(IJavaElement javaElement, String name) throws JavaModelException { String elemName = javaElement.getElementName(); if (name.equals(elemName)) { if (javaElement instanceof SourceType) { SourceType source = (SourceType) javaElement; return getLineStart(source); } } if (javaElement instanceof IParent) { IJavaElement[] children = ((IParent) javaElement).getChildren(); for (int i = 0; i < children.length; i++) { // recursive call int line = findInnerClassSourceLine(children[i], name); if (line > 0) { return line; } } } return -1; } /** * Remove all FindBugs problem markers for given project. * * @param project the project * @throws CoreException */ public static void removeMarkers(IProject project) throws CoreException { // remove any markers added by our builder project.deleteMarkers( FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE); } /** * Given current active bug category set, minimum warning priority, * and previous user classification, return whether or not a warning * (bug instance) should be displayed using a marker. * * @param bugInstance the warning * @param filterSettings project filter settings * @return true if the warning should be displayed, false if not */ public static boolean displayWarning(BugInstance bugInstance, ProjectFilterSettings filterSettings) { // Detector plugins need to be loaded for category filtering to work! DetectorFactoryCollection.instance(); return filterSettings.displayWarning(bugInstance); } /** * Attempt to redisplay FindBugs problem markers for * given project. * * @param project the project * @param shell Shell the progress dialog should be tied to */ public static void redisplayMarkers(final IProject project, Shell shell) { ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(shell); try { progressDialog.run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { // Get user preferences for project, // so we know what to diplay UserPreferences userPrefs = FindbugsPlugin.getUserPreferences(project); // Get the saved bug collection for the project SortedBugCollection bugCollection = FindbugsPlugin.getBugCollection(project, monitor); if (bugCollection != null) { // Remove old markers MarkerUtil.removeMarkers(project); // Display warnings for (Iterator i = bugCollection.iterator(); i.hasNext();) { BugInstance bugInstance = (BugInstance) i.next(); if (displayWarning(bugInstance, userPrefs.getFilterSettings())) { MarkerUtil.createMarker(bugInstance, project); } } } } catch (RuntimeException e) { throw e; } catch (Exception e) { // Multiple checked exception types caught here FindbugsPlugin.getDefault().logException( e, "Error redisplaying FindBugs warning markers"); } } }); } catch (RuntimeException e) { throw e; } catch (Exception e) { // Multiple checked exception types caught here FindbugsPlugin.getDefault().logException( e, "Error redisplaying FindBugs warning markers"); } } /** * Find the BugInstance associated with given FindBugs marker. * * @param marker a FindBugs marker * @return the BugInstance associated with the marker, * or null if we can't find the BugInstance */ public static BugInstance findBugInstanceForMarker(IMarker marker) { IResource resource = marker.getResource(); if (resource == null) { // Also shouldn't happen. FindbugsPlugin.getDefault().logError("No resource for warning marker"); return null; } IProject project = resource.getProject(); if (project == null) { // Also shouldn't happen. FindbugsPlugin.getDefault().logError("No project for warning marker"); return null; } try { String markerType = marker.getType(); //System.out.println("Marker type is " + markerType); if (!markerType.equals(FindBugsMarker.NAME)) { FindbugsPlugin.getDefault().logError("Selected marker is not a FindBugs marker"); return null; } // We have a FindBugs marker. Get the corresponding BugInstance. String uniqueId = marker.getAttribute(FindBugsMarker.UNIQUE_ID, null); if (uniqueId == null) { FindbugsPlugin.getDefault().logError("Marker does not contain unique id for warning"); return null; } BugCollection bugCollection = FindbugsPlugin.getBugCollection(project, null); if (bugCollection == null) { FindbugsPlugin.getDefault().logError("Could not get BugCollection for FindBugs marker"); return null; } BugInstance bug = bugCollection.findBug( (String) marker.getAttribute(FindBugsMarker.UNIQUE_ID), (String) marker.getAttribute(FindBugsMarker.BUG_TYPE), (Integer)marker.getAttribute(IMarker.LINE_NUMBER)); return bug; } catch (RuntimeException e) { throw e; } catch (Exception e) { // Multiple exception types caught here FindbugsPlugin.getDefault().logException(e, "Could not get BugInstance for FindBugs marker"); return null; } } /** * Return the marker for given warning. * * @param project the project in which the warning was reported * @param warning the warning * @return the marker, or null if no marker is displayed for this warning * (or we can't find the marker for some reason) */ public IMarker findMarkerForWarning(IProject project, BugInstance warning) { String warningUID = warning.getInstanceHash(); if (warningUID == null) { FindbugsPlugin.getDefault().logError("Bug instance has no unique id"); return null; } try { IResource resource = getUnderlyingResource(warning, project); IMarker[] markerList = resource.findMarkers(FindBugsMarker.NAME, false, IResource.DEPTH_INFINITE); for (int i = 0; i < markerList.length; ++i) { IMarker marker = markerList[i]; String markerUID = marker.getAttribute(FindBugsMarker.UNIQUE_ID, ""); if (warningUID.equals(markerUID)) return marker; } return null; } catch (JavaModelException e) { FindbugsPlugin.getDefault().logException(e, "Could not get marker for BugInstance"); return null; } catch (CoreException e) { FindbugsPlugin.getDefault().logException(e, "Could not get marker for BugInstance"); return null; } } /** * Fish an IMarker out of given selection. * * @param selection the selection * @return the selected IMarker, or null if we can't find an IMarker * in the selection */ public static IMarker getMarkerFromSelection(ISelection selection) { if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; for (Iterator i = structuredSelection.iterator(); i.hasNext(); ) { Object selectedObj = i.next(); //System.out.println("\tSelection element: " + selectedObj.getClass().getName()); if (selectedObj instanceof IMarker) { System.out.println("Selection element is an IMarker!"); return (IMarker) selectedObj; } } } return null; } }
package io.yawp.repository; import io.yawp.commons.http.RequestContext; import io.yawp.commons.utils.JsonUtils; import io.yawp.commons.utils.ReflectionUtils; import io.yawp.repository.query.QueryBuilder; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; public class Feature { protected Repository yawp; protected RequestContext requestContext; public void setRepository(Repository yawp) { this.yawp = yawp; this.requestContext = yawp.getRequestContext(); } public <T> QueryBuilder<T> yawp(Class<T> clazz) { return yawp.query(clazz); } public <T> QueryBuilder<T> yawpWithHooks(Class<T> clazz) { return yawp.queryWithHooks(clazz); } public boolean isOnRequest() { return requestContext != null; } public <T extends Feature> T feature(Class<T> clazz) { try { T feature = clazz.newInstance(); feature.setRepository(yawp); return feature; } catch (Exception e) { throw new RuntimeException(e); } } public <T> IdRef<T> id(Class<T> clazz, Long id) { return IdRef.create(yawp, clazz, id); } public <T> IdRef<T> id(Class<T> clazz, String name) { return IdRef.create(yawp, clazz, name); } public <T> T from(String json, Class<T> clazz) { return JsonUtils.from(yawp, json, clazz); } public <T> List<T> fromList(String json, Class<T> clazz) { return JsonUtils.fromList(yawp, json, clazz); } public <K, V> Map<K, V> fromMap(String json, Class<K> keyClazz, Class<V> valueClazz) { return JsonUtils.fromMap(yawp, json, keyClazz, valueClazz); } public String to(Object object) { return JsonUtils.to(object); } protected Map<String, Object> asMap(Object object) { try { Map<String, Object> map = new HashMap<>(); List<Field> fields = ReflectionUtils.getFieldsRecursively(object.getClass()); for (Field field : fields) { field.setAccessible(true); map.put(field.getName(), field.get(object)); } return map; } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
package com.jme3.network.base; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import com.jme3.network.*; import com.jme3.network.kernel.*; import com.jme3.network.message.ClientRegistrationMessage; //hopefully temporary import com.jme3.network.message.DisconnectMessage; //hopefully temporary import com.jme3.network.serializing.Serializer; /** * A default implementation of the Server interface that delegates * its network connectivity to kernel.Kernel. * * @version $Revision$ * @author Paul Speed */ public class DefaultServer implements Server { static Logger log = Logger.getLogger(DefaultServer.class.getName()); private boolean isRunning = false; private AtomicInteger nextId = new AtomicInteger(0); private String gameName; private int version; private Kernel reliable; private KernelAdapter reliableAdapter; private Kernel fast; private KernelAdapter fastAdapter; private Redispatch dispatcher = new Redispatch(); private Map<Integer,HostedConnection> connections = new ConcurrentHashMap<Integer,HostedConnection>(); private Map<Endpoint,HostedConnection> endpointConnections = new ConcurrentHashMap<Endpoint,HostedConnection>(); // Keeps track of clients for whom we've only received the UDP // registration message private Map<Long,Connection> connecting = new ConcurrentHashMap<Long,Connection>(); private MessageListenerRegistry<HostedConnection> messageListeners = new MessageListenerRegistry<HostedConnection>(); private List<ConnectionListener> connectionListeners = new CopyOnWriteArrayList<ConnectionListener>(); public DefaultServer( String gameName, int version, Kernel reliable, Kernel fast ) { if( reliable == null ) throw new IllegalArgumentException( "Default server reqiures a reliable kernel instance." ); this.gameName = gameName; this.version = version; this.reliable = reliable; this.fast = fast; reliableAdapter = new KernelAdapter( this, reliable, dispatcher, true ); if( fast != null ) { fastAdapter = new KernelAdapter( this, fast, dispatcher, false ); } } public String getGameName() { return gameName; } public int getVersion() { return version; } public void start() { if( isRunning ) throw new IllegalStateException( "Server is already started." ); // Initialize the kernels reliable.initialize(); if( fast != null ) { fast.initialize(); } // Start em up reliableAdapter.start(); if( fastAdapter != null ) { fastAdapter.start(); } isRunning = true; } public boolean isRunning() { return isRunning; } public void close() { if( !isRunning ) throw new IllegalStateException( "Server is not started." ); try { // Kill the adpaters, they will kill the kernels if( fastAdapter != null ) { fastAdapter.close(); } reliableAdapter.close(); isRunning = false; } catch( InterruptedException e ) { throw new RuntimeException( "Interrupted while closing", e ); } } public void broadcast( Message message ) { broadcast( null, message ); } public void broadcast( Filter<? super HostedConnection> filter, Message message ) { ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); FilterAdapter adapter = filter == null ? null : new FilterAdapter(filter); // Ignore the filter for the moment if( message.isReliable() || fast == null ) { // Don't need to copy the data because message protocol is already // giving us a fresh buffer reliable.broadcast( adapter, buffer, true, false ); } else { fast.broadcast( adapter, buffer, false, false ); } } public HostedConnection getConnection( int id ) { return connections.get(id); } public Collection<HostedConnection> getConnections() { return Collections.unmodifiableCollection((Collection<HostedConnection>)connections.values()); } public void addConnectionListener( ConnectionListener listener ) { connectionListeners.add(listener); } public void removeConnectionListener( ConnectionListener listener ) { connectionListeners.remove(listener); } public void addMessageListener( MessageListener<? super HostedConnection> listener ) { messageListeners.addMessageListener( listener ); } public void addMessageListener( MessageListener<? super HostedConnection> listener, Class... classes ) { messageListeners.addMessageListener( listener, classes ); } public void removeMessageListener( MessageListener<? super HostedConnection> listener ) { messageListeners.removeMessageListener( listener ); } public void removeMessageListener( MessageListener<? super HostedConnection> listener, Class... classes ) { messageListeners.removeMessageListener( listener, classes ); } protected void dispatch( HostedConnection source, Message m ) { if( source == null ) { messageListeners.messageReceived( source, m ); } else { // A semi-heavy handed way to make sure the listener // doesn't get called at the same time from two different // threads for the same hosted connection. synchronized( source ) { messageListeners.messageReceived( source, m ); } } } protected void fireConnectionAdded( HostedConnection conn ) { for( ConnectionListener l : connectionListeners ) { l.connectionAdded( this, conn ); } } protected void fireConnectionRemoved( HostedConnection conn ) { for( ConnectionListener l : connectionListeners ) { l.connectionRemoved( this, conn ); } } protected void registerClient( KernelAdapter ka, Endpoint p, ClientRegistrationMessage m ) { Connection addedConnection = null; Connection bootedConnection = null; // generally this will only be called by one thread but it's // important enough I won't take chances synchronized( this ) { // Grab the random ID that the client created when creating // its two registration messages long tempId = m.getId(); // See if we already have one Connection c = connecting.remove(tempId); if( c == null ) { c = new Connection(); log.log( Level.FINE, "Registering client for endpoint, pass 1:{0}.", p ); } else { log.log( Level.FINE, "Refining client registration for endpoint:{0}.", p ); } // Fill in what we now know if( ka == fastAdapter ) { c.fast = p; if( c.reliable == null ) { // Tuck it away for later connecting.put(tempId, c); } } else { // It must be the reliable one c.reliable = p; // Validate the name and version which is only sent // over the reliable connection at this point. if( !getGameName().equals(m.getGameName()) || getVersion() != m.getVersion() ) { log.log( Level.INFO, "Kicking client due to name/version mismatch:{0}.", c ); // Need to kick them off... I may regret doing this from within // the sync block but the alternative is more code c.close( "Server client mismatch, server:" + getGameName() + " v" + getVersion() + " client:" + m.getGameName() + " v" + m.getVersion() ); return; } if( c.fast == null && fastAdapter != null ) { // Still waiting for the fast connection to // register connecting.put(tempId, c); } } if( !connecting.containsKey(tempId) ) { // Then we are fully connected if( connections.put( c.getId(), c ) == null ) { if( c.fast != null ) { endpointConnections.put( c.fast, c ); } endpointConnections.put( c.reliable, c ); addedConnection = c; } } } // Best to do this outside of the synch block to avoid // over synchronizing which is the path to deadlocks if( addedConnection != null ) { log.log( Level.INFO, "Client registered:{0}.", addedConnection ); // Send the ID back to the client letting it know it's // fully connected. m = new ClientRegistrationMessage(); m.setId( addedConnection.getId() ); m.setReliable(true); addedConnection.send(m); // Now we can notify the listeners about the // new connection. fireConnectionAdded( addedConnection ); } } protected HostedConnection getConnection( Endpoint endpoint ) { return endpointConnections.get(endpoint); } protected void connectionClosed( Endpoint p ) { log.log( Level.INFO, "Connection closed:{0}.", p ); // Try to find the endpoint in all ways that it might // exist. Note: by this point the channel is closed // already. // Also note: this method will be called twice per // HostedConnection if it has two endpoints. Connection removed = null; synchronized( this ) { // Just in case the endpoint was still connecting connecting.values().remove(p); // And the regular management removed = (Connection)endpointConnections.remove(p); if( removed != null ) { connections.remove( removed.getId() ); } } // Better not to fire events while we hold a lock // so always do this outside the synch block. if( removed != null ) { log.log( Level.INFO, "Client closed:{0}.", removed ); removed.closeConnection(); } } protected class Connection implements HostedConnection { private int id; private Endpoint reliable; private Endpoint fast; private boolean closed; private Map<String,Object> sessionData = new ConcurrentHashMap<String,Object>(); public Connection() { id = nextId.getAndIncrement(); } public Server getServer() { return DefaultServer.this; } public int getId() { return id; } public String getAddress() { return reliable == null ? null : reliable.getAddress(); } public void send( Message message ) { ByteBuffer buffer = MessageProtocol.messageToBuffer(message, null); if( message.isReliable() || fast == null ) { reliable.send( buffer ); } else { fast.send( buffer ); } } protected void closeConnection() { if( closed ) return; closed = true; // Make sure both endpoints are closed. Note: reliable // should always already be closed through all paths that I // can conceive... but it doesn't hurt to be sure. if( reliable != null && reliable.isConnected() ) { reliable.close(); } if( fast != null && fast.isConnected() ) { fast.close(); } fireConnectionRemoved( this ); } public void close( String reason ) { // Send a reason DisconnectMessage m = new DisconnectMessage(); m.setType( DisconnectMessage.KICK ); m.setReason( reason ); m.setReliable( true ); send( m ); // Just close the reliable endpoint // fast will be cleaned up as a side-effect // when closeConnection() is called by the // connectionClosed() endpoint callback. if( reliable != null ) { // Close with flush so we make sure our // message gets out reliable.close(true); } } public Object setAttribute( String name, Object value ) { if( value == null ) return sessionData.remove(name); return sessionData.put(name, value); } @SuppressWarnings("unchecked") public <T> T getAttribute( String name ) { return (T)sessionData.get(name); } public Set<String> attributeNames() { return Collections.unmodifiableSet(sessionData.keySet()); } public String toString() { return "Connection[ id=" + id + ", reliable=" + reliable + ", fast=" + fast + " ]"; } } protected class Redispatch implements MessageListener<HostedConnection> { public void messageReceived( HostedConnection source, Message m ) { dispatch( source, m ); } } protected class FilterAdapter implements Filter<Endpoint> { private Filter<? super HostedConnection> delegate; public FilterAdapter( Filter<? super HostedConnection> delegate ) { this.delegate = delegate; } public boolean apply( Endpoint input ) { HostedConnection conn = getConnection( input ); if( conn == null ) return false; return delegate.apply(conn); } } }
package org.neo4j.ha; import static org.junit.Assert.assertEquals; import static org.neo4j.backup.TestBackupToolEmbedded.BACKUP_PATH; import static org.neo4j.backup.TestBackupToolEmbedded.PATH; import static org.neo4j.backup.TestBackupToolEmbedded.createSomeData; import static org.neo4j.backup.TestBackupToolEmbedded.runBackupToolFromOtherJvmToGetExitCode; import static org.neo4j.helpers.collection.MapUtil.stringMap; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Test; import org.neo4j.backup.OnlineBackupSettings; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.factory.GraphDatabaseSetting; import org.neo4j.graphdb.index.IndexProvider; import org.neo4j.helpers.Service; import org.neo4j.kernel.HighlyAvailableGraphDatabase; import org.neo4j.kernel.KernelExtension; import org.neo4j.kernel.ha.HaSettings; import org.neo4j.kernel.impl.cache.CacheProvider; import org.neo4j.test.DbRepresentation; import org.neo4j.test.ha.LocalhostZooKeeperCluster; public class TestBackupToolHa { private LocalhostZooKeeperCluster zk; private List<GraphDatabaseService> instances; private DbRepresentation representation; public void startCluster( String clusterName ) throws Exception { FileUtils.deleteDirectory( new File( PATH ) ); FileUtils.deleteDirectory( new File( BACKUP_PATH ) ); zk = LocalhostZooKeeperCluster.standardZoo( getClass() ); instances = new ArrayList<GraphDatabaseService>(); for ( int i = 0; i < 3; i++ ) { String storeDir = new File( PATH, "" + i ).getAbsolutePath(); Map<String, String> config = stringMap( HaSettings.server_id.name(), "" + i, HaSettings.server.name(), "localhost:" + (6666+i), HaSettings.coordinators.name(), zk.getConnectionString(), OnlineBackupSettings.online_backup_enabled.name(), GraphDatabaseSetting.TRUE, OnlineBackupSettings.online_backup_port.name(), ""+(4444+i) ); if ( clusterName != null ) config.put( HaSettings.cluster_name.name(), clusterName ); GraphDatabaseService instance = new HighlyAvailableGraphDatabase( storeDir, config, Service.load( IndexProvider.class ), Service.load( KernelExtension.class ), Service.load( CacheProvider.class ) ); instances.add( instance ); } // Really doesn't matter which instance representation = createSomeData( instances.get( 1 ) ); } @After public void after() throws Exception { if(instances != null) { for ( GraphDatabaseService instance : instances ) { instance.shutdown(); } } if(zk != null) { zk.shutdown(); } } @Test public void makeSureBackupCanBePerformedFromClusterWithDefaultName() throws Exception { testBackupFromCluster( null, null ); } @Test public void makeSureBackupCanBePerformedFromClusterWithCustomName() throws Exception { String clusterName = "local.jvm.cluster"; testBackupFromCluster( clusterName, clusterName ); } @Test public void makeSureBackupCannotBePerformedFromNonExistentCluster() throws Exception { String clusterName = "local.jvm.cluster"; startCluster( clusterName ); assertEquals( 1, runBackupToolFromOtherJvmToGetExitCode( backupArguments( true, "ha://localhost:2181", BACKUP_PATH, null ) ) ); } private void testBackupFromCluster( String clusterName, String askForCluster ) throws Exception { startCluster( clusterName ); assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( backupArguments( true, "ha://localhost:2181", BACKUP_PATH, clusterName ) ) ); assertEquals( representation, DbRepresentation.of( BACKUP_PATH ) ); DbRepresentation newRepresentation = createSomeData( instances.get( 2 ) ); assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( backupArguments( false, "ha://localhost:2182", BACKUP_PATH, clusterName ) ) ); assertEquals( newRepresentation, DbRepresentation.of( BACKUP_PATH ) ); } private String[] backupArguments( boolean trueForFull, String from, String to, String clusterName ) { List<String> args = new ArrayList<String>(); args.add( trueForFull ? "-full" : "-incremental" ); args.add( "-from" ); args.add( from ); args.add( "-to" ); args.add( to ); if ( clusterName != null ) { args.add( "-cluster" ); args.add( clusterName ); } return args.toArray( new String[args.size()] ); } }
package pl.gda.pg.student.project.server; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import com.esotericsoftware.kryonet.Server; import pl.gda.pg.student.project.kryonetcommon.ConnectionSettings; import pl.gda.pg.student.project.libgdxcommon.Assets; import pl.gda.pg.student.project.libgdxcommon.StateManager; import pl.gda.pg.student.project.libgdxcommon.exception.GameException; import pl.gda.pg.student.project.libgdxcommon.objects.GameObject; import pl.gda.pg.student.project.libgdxcommon.objects.MovableGameObject; import pl.gda.pg.student.project.packets.creating.CreateObjectPacket; import pl.gda.pg.student.project.packets.movement.ObjectMoveDownPacket; import pl.gda.pg.student.project.packets.movement.ObjectMoveLeftPacket; import pl.gda.pg.student.project.packets.movement.ObjectMoveRightPacket; import pl.gda.pg.student.project.packets.movement.ObjectMoveUpPacket; import pl.gda.pg.student.project.packets.movement.ObjectSetPositionPacket; import pl.gda.pg.student.project.server.helpers.PlayerPositioner; import pl.gda.pg.student.project.server.objects.ObjectsIdentifier; import pl.gda.pg.student.project.server.objects.ServerPlayer; import pl.gda.pg.student.project.server.states.ServerPlayState; import java.io.IOException; import java.util.Map; public class GameServer extends ApplicationAdapter { private PlayerPositioner positioner = new PlayerPositioner(); private SpriteBatch batch; public static Assets assets; private StateManager states; private Server server; private ServerPlayState gameState; @Override public void create() { server = initializeServer(); assets = new Assets(); batch = new SpriteBatch(); states = new StateManager(); gameState = new ServerPlayState(); states.push(gameState); } private Server initializeServer() { Server server = new Server(); server.addListener(new ServerListener()); server.start(); tryBindingServer(server, ConnectionSettings.TCP_PORT, ConnectionSettings.UDP_PORT); return server; } private void tryBindingServer(Server server, int tcpPort, int udpPort) { try { server.bind(tcpPort, udpPort); } catch (IOException e) { throw new CannotBindServerException(e.getMessage()); } } @Override public void render() { update(); Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); states.render(batch); batch.end(); } private void update() { states.update(); } @Override public void dispose() { assets.dispose(); } private void userConnected(int clientId) { sendGameStateInfo(clientId); Vector2 playerPosition = positioner.getPosition(); informOthersAboutNewPlayer(clientId, playerPosition); sendPositionUpdateInfoToNewClient(clientId, playerPosition); } private void sendGameStateInfo(int clientId) { Map<Long, GameObject> gameObjects = gameState.getGameObjects(); for(GameObject object : gameObjects.values()) sendObjectCreationInfo(object, clientId); } private void sendObjectCreationInfo(GameObject object, int targetClientId) { CreateObjectPacket createObjectPacket = new CreateObjectPacket(); createObjectPacket.id = object.getId(); createObjectPacket.xPosition = object.getX(); createObjectPacket.yPosition = object.getY(); createObjectPacket.objectType = ObjectsIdentifier.getObjectIdentifier(object.getClass()); server.sendToAllTCP(targetClientId); } private void informOthersAboutNewPlayer(int id, Vector2 playerPosition) { CreateObjectPacket createNewPlayer = new CreateObjectPacket(); createNewPlayer.id = id; createNewPlayer.objectType = ObjectsIdentifier.getObjectIdentifier(ServerPlayer.class); createNewPlayer.xPosition = playerPosition.x; createNewPlayer.yPosition = playerPosition.y; server.sendToAllExceptTCP(id, createNewPlayer); } private void sendPositionUpdateInfoToNewClient(int clientId, Vector2 playerPosition) { } private static class CannotBindServerException extends GameException { public CannotBindServerException(String message) { super(message); } } private class ServerListener extends Listener { @Override public void connected(Connection connection) { userConnected(connection.getID()); System.out.println("Client connected server side, id: " + connection.getID()); } @Override public void disconnected(Connection connection) { System.out.println("Client connected server side, id: " + connection.getID()); } @Override public void received(Connection connection, Object object) { if(object instanceof ObjectSetPositionPacket) { ObjectSetPositionPacket setPositionPacket = (ObjectSetPositionPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(setPositionPacket.id); operationTarget.setPosition(setPositionPacket.x, setPositionPacket.y); server.sendToAllTCP(setPositionPacket); } else if(object instanceof ObjectMoveLeftPacket) { ObjectMoveLeftPacket moveLeftPacket = (ObjectMoveLeftPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveLeftPacket.id); operationTarget.moveLeft(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof ObjectMoveRightPacket) { ObjectMoveRightPacket moveRightPacket = (ObjectMoveRightPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveRight(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if (object instanceof ObjectMoveUpPacket) { ObjectMoveUpPacket moveRightPacket = (ObjectMoveUpPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveUp(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } else if(object instanceof ObjectMoveDownPacket) { ObjectMoveDownPacket moveRightPacket = (ObjectMoveDownPacket)object; MovableGameObject operationTarget = (MovableGameObject)gameState.getObject(moveRightPacket.id); operationTarget.moveDown(gameState.getGameObjects().values()); ObjectSetPositionPacket updatePositionPacket = createSetPositionPacketByObject(operationTarget); server.sendToAllTCP(updatePositionPacket); } System.out.println("Server side: object reveived from client id: " + connection.getID() + " " + object); } private ObjectSetPositionPacket createSetPositionPacketByObject(GameObject object) { ObjectSetPositionPacket packet = new ObjectSetPositionPacket(); packet.id = object.getId(); packet.x = object.getX(); packet.y = object.getY(); return packet; } } }
package org.exist.storage.lock; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import net.jcip.annotations.ThreadSafe; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.storage.NativeBroker; import org.exist.storage.lock.Lock.LockMode; import org.exist.storage.lock.Lock.LockType; import org.exist.storage.txn.Txn; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.StampedLock; import java.util.function.Consumer; import static org.exist.storage.lock.LockTable.LockEventType.*; /** * The Lock Table holds the details of * threads awaiting to acquire a Lock * and threads that have acquired a lock. * * It is arranged by the id of the lock * which is typically an indicator of the * lock subject. * * @author <a href="mailto:adam@evolvedbinary.com">Adam Retter</a> */ public class LockTable { public static final String PROP_DISABLE = "exist.locktable.disable"; public static final String PROP_TRACE_STACK_DEPTH = "exist.locktable.trace.stack.depth"; private static final Logger LOG = LogManager.getLogger(LockTable.class); private static final String THIS_CLASS_NAME = LockTable.class.getName(); /** * Set to false to disable all events */ private volatile boolean disableEvents = Boolean.getBoolean(PROP_DISABLE); /** * Whether we should try and trace the stack for the lock event, -1 means all stack, * 0 means no stack, n means n stack frames, 5 is a reasonable value */ private volatile int traceStackDepth = Optional.ofNullable(Integer.getInteger(PROP_TRACE_STACK_DEPTH)) .orElse(0); /** * Lock event listeners */ private final StampedLock listenersLock = new StampedLock(); @GuardedBy("listenersWriteLock") private volatile LockEventListener[] listeners = null; /** * Table of threads attempting to acquire a lock */ private final Map<Thread, Entry> attempting = new ConcurrentHashMap<>(60); /** * Table of threads which have acquired lock(s) */ private final Map<Thread, Entries> acquired = new ConcurrentHashMap<>(60); LockTable() { // add a log listener if trace level logging is enabled if(LOG.isTraceEnabled()) { registerListener(new LockEventLogListener(LOG, Level.TRACE)); } } /** * Shuts down the lock table processor. * * After calling this, no further lock * events will be reported. */ public void shutdown() { } /** * Set the depth at which we should trace lock events through the stack * * @param traceStackDepth -1 traces the whole stack, 0 means no stack traces, n means n stack frames */ public void setTraceStackDepth(final int traceStackDepth) { this.traceStackDepth = traceStackDepth; } public void attempt(final long groupId, final String id, final LockType lockType, final LockMode mode) { event(Attempt, groupId, id, lockType, mode); } public void attemptFailed(final long groupId, final String id, final LockType lockType, final LockMode mode) { event(AttemptFailed, groupId, id, lockType, mode); } public void acquired(final long groupId, final String id, final LockType lockType, final LockMode mode) { event(Acquired, groupId, id, lockType, mode); } public void released(final long groupId, final String id, final LockType lockType, final LockMode mode) { event(Released, groupId, id, lockType, mode); } private void event(final LockEventType lockEventType, final long groupId, final String id, final LockType lockType, final LockMode lockMode) { if(disableEvents) { return; } final long timestamp = System.nanoTime(); final Thread currentThread = Thread.currentThread(); // if(ignoreEvent(threadName, id)) { // return; // /** // * Very useful for debugging Lock life cycles // */ // if (sanityCheck) { // sanityCheckLockLifecycles(lockEventType, groupId, id, lockType, lockMode, threadName, 1, timestamp, stackTrace); switch (lockEventType) { case Attempt: Entry entry = attempting.get(currentThread); if (entry == null) { // happens once per thread! entry = new Entry(); attempting.put(currentThread, entry); } entry.id = id; entry.lockType = lockType; entry.lockMode = lockMode; entry.owner = currentThread.getName(); if(traceStackDepth == 0) { entry.stackTraces = null; } else { entry.stackTraces = new ArrayList<>(); entry.stackTraces.add(getStackTrace(currentThread)); } // write count last to ensure reader-thread visibility of above fields entry.count = 1; notifyListeners(lockEventType, timestamp, groupId, entry); break; case AttemptFailed: final Entry attemptFailedEntry = attempting.get(currentThread); if (attemptFailedEntry == null || attemptFailedEntry.count == 0) { LOG.error("No entry found when trying to remove failed `attempt` for: id={}, thread={}", id, currentThread.getName()); break; } // mark attempt as unused attemptFailedEntry.count = 0; notifyListeners(lockEventType, timestamp, groupId, attemptFailedEntry); break; case Acquired: final Entry attemptEntry = attempting.get(currentThread); if (attemptEntry == null || attemptEntry.count == 0) { LOG.error("No entry found when trying to remove `attempt` to promote to `acquired` for: id={}, thread={}", id, currentThread.getName()); break; } // we now either add or merge the `attemptEntry` with the `acquired` table Entries acquiredEntries = acquired.get(currentThread); if (acquiredEntries == null) { final Entry acquiredEntry = new Entry(); acquiredEntry.setFrom(attemptEntry); acquiredEntries = new Entries(acquiredEntry); acquired.put(currentThread, acquiredEntries); notifyListeners(lockEventType, timestamp, groupId, acquiredEntry); } else { final Entry acquiredEntry = acquiredEntries.merge(attemptEntry); notifyListeners(lockEventType, timestamp, groupId, acquiredEntry); } // mark attempt as unused attemptEntry.count = 0; break; case Released: final Entries entries = acquired.get(currentThread); if (entries == null) { LOG.error("No entries found when trying to `release` for: id={}, thread={}", id, currentThread.getName()); break; } final Entry releasedEntry = entries.unmerge(id, lockType, lockMode); if (releasedEntry == null) { LOG.error("Unable to unmerge entry for `release`: id={}, threadName={}", id, currentThread.getName()); break; } notifyListeners(lockEventType, timestamp, groupId, releasedEntry); break; } } /** * There is one Entries object for each writing-thread, * however it may be read from other threads which * is why it needs to be thread-safe. */ @ThreadSafe private static class Entries { private final StampedLock entriesLock = new StampedLock(); @GuardedBy("entriesLock") private final ObjectLinkedOpenHashSet<Entry> entries = new ObjectLinkedOpenHashSet<>(); public Entries(final Entry entry) { entries.add(entry); } private @Nullable Entry findEntry(final Entry entry) { // optimistic read long stamp = entriesLock.tryOptimisticRead(); //TODO(AR) attempt optimisation for most recently added entry with entries.last() final Entry local = entries.get(entry); if (entriesLock.validate(stamp)) { return local; } // otherwise... pessimistic read stamp = entriesLock.readLock(); try { return entries.get(entry); } finally { entriesLock.unlockRead(stamp); } } public Entry merge(final Entry attemptEntry) { final Entry local = findEntry(attemptEntry); // if found, do the merge if (local != null) { if (attemptEntry.stackTraces != null) { local.stackTraces.addAll(attemptEntry.stackTraces); } local.count += attemptEntry.count; return local; } // else, add it final Entry acquiredEntry = new Entry(); acquiredEntry.setFrom(attemptEntry); final long stamp = entriesLock.writeLock(); try { entries.add(acquiredEntry); return acquiredEntry; } finally { entriesLock.unlockWrite(stamp); } } @Nullable public Entry unmerge(final String id, final LockType lockType, final LockMode lockMode) { final Entry key = new Entry(id, lockType, lockMode, null, null); // optimistic read long stamp = entriesLock.tryOptimisticRead(); Entry local = entries.get(key); // if count is equal to 1 we can just remove from the list rather than decrementing if (local.count == 1) { final long writeStamp = entriesLock.tryConvertToWriteLock(stamp); if (writeStamp != 0l) { try { //TODO(AR) we need to recycle the entry here! ... nope do it in the caller! entries.remove(local); local.count return local; } finally { entriesLock.unlockWrite(writeStamp); } } } else { if (entriesLock.validate(stamp)) { // do the unmerge bit if (local.stackTraces != null) { local.stackTraces.remove(local.stackTraces.size() - 1); } local.count = local.count - 1; //done return local; } } // otherwise... pessimistic read boolean mustRemove; stamp = entriesLock.readLock(); try { local = entries.get(key); // if count is equal to 1 we can just remove from the list rather than decrementing if (local.count == 1) { final long writeStamp = entriesLock.tryConvertToWriteLock(stamp); if (writeStamp != 0l) { stamp = writeStamp; // NOTE: this causes the write lock to be released in the finally further down //TODO(AR) we need to recycle the entry here! ... nope do it in the caller! entries.remove(local); local.count return local; } } else { // do the unmerge bit if (local.stackTraces != null) { local.stackTraces.remove(local.stackTraces.size() - 1); } local.count = local.count - 1; //done return local; } mustRemove = true; } finally { entriesLock.unlock(stamp); } // unable to remove by tryConvertToWriteLock above, so directly acquire write lock if (mustRemove) { stamp = entriesLock.writeLock(); try { entries.remove(local); local.count return local; } finally { entriesLock.unlockWrite(stamp); } } return null; } public void forEach(final Consumer<Entry> entryConsumer) { final long stamp = entriesLock.readLock(); try { entries.forEach(entryConsumer); } finally { entriesLock.unlockRead(stamp); } } } @Nullable private StackTraceElement[] getStackTrace(final Thread thread) { final StackTraceElement[] stackTrace = thread.getStackTrace(); final int lastStackTraceElementIdx = stackTrace.length - 1; final int from = findFirstExternalFrame(stackTrace); final int to; if (traceStackDepth == -1) { to = lastStackTraceElementIdx; } else { final int calcTo = from + traceStackDepth; if (calcTo > lastStackTraceElementIdx) { to = lastStackTraceElementIdx; } else { to = calcTo; } } return Arrays.copyOfRange(stackTrace, from, to); } private int findFirstExternalFrame(final StackTraceElement[] stackTrace) { // we start with i = 1 to avoid Thread#getStackTrace() frame for(int i = 1; i < stackTrace.length; i++) { if(!THIS_CLASS_NAME.equals(stackTrace[i].getClassName())) { return i; } } return 0; } public void registerListener(final LockEventListener lockEventListener) { final long stamp = listenersLock.writeLock(); try { // extend listeners by 1 if (listeners == null) { listeners = new LockEventListener[1]; listeners[0] = lockEventListener; } else { final LockEventListener[] newListeners = new LockEventListener[listeners.length + 1]; System.arraycopy(listeners, 0, newListeners, 0, listeners.length); newListeners[listeners.length] = lockEventListener; listeners = newListeners; } } finally { listenersLock.unlockWrite(stamp); } lockEventListener.registered(); } public void deregisterListener(final LockEventListener lockEventListener) { final long stamp = listenersLock.writeLock(); try { // reduce listeners by 1 for (int i = listeners.length - 1; i > -1; i // intentionally compare by identity! if (listeners[i] == lockEventListener) { if (i == 0 && listeners.length == 1) { listeners = null; break; } final LockEventListener[] newListeners = new LockEventListener[listeners.length - 1]; System.arraycopy(listeners, 0, newListeners, 0, i); if (listeners.length != i) { System.arraycopy(listeners, i + 1, newListeners, i, listeners.length - i - 1); } listeners = newListeners; break; } } } finally { listenersLock.unlockWrite(stamp); } lockEventListener.unregistered(); } /** * Get's a copy of the current lock attempt information * * @return lock attempt information */ public Map<String, Map<LockType, List<LockModeOwner>>> getAttempting() { final Map<String, Map<LockType, List<LockModeOwner>>> result = new HashMap<>(); final Iterator<Entry> it = attempting.values().iterator(); while (it.hasNext()) { final Entry entry = it.next(); // read count (volatile) first to ensure visibility final int localCount = entry.count; if (localCount == 0) { // attempt entry object is marked as unused continue; } result.compute(entry.id, (_k, v) -> { if (v == null) { v = new HashMap<>(); } v.compute(entry.lockType, (_k1, v1) -> { if (v1 == null) { v1 = new ArrayList<>(); } v1.add(new LockModeOwner(entry.lockMode, entry.owner, entry.stackTraces != null ? entry.stackTraces.get(0) : null)); return v1; }); return v; }); } return result; } /** * Get's a copy of the current acquired lock information * * @return acquired lock information */ public Map<String, Map<LockType, Map<LockMode, Map<String, LockCountTraces>>>> getAcquired() { final Map<String, Map<LockType, Map<LockMode, Map<String, LockCountTraces>>>> result = new HashMap<>(); final Iterator<Entries> it = acquired.values().iterator(); while (it.hasNext()) { final Entries entries = it.next(); entries.forEach(entry -> { // read count (volatile) first to ensure visibility final int localCount = entry.count; result.compute(entry.id, (_k, v) -> { if (v == null) { v = new EnumMap<>(LockType.class); } v.compute(entry.lockType, (_k1, v1) -> { if (v1 == null) { v1 = new EnumMap<>(LockMode.class); } v1.compute(entry.lockMode, (_k2, v2) -> { if (v2 == null) { v2 = new HashMap<>(); } v2.compute(entry.owner, (_k3, v3) -> { if (v3 == null) { v3 = new LockCountTraces(localCount, entry.stackTraces); } else { v3.count += localCount; if (entry.stackTraces != null) { v3.traces.addAll(entry.stackTraces); } } return v3; }); return v2; }); return v1; }); return v; }); }); } return result; } public static class LockModeOwner { final LockMode lockMode; final String ownerThread; @Nullable final StackTraceElement[] trace; public LockModeOwner(final LockMode lockMode, final String ownerThread, @Nullable final StackTraceElement[] trace) { this.lockMode = lockMode; this.ownerThread = ownerThread; this.trace = trace; } public LockMode getLockMode() { return lockMode; } public String getOwnerThread() { return ownerThread; } @Nullable public StackTraceElement[] getTrace() { return trace; } } public static class LockCountTraces { int count; @Nullable final List<StackTraceElement[]> traces; public LockCountTraces(final int count, @Nullable final List<StackTraceElement[]> traces) { this.count = count; this.traces = traces; } public int getCount() { return count; } @Nullable public List<StackTraceElement[]> getTraces() { return traces; } } private void notifyListeners(final LockEventType lockEventType, final long timestamp, final long groupId, final Entry entry) { if (listeners == null) { return; } final long stamp = listenersLock.readLock(); try { for (int i = 0; i < listeners.length; i ++) { try { listeners[i].accept(lockEventType, timestamp, groupId, entry); } catch (final Exception e) { LOG.error("Listener '{}' error: ", listeners[i].getClass().getName(), e); } } } finally { listenersLock.unlockRead(stamp); } } private static @Nullable <T> List<T> List(@Nullable final T item) { if (item == null) { return null; } final List<T> list = new ArrayList<>(); list.add(item); return list; } public interface LockEventListener { default void registered() {} void accept(final LockEventType lockEventType, final long timestamp, final long groupId, final Entry entry); default void unregistered() {} } public enum LockEventType { Attempt, AttemptFailed, Acquired, Released } public static String formatString(final LockEventType lockEventType, final long groupId, final String id, final LockType lockType, final LockMode lockMode, final String threadName, final int count, final long timestamp, @Nullable final StackTraceElement[] stackTrace) { final StringBuilder builder = new StringBuilder() .append(lockEventType.name()) .append(' ') .append(lockType.name()); if(groupId > -1) { builder .append(" .append(groupId); } builder.append('(') .append(lockMode.toString()) .append(") of ") .append(id); if(stackTrace != null) { final String reason = getSimpleStackReason(stackTrace); if(reason != null) { builder .append(" for .append(reason); } } builder .append(" by ") .append(threadName) .append(" at ") .append(timestamp); if (lockEventType == Acquired || lockEventType == Released) { builder .append(". count=") .append(Integer.toString(count)); } return builder.toString(); } private static final String NATIVE_BROKER_CLASS_NAME = NativeBroker.class.getName(); private static final String COLLECTION_STORE_CLASS_NAME = NativeBroker.class.getName(); private static final String TXN_CLASS_NAME = Txn.class.getName(); @Nullable public static String getSimpleStackReason(final StackTraceElement[] stackTrace) { for (final StackTraceElement stackTraceElement : stackTrace) { final String className = stackTraceElement.getClassName(); if (className.equals(NATIVE_BROKER_CLASS_NAME) || className.equals(COLLECTION_STORE_CLASS_NAME) || className.equals(TXN_CLASS_NAME)) { if (!(stackTraceElement.getMethodName().endsWith("LockCollection") || stackTraceElement.getMethodName().equals("lockCollectionCache"))) { return stackTraceElement.getMethodName() + '(' + stackTraceElement.getLineNumber() + ')'; } } } return null; } /** * Represents an entry in the {@link #attempting} or {@link #acquired} lock table. * * All class members are only written from a single * thread. * * However, they may be read from the same writer thread or a different read-only thread. * The member `count` is written last by the writer thread * and read first by the read-only reader thread to ensure correct visibility * of the member values. */ public static class Entry { String id; LockType lockType; LockMode lockMode; String owner; @Nullable List<StackTraceElement[]> stackTraces; /** * Intentionally marked volatile. * All variables visible before this point become available * to the reading thread. */ volatile int count = 0; private Entry() { } private Entry(final String id, final LockType lockType, final LockMode lockMode, final String owner, @Nullable final StackTraceElement[] stackTrace) { this.id = id; this.lockType = lockType; this.lockMode = lockMode; this.owner = owner; if (stackTrace != null) { this.stackTraces = new ArrayList<>(); this.stackTraces.add(stackTrace); } else { this.stackTraces = null; } // write last to ensure reader visibility of above fields! this.count = 1; } public void setFrom(final Entry entry) { this.id = entry.id; this.lockType = entry.lockType; this.lockMode = entry.lockMode; this.owner = entry.owner; if (entry.stackTraces != null) { this.stackTraces = new ArrayList<>(entry.stackTraces); } else { this.stackTraces = null; } // write last to ensure reader visibility of above fields! this.count = entry.count; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || Entry.class != o.getClass()) return false; Entry entry = (Entry) o; return lockType == entry.lockType && lockMode == entry.lockMode && id.equals(entry.id); } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + lockType.hashCode(); result = 31 * result + lockMode.hashCode(); return result; } public String getId() { return id; } public LockType getLockType() { return lockType; } public LockMode getLockMode() { return lockMode; } public String getOwner() { return owner; } @Nullable public List<StackTraceElement[]> getStackTraces() { return stackTraces; } public int getCount() { return count; } } /** debugging tools below **/ // public static final String PROP_SANITY_CHECK = "exist.locktable.sanity.check"; // /** // * Set to true to enable sanity checking of lock leases // */ // private volatile boolean sanityCheck = Boolean.getBoolean(PROP_SANITY_CHECK); // /** // * Holds a count of READ and WRITE locks by {@link Entry#id} // * Only used for debugging,see {@link #sanityCheckLockLifecycles(LockEventType, long, String, LockType, // * LockMode, String, int, long, StackTraceElement[])}. // */ // @GuardedBy("this") private final Map<String, Tuple2<Long, Long>> lockCounts = new HashMap<>(); // /** // * Checks that there are not more releases that there are acquires // */ // private void sanityCheckLockLifecycles(final LockEventType lockEventType, final long groupId, final String id, // final LockType lockType, final LockMode lockMode, final String threadName, final int count, // final long timestamp, @Nullable final StackTraceElement[] stackTrace) { // synchronized(lockCounts) { // long read = 0; // long write = 0; // final Tuple2<Long, Long> lockCount = lockCounts.get(id); // if(lockCount != null) { // read = lockCount._1; // write = lockCount._2; // if(lockEventType == Acquired) { // if(lockMode == LockMode.READ_LOCK) { // read++; // } else if(lockMode == LockMode.WRITE_LOCK) { // write++; // } else if(lockEventType == Released) { // if(lockMode == LockMode.READ_LOCK) { // if(read == 0) { // read--; // } else if(lockMode == LockMode.WRITE_LOCK) { // if(write == 0) { // write--; // if(LOG.isTraceEnabled()) { // LOG.trace("QUEUE: {} (read={} write={})", formatString(lockEventType, groupId, id, lockType, lockMode, // threadName, count, timestamp, stackTrace), read, write); // lockCounts.put(id, Tuple(read, write)); // /** // * Simple filtering to ignore events that are not of interest // * // * @param threadName The name of the thread that triggered the event // * @param id The id of the lock // * // * @return true if the event should be ignored // */ // private boolean ignoreEvent(final String threadName, final String id) { // // useful for debugging specific log events // return threadName.startsWith("DefaultQuartzScheduler_") // || id.equals("dom.dbx") // || id.equals("collections.dbx") // || id.equals("collections.dbx") // || id.equals("structure.dbx") // || id.equals("values.dbx") // || id.equals("CollectionCache"); }
package litmus.functional; import org.fest.assertions.Assertions; import org.fest.assertions.GenericAssert; import play.mvc.Http; import static org.fest.assertions.Assertions.assertThat; import static play.mvc.Http.StatusCode.*; public class ResponseAssert extends GenericAssert<ResponseAssert, Response> { private Response response; protected ResponseAssert(Response response) { super(ResponseAssert.class, response); this.response = response; } public ResponseAssert isStatus(int httpStatusCode) { assertThat(response.getStatus()).isEqualTo(httpStatusCode); return this; } public ResponseAssert isOk() { return isStatus(OK); } public ResponseAssert isNotFound() { return isStatus(NOT_FOUND); } public ResponseAssert isForbidden() { return isStatus(FORBIDDEN); } public ResponseAssert isSuccess() { assertThat(response.isSuccess()).isTrue(); return this; } public ResponseAssert isNoSuccess() { assertThat(response.isSuccess()).isFalse(); return this; } public ResponseAssert isError() { assertThat(response.isError()).isTrue(); return this; } public ResponseAssert isNoError() { assertThat(response.isError()).isFalse(); return this; } public ResponseAssert isRedirect() { assertThat(response.isRedirect()).as("Expected a redirect, but status code was " + response.getStatus()).isTrue(); return this; } public ResponseAssert isNoRedirect() { assertThat(response.isRedirect()).isFalse(); return this; } public ResponseAssert isRedirectTo(String location) { isRedirect(); hasHeaderValue("location", location); return this; } public ResponseAssert hasHeader(String name) { assertThat(response.getHeader(name)).isNotNull(); return this; } public ResponseAssert hasNoHeader(String name) { assertThat(response.getHeader(name)).isNull(); return this; } public ResponseAssert hasHeaderValue(String headerName, String headerValue) { assertThat(response.getHeader(headerName)).isEqualToIgnoringCase(headerValue); return this; } public ResponseAssert hasFlashParam(String name) { FunctionalAssertions.assertThat(response.getFlashParam(name)).isNotNull(); return this; } public ResponseAssert hasFlashParam(String name, String value) { FunctionalAssertions.assertThat(response.getFlashParam(name)).isEqualTo(value); return this; } public ResponseAssert hasNoFlashParam(String name) { FunctionalAssertions.assertThat(response.getFlashParam(name)).isNull(); return this; } public ResponseAssert hasCookie(String name) { Http.Cookie cookie = response.getCookie(name); Assertions.assertThat(cookie).describedAs(String.format("cookie [%s] not found", name)).isNotNull(); return this; } public ResponseAssert hasCookieValue(String name, String value) { Http.Cookie cookie = response.getCookie(name); Assertions.assertThat(cookie).describedAs(String.format("cookie [%s] not found", name)).isNotNull(); Assertions.assertThat(cookie.value).isEqualTo(value); return this; } public ResponseAssert hasNoCookie(String cookieName) { Assertions.assertThat(response.getCookie(cookieName)).isNull(); return this; } public ResponseAssert hasRenderArg(String name) { Assertions.assertThat(response.getRenderArgs().get(name)).isNotNull(); return this; } public ResponseAssert hasRenderArgValue(String name, Object expected) { Assertions.assertThat(response.getRenderArgs().get(name)).isEqualTo(expected); return this; } public ResponseAssert hasNoRenderArg(String name) { FunctionalAssertions.assertThat(response.getRenderArgs().get(name)).isNull(); return this; } public ResponseAssert isHtml() { return hasContentType("text/html"); } public ResponseAssert isXml() { return hasContentType("text/xml"); } public ResponseAssert isJson() { return hasContentType("application/json"); } public ResponseAssert isText() { return hasContentType("text/plain"); } public ResponseAssert hasContentType(String contentType) { FunctionalAssertions.assertThat(response.getContentType()).isEqualTo(contentType); return this; } public ResponseAssert isEncoded(String encoding) { assertThat(response.getEncoding()).isEqualToIgnoringCase(encoding); return this; } public ResponseAssert isUtf8() { return isEncoded("utf-8"); } }
package bisq.core.btc.wallet; import bisq.core.btc.exceptions.TransactionVerificationException; import bisq.core.btc.exceptions.WalletException; import bisq.core.btc.listeners.AddressConfidenceListener; import bisq.core.btc.listeners.BalanceListener; import bisq.core.btc.listeners.TxConfidenceListener; import bisq.core.btc.setup.WalletsSetup; import bisq.core.provider.fee.FeeService; import bisq.core.user.Preferences; import bisq.common.config.Config; import bisq.common.handlers.ErrorMessageHandler; import bisq.common.handlers.ResultHandler; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.BlockChain; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Context; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.InsufficientMoneyException; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.VerificationException; import org.bitcoinj.core.listeners.NewBestBlockListener; import org.bitcoinj.core.listeners.TransactionConfidenceEventListener; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptChunk; import org.bitcoinj.script.ScriptException; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.signers.TransactionSigner; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.DecryptingKeyBag; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyBag; import org.bitcoinj.wallet.KeyChain; import org.bitcoinj.wallet.RedeemData; import org.bitcoinj.wallet.SendRequest; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import org.bitcoinj.wallet.listeners.ScriptsChangeEventListener; import org.bitcoinj.wallet.listeners.WalletChangeEventListener; import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener; import org.bitcoinj.wallet.listeners.WalletCoinsSentEventListener; import org.bitcoinj.wallet.listeners.WalletReorganizeEventListener; import javax.inject.Inject; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.MoreExecutors; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import org.bouncycastle.crypto.params.KeyParameter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * Abstract base class for BTC and BSQ wallet. Provides all non-trade specific functionality. */ @Slf4j public abstract class WalletService { protected final WalletsSetup walletsSetup; protected final Preferences preferences; protected final FeeService feeService; protected final NetworkParameters params; protected final BisqWalletListener walletEventListener = new BisqWalletListener(); protected final CopyOnWriteArraySet<AddressConfidenceListener> addressConfidenceListeners = new CopyOnWriteArraySet<>(); protected final CopyOnWriteArraySet<TxConfidenceListener> txConfidenceListeners = new CopyOnWriteArraySet<>(); protected final CopyOnWriteArraySet<BalanceListener> balanceListeners = new CopyOnWriteArraySet<>(); @Getter protected Wallet wallet; @Getter protected KeyParameter aesKey; @Getter protected IntegerProperty chainHeightProperty = new SimpleIntegerProperty(); // Constructor @Inject WalletService(WalletsSetup walletsSetup, Preferences preferences, FeeService feeService) { this.walletsSetup = walletsSetup; this.preferences = preferences; this.feeService = feeService; params = walletsSetup.getParams(); } // Lifecycle public void shutDown() { if (wallet != null) { //noinspection deprecation wallet.removeCoinsReceivedEventListener(walletEventListener); wallet.removeCoinsSentEventListener(walletEventListener); wallet.removeReorganizeEventListener(walletEventListener); wallet.removeTransactionConfidenceEventListener(walletEventListener); } } // Package scope Methods void decryptWallet(@NotNull KeyParameter key) { wallet.decrypt(key); aesKey = null; } void encryptWallet(KeyCrypterScrypt keyCrypterScrypt, KeyParameter key) { if (this.aesKey != null) { log.warn("encryptWallet called but we have a aesKey already set. " + "We decryptWallet with the old key before we apply the new key."); decryptWallet(this.aesKey); } wallet.encrypt(keyCrypterScrypt, key); aesKey = key; } void setAesKey(KeyParameter aesKey) { this.aesKey = aesKey; } abstract String getWalletAsString(boolean includePrivKeys); // Listener public void addAddressConfidenceListener(AddressConfidenceListener listener) { addressConfidenceListeners.add(listener); } public void removeAddressConfidenceListener(AddressConfidenceListener listener) { addressConfidenceListeners.remove(listener); } public void addTxConfidenceListener(TxConfidenceListener listener) { txConfidenceListeners.add(listener); } public void removeTxConfidenceListener(TxConfidenceListener listener) { txConfidenceListeners.remove(listener); } public void addBalanceListener(BalanceListener listener) { balanceListeners.add(listener); } public void removeBalanceListener(BalanceListener listener) { balanceListeners.remove(listener); } // Checks public static void checkWalletConsistency(Wallet wallet) throws WalletException { try { checkNotNull(wallet); checkState(wallet.isConsistent()); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); throw new WalletException(t); } } public static void verifyTransaction(Transaction transaction) throws TransactionVerificationException { try { transaction.verify(); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); throw new TransactionVerificationException(t); } } public static void checkAllScriptSignaturesForTx(Transaction transaction) throws TransactionVerificationException { for (int i = 0; i < transaction.getInputs().size(); i++) { WalletService.checkScriptSig(transaction, transaction.getInputs().get(i), i); } } public static void checkScriptSig(Transaction transaction, TransactionInput input, int inputIndex) throws TransactionVerificationException { try { checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null"); input.getScriptSig().correctlySpends(transaction, inputIndex, input.getConnectedOutput().getScriptPubKey(), Script.ALL_VERIFY_FLAGS); } catch (Throwable t) { t.printStackTrace(); log.error(t.getMessage()); throw new TransactionVerificationException(t); } } // Sign tx public static void signTransactionInput(Wallet wallet, KeyParameter aesKey, Transaction tx, TransactionInput txIn, int index) { KeyBag maybeDecryptingKeyBag = new DecryptingKeyBag(wallet, aesKey); if (txIn.getConnectedOutput() != null) { try { // We assume if it's already signed, it's hopefully got a SIGHASH type that will not invalidate when // we sign missing pieces (to check this would require either assuming any signatures are signing // standard output types or a way to get processed signatures out of script execution) txIn.getScriptSig().correctlySpends(tx, index, txIn.getConnectedOutput().getScriptPubKey(), Script.ALL_VERIFY_FLAGS); log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", index); return; } catch (ScriptException e) { // Expected. } Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey(); RedeemData redeemData = txIn.getConnectedRedeemData(maybeDecryptingKeyBag); checkNotNull(redeemData, "Transaction exists in wallet that we cannot redeem: %s", txIn.getOutpoint().getHash()); txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript)); TransactionSigner.ProposedTransaction propTx = new TransactionSigner.ProposedTransaction(tx); Transaction partialTx = propTx.partialTx; txIn = partialTx.getInput(index); if (txIn.getConnectedOutput() != null) { // If we don't have a sig we don't do the check to avoid error reports of failed sig checks final List<ScriptChunk> chunks = txIn.getConnectedOutput().getScriptPubKey().getChunks(); if (!chunks.isEmpty() && chunks.get(0).data != null && chunks.get(0).data.length > 0) { try { // We assume if it's already signed, it's hopefully got a SIGHASH type that will not invalidate when // we sign missing pieces (to check this would require either assuming any signatures are signing // standard output types or a way to get processed signatures out of script execution) txIn.getScriptSig().correctlySpends(tx, index, txIn.getConnectedOutput().getScriptPubKey(), Script.ALL_VERIFY_FLAGS); log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", index); return; } catch (ScriptException e) { // Expected. } } redeemData = txIn.getConnectedRedeemData(maybeDecryptingKeyBag); scriptPubKey = txIn.getConnectedOutput().getScriptPubKey(); checkNotNull(redeemData, "redeemData must not be null"); ECKey pubKey = redeemData.keys.get(0); if (pubKey instanceof DeterministicKey) propTx.keyPaths.put(scriptPubKey, (((DeterministicKey) pubKey).getPath())); ECKey key; if ((key = redeemData.getFullKey()) == null) { log.warn("No local key found for input {}", index); return; } Script inputScript = txIn.getScriptSig(); byte[] script = redeemData.redeemScript.getProgram(); try { TransactionSignature signature = partialTx.calculateSignature(index, key, script, Transaction.SigHash.ALL, false); inputScript = scriptPubKey.getScriptSigWithSignature(inputScript, signature.encodeToBitcoin(), 0); txIn.setScriptSig(inputScript); } catch (ECKey.KeyIsEncryptedException e1) { throw e1; } catch (ECKey.MissingPrivateKeyException e1) { log.warn("No private key in keypair for input {}", index); } } else { log.warn("Missing connected output, assuming input {} is already signed.", index); } } else { log.error("Missing connected output, assuming already signed."); } } // Broadcast tx public void broadcastTx(Transaction tx, TxBroadcaster.Callback callback) { TxBroadcaster.broadcastTx(wallet, walletsSetup.getPeerGroup(), tx, callback); } public void broadcastTx(Transaction tx, TxBroadcaster.Callback callback, int timeOut) { TxBroadcaster.broadcastTx(wallet, walletsSetup.getPeerGroup(), tx, callback, timeOut); } // TransactionConfidence @Nullable public TransactionConfidence getConfidenceForAddress(Address address) { List<TransactionConfidence> transactionConfidenceList = new ArrayList<>(); if (wallet != null) { Set<Transaction> transactions = wallet.getTransactions(false); if (transactions != null) { transactionConfidenceList.addAll(transactions.stream().map(tx -> getTransactionConfidence(tx, address)).collect(Collectors.toList())); } } return getMostRecentConfidence(transactionConfidenceList); } @Nullable public TransactionConfidence getConfidenceForTxId(String txId) { if (wallet != null) { Set<Transaction> transactions = wallet.getTransactions(false); for (Transaction tx : transactions) { if (tx.getTxId().toString().equals(txId)) return tx.getConfidence(); } } return null; } protected TransactionConfidence getTransactionConfidence(Transaction tx, Address address) { List<TransactionConfidence> transactionConfidenceList = getOutputsWithConnectedOutputs(tx) .stream() .filter(WalletService::isOutputScriptConvertibleToAddress) .filter(output -> address != null && address.equals(getAddressFromOutput(output))) .map(o -> tx.getConfidence()) .collect(Collectors.toList()); return getMostRecentConfidence(transactionConfidenceList); } protected List<TransactionOutput> getOutputsWithConnectedOutputs(Transaction tx) { List<TransactionOutput> transactionOutputs = tx.getOutputs(); List<TransactionOutput> connectedOutputs = new ArrayList<>(); // add all connected outputs from any inputs as well List<TransactionInput> transactionInputs = tx.getInputs(); for (TransactionInput transactionInput : transactionInputs) { TransactionOutput transactionOutput = transactionInput.getConnectedOutput(); if (transactionOutput != null) { connectedOutputs.add(transactionOutput); } } List<TransactionOutput> mergedOutputs = new ArrayList<>(); mergedOutputs.addAll(transactionOutputs); mergedOutputs.addAll(connectedOutputs); return mergedOutputs; } @Nullable protected TransactionConfidence getMostRecentConfidence(List<TransactionConfidence> transactionConfidenceList) { TransactionConfidence transactionConfidence = null; for (TransactionConfidence confidence : transactionConfidenceList) { if (confidence != null) { if (transactionConfidence == null || confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.PENDING) || (confidence.getConfidenceType().equals(TransactionConfidence.ConfidenceType.BUILDING) && transactionConfidence.getConfidenceType().equals( TransactionConfidence.ConfidenceType.BUILDING) && confidence.getDepthInBlocks() < transactionConfidence.getDepthInBlocks())) { transactionConfidence = confidence; } } } return transactionConfidence; } // Balance public Coin getAvailableConfirmedBalance() { return wallet != null ? wallet.getBalance(Wallet.BalanceType.AVAILABLE) : Coin.ZERO; } public Coin getEstimatedBalance() { return wallet != null ? wallet.getBalance(Wallet.BalanceType.ESTIMATED) : Coin.ZERO; } public Coin getBalanceForAddress(Address address) { return wallet != null ? getBalance(wallet.calculateAllSpendCandidates(), address) : Coin.ZERO; } protected Coin getBalance(List<TransactionOutput> transactionOutputs, Address address) { Coin balance = Coin.ZERO; for (TransactionOutput output : transactionOutputs) { if (!isDustAttackUtxo(output)) { if (isOutputScriptConvertibleToAddress(output) && address != null && address.equals(getAddressFromOutput(output))) balance = balance.add(output.getValue()); } } return balance; } protected abstract boolean isDustAttackUtxo(TransactionOutput output); public Coin getBalance(TransactionOutput output) { return getBalanceForAddress(getAddressFromOutput(output)); } public Coin getTxFeeForWithdrawalPerByte() { Coin fee = (preferences.isUseCustomWithdrawalTxFee()) ? Coin.valueOf(preferences.getWithdrawalTxFeeInBytes()) : feeService.getTxFeePerByte(); log.info("tx fee = " + fee.toFriendlyString()); return fee; } // Tx outputs public int getNumTxOutputsForAddress(Address address) { List<TransactionOutput> transactionOutputs = new ArrayList<>(); wallet.getTransactions(false).forEach(t -> transactionOutputs.addAll(t.getOutputs())); int outputs = 0; for (TransactionOutput output : transactionOutputs) { if (isOutputScriptConvertibleToAddress(output) && address != null && address.equals(getAddressFromOutput(output))) outputs++; } return outputs; } public boolean isAddressUnused(Address address) { return getNumTxOutputsForAddress(address) == 0; } // Empty complete Wallet public void emptyBtcWallet(String toAddress, KeyParameter aesKey, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) throws InsufficientMoneyException, AddressFormatException { SendRequest sendRequest = SendRequest.emptyWallet(Address.fromString(params, toAddress)); sendRequest.fee = Coin.ZERO; sendRequest.feePerKb = getTxFeeForWithdrawalPerByte().multiply(1000); sendRequest.aesKey = aesKey; Wallet.SendResult sendResult = wallet.sendCoins(sendRequest); printTx("empty btc wallet", sendResult.tx); Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction result) { log.info("emptyBtcWallet onSuccess Transaction=" + result); resultHandler.handleResult(); } @Override public void onFailure(@NotNull Throwable t) { log.error("emptyBtcWallet onFailure " + t.toString()); errorMessageHandler.handleErrorMessage(t.getMessage()); } }, MoreExecutors.directExecutor()); } // Getters public Transaction getTxFromSerializedTx(byte[] tx) { return new Transaction(params, tx); } public NetworkParameters getParams() { return params; } public int getBestChainHeight() { final BlockChain chain = walletsSetup.getChain(); return isWalletReady() && chain != null ? chain.getBestChainHeight() : 0; } public Transaction getClonedTransaction(Transaction tx) { return new Transaction(params, tx.bitcoinSerialize()); } // Wallet delegates to avoid direct access to wallet outside the service class public void addChangeEventListener(WalletChangeEventListener listener) { wallet.addChangeEventListener(Threading.USER_THREAD, listener); } public void removeChangeEventListener(WalletChangeEventListener listener) { wallet.removeChangeEventListener(listener); } @SuppressWarnings("deprecation") public void addNewBestBlockListener(NewBestBlockListener listener) { //noinspection deprecation final BlockChain chain = walletsSetup.getChain(); if (isWalletReady() && chain != null) chain.addNewBestBlockListener(listener); } @SuppressWarnings("deprecation") public void removeNewBestBlockListener(NewBestBlockListener listener) { //noinspection deprecation final BlockChain chain = walletsSetup.getChain(); if (isWalletReady() && chain != null) chain.removeNewBestBlockListener(listener); } public boolean isWalletReady() { return wallet != null; } public DeterministicSeed getKeyChainSeed() { return wallet.getKeyChainSeed(); } @Nullable public KeyCrypter getKeyCrypter() { return wallet.getKeyCrypter(); } public boolean checkAESKey(KeyParameter aesKey) { return wallet.checkAESKey(aesKey); } @Nullable public DeterministicKey findKeyFromPubKeyHash(byte[] pubKeyHash) { return wallet.getActiveKeyChain().findKeyFromPubHash(pubKeyHash); } @Nullable public DeterministicKey findKeyFromPubKey(byte[] pubKey) { return wallet.getActiveKeyChain().findKeyFromPubKey(pubKey); } public boolean isEncrypted() { return wallet.isEncrypted(); } public List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead) { // Returns a list ordered by tx.getUpdateTime() desc return wallet.getRecentTransactions(numTransactions, includeDead); } public int getLastBlockSeenHeight() { return wallet.getLastBlockSeenHeight(); } /** * Check if there are more than 20 unconfirmed transactions in the chain right now. * * @return true when queue is full */ public boolean isUnconfirmedTransactionsLimitHit() { return 20 < getTransactions(true).stream().filter(transaction -> transaction.isPending()).count(); } public Set<Transaction> getTransactions(boolean includeDead) { return wallet.getTransactions(includeDead); } public Coin getBalance(@SuppressWarnings("SameParameterValue") Wallet.BalanceType balanceType) { return wallet.getBalance(balanceType); } @Nullable public Transaction getTransaction(Sha256Hash hash) { return wallet.getTransaction(hash); } @Nullable public Transaction getTransaction(String txId) { return getTransaction(Sha256Hash.wrap(txId)); } public boolean isTransactionOutputMine(TransactionOutput transactionOutput) { return transactionOutput.isMine(wallet); } /* public boolean isTxOutputMine(TxOutput txOutput) { try { Script script = txOutput.getScript(); if (script.isSentToRawPubKey()) { byte[] pubkey = script.getPubKey(); return wallet.isPubKeyMine(pubkey); } if (script.isPayToScriptHash()) { return wallet.isPayToScriptHashMine(script.getPubKeyHash()); } else { byte[] pubkeyHash = script.getPubKeyHash(); return wallet.isPubKeyHashMine(pubkeyHash); } } catch (ScriptException e) { // Just means we didn't understand the output of this transaction: ignore it. log.debug("Could not parse tx output script: {}", e.toString()); return false; } }*/ public Coin getValueSentFromMeForTransaction(Transaction transaction) throws ScriptException { return transaction.getValueSentFromMe(wallet); } public Coin getValueSentToMeForTransaction(Transaction transaction) throws ScriptException { return transaction.getValueSentToMe(wallet); } // Util public static void printTx(String tracePrefix, Transaction tx) { log.info("\n" + tracePrefix + ":\n" + tx.toString()); } public static boolean isOutputScriptConvertibleToAddress(TransactionOutput output) { return ScriptPattern.isP2PKH(output.getScriptPubKey()) || ScriptPattern.isP2SH(output.getScriptPubKey()) || ScriptPattern.isP2WH(output.getScriptPubKey()); } @Nullable public static Address getAddressFromOutput(TransactionOutput output) { return isOutputScriptConvertibleToAddress(output) ? output.getScriptPubKey().getToAddress(Config.baseCurrencyNetworkParameters()) : null; } @Nullable public static String getAddressStringFromOutput(TransactionOutput output) { return isOutputScriptConvertibleToAddress(output) ? output.getScriptPubKey().getToAddress(Config.baseCurrencyNetworkParameters()).toString() : null; } /** * @param serializedTransaction The serialized transaction to be added to the wallet * @return The transaction we added to the wallet, which is different as the one we passed as argument! * @throws VerificationException */ public static Transaction maybeAddTxToWallet(byte[] serializedTransaction, Wallet wallet, TransactionConfidence.Source source) throws VerificationException { Transaction tx = new Transaction(wallet.getParams(), serializedTransaction); Transaction walletTransaction = wallet.getTransaction(tx.getTxId()); if (walletTransaction == null) { // We need to recreate the transaction otherwise we get a null pointer... tx.getConfidence(Context.get()).setSource(source); //wallet.maybeCommitTx(tx); wallet.receivePending(tx, null, true); return tx; } else { return walletTransaction; } } public static Transaction maybeAddNetworkTxToWallet(byte[] serializedTransaction, Wallet wallet) throws VerificationException { return maybeAddTxToWallet(serializedTransaction, wallet, TransactionConfidence.Source.NETWORK); } public static Transaction maybeAddSelfTxToWallet(Transaction transaction, Wallet wallet) throws VerificationException { return maybeAddTxToWallet(transaction, wallet, TransactionConfidence.Source.SELF); } public static Transaction maybeAddTxToWallet(Transaction transaction, Wallet wallet, TransactionConfidence.Source source) throws VerificationException { return maybeAddTxToWallet(transaction.bitcoinSerialize(), wallet, source); } // bisqWalletEventListener @SuppressWarnings("deprecation") public class BisqWalletListener implements WalletCoinsReceivedEventListener, WalletCoinsSentEventListener, WalletReorganizeEventListener, TransactionConfidenceEventListener { @Override public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { notifyBalanceListeners(tx); } @Override public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { notifyBalanceListeners(tx); } @Override public void onReorganize(Wallet wallet) { log.warn("onReorganize "); } @Override public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) { for (AddressConfidenceListener addressConfidenceListener : addressConfidenceListeners) { List<TransactionConfidence> transactionConfidenceList = new ArrayList<>(); transactionConfidenceList.add(getTransactionConfidence(tx, addressConfidenceListener.getAddress())); TransactionConfidence transactionConfidence = getMostRecentConfidence(transactionConfidenceList); addressConfidenceListener.onTransactionConfidenceChanged(transactionConfidence); } txConfidenceListeners.stream() .filter(txConfidenceListener -> tx != null && tx.getTxId().toString() != null && txConfidenceListener != null && tx.getTxId().toString().equals(txConfidenceListener.getTxID())) .forEach(txConfidenceListener -> txConfidenceListener.onTransactionConfidenceChanged(tx.getConfidence())); } void notifyBalanceListeners(Transaction tx) { for (BalanceListener balanceListener : balanceListeners) { Coin balance; if (balanceListener.getAddress() != null) balance = getBalanceForAddress(balanceListener.getAddress()); else balance = getAvailableConfirmedBalance(); balanceListener.onBalanceChanged(balance, tx); } } } }
package org.camunda.spin.json; import org.camunda.spin.Spin; import org.camunda.spin.SpinList; import org.camunda.spin.spi.SpinDataFormatException; import java.util.List; import java.util.Map; /** * A json node. * * @author Thorben Lindhauer * @author Stefan Hentschel */ public abstract class SpinJsonNode extends Spin<SpinJsonNode> { /** * Fetches the first index of the searched object in an array. * * @param searchObject Object for which the index should be searched. * @return {@link Integer} index of searchObject. * @throws SpinJsonException if the current node is not an array. * @throws SpinJsonPropertyException if object is not found. */ public abstract Integer indexOf(Object searchObject); /** * Fetches the last index of the searched object in an array. * * @param searchObject Object for which the index should be searched. * @return {@link Integer} index of searchObject or -1 if object not found. * @throws SpinJsonException if the current node is not an array. */ public abstract Integer lastIndexOf(Object searchObject); /** * Check if this node is an object node. * * @return true if the node is an object, false otherwise */ public abstract boolean isObject(); /** * Check if this node has a property with the given name. * * @param name the name of the property * @return true if this node has a property with this name, false otherwise */ public abstract boolean hasProp(String name); /** * Get the property of this node with the given name. * * @param name the name of the property * @return {@link SpinJsonNode} representation of the property */ public abstract SpinJsonNode prop(String name); /** * Set a new String property in this node. * * @param name the name of the new property * @param newProperty the new String property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, String newProperty); /** * Set a new Number property in this node. * * @param name the name of the new property * @param newProperty the new Number property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, Number newProperty); /** * Set a new int property in this node. * * @param name the name of the new property * @param newProperty the new int property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, int newProperty); /** * Set a new float property in this node. * * @param name the name of the new property * @param newProperty the new float property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, float newProperty); /** * Set a new long property in this node. * * @param name the name of the new property * @param newProperty the new long property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, long newProperty); /** * Set a new boolean property in this node. * * @param name the name of the new property * @param newProperty the new boolean property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, boolean newProperty); /** * Set a new Boolean property in this node. * * @param name the name of the new property * @param newProperty the new Boolean property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, Boolean newProperty); /** * Set a new List property in this node. * * @param name the name of the new property * @param newProperty the new List property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, List<Object> newProperty); /** * Set a new Map property in this node. * * @param name the name of the new property * @param newProperty the new Map property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, Map<String, Object> newProperty); /** * Set a new SpinJsonNode Object property in this node. * * @param name the name of the new property * @param newProperty the new SpinJsonNode Object property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode prop(String name, SpinJsonNode newProperty); /** * Remove a property of the given node by name. * @param name name of the property * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode deleteProp(String name); /** * Removes a number of properties by a given list of names. * @param names list of names * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode deleteProp(List<String> names); /** * Appends a object to the end of the current array node * @param property property which should be append * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode append(Object property); public abstract SpinJsonNode insertAt(int index, Object property); /** * Inserts an object BEFORE an specific object in an array * * @param searchObject Object which is searched * @param insertObject Object which will be inserted * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode insertBefore(Object searchObject, Object insertObject); /** * Inserts an object AFTER an specific object in an array * * @param searchObject Object which is searched * @param insertObject Object which will be inserted * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode insertAfter(Object searchObject, Object insertObject); /** * Removes the first appearance of an object from the current array * * @param property object which should be deleted * @return {@link SpinJsonNode} representation of the current node */ public abstract SpinJsonNode remove(Object property); /** * Removes the last appearance of an object from the current array * * @param property object which should be deleted * @return {@link SpinJsonNode} representation of the current node * */ public abstract SpinJsonNode removeLast(Object property); public abstract SpinJsonNode removeAt(int index); /** * Check if this node is a boolean value. * * @return true if this node is a boolean value, false otherwise */ public abstract Boolean isBoolean(); /** * Get this node as a boolean value. * * @return the boolean value of this node * @throws SpinDataFormatException if this node is not a boolean value */ public abstract Boolean boolValue(); /** * Check if this node is a number value. * * @return true if this node is a number value, false otherwise */ public abstract Boolean isNumber(); /** * Get this node as a number value. * * @return the number value of this node * @throws SpinDataFormatException if this node is not a number value */ public abstract Number numberValue(); /** * Check if this node is a string value. * * @return true if this node is a string value, false otherwise */ public abstract Boolean isString(); /** * Get this node as a string value. * * @return the string value of this node * @throws SpinDataFormatException if this node is not a string value */ public abstract String stringValue(); /** * Check if this node represents a null value. * * @return true if this node is a null value, false otherwise */ public abstract Boolean isNull(); /** * Check if this node is a value. * * @return true if this node is a value, false otherwise */ public abstract Boolean isValue(); /** * Gets the actual value of the node, in case it is a Boolean/String/Number/Null node. * In that case a Java Boolean/String/Number or null is returned. * * @return the value of this node * @throws SpinDataFormatException if this node is not a Boolean/String/Number/Nul value */ public abstract Object value(); /** * Check if this node is a array value. * * @return true if this node is a array value, false otherwise */ public abstract Boolean isArray(); /** * Get this node as list. * If the current node is an array, this method returns a {@link SpinList} which contains copies of all * JSON nodes contained in the current node. Changes to the the elements in the list will not propagate * to the original nodes. * * @return the list value of this node * @throws SpinDataFormatException if this node is not an array */ public abstract SpinList<SpinJsonNode> elements(); /** * Get the field names of this node (i.e. the property names). * * @return the list of field names * @throws SpinDataFormatException if this node is not a array value */ public abstract List<String> fieldNames(); /** * Creates a JsonPath query on this element. * * @param expression the JsonPath expression * @return the JsonPath query */ public abstract SpinJsonPathQuery jsonPath(String expression); }
package edu.umd.cs.findbugs.ba; /** * Convenience class for defining Dataflow classes which use a * BasicAbstractDataflowAnalysis subtype. The main functionality is offering * getFact{At,After}Location() methods which forward to the actual * analysis object. * * @see edu.umd.cs.findbugs.ba.Dataflow * @see edu.umd.cs.findbugs.ba.BasicAbstractDataflowAnalysis * @author David Hovemeyer */ public class AbstractDataflow<Fact, AnalysisType extends BasicAbstractDataflowAnalysis<Fact>> extends Dataflow<Fact, AnalysisType> { /** * Constructor. * * @param cfg CFG of the method on which dfa is performed * @param analysis the dataflow analysis */ public AbstractDataflow(CFG cfg, AnalysisType analysis) { super(cfg, analysis); } /** * Get the fact that is true on the given control edge. * * @param edge the edge * @return the fact that is true on the edge * @throws DataflowAnalysisException */ public Fact getFactOnEdge(Edge edge) throws DataflowAnalysisException { return getAnalysis().getFactOnEdge(edge); } public void dumpDataflow() { try { for(Location loc : getCFG().orderedLocations()) { System.out.println("\nBefore: " + getFactAtLocation(loc)); System.out.println("Location: " + loc); System.out.println("After: " + getFactAfterLocation(loc)); } } catch (DataflowAnalysisException e) { AnalysisContext.logError("error dumping dataflow analysis", e); System.out.println(e); } } }
package org.javarosa.core.util; import java.util.Vector; /** * * Only use for J2ME Compatible Vectors * * A SizeBoundVector that enforces that all member items be unique. You must * implement the .equals() method of class E * * @author wspride * */ public class SizeBoundUniqueVector<E> extends SizeBoundVector<E> { public SizeBoundUniqueVector(int sizeLimit) { super(sizeLimit); } /* (non-Javadoc) * @see java.util.Vector#addElement(java.lang.Object) */ public synchronized void addElement(E obj) { add(obj); } public synchronized boolean add(E obj) { if(this.size() == limit) { additional++; return true; } else if(this.contains(obj)){ return false; } else { super.addElement(obj); return true; } } }
package edu.umd.cs.findbugs.detect; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.IntAnnotation; import edu.umd.cs.findbugs.LocalVariableAnnotation; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.Item; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; import edu.umd.cs.findbugs.visitclass.Util; public class FindPuzzlers extends OpcodeStackDetector { final BugReporter bugReporter; final BugAccumulator bugAccumulator; public FindPuzzlers(BugReporter bugReporter) { this.bugReporter = bugReporter; this.bugAccumulator = new BugAccumulator(bugReporter); } @Override public void visit(Code obj) { prevOpcodeIncrementedRegister = -1; best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG = LOW_PRIORITY+1; prevOpCode = NOP; previousMethodInvocation = null; badlyComputingOddState = 0; resetIMulCastLong(); imul_distance = 10000; ternaryConversionState = 0; super.visit(obj); bugAccumulator.reportAccumulatedBugs(); } int imul_constant; int imul_distance; boolean imul_operand_is_parameter; int prevOpcodeIncrementedRegister; int valueOfConstantArgumentToShift; int best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG ; boolean constantArgumentToShift; boolean shiftOfNonnegativeValue; int ternaryConversionState = 0; int badlyComputingOddState; int prevOpCode; XMethod previousMethodInvocation; boolean isTigerOrHigher; @Override public void visit(JavaClass obj) { isTigerOrHigher = obj.getMajor() >= MAJOR_1_5; } private void resetIMulCastLong() { imul_constant = 1; imul_operand_is_parameter = false; } private int adjustPriority(int factor, int priority) { if (factor <= 4) return LOW_PRIORITY+2; if (factor <= 10000) return priority+1; if (factor <= 60*60*1000) return priority; return priority-1; } private int adjustMultiplier(Object constant, int mul) { if (!(constant instanceof Integer)) return mul; return Math.abs(((Integer) constant).intValue()) * mul; } @Override public void sawOpcode(int seen) { // System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " + ternaryConversionState); if (seen == IMUL) { if (imul_distance != 1) resetIMulCastLong(); imul_distance = 0; if (stack.getStackDepth() > 1) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); imul_constant = adjustMultiplier(item0.getConstant(), imul_constant); imul_constant = adjustMultiplier(item1.getConstant(), imul_constant); if (item0.isInitialParameter() || item1.isInitialParameter()) imul_operand_is_parameter = true; }} else { imul_distance++; } if (prevOpCode == IMUL && seen == I2L) { int priority = adjustPriority(imul_constant, NORMAL_PRIORITY); if (priority >= LOW_PRIORITY && imul_operand_is_parameter) priority = NORMAL_PRIORITY; if (priority <= best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG) { best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG = priority; bugAccumulator.accumulateBug(new BugInstance(this, "ICAST_INTEGER_MULTIPLY_CAST_TO_LONG", priority) .addClassAndMethod(this), this); } } if (getMethodName().equals("<clinit>") && (seen == PUTSTATIC || seen == GETSTATIC || seen == INVOKESTATIC)) { String clazz = getClassConstantOperand(); if (!clazz.equals(getClassName())) { try { JavaClass targetClass = Repository.lookupClass(clazz); if (Repository.instanceOf(targetClass, getThisClass())) { int priority = NORMAL_PRIORITY; if (seen == GETSTATIC) priority if (!targetClass.isPublic()) priority++; bugAccumulator.accumulateBug(new BugInstance(this, "IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION", priority) .addClassAndMethod(this).addClass(getDottedClassConstantOperand()), this); } } catch (ClassNotFoundException e) { // ignore it } } } if (false && (seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("equals") && getSigConstantOperand().equals("(Ljava/lang/Object;)Z") && stack.getStackDepth() > 1) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item0.isArray() || item1.isArray()) { bugAccumulator.accumulateBug(new BugInstance("EC_BAD_ARRAY_COMPARE", NORMAL_PRIORITY) .addClassAndMethod(this), this); } } if (seen >= IALOAD && seen <= SALOAD || seen >= IASTORE && seen <= SASTORE ) { Item index = stack.getStackItem(0); if (index.getSpecialKind() == Item.AVERAGE_COMPUTED_USING_DIVISION) bugAccumulator.accumulateBug(new BugInstance(this, "IM_AVERAGE_COMPUTATION_COULD_OVERFLOW", NORMAL_PRIORITY) .addClassAndMethod(this), this); } if ((seen == IFEQ || seen == IFNE) && getPrevOpcode(1) == IMUL && ( getPrevOpcode(2) == SIPUSH || getPrevOpcode(2) == BIPUSH ) && getPrevOpcode(3) == IREM ) bugAccumulator.accumulateBug(new BugInstance(this, "IM_MULTIPLYING_RESULT_OF_IREM", LOW_PRIORITY) .addClassAndMethod(this), this); if (seen == I2S && getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue && (!constantArgumentToShift || valueOfConstantArgumentToShift % 16 != 0) || seen == I2B && getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue && (!constantArgumentToShift || valueOfConstantArgumentToShift % 8 != 0)) bugAccumulator.accumulateBug(new BugInstance(this, "ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT", NORMAL_PRIORITY) .addClassAndMethod(this), this); constantArgumentToShift = false; shiftOfNonnegativeValue = false; if ( (seen == IUSHR || seen == ISHR || seen == ISHL )) { if (stack.getStackDepth() <= 1) { // don't understand; lie so other detectors won't get concerned constantArgumentToShift = true; valueOfConstantArgumentToShift = 8; } else { Object rightHandSide = stack.getStackItem(0).getConstant(); Object leftHandSide = stack.getStackItem(1).getConstant(); shiftOfNonnegativeValue = stack.getStackItem(1).isNonNegative(); if (rightHandSide instanceof Integer) { constantArgumentToShift = true; valueOfConstantArgumentToShift = ((Integer) rightHandSide); if (valueOfConstantArgumentToShift < 0 || valueOfConstantArgumentToShift >= 32) bugAccumulator.accumulateBug(new BugInstance(this, "ICAST_BAD_SHIFT_AMOUNT", valueOfConstantArgumentToShift < 0 ? LOW_PRIORITY : HIGH_PRIORITY) .addClassAndMethod(this) .addInt(valueOfConstantArgumentToShift).describe(IntAnnotation.INT_SHIFT), this); } if (leftHandSide != null && leftHandSide instanceof Integer && ((Integer) leftHandSide) > 0) { // boring; lie so other detectors won't get concerned constantArgumentToShift = true; valueOfConstantArgumentToShift = 8; } } } if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 0 && getClassConstantOperand().equals("java/util/Date") && getNameConstantOperand().equals("setMonth") && getSigConstantOperand().equals("(I)V")) { OpcodeStack.Item item = stack.getStackItem(0); Object o = item.getConstant(); if (o != null && o instanceof Integer) { int v = (Integer) o; if (v < 0 || v > 11) bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", NORMAL_PRIORITY) .addClassAndMethod(this) .addInt(v).describe(IntAnnotation.INT_VALUE) .addCalledMethod(this) .addSourceLine(this) ); } } if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 1 && getClassConstantOperand().equals("java/util/Calendar") && getNameConstantOperand().equals("set") || seen == INVOKESPECIAL && stack.getStackDepth() > 1 && getClassConstantOperand().equals("java/util/GregorianCalendar") && getNameConstantOperand().equals("<init>") ) { String sig = getSigConstantOperand(); if (sig.startsWith("(III")) { int pos = sig.length() - 5; OpcodeStack.Item item = stack.getStackItem(pos); Object o = item.getConstant(); if (o != null && o instanceof Integer) { int v = (Integer) o; if (v < 0 || v > 11) bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", NORMAL_PRIORITY) .addClassAndMethod(this) .addInt(v).describe(IntAnnotation.INT_VALUE) .addCalledMethod(this) .addSourceLine(this) ); } } } if (isRegisterStore() && (seen == ISTORE || seen == ISTORE_0 || seen == ISTORE_1 || seen == ISTORE_2 || seen == ISTORE_3) && getRegisterOperand() == prevOpcodeIncrementedRegister) { bugAccumulator.accumulateBug(new BugInstance(this, "DLS_OVERWRITTEN_INCREMENT", HIGH_PRIORITY) .addClassAndMethod(this), this); } if (seen == IINC) { prevOpcodeIncrementedRegister = getRegisterOperand(); } else prevOpcodeIncrementedRegister = -1; // Java Puzzlers, Chapter 2, puzzle 1 // Look for ICONST_2 IREM ICONST_1 IF_ICMPNE L1 switch (badlyComputingOddState) { case 0: if (seen == ICONST_2) badlyComputingOddState++; break; case 1: if (seen == IREM) { OpcodeStack.Item item = stack.getStackItem(1); if (item.getSpecialKind() != OpcodeStack.Item.MATH_ABS) badlyComputingOddState++; else badlyComputingOddState = 0; } else badlyComputingOddState = 0; break; case 2: if (seen == ICONST_1) badlyComputingOddState++; else badlyComputingOddState = 0; break; case 3: if (seen == IF_ICMPEQ || seen == IF_ICMPNE) { bugAccumulator.accumulateBug(new BugInstance(this, "IM_BAD_CHECK_FOR_ODD", NORMAL_PRIORITY) .addClassAndMethod(this), this); } badlyComputingOddState = 0; break; } // Java Puzzlers, chapter 3, puzzle 12 if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 0 && (getNameConstantOperand().equals("toString") && getSigConstantOperand().equals("()Ljava/lang/String;") || getNameConstantOperand().equals("append") && getSigConstantOperand().equals("(Ljava/lang/Object;)Ljava/lang/StringBuilder;") && getClassConstantOperand().equals("java/lang/StringBuilder") || getNameConstantOperand().equals("append") && getSigConstantOperand().equals("(Ljava/lang/Object;)Ljava/lang/StringBuffer;") && getClassConstantOperand().equals("java/lang/StringBuffer") ) ) { String classConstants = getClassConstantOperand(); OpcodeStack.Item item = stack.getStackItem(0); String signature = item.getSignature(); if (signature != null && signature.startsWith("[")) { String name = "anonymous array"; int reg = item.getRegisterNumber(); if(reg != -1) { LocalVariableAnnotation lva = LocalVariableAnnotation.getLocalVariableAnnotation( getMethod(), reg, getPC(), getPC()-1); name = "array " + lva.getName() + "[]"; } bugAccumulator.accumulateBug(new BugInstance(this, "DMI_INVOKING_TOSTRING_ON_ARRAY", NORMAL_PRIORITY) .addClassAndMethod(this) .addString(name), this); } } if (isTigerOrHigher) { if (previousMethodInvocation != null && prevOpCode == INVOKESPECIAL && seen == INVOKEVIRTUAL) { String classNameForPreviousMethod = previousMethodInvocation.getClassName(); String classNameForThisMethod = getClassConstantOperand(); if (classNameForPreviousMethod.startsWith("java.lang.") && classNameForPreviousMethod.equals(classNameForThisMethod.replace('/','.')) && getNameConstantOperand().endsWith("Value") && getSigConstantOperand().length() == 3) { if (getSigConstantOperand().charAt(2) == previousMethodInvocation.getSignature().charAt(1)) bugAccumulator.accumulateBug(new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED", NORMAL_PRIORITY) .addClassAndMethod(this), this); else bugAccumulator.accumulateBug(new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION", NORMAL_PRIORITY) .addClassAndMethod(this), this); ternaryConversionState = 1; } else ternaryConversionState = 0; } else if (seen == INVOKEVIRTUAL) { if (getClassConstantOperand().startsWith("java/lang") && getNameConstantOperand().endsWith("Value") && getSigConstantOperand().length() == 3) ternaryConversionState = 1; else ternaryConversionState = 0; }else if (ternaryConversionState == 1) { if (I2L <= seen && seen <= I2S) ternaryConversionState = 2; else ternaryConversionState = 0; } else if (ternaryConversionState == 2) { ternaryConversionState = 0; if (seen == GOTO) bugReporter.reportBug(new BugInstance(this, "BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } } if (seen == INVOKESTATIC) if ((getNameConstantOperand().startsWith("assert") || getNameConstantOperand().startsWith("fail")) && getMethodName().equals("run") && implementsRunnable(getThisClass())) { try { int size1 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(), "java/lang/Throwable", getPC()); int size2 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(), "java/lang/Error", getPC()); int size3 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(), "java/lang/AssertionFailureError", getPC()); int size = Math.min(Math.min( size1, size2), size3); if (size == Integer.MAX_VALUE) { JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(getClassConstantOperand().replace('/', '.')); if (targetClass.getSuperclassName().startsWith("junit")) { bugAccumulator.accumulateBug(new BugInstance(this, "IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD", NORMAL_PRIORITY) .addClassAndMethod(this), this); } } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } } if (seen == INVOKESPECIAL && getClassConstantOperand().startsWith("java/lang/") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().length() == 4 ) previousMethodInvocation = XFactory.createReferencedXMethod(this); else if (seen == INVOKESTATIC && getClassConstantOperand().startsWith("java/lang/") && getNameConstantOperand().equals("valueOf") && getSigConstantOperand().length() == 4) previousMethodInvocation = XFactory.createReferencedXMethod(this); else previousMethodInvocation = null; prevOpCode = seen; } boolean implementsRunnable(JavaClass obj) { if (obj.getSuperclassName().equals("java.lang.Thread")) return true; for(String s : obj.getInterfaceNames()) if (s.equals("java.lang.Runnable")) return true; return false; } }
package edu.umd.cs.findbugs.detect; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.IntAnnotation; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.Item; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XMethod; public class FindPuzzlers extends BytecodeScanningDetector { BugReporter bugReporter; public FindPuzzlers(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visit(Code obj) { prevOpcodeIncrementedRegister = -1; best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG = LOW_PRIORITY+1; prevOpCode = NOP; previousMethodInvocation = null; stack.resetForMethodEntry(this); badlyComputingOddState = 0; resetIMulCastLong(); imul_distance = 10000; ternaryConversionState = 0; super.visit(obj); } int imul_constant; int imul_distance; boolean imul_operand_is_parameter; int prevOpcodeIncrementedRegister; int valueOfConstantArgumentToShift; int best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG ; boolean constantArgumentToShift; boolean shiftOfNonnegativeValue; int ternaryConversionState = 0; int badlyComputingOddState; int prevOpCode; XMethod previousMethodInvocation; OpcodeStack stack = new OpcodeStack(); boolean isTigerOrHigher; @Override public void visit(JavaClass obj) { isTigerOrHigher = obj.getMajor() >= MAJOR_1_5; } private void resetIMulCastLong() { imul_constant = 1; imul_operand_is_parameter = false; } private int adjustPriority(int factor, int priority) { if (factor <= 4) return LOW_PRIORITY+2; if (factor <= 10000) return priority+1; if (factor <= 60*60*1000) return priority; return priority-1; } private int adjustMultiplier(Object constant, int mul) { if (!(constant instanceof Integer)) return mul; return Math.abs(((Integer) constant).intValue()) * mul; } @Override public void sawOpcode(int seen) { stack.mergeJumps(this); // System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " + ternaryConversionState); if (seen == IMUL) { if (imul_distance != 1) resetIMulCastLong(); imul_distance = 0; if (stack.getStackDepth() > 1) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); imul_constant = adjustMultiplier(item0.getConstant(), imul_constant); imul_constant = adjustMultiplier(item1.getConstant(), imul_constant); if (item0.isInitialParameter() || item1.isInitialParameter()) imul_operand_is_parameter = true; }} else { imul_distance++; } if (prevOpCode == IMUL && seen == I2L) { int priority = adjustPriority(imul_constant, NORMAL_PRIORITY); if (priority >= LOW_PRIORITY && imul_operand_is_parameter) priority = NORMAL_PRIORITY; if (priority <= best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG) { best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG = priority; bugReporter.reportBug(new BugInstance(this, "ICAST_INTEGER_MULTIPLY_CAST_TO_LONG", priority) .addClassAndMethod(this) .addSourceLine(this)); } } if (getMethodName().equals("<clinit>") && (seen == PUTSTATIC || seen == GETSTATIC || seen == INVOKESTATIC)) { String clazz = getClassConstantOperand(); if (!clazz.equals(getClassName())) { try { JavaClass targetClass = Repository.lookupClass(clazz); if (Repository.instanceOf(targetClass, getThisClass())) { int priority = NORMAL_PRIORITY; if (seen == GETSTATIC) priority if (!targetClass.isPublic()) priority++; bugReporter.reportBug(new BugInstance(this, "IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION", priority) .addClassAndMethod(this).addClass(getDottedClassConstantOperand()) .addSourceLine(this) ); } } catch (ClassNotFoundException e) { // ignore it } } } if (false && (seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("equals") && getSigConstantOperand().equals("(Ljava/lang/Object;)Z") && stack.getStackDepth() > 1) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item0.isArray() || item1.isArray()) { bugReporter.reportBug(new BugInstance("EC_BAD_ARRAY_COMPARE", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } } if (seen >= IALOAD && seen <= SALOAD || seen >= IASTORE && seen <= SASTORE ) { Item index = stack.getStackItem(0); if (index.getSpecialKind() == Item.AVERAGE_COMPUTED_USING_DIVISION) bugReporter.reportBug(new BugInstance(this, "IM_AVERAGE_COMPUTATION_COULD_OVERFLOW", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } if ((seen == IFEQ || seen == IFNE) && getPrevOpcode(1) == IMUL && ( getPrevOpcode(2) == SIPUSH || getPrevOpcode(2) == BIPUSH ) && getPrevOpcode(3) == IREM ) bugReporter.reportBug(new BugInstance(this, "IM_MULTIPLYING_RESULT_OF_IREM", LOW_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); if (seen == I2S && getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue && (!constantArgumentToShift || valueOfConstantArgumentToShift % 16 != 0) || seen == I2B && getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue && (!constantArgumentToShift || valueOfConstantArgumentToShift % 8 != 0)) bugReporter.reportBug(new BugInstance(this, "ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT", NORMAL_PRIORITY) .addClassAndMethod(this).addSourceLine(this)); constantArgumentToShift = false; shiftOfNonnegativeValue = false; if ( (seen == IUSHR || seen == ISHR || seen == ISHL )) { if (stack.getStackDepth() <= 1) { // don't understand; lie so other detectors won't get concerned constantArgumentToShift = true; valueOfConstantArgumentToShift = 8; } else { Object rightHandSide = stack.getStackItem(0).getConstant(); Object leftHandSide = stack.getStackItem(1).getConstant(); shiftOfNonnegativeValue = stack.getStackItem(1).isNonNegative(); if (rightHandSide instanceof Integer) { constantArgumentToShift = true; valueOfConstantArgumentToShift = ((Integer) rightHandSide); if (valueOfConstantArgumentToShift < 0 || valueOfConstantArgumentToShift >= 32) bugReporter.reportBug(new BugInstance(this, "ICAST_BAD_SHIFT_AMOUNT", valueOfConstantArgumentToShift < 0 ? LOW_PRIORITY : HIGH_PRIORITY) .addClassAndMethod(this) .addInt(valueOfConstantArgumentToShift).describe(IntAnnotation.INT_SHIFT) .addSourceLine(this) ); } if (leftHandSide != null && leftHandSide instanceof Integer && ((Integer) leftHandSide) > 0) { // boring; lie so other detectors won't get concerned constantArgumentToShift = true; valueOfConstantArgumentToShift = 8; } } } if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 0 && getClassConstantOperand().equals("java/util/Date") && getNameConstantOperand().equals("setMonth") && getSigConstantOperand().equals("(I)V")) { OpcodeStack.Item item = stack.getStackItem(0); Object o = item.getConstant(); if (o != null && o instanceof Integer) { int v = (Integer) o; if (v < 0 || v > 11) bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", NORMAL_PRIORITY) .addClassAndMethod(this) .addInt(v).describe(IntAnnotation.INT_VALUE) .addCalledMethod(this) .addSourceLine(this) ); } } if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 1 && getClassConstantOperand().equals("java/util/Calendar") && getNameConstantOperand().equals("set") || seen == INVOKESPECIAL && stack.getStackDepth() > 1 && getClassConstantOperand().equals("java/util/GregorianCalendar") && getNameConstantOperand().equals("<init>") ) { String sig = getSigConstantOperand(); if (sig.startsWith("(III")) { int pos = sig.length() - 5; OpcodeStack.Item item = stack.getStackItem(pos); Object o = item.getConstant(); if (o != null && o instanceof Integer) { int v = (Integer) o; if (v < 0 || v > 11) bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", NORMAL_PRIORITY) .addClassAndMethod(this) .addInt(v).describe(IntAnnotation.INT_VALUE) .addCalledMethod(this) .addSourceLine(this) ); } } } if (isRegisterStore() && (seen == ISTORE || seen == ISTORE_0 || seen == ISTORE_1 || seen == ISTORE_2 || seen == ISTORE_3) && getRegisterOperand() == prevOpcodeIncrementedRegister) { bugReporter.reportBug(new BugInstance(this, "DLS_OVERWRITTEN_INCREMENT", HIGH_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } if (seen == IINC) { prevOpcodeIncrementedRegister = getRegisterOperand(); } else prevOpcodeIncrementedRegister = -1; // Java Puzzlers, Chapter 2, puzzle 1 // Look for ICONST_2 IREM ICONST_1 IF_ICMPNE L1 switch (badlyComputingOddState) { case 0: if (seen == ICONST_2) badlyComputingOddState++; break; case 1: if (seen == IREM) { OpcodeStack.Item item = stack.getStackItem(1); if (item.getSpecialKind() != OpcodeStack.Item.MATH_ABS) badlyComputingOddState++; else badlyComputingOddState = 0; } else badlyComputingOddState = 0; break; case 2: if (seen == ICONST_1) badlyComputingOddState++; else badlyComputingOddState = 0; break; case 3: if (seen == IF_ICMPEQ || seen == IF_ICMPNE) { bugReporter.reportBug(new BugInstance(this, "IM_BAD_CHECK_FOR_ODD", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } badlyComputingOddState = 0; break; } // Java Puzzlers, chapter 3, puzzle 12 if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 0 && (getNameConstantOperand().equals("toString") && getSigConstantOperand().equals("()Ljava/lang/String;") || getNameConstantOperand().equals("append") && getSigConstantOperand().equals("(Ljava/lang/Object;)Ljava/lang/StringBuilder;") && getClassConstantOperand().equals("java/lang/StringBuilder") || getNameConstantOperand().equals("append") && getSigConstantOperand().equals("(Ljava/lang/Object;)Ljava/lang/StringBuffer;") && getClassConstantOperand().equals("java/lang/StringBuffer") ) ) { String classConstants = getClassConstantOperand(); OpcodeStack.Item item = stack.getStackItem(0); String signature = item.getSignature(); if (signature != null && signature.startsWith("[")) bugReporter.reportBug(new BugInstance(this, "DMI_INVOKING_TOSTRING_ON_ARRAY", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } if (isTigerOrHigher) { if (previousMethodInvocation != null && prevOpCode == INVOKESPECIAL && seen == INVOKEVIRTUAL) { String classNameForPreviousMethod = previousMethodInvocation.getClassName(); String classNameForThisMethod = getClassConstantOperand(); if (classNameForPreviousMethod.startsWith("java.lang.") && classNameForPreviousMethod.equals(classNameForThisMethod.replace('/','.')) && getNameConstantOperand().endsWith("Value") && getSigConstantOperand().length() == 3) { if (getSigConstantOperand().charAt(2) == previousMethodInvocation.getSignature().charAt(1)) bugReporter.reportBug(new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); else bugReporter.reportBug(new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); ternaryConversionState = 1; } else ternaryConversionState = 0; } else if (seen == INVOKEVIRTUAL) { if (getClassConstantOperand().startsWith("java/lang") && getNameConstantOperand().endsWith("Value") && getSigConstantOperand().length() == 3) ternaryConversionState = 1; else ternaryConversionState = 0; }else if (ternaryConversionState == 1) { if (I2L <= seen && seen <= I2S) ternaryConversionState = 2; else ternaryConversionState = 0; } else if (ternaryConversionState == 2) { ternaryConversionState = 0; if (seen == GOTO) bugReporter.reportBug(new BugInstance(this, "BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } } if (seen == INVOKESTATIC) if ((getNameConstantOperand().startsWith("assert") || getNameConstantOperand().startsWith("fail"))&& getMethodName().equals("run") && implementsRunnable(getThisClass())) { try { JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(getClassConstantOperand().replace('/', '.')); if (targetClass.getSuperclassName().startsWith("junit")) { bugReporter.reportBug(new BugInstance(this, "IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this)); } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } } stack.sawOpcode(this,seen); if (seen == INVOKESPECIAL && getClassConstantOperand().startsWith("java/lang/") && getNameConstantOperand().equals("<init>") && getSigConstantOperand().length() == 4 ) previousMethodInvocation = XFactory.createReferencedXMethod(this); else if (seen == INVOKESTATIC && getClassConstantOperand().startsWith("java/lang/") && getNameConstantOperand().equals("valueOf") && getSigConstantOperand().length() == 4) previousMethodInvocation = XFactory.createReferencedXMethod(this); else previousMethodInvocation = null; prevOpCode = seen; } boolean implementsRunnable(JavaClass obj) { if (obj.getSuperclassName().equals("java.lang.Thread")) return true; for(String s : obj.getInterfaceNames()) if (s.equals("java.lang.Runnable")) return true; return false; } }
package tech.tablesaw.io.csv; import org.junit.Ignore; import org.junit.Test; import tech.tablesaw.api.ColumnType; import tech.tablesaw.api.ShortColumn; import tech.tablesaw.api.Table; import tech.tablesaw.columns.Column; import tech.tablesaw.io.csv.CsvReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static tech.tablesaw.api.ColumnType.*; import static tech.tablesaw.api.QueryHelper.column; /** * Tests for CSV Reading */ public class CsvReaderTest { private final ColumnType[] bus_types = {SHORT_INT, CATEGORY, CATEGORY, FLOAT, FLOAT}; @Test public void testWithBusData() throws Exception { // Read the CSV file Table table = CsvReader.read(bus_types, true, ',', "../data/bus_stop_test.csv"); // Look at the column names assertEquals("[stop_id, stop_name, stop_desc, stop_lat, stop_lon]", table.columnNames().toString()); table = table.sortDescendingOn("stop_id"); table.removeColumns("stop_desc"); Column c = table.floatColumn("stop_lat"); Table v = table.selectWhere(column("stop_lon").isGreaterThan(-0.1f)); } @Test public void testWithBushData() throws Exception { // Read the CSV file ColumnType[] types = {LOCAL_DATE, SHORT_INT, CATEGORY}; Table table = CsvReader.read(types, "../data/BushApproval.csv"); assertEquals(323, table.rowCount()); // Look at the column names assertEquals("[date, approval, who]", table.columnNames().toString()); } @Test public void testBushDataWithoutSamplingForTypeDetection() throws Exception { // Read the CSV file File file = new File("../data/BushApproval.csv"); Table table = CsvReader.read(new FileReader(file), file.getName(), true, ',', true); assertEquals(323, table.rowCount()); // Look at the column names assertEquals("[date, approval, who]", table.columnNames().toString()); } @Test public void testDataTypeDetection() throws Exception { Reader reader = new FileReader(new File("../data/bus_stop_test.csv")); char delimiter = ','; List<String[]> rows = CsvReader.parseCsv(reader, delimiter); ColumnType[] columnTypes = CsvReader.detectColumnTypes(rows, true, delimiter, false); assertTrue(Arrays.equals(bus_types, columnTypes)); } @Test public void testPrintStructure() throws Exception { String output = "ColumnType[] columnTypes = {\n" + "LOCAL_DATE, // 0 date \n" + "SHORT_INT, // 1 approval \n" + "CATEGORY, // 2 who \n" + "}\n"; assertEquals(output, CsvReader.printColumnTypes("../data/BushApproval.csv", true, ',')); } @Test public void testDataTypeDetection2() throws Exception { Reader reader = new FileReader(new File("../data/BushApproval.csv")); char delimiter = ','; List<String[]> rows = CsvReader.parseCsv(reader, delimiter); ColumnType[] columnTypes = CsvReader.detectColumnTypes(rows, true, ',', false); assertEquals(ColumnType.LOCAL_DATE, columnTypes[0]); assertEquals(ColumnType.SHORT_INT, columnTypes[1]); assertEquals(ColumnType.CATEGORY, columnTypes[2]); } @Ignore @Test public void testLoadFromUrl() throws Exception { ColumnType[] types = {LOCAL_DATE, SHORT_INT, CATEGORY}; String location = "https://raw.githubusercontent.com/jtablesaw/tablesaw/master/data/BushApproval.csv"; Table table; try (Reader input = new InputStreamReader(new URL(location).openStream())) { table = Table.createFromReader(input, "Bush approval ratings", types, true, ','); } assertNotNull(table); } @Test public void testBoundary1() throws Exception { Table table1 = Table.createFromCsv("../data/boundaryTest1.csv"); table1.structure(); // just make sure the import completed } @Test public void testBoundary2() throws Exception { Table table1 = Table.createFromCsv("../data/boundaryTest2.csv"); table1.structure(); // just make sure the import completed } @Test public void testReadFailure() throws Exception { Table table1 = Table.createFromCsv("../data/read_failure_test.csv"); table1.structure(); // just make sure the import completed ShortColumn test = table1.shortColumn("Test"); System.out.println(test.summary().print()); } @Test public void testReadFailure2() throws Exception { Table table1 = Table.createFromCsv("../data/read_failure_test2.csv"); table1.structure(); // just make sure the import completed ShortColumn test = table1.shortColumn("Test"); System.out.println(test.summary().print()); } }
import java.util.regex.Matcher; import java.util.regex.Pattern; final class Acronym { private final String acronym; Acronym(String phrase) { acronym = generateAcronym(phrase); } String get() { return acronym; } private String generateAcronym(String phrase){ final Pattern BREAK_WORDS = Pattern.compile("[A-Z]+[a-z]*|[a-z]+"); final Matcher matcher = BREAK_WORDS.matcher(phrase); final StringBuilder stringBuilder = new StringBuilder(); while (matcher.find()){ stringBuilder.append(matcher.group().charAt(0)); } return stringBuilder.toString().toUpperCase(); } }
package tem.dataflow; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import com.google.common.io.ByteSource; public final class StreamingWorkflow { @Test public void flowsTwice() throws IOException { ByteSource from = Res.byteSource(); ByteSource first = new PrintAndPassThrough(from, "\nfirst"); ByteSource second = new PrintAndPassThrough(first, "second"); second.copyTo(System.out); second.copyTo(System.out); } private static final class PrintAndPassThrough extends ByteSource { private final ByteSource from; private final String toPrint; public PrintAndPassThrough(ByteSource from, String toPrint) { this.from = from; this.toPrint = toPrint; } @Override public InputStream openStream() throws IOException { InputStream input = from.openStream(); System.out.println(toPrint); return input; } } }
package qa.testing; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class CreateAccount { private WebDriver driver; private WebDriverWait wait; @Before public void startChrome(){ driver = new ChromeDriver(); wait = new WebDriverWait(driver, 10); } @Test public void createAccount(){ driver.get("http://localhost/litecart/en/"); driver.findElement(By.xpath("//a[text()='Create Account']")).click(); driver.findElement(By.name("firstname")).sendKeys("firstname"); driver.findElement(By.name("lastname")).sendKeys("lastname"); driver.findElement(By.name("address1")).sendKeys("address1"); driver.findElement(By.name("postcode")).sendKeys(RandomStringUtils.randomNumeric(5)); driver.findElement(By.name("city")).sendKeys("city"); Select select = new Select(driver.findElement(By.name("country_code"))); select.selectByVisibleText("United States"); driver.findElement(By.name("phone")).sendKeys(RandomStringUtils.randomNumeric(10)); String email = RandomStringUtils.randomAlphanumeric(10)+"@com"; driver.findElement(By.name("email")).sendKeys(email); driver.findElement(By.name("password")).sendKeys("123456"); driver.findElement(By.name("confirmed_password")).sendKeys("123456"); driver.findElement(By.name("create_account")).click(); driver.findElement(By.linkText("Logout")).click(); driver.findElement(By.name("email")).sendKeys(email); driver.findElement(By.name("password")).sendKeys("123456"); driver.findElement(By.name("login")).click(); driver.findElement(By.linkText("Logout")).click(); } @After public void stop(){ driver.quit(); driver = null; } }