answer
stringlengths
17
10.2M
package com.gmail.nuclearcat1337.snitch_master.snitches; import com.gmail.nuclearcat1337.snitch_master.SnitchMaster; import com.gmail.nuclearcat1337.snitch_master.api.SnitchListQualifier; import com.gmail.nuclearcat1337.snitch_master.locatableobjectlist.LocatableObjectList; import com.gmail.nuclearcat1337.snitch_master.util.Color; import java.io.*; import java.util.*; public class SnitchManager { private static final SnitchListQualifier friendly = new SnitchListQualifier("origin == 'jalist' || origin == 'chat'"); private static final SnitchListQualifier neutral = new SnitchListQualifier("origin == 'manual'"); public static SnitchList[] getDefaultSnitchLists(SnitchManager manager) { return new SnitchList[]{ new SnitchList(manager,SnitchManager.friendly, true, "Friendly",new Color(0, (int)(0.56D*255D), 255)), new SnitchList(manager,SnitchManager.neutral, true, "Neutral",new Color(238, 210, 2))}; //"Safety Yellow" } private static final String modSnitchesFile = SnitchMaster.modDataFolder+"/Snitches.csv"; private static final String modSnitchListsFile = SnitchMaster.modDataFolder+"/SnitchLists.csv"; private final SnitchMaster snitchMaster; private final LocatableObjectList<Snitch> snitches; private final List<SnitchList> snitchLists; private boolean globalRender; public SnitchManager(SnitchMaster snitchMaster) { this.snitchMaster = snitchMaster; snitches = new LocatableObjectList<>(); snitchLists = new ArrayList<>(); globalRender = true; loadSnitchLists(new File(modSnitchListsFile)); loadSnitches(new File(modSnitchesFile)); if(snitchLists.isEmpty()) //If we load the lists from the file and there are none, create the default ones { for(SnitchList list : getDefaultSnitchLists(this)) snitchLists.add(list); } } public SnitchList getRenderListForSnitch(Snitch snitch) { for(SnitchList list : snitch.attachedSnitchLists) if(list.shouldRenderSnitches()) return list; return null; } public List<SnitchList> getSnitchListsForSnitch(Snitch snitch) { return snitch.attachedSnitchLists; } public boolean doesListWithNameExist(String name) { for (SnitchList list : snitchLists) { if(list.getListName().equalsIgnoreCase(name)) return true; } return false; } public SnitchList createSnitchList(String name, SnitchListQualifier qualifier, boolean render, Color color) { if(doesListWithNameExist(name)) return null; SnitchList list = new SnitchList(this,qualifier,render,name,color); for(Snitch snitch : getSnitches()) if(qualifier.isQualified(snitch)) attachListToSnitch(list,snitch); snitchLists.add(list); saveSnitchLists(); return list; } public boolean removeSnitchList(String name) { if(!doesListWithNameExist(name)) return false; for(int i = 0; i < snitchLists.size(); i++) { if (snitchLists.get(i).getListName().equalsIgnoreCase(name)) { SnitchList list = snitchLists.remove(i); //Now we need to update the render priority of all the remaining snitch lists //And remove any references to this list from the attached snitch lists for(int j = 0; j < snitchLists.size(); j++) snitchLists.get(j).setRenderPriorityUnchecked(j+1); for(Snitch snitch : getSnitchesInList(list)) snitch.attachedSnitchLists.remove(list); saveSnitchLists(); return true; } } return false; } public void toggleGlobalRender() { this.globalRender = !this.globalRender; } public boolean getGlobalRender() { return globalRender; } public ArrayList<Snitch> getSnitchesInList(SnitchList list) { ArrayList<Snitch> attachedSnitches = new ArrayList<>(); for(Snitch snitch : snitches) { if(snitch.attachedSnitchLists.contains(list)) attachedSnitches.add(snitch); } return attachedSnitches; } /** * Submits a Snitch for processing and adding to the Snitch collection. * The Snitch is added to all SnitchLists, JourneyMap, (if applicable) and then saved to a file. */ public void submitSnitch(Snitch snitch) { //Check to see if there is already a snitch at this location Snitch contains = snitches.get(snitch.getLocation()); //Check if the snitch that was submitted already exists if(contains != null) { //If it does then change the cull time and group contains.setCullTime(snitch.getCullTime()); contains.setGroupName(snitch.getGroupName()); contains.setSnitchName(snitch.getSnitchName()); //Clear the attached snitch lists because we are going to requalify the snitch because some attributes changed contains.attachedSnitchLists.clear(); } else { //Just some reference rearranging contains = snitch; //add the snitch to the collection snitches.add(contains); } //Go through all the snitch lists to see if this snitch should be in them for(SnitchList list : snitchLists) { //If it should then attach the snitch list to the snitch if(list.getQualifier().isQualified(contains)) attachListToSnitch(list,contains); } //send it to journey map if that is enabled snitchMaster.individualJourneyMapUpdate(contains); } public void saveSnitchLists() { ArrayList<String> csvs = new ArrayList<>(); for(SnitchList list : snitchLists) csvs.add(SnitchList.ConvertSnitchListToCSV(list)); writeToCSV(new File(modSnitchListsFile),csvs); } public void saveSnitches() { ArrayList<String> csvs = new ArrayList<>(); for(Snitch snitch : snitches) csvs.add(Snitch.ConvertSnitchToCSV(snitch)); writeToCSV(new File(modSnitchesFile),csvs); } public LocatableObjectList<Snitch> getSnitches() { return snitches; } public Collection<SnitchList> getSnitchLists() { return snitchLists; } void journeyMapRedisplay(SnitchList list) { snitchMaster.snitchListJourneyMapUpdate(list); } void changeListRenderPriority(SnitchList list, boolean increase) { int index = snitchLists.indexOf(list); int targetIndex = increase ? index-1 : index+1; //If they were successfully swapped if(swapIfPossible(snitchLists,index,targetIndex)) { //Update the list objects actual render priority snitchLists.get(index).setRenderPriorityUnchecked(index+1); snitchLists.get(targetIndex).setRenderPriorityUnchecked(targetIndex+1); for(Snitch snitch : getSnitchesInList(list)) { Collections.sort(snitch.attachedSnitchLists,listComparator); } } } void requalifyList(SnitchList list) { for(Snitch snitch : getSnitchesInList(list)) snitch.attachedSnitchLists.remove(list); SnitchListQualifier qualifier = list.getQualifier(); for(Snitch snitch : getSnitches()) if(qualifier.isQualified(snitch)) attachListToSnitch(list,snitch); snitchMaster.fullJourneyMapUpdate(); } private void attachListToSnitch(SnitchList list, Snitch snitch) { List<SnitchList> attached = snitch.attachedSnitchLists; int i = 0; for(; i < attached.size(); i++) { if(list.getRenderPriority() < attached.get(i).getRenderPriority()) break; } attached.add(i,list); } //True if they were swapped //False otherwise private static <T> boolean swapIfPossible(List<T> list, int index, int targetIndex) { if(list.size() < 2) //Cant swap if there are less than 2 items return false; //Make sure both the indices are valid for the list if(index >= 0 && index < list.size() && targetIndex >= 0 && targetIndex < list.size()) { T temp = list.get(targetIndex); list.set(targetIndex,list.get(index)); list.set(index,temp); return true; } return false; } private static void writeToCSV(File file, List<String> lines) { if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return; } } try(FileWriter writer = new FileWriter(file)) { for(String line : lines) { writer.write(line); writer.write(System.lineSeparator()); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } } private void loadSnitches(File file) { try { if (file.exists()) { try (BufferedReader br = new BufferedReader(new FileReader(file))) { for (String line = null; (line = br.readLine()) != null; ) { Snitch snitch = Snitch.GetSnitchFromCSV(line); if (snitch != null) submitSnitch(snitch); } } } } catch (IOException e) { } } private void loadSnitchLists(File file) { try { if (file.exists()) { try (BufferedReader br = new BufferedReader(new FileReader(file))) { for (String line = null; (line = br.readLine()) != null; ) { SnitchList list = SnitchList.GetSnitchListFromCSV(line,this); if(list != null) this.snitchLists.add(list); } } } } catch (IOException e) { } } /** * A comparator that sorts SnitchLists according to their render priorities. */ private static class SnitchListComparator implements Comparator<SnitchList> { @Override public int compare(SnitchList one, SnitchList two) { return Integer.compare(one.getRenderPriority(),two.getRenderPriority()); } } /** * A static instance of the SnitchList comparator to use in all instances of the Snitch class. */ private static final SnitchListComparator listComparator = new SnitchListComparator(); }
package com.googlecode.jsonrpc4j.spring; import com.fasterxml.jackson.databind.ObjectMapper; import com.googlecode.jsonrpc4j.JsonRpcService; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.io.Resource; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.ClassMetadata; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; import static java.lang.String.format; import static org.springframework.util.ClassUtils.convertClassNameToResourcePath; import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX; /** * Auto-creates proxies for service interfaces annotated with {@link JsonRpcService}. */ public class AutoJsonRpcClientProxyCreator implements BeanFactoryPostProcessor, ApplicationContextAware { private static final Logger LOG = Logger.getLogger(AutoJsonRpcClientProxyCreator.class.getName()); private ApplicationContext applicationContext; private String scanPackage; private URL baseUrl; private ObjectMapper objectMapper; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(applicationContext); DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory; String resolvedPath = resolvePackageToScan(); LOG.fine(format("Scanning '%s' for JSON-RPC service interfaces.", resolvedPath)); try { for (Resource resource : applicationContext.getResources(resolvedPath)) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); ClassMetadata classMetadata = metadataReader.getClassMetadata(); AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); String jsonRpcPathAnnotation = JsonRpcService.class.getName(); if (annotationMetadata.isAnnotated(jsonRpcPathAnnotation)) { String className = classMetadata.getClassName(); String path = (String) annotationMetadata.getAnnotationAttributes(jsonRpcPathAnnotation).get("value"); boolean useNamedParams = (Boolean) annotationMetadata.getAnnotationAttributes(jsonRpcPathAnnotation).get("useNamedParams"); LOG.fine(format("Found JSON-RPC service to proxy [%s] on path '%s'.", className, path)); registerJsonProxyBean(dlbf, className, path, useNamedParams); } } } } catch (IOException e) { throw new RuntimeException(format("Cannot scan package '%s' for classes.", resolvedPath), e); } } /** * Converts the scanPackage to something that the resource loader can handle. */ private String resolvePackageToScan() { return CLASSPATH_URL_PREFIX + convertClassNameToResourcePath(scanPackage) + "*.class"; } /** * Registers a new proxy bean with the bean factory. */ private void registerJsonProxyBean(DefaultListableBeanFactory dlbf, String className, String path, boolean useNamedParams) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder .rootBeanDefinition(JsonProxyFactoryBean.class) .addPropertyValue("serviceUrl", appendBasePath(path)) .addPropertyValue("serviceInterface", className) .addPropertyValue("useNamedParams", useNamedParams); if (objectMapper != null) { beanDefinitionBuilder.addPropertyValue("objectMapper", objectMapper); } dlbf.registerBeanDefinition(className + "-clientProxy", beanDefinitionBuilder.getBeanDefinition()); } /** * Appends the base path to the path found in the interface. */ private String appendBasePath(String path) { try { return new URL(baseUrl, path).toString(); } catch (MalformedURLException e) { throw new RuntimeException(format("Cannot combine URLs '%s' and '%s' to valid URL.", baseUrl, path), e); } } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void setBaseUrl(URL baseUrl) { this.baseUrl = baseUrl; } public void setScanPackage(String scanPackage) { this.scanPackage = scanPackage; } public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } }
package com.infinityraider.agricraft.content.world; import com.infinityraider.agricraft.AgriCraft; import com.infinityraider.agricraft.api.v1.AgriApi; import com.infinityraider.agricraft.content.core.BlockCrop; import com.infinityraider.agricraft.content.core.TileEntityCrop; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.nbt.Tag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.util.Optional; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class CropStickProcessor extends StructureProcessor { private static final String FIELD_GENOME = "IL_FIELD_0"; private static final String FIELD_GROWTH = "IL_FIELD_1"; public static final Codec<CropStickProcessor> CODEC = RecordCodecBuilder.create(instance -> instance.group( ResourceLocation.CODEC.optionalFieldOf("structure", new ResourceLocation("empty")).forGetter(CropStickProcessor::getStructure)) .apply(instance, instance.stable(CropStickProcessor::new)) ); private final ResourceLocation structure; public CropStickProcessor(ResourceLocation structure) { this.structure = structure; } public ResourceLocation getStructure() { return this.structure; } @Override protected StructureProcessorType<?> getType() { return AgriCraft.instance.getStructureRegistry().cropStickProcessor; } @Nullable @Override public StructureTemplate.StructureBlockInfo process(LevelReader world, BlockPos structureOrigin, BlockPos parentOrigin, StructureTemplate.StructureBlockInfo templateInfo, StructureTemplate.StructureBlockInfo worldInfo, StructurePlaceSettings settings, @Nullable StructureTemplate template) { // check if the block is a crop block BlockState state = worldInfo.state; if (!(state.getBlock() instanceof BlockCrop)) { return worldInfo; } // check if the crop block is just single crop sticks BlockCrop blockCrop = (BlockCrop) state.getBlock(); if (!blockCrop.hasCropSticks(state) || blockCrop.hasCrossSticks(state) || blockCrop.hasPlantOrWeeds(state)) { return worldInfo; } // set the nbt to load to the tile entity if (worldInfo.nbt.contains(FIELD_GENOME, Tag.TAG_COMPOUND) && worldInfo.nbt.contains(FIELD_GROWTH, Tag.TAG_COMPOUND)) { boolean planted = AgriApi.getWorldGenPlantManager().generateGenomeFor(this.getStructure(), settings.getRandom(worldInfo.pos)).map(genome -> { TileEntityCrop.GENOME_WRITER.accept(Optional.of(genome), worldInfo.nbt.getCompound(FIELD_GENOME)); TileEntityCrop.GROWTH_WRITER.accept(genome.getPlant().getInitialGrowthStage(), worldInfo.nbt.getCompound(FIELD_GROWTH)); return true; }).orElse(false); // if a plant has been set, we must also set the block state to indicate that there is a plant if(planted) { return new StructureTemplate.StructureBlockInfo(worldInfo.pos, blockCrop.applyPlant(state), worldInfo.nbt.copy()); } else { AgriCraft.instance.getLogger().debug("Skipped generation of random plant as none are registered for " + this.getStructure()); } } // return the world info return worldInfo; } }
package com.itemis.maven.plugins.unleash.scm.providers; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.jgit.api.AddCommand; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.CommitCommand; import org.eclipse.jgit.api.CreateBranchCommand; import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode; import org.eclipse.jgit.api.DeleteTagCommand; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.LogCommand; import org.eclipse.jgit.api.LsRemoteCommand; import org.eclipse.jgit.api.MergeCommand; import org.eclipse.jgit.api.MergeCommand.FastForwardMode; import org.eclipse.jgit.api.PushCommand; import org.eclipse.jgit.api.ResetCommand.ResetType; import org.eclipse.jgit.api.RevertCommand; import org.eclipse.jgit.api.TagCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.merge.MergeStrategy; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.RemoteRefUpdate.Status; import org.eclipse.jgit.transport.TagOpt; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.itemis.maven.plugins.unleash.scm.ScmException; import com.itemis.maven.plugins.unleash.scm.ScmOperation; import com.itemis.maven.plugins.unleash.scm.ScmProvider; import com.itemis.maven.plugins.unleash.scm.annotations.ScmProviderType; import com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitFullMergeStrategy; import com.itemis.maven.plugins.unleash.scm.providers.util.GitUtil; import com.itemis.maven.plugins.unleash.scm.requests.BranchRequest; import com.itemis.maven.plugins.unleash.scm.requests.CheckoutRequest; import com.itemis.maven.plugins.unleash.scm.requests.CommitRequest; import com.itemis.maven.plugins.unleash.scm.requests.CommitRequest.Builder; import com.itemis.maven.plugins.unleash.scm.requests.DeleteBranchRequest; import com.itemis.maven.plugins.unleash.scm.requests.DeleteTagRequest; import com.itemis.maven.plugins.unleash.scm.requests.HistoryRequest; import com.itemis.maven.plugins.unleash.scm.requests.PushRequest; import com.itemis.maven.plugins.unleash.scm.requests.RevertCommitsRequest; import com.itemis.maven.plugins.unleash.scm.requests.TagRequest; import com.itemis.maven.plugins.unleash.scm.requests.UpdateRequest; import com.itemis.maven.plugins.unleash.scm.results.HistoryCommit; import com.itemis.maven.plugins.unleash.scm.results.HistoryResult; @ScmProviderType("git") public class ScmProviderGit implements ScmProvider { private static final String LOG_PREFIX = "Git - "; private Logger log; private Git git; private PersonIdent personIdent; private CredentialsProvider credentialsProvider; private File workingDir; private List<String> additionalThingsToPush; private GitUtil util; @Override public void initialize(File workingDirectory, Optional<Logger> logger, Optional<String> username, Optional<String> password) { this.log = logger.or(Logger.getLogger(ScmProvider.class.getName())); this.workingDir = workingDirectory; this.additionalThingsToPush = Lists.newArrayList(); if (workingDirectory.exists() && workingDirectory.isDirectory() && workingDirectory.list().length > 0) { try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repo = builder.findGitDir(this.workingDir).build(); this.git = Git.wrap(repo); this.personIdent = new PersonIdent(repo); this.util = new GitUtil(this.git); } catch (IOException e) { e.printStackTrace(); } } if (username.isPresent()) { this.credentialsProvider = new UsernamePasswordCredentialsProvider(username.get(), password.or("")); } } @Override public void close() { if (this.git != null) { this.git.close(); } } @Override public void checkout(CheckoutRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Checking out from remote repository."); } // check if local working dir is empty if (this.workingDir.exists() && this.workingDir.list().length > 0) { throw new ScmException(ScmOperation.CHECKOUT, "Unable to checkout remote repository '" + request.getRemoteRepositoryUrl() + "'. Local working directory '" + this.workingDir.getAbsolutePath() + "' is not empty!"); } try { if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Cloning remote repository."); StringBuilder message = new StringBuilder(LOG_PREFIX).append("Clone info:\n"); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- REMOTE_URL: ").append(request.getRemoteRepositoryUrl()); this.log.fine(message.toString()); } CloneCommand clone = Git.cloneRepository().setDirectory(this.workingDir).setURI(request.getRemoteRepositoryUrl()) .setCredentialsProvider(this.credentialsProvider); if (!request.checkoutWholeRepository()) { clone.setNoCheckout(true); } this.git = clone.call(); this.util = new GitUtil(this.git); if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Cloning remote repository finished successfully.\n"); } } catch (GitAPIException e) { throw new ScmException(ScmOperation.CHECKOUT, "Unable to clone remote git repository '" + request.getRemoteRepositoryUrl() + "' into local working directory '" + this.workingDir.getAbsolutePath() + "'.", e); } if (!request.checkoutWholeRepository()) { // 1. checkout single filepaths from the repository String revision = request.getRevision().or(Constants.HEAD); if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Checking out single files only."); StringBuilder message = new StringBuilder(LOG_PREFIX).append("Checkout info:\n"); message.append("\t- FILES: ").append(Joiner.on(',').join(request.getPathsToCheckout())).append('\n'); message.append("\t- REVISION: ").append(revision); this.log.fine(message.toString()); } try { CheckoutCommand checkout = this.git.checkout().setStartPoint(revision).setAllPaths(false); for (String path : request.getPathsToCheckout()) { checkout.addPath(path); } checkout.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.CHECKOUT, "Unable to checkout commit with id '" + request.getRevision().get() + "' into local working directory '" + this.workingDir.getAbsolutePath() + "'.", e); } } else if (request.checkoutBranch()) { // 2. checkout a specific branch (and even a commit from this branch) if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Checking out branch" + request.getBranch().get() + "."); } if (hasBranch(request.getBranch().get())) { RevCommit startPoint = this.util.resolveCommit(request.getRevision(), request.getBranch()); if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Checkout info:\n"); message.append("\t- BRANCH: ").append(request.getBranch().get()).append('\n'); message.append("\t- REVISION: ").append(startPoint.getName()); this.log.fine(message.toString()); } try { CheckoutCommand checkout = this.git.checkout().setName(request.getBranch().get()).setCreateBranch(true) .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).setStartPoint(startPoint); checkout.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.CHECKOUT, "Unable to checkout '" + request.getBranch().get() + "' into local working directory '" + this.workingDir.getAbsolutePath() + "'.", e); } } else { if (this.log.isLoggable(Level.WARNING)) { StringBuilder message = new StringBuilder(LOG_PREFIX) .append("The remote repository contains no branch with name '").append(request.getBranch().get()) .append("'. Staying on current branch '").append(this.util.getCurrentBranchName()).append("'."); this.log.warning(message.toString()); } } } else if (request.checkoutTag()) { // 3. checkout a specific tag if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Checking out tag" + request.getTag().get() + "."); } if (hasTag(request.getTag().get())) { try { CheckoutCommand checkout = this.git.checkout().setName(request.getTag().get()); checkout.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.CHECKOUT, "Unable to checkout tag '" + request.getTag().get() + "' into local working directory '" + this.workingDir.getAbsolutePath() + "'.", e); } } else { if (this.log.isLoggable(Level.WARNING)) { StringBuilder message = new StringBuilder(LOG_PREFIX) .append("The remote repository contains no tag with name '").append(request.getTag().get()) .append("'. Staying on current branch '").append(this.util.getCurrentBranchName()).append("'."); this.log.warning(message.toString()); } } } else if (request.getRevision().isPresent()) { // 4. checkout a specific commit if no branch or tag is specified if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Checking out a specific revision from current branch."); StringBuilder message = new StringBuilder(LOG_PREFIX).append("Checkout info:\n"); message.append("\t- BRANCH: ").append(this.util.getCurrentBranchName()).append('\n'); message.append("\t- REVISION: ").append(request.getRevision().get()); this.log.fine(message.toString()); } try { CheckoutCommand checkout = this.git.checkout().setName(request.getRevision().get()); checkout.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.CHECKOUT, "Unable to checkout commit with id '" + request.getRevision().get() + "' into local working directory '" + this.workingDir.getAbsolutePath() + "'.", e); } } if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Checkout finished successfully!"); } } @Override public String commit(CommitRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Committing local changes."); } if (!this.util.isDirty(request.getPathsToCommit())) { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Nothing to commit here."); } return request.push() ? getLatestRemoteRevision() : getLocalRevision(); } if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX + "Commit info:\n"); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- MERGE_STRATEGY: ").append(request.getMergeStrategy()).append('\n'); message.append("\t- PUSH: ").append(request.push()).append('\n'); message.append("\t- COMMIT_ALL_CHANGES: ").append(request.commitAllChanges()); if (!request.commitAllChanges()) { message.append("\n\t- FILES: ").append(Joiner.on(',').join(request.getPathsToCommit())); } this.log.fine(message.toString()); } // add all changes to be committed (either everything or the specified paths) AddCommand add = this.git.add(); if (request.commitAllChanges()) { if (request.includeUntrackedFiles()) { add.addFilepattern("."); } else { for (String path : this.util.getUncommittedChangedPaths()) { add.addFilepattern(path); } } } else { for (String path : request.getPathsToCommit()) { add.addFilepattern(path); } } try { add.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.COMMIT, "Unable to add local changes to the index.", e); } // commit all added changes CommitCommand commit = this.git.commit().setMessage(request.getMessage()).setCommitter(this.personIdent); if (request.commitAllChanges()) { commit.setAll(true); } else { for (String path : request.getPathsToCommit()) { commit.setOnly(path); } } String newRevision = null; try { RevCommit result = commit.call(); newRevision = result.getName(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.DELETE_TAG, "Could not commit chanhes of local repository.", e); } if (request.push()) { PushRequest pr = PushRequest.builder().mergeStrategy(request.getMergeStrategy()) .mergeClient(request.getMergeClient().orNull()).build(); push(pr); newRevision = getLatestRemoteRevision(); } if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Commit finished successfully. New revision is: " + newRevision); } return newRevision; } @Override public String push(PushRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Pushing local changes to remote repository."); } String localBranchName = this.util.getCurrentBranchName(); String remoteBranchName = this.util.getRemoteBranchName(localBranchName); String remoteName = this.util.getRemoteName(localBranchName); String remoteUrl = this.util.getConnectionUrlOfRemote(remoteName); if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX + "Push info:\n"); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- LOCAL_BRANCH: ").append(localBranchName).append('\n'); message.append("\t- REMOTE_BRANCH: ").append(remoteBranchName).append('\n'); message.append("\t- REMOTE: ").append(remoteName).append('\n'); message.append("\t- REMOTE_URL: ").append(remoteUrl).append('\n'); message.append("\t- MERGE_STRATEGY: ").append(request.getMergeStrategy()).append('\n'); this.log.fine(message.toString()); } // 1. update the local repository before pushing to remote UpdateRequest ur = UpdateRequest.builder().mergeStrategy(request.getMergeStrategy()) .mergeClient(request.getMergeClient().orNull()).build(); update(ur); try { // 2. push local changes to remote repository PushCommand push = this.git.push().setRemote(remoteName).setCredentialsProvider(this.credentialsProvider) .setAtomic(true).setPushAll().setPushTags(); for (String additional : this.additionalThingsToPush) { push.add(additional); } Iterable<PushResult> results = push.call(); Status failureStatus = null; String reason = null; resultLoop: for (PushResult result : results) { Collection<RemoteRefUpdate> updates = result.getRemoteUpdates(); for (RemoteRefUpdate update : updates) { if (update.getStatus() != Status.OK && update.getStatus() != Status.UP_TO_DATE) { failureStatus = update.getStatus(); reason = update.getMessage(); break resultLoop; } } } if (failureStatus != null) { StringBuilder message = new StringBuilder( "Could not push local changes to the remote repository due to the following error: [").append(failureStatus) .append("] "); if (reason != null) { message.append(reason); } throw new ScmException(ScmOperation.PUSH, message.toString()); } this.additionalThingsToPush.clear(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.PUSH, "Could not push local commits to remote repository", e); } String newRemoteRevision = getLatestRemoteRevision(); if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Push finished successfully. New remote revision is: " + newRemoteRevision); } return newRemoteRevision; } @Override public String update(UpdateRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Updating local repository with remote changes."); } String localBranchName = this.util.getCurrentBranchName(); String remoteBranchName = this.util.getRemoteBranchName(localBranchName); String remoteName = this.util.getRemoteName(localBranchName); String connectionUrl = this.util.getConnectionUrlOfRemote(remoteName); // TODO update paths only? if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Fetching remote updates."); StringBuilder message = new StringBuilder(LOG_PREFIX).append("Fetch info:\n"); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- REMOTE: ").append(remoteName).append('\n'); message.append("\t- REMOTE_URL: ").append(connectionUrl); this.log.fine(message.toString()); } try { FetchCommand fetch = this.git.fetch().setRemote(remoteName).setCredentialsProvider(this.credentialsProvider) .setTagOpt(TagOpt.AUTO_FOLLOW).setRemoveDeletedRefs(true); fetch.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.UPDATE, "Could not fetch changes from Git remote '" + remoteName + " [" + connectionUrl + "]'.", e); } MergeCommand merge = this.git.merge().setFastForward(FastForwardMode.FF).setCommit(true).setMessage("Merge"); switch (request.getMergeStrategy()) { case USE_LOCAL: merge.setStrategy(MergeStrategy.OURS); break; case USE_REMOTE: merge.setStrategy(MergeStrategy.THEIRS); break; case FULL_MERGE: merge.setStrategy(new UnleashGitFullMergeStrategy(request.getMergeClient().get())); break; case DO_NOT_MERGE: // nothing to do here! break; default: throw new UnsupportedOperationException( "Unknown merge strategy! API and implementation versions are incompatible!"); } String requestedRevision = request.getTargetRevision().or(getLatestRemoteRevision()); try { ObjectId revision = this.git.getRepository().resolve(requestedRevision); merge.include(revision); } catch (Exception e) { throw new ScmException(ScmOperation.MERGE, "No Git commit id found for String '" + requestedRevision + "'.", e); } if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Merging remote updates into local working copy."); StringBuilder message = new StringBuilder(LOG_PREFIX).append("Merge info:\n"); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- REMOTE: ").append(remoteName).append('\n'); message.append("\t- REMOTE_BRANCH: ").append(remoteBranchName).append('\n'); message.append("\t- REMOTE_REVISION: ").append(requestedRevision).append('\n'); message.append("\t- LOCAL_BRANCH: ").append(localBranchName).append('\n'); message.append("\t- LOCAL_REVISION: ").append(getLocalRevision()).append('\n'); message.append("\t- MERGE_STRATEGY: ").append(request.getMergeStrategy()); this.log.fine(message.toString()); } try { merge.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.MERGE, "Could not merge changes fetched from Git remote '" + remoteName + " [" + connectionUrl + "]' into local working copy '" + this.workingDir.getAbsolutePath() + "'.", e); } String newRevision = getLocalRevision(); if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Update finished successfully. New revision is: " + newRevision); } return newRevision; } @Override public String tag(TagRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Tagging local repository with '" + request.getTagName() + "'"); } if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Tag info:\n"); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- TAG_NAME: ").append(request.getTagName()).append('\n'); message.append("\t- USE_WORKING_COPY: ").append(request.tagFromWorkingCopy()).append('\n'); if (request.tagFromWorkingCopy()) { message.append("\t- COMMIT_BEFORE_TAGGING: ").append(request.commitBeforeTagging()).append('\n'); message.append("\t- MERGE_STRATEGY: ").append(request.getMergeStrategy()); } else { message.append("\t- REMOTE_URL: ").append(request.getRemoteRepositoryUrl()).append('\n'); message.append("\t- REVISION: ").append(request.getRevision()); } this.log.fine(message.toString()); } if (request.tagFromWorkingCopy()) { // 1. commit the changes (no merging because we stay local!) String preTagCommitMessage = request.getPreTagCommitMessage() .or("Preparation for tag creation (Tag name: '" + request.getTagName() + "')."); Builder builder = CommitRequest.builder().message(preTagCommitMessage); if (request.includeUntrackedFiles()) { builder.includeUntrackedFiles(); } commit(builder.build()); try { // 2. tag local revision TagCommand tag = this.git.tag().setName(request.getTagName()).setMessage(request.getMessage()) .setAnnotated(true).setTagger(this.personIdent); tag.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.TAG, "An error occurred during local Git tag creation.", e); } if (!request.commitBeforeTagging()) { try { // 3. deletes the local commit that had been done for tag creation. this.git.reset().setMode(ResetType.MIXED).setRef(Constants.HEAD + "~1").call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.TAG, "An error occurred during local commit resetting (no pre-tag commit was requested).", e); } } String newRevision; String tagPushName = GitUtil.TAG_NAME_PREFIX + request.getTagName(); if (request.push()) { if (request.commitBeforeTagging()) { // if the commit shall be kept, push everything with update of the local WC! PushRequest pr = PushRequest.builder().mergeStrategy(request.getMergeStrategy()) .mergeClient(request.getMergeClient().orNull()).build(); newRevision = push(pr); } else { // if the commit was deleted, just push the tag String localBranchName = this.util.getCurrentBranchName(); String remoteName = this.util.getRemoteName(localBranchName); String connectionUrl = this.util.getConnectionUrlOfRemote(remoteName); try { PushCommand push = this.git.push().setRemote(remoteName).setCredentialsProvider(this.credentialsProvider) .add(tagPushName); push.call(); newRevision = getLatestRemoteRevision(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.PUSH, "Unable to push locally created tag '" + request.getTagName() + "' to remote '" + remoteName + "[" + connectionUrl + "]+'.", e); } } } else { newRevision = getLocalRevision(); } if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Tag creation finished successfully. New revision is: " + newRevision); } return newRevision; } else { // TODO implement tagging from url! // git doesn't support remote tagging but we could clone in bare mode, create the tag, push it and delete the // cloned repo afterwards throw new UnsupportedOperationException( "This SCM provider doesn't support tagging from remote URLs only. This feature needs some workarounds and is scheduled for a later version."); } } @Override public boolean hasTag(String tagName) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Searching for Git tag '" + tagName + "'"); } String localBranchName = this.util.getCurrentBranchName(); String remoteName = this.util.getRemoteName(localBranchName); String remoteUrl = this.util.getConnectionUrlOfRemote(remoteName); if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Query info:\n"); message.append("\t- TAG_NAME: ").append(tagName).append('\n'); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- REMOTE: ").append(remoteName).append('\n'); message.append("\t- REMOTE_URL: ").append(remoteUrl); this.log.fine(message.toString()); } try { LsRemoteCommand lsRemote = this.git.lsRemote().setRemote(remoteName) .setCredentialsProvider(this.credentialsProvider).setTags(true); String tagRefName = GitUtil.TAG_NAME_PREFIX + tagName; for (Ref tag : lsRemote.call()) { if (Objects.equal(tag.getName(), tagRefName)) { return true; } } } catch (GitAPIException e) { throw new ScmException(ScmOperation.INFO, "An error occurred while querying the remote git repository for tag '" + tagName + "'.", e); } return false; } @Override public String deleteTag(DeleteTagRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Deleting Git tag"); } String localBranchName = this.util.getCurrentBranchName(); String remoteName = this.util.getRemoteName(localBranchName); String remoteUrl = this.util.getConnectionUrlOfRemote(remoteName); boolean hasRemoteTag = hasTag(request.getTagName()); // 1. fetch the tag from remote if it is not known locally and the remote one exists if (!this.util.hasLocalTag(request.getTagName()) && hasRemoteTag) { if (this.log.isLoggable(Level.FINE)) { this.log.fine(LOG_PREFIX + "Fetching remote tag"); } try { this.git.fetch().setRemote(remoteName).setTagOpt(TagOpt.FETCH_TAGS) .setCredentialsProvider(this.credentialsProvider).call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.DELETE_TAG, "Unable to fetch tags for deletion of tag '" + request.getTagName() + "' from remote '" + remoteName + "[" + remoteUrl + "]'.", e); } } // proceed only if tag exists locally (if this is not the case at this point, it doesn't exist remotely either) if (this.util.hasLocalTag(request.getTagName())) { if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Tag info:\n"); message.append("\t- TAG_NAME: ").append(request.getTagName()).append('\n'); message.append("\t- REMOTE: ").append(remoteName).append('\n'); message.append("\t- REMOTE_URL: ").append(remoteUrl); this.log.fine(message.toString()); } try { // 2. delete the tag locally DeleteTagCommand deleteTag = this.git.tagDelete().setTags(GitUtil.TAG_NAME_PREFIX + request.getTagName()); deleteTag.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.DELETE_TAG, "An error occurred during the local deletion of tag '" + request.getTagName() + "'.", e); } try { // 3. if the tag exists in the remote repository the remote tag gets either deletet or will be scheduled for // deletion on next push if (hasRemoteTag) { String tagPushName = ":" + GitUtil.TAG_NAME_PREFIX + request.getTagName(); if (request.push()) { PushCommand push = this.git.push().setRemote(remoteName).setCredentialsProvider(this.credentialsProvider) .add(tagPushName); push.call(); } else { this.additionalThingsToPush.add(tagPushName); } } } catch (GitAPIException e) { throw new ScmException(ScmOperation.DELETE_TAG, "An error occurred during the deletion of tag '" + request.getTagName() + "' from remote '" + remoteName + "[" + remoteUrl + "]'.", e); } } return getLatestRemoteRevision(); } @Override public String branch(BranchRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Branching local repository."); } if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Branch info:\n"); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- BRANCH_NAME: ").append(request.getBranchName()).append('\n'); message.append("\t- USE_WORKING_COPY: ").append(request.branchFromWorkingCopy()).append('\n'); if (request.branchFromWorkingCopy()) { message.append("\t- COMMIT_BEFORE_BRANCHING: ").append(request.commitBeforeBranching()).append('\n'); message.append("\t- MERGE_STRATEGY: ").append(request.getMergeStrategy()); } else { message.append("\t- REMOTE_URL: ").append(request.getRemoteRepositoryUrl()).append('\n'); message.append("\t- REVISION: ").append(request.getRevision()); } this.log.fine(message.toString()); } if (request.branchFromWorkingCopy()) { if (this.util.hasLocalBranch(request.getBranchName())) { // QUESTION eventually checkout local branch instead? throw new ScmException(ScmOperation.BRANCH, "A local branch with this name already exists!"); } if (hasBranch(request.getBranchName())) { // QUESTION eventually fetch branch and create a local one tracking this one instead? throw new ScmException(ScmOperation.BRANCH, "A remote branch with this name already exists!"); } // 1. commit the changes if branching from WC is requested(no merging!) if (!request.getRevision().isPresent()) { String preBranchCommitMessage = request.getPreBranchCommitMessage() != null ? request.getPreBranchCommitMessage() : request.getMessage(); CommitRequest cr = CommitRequest.builder().message(preBranchCommitMessage).noMerge().build(); commit(cr); } try { // 2. branch from WC CreateBranchCommand branch = this.git.branchCreate().setName(request.getBranchName()) .setUpstreamMode(SetupUpstreamMode.TRACK).setStartPoint(request.getRevision().or(Constants.HEAD)); branch.call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.BRANCH, "Could not create local branch '" + request.getBranchName() + "' in working copy '" + this.workingDir.getAbsolutePath() + "'", e); } // 3. deletes the local commit that had been done for branch creation. if (!request.commitBeforeBranching()) { try { this.git.reset().setMode(ResetType.MIXED).setRef(Constants.HEAD + "~1").call(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.BRANCH, "An error occurred during local commit resetting (no pre-branch commit was requested).", e); } } String branchPushName = GitUtil.HEADS_NAME_PREFIX + request.getBranchName(); String newRevision; if (request.push()) { if (request.commitBeforeBranching()) { // if the commit shall be kept, push everything with update of the local WC! PushRequest pr = PushRequest.builder().mergeStrategy(request.getMergeStrategy()) .mergeClient(request.getMergeClient().orNull()).build(); newRevision = push(pr); } else { String localBranchName = this.util.getCurrentBranchName(); String remoteName = this.util.getRemoteName(localBranchName); String connectionUrl = this.util.getConnectionUrlOfRemote(remoteName); try { PushCommand push = this.git.push().setRemote(remoteName).setCredentialsProvider(this.credentialsProvider) .add(branchPushName); push.call(); newRevision = getLatestRemoteRevision(); } catch (GitAPIException e) { throw new ScmException(ScmOperation.PUSH, "Unable to push locally created branch '" + request.getBranchName() + "' to remote '" + remoteName + "[" + connectionUrl + "]+'.", e); } } } else { newRevision = getLocalRevision(); } if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Branch creation finished successfully. New revision is: " + newRevision); } return newRevision; } else { // TODO implement remote branching -> similar to remote tagging! throw new UnsupportedOperationException( "This SCM provider doesn't support tagging from remote URLs only. This feature needs some workarounds and is scheduled for a later version."); } } @Override public boolean hasBranch(String branchName) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Searching for Git branch"); } String localBranchName = this.util.getCurrentBranchName(); String remoteName = this.util.getRemoteName(localBranchName); String remoteUrl = this.util.getConnectionUrlOfRemote(remoteName); if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Query info:\n"); message.append("\t- BRANCH_NAME: ").append(branchName).append('\n'); message.append("\t- WORKING_DIR: ").append(this.workingDir.getAbsolutePath()).append('\n'); message.append("\t- REMOTE: ").append(remoteName).append('\n'); message.append("\t- REMOTE_URL: ").append(remoteUrl); this.log.fine(message.toString()); } try { LsRemoteCommand lsRemote = this.git.lsRemote().setRemote(remoteName) .setCredentialsProvider(this.credentialsProvider).setHeads(true); Collection<Ref> branches = lsRemote.call(); for (Ref branch : branches) { if (Objects.equal(branch.getName(), GitUtil.HEADS_NAME_PREFIX + branchName)) { return true; } } } catch (GitAPIException e) { throw new ScmException(ScmOperation.INFO, "An error occurred while querying the remote git repository for branch '" + branchName + "'.", e); } return false; } @Override public String deleteBranch(DeleteBranchRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Deleting Git branch"); } String localBranchName = this.util.getCurrentBranchName(); String remoteName = this.util.getRemoteName(localBranchName); String remoteUrl = this.util.getConnectionUrlOfRemote(remoteName); if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Branch info:\n"); message.append("\t- TAG_NAME: ").append(request.getBranchName()).append('\n'); message.append("\t- REMOTE: ").append(remoteName).append('\n'); message.append("\t- REMOTE_URL: ").append(remoteUrl); this.log.fine(message.toString()); } if (this.util.hasLocalBranch(request.getBranchName())) { try { this.git.branchDelete().setBranchNames(GitUtil.HEADS_NAME_PREFIX + request.getBranchName()).setForce(true) .call(); } catch (GitAPIException e) { e.printStackTrace(); } } if (hasBranch(request.getBranchName())) { if (request.push()) { try { this.git.push().setCredentialsProvider(this.credentialsProvider).setRemote(remoteName) .add(":" + GitUtil.HEADS_NAME_PREFIX + request.getBranchName()).call(); } catch (GitAPIException e) { e.printStackTrace(); } } else { this.additionalThingsToPush.add(":" + GitUtil.HEADS_NAME_PREFIX + request.getBranchName()); } } return getLatestRemoteRevision(); } @Override public String revertCommits(RevertCommitsRequest request) throws ScmException { if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Reverting Git commits"); } if (this.log.isLoggable(Level.FINE)) { StringBuilder message = new StringBuilder(LOG_PREFIX).append("Commit info:\n"); message.append("\t- FROM: ").append(request.getFromRevision()).append('\n'); message.append("\t- TO: ").append(request.getToRevision()).append('\n'); message.append("\t- MERGE_STRATEGY: ").append(request.getMergeStrategy()).append('\n'); this.log.fine(message.toString()); } // update to HEAD revision first then revert commits! UpdateRequest updateRequest = UpdateRequest.builder().mergeStrategy(request.getMergeStrategy()) .mergeClient(request.getMergeClient().orNull()).build(); update(updateRequest); RevCommit from = this.util.resolveCommit(Optional.of(request.getFromRevision()), Optional.<String> absent()); RevCommit to = this.util.resolveCommit(Optional.of(request.getToRevision()), Optional.<String> absent()); int diff = from.getCommitTime() - to.getCommitTime(); if (diff == 0) { // nothing to revert! return the latest remote version return getLatestRemoteRevision(); } else if (diff < 0) { // older from version (wrong direction! throw new ScmException(ScmOperation.REVERT_COMMITS, "Error reverting commits in remote repository. \"FROM\" revision (" + request.getFromRevision() + ") is older than \"TO\" revision (" + request.getToRevision() + ")"); } try { RevertCommand revert = this.git.revert(); List<RevCommit> commitsToRevert = this.util.resolveCommitRange(request.getToRevision(), request.getFromRevision()); for (RevCommit commit : commitsToRevert) { revert.include(commit); } switch (request.getMergeStrategy()) { case USE_LOCAL: revert.setStrategy(MergeStrategy.OURS); break; case USE_REMOTE: revert.setStrategy(MergeStrategy.THEIRS); break; case FULL_MERGE: revert.setStrategy(new UnleashGitFullMergeStrategy(request.getMergeClient().get())); break; case DO_NOT_MERGE: // nothing to do here! break; default: throw new UnsupportedOperationException( "Unknown merge strategy! API and implementation versions are incompatible!"); } revert.call(); } catch (Exception e) { throw new ScmException(ScmOperation.REVERT_COMMITS, "An error occurred during the reversion of commits.", e); } String newRevision; if (request.push()) { PushRequest pr = PushRequest.builder().mergeStrategy(request.getMergeStrategy()) .mergeClient(request.getMergeClient().orNull()).build(); newRevision = push(pr); } else { newRevision = getLocalRevision(); } if (this.log.isLoggable(Level.INFO)) { this.log.info(LOG_PREFIX + "Revert finished successfully. New revision is: " + newRevision); } return newRevision; } @Override public String getLocalRevision() { try { RevCommit revCommit = this.git.log().call().iterator().next(); return revCommit.getName(); } catch (GitAPIException e) { throw new IllegalStateException("Could not determine the last revision commit of the local repository.", e); } } @Override public String getLatestRemoteRevision() { try { String localBranchName = this.util.getCurrentBranchName(); String remoteName = this.util.getRemoteBranchName(localBranchName); Collection<Ref> branches = this.git.lsRemote().setCredentialsProvider(this.credentialsProvider).setHeads(true) .call(); for (Ref branch : branches) { if (Objects.equal(branch.getTarget().getName(), remoteName)) { return branch.getObjectId().getName(); } } } catch (Exception e) { e.printStackTrace(); } return ""; } @Override public String calculateTagConnectionString(String currentConnectionString, String tagName) { // connection string only points to the git dir and branches/tags have to be specified and checked out separately return currentConnectionString; } @Override public String calculateBranchConnectionString(String currentConnectionString, String branchName) { // connection string only points to the git dir and branches/tags have to be specified and checked out separately return currentConnectionString; } @Override public boolean isTagInfoIncludedInConnection() { // connection string only points to the git dir and branches/tags have to be specified and checked out separately return false; } @Override // TODO logging! public HistoryResult getHistory(HistoryRequest request) throws ScmException { HistoryResult.Builder historyBuilder = HistoryResult.builder(); if (request.getRemoteRepositoryUrl().isPresent()) { throw new ScmException(ScmOperation.INFO, "Remote history retrieval is not supported by Git!"); } try { LogCommand logCommand = this.git.log(); if (request.getMessageFilters().isEmpty()) { // set the limit of commits to be retrieved only if no filters are provided since the user wants to see the // specified number of commits but some could be filtered out logCommand.setMaxCount((int) request.getMaxResults()); } AnyObjectId startId = getTagRevisionOrDefault(request.getStartTag(), request.getStartRevision().orNull()); AnyObjectId endId = getTagRevisionOrDefault(request.getEndTag(), request.getEndRevision().or(this.git.getRepository().resolve("HEAD").name())); if (startId != null && endId != null) { logCommand.addRange(startId, endId); } else if (startId != null) { logCommand.add(startId); } else if (endId != null) { logCommand.add(endId); } Set<String> messageFilterPatterns = request.getMessageFilters(); int commitsAdded = 0; for (RevCommit revCommit : logCommand.call()) { if (commitsAdded == request.getMaxResults()) { break; } if (isFilteredMessage(revCommit.getShortMessage(), messageFilterPatterns)) { continue; } HistoryCommit.Builder b = HistoryCommit.builder(); b.setRevision(revCommit.getId().name()); b.setMessage(revCommit.getShortMessage()); PersonIdent authorIdent = revCommit.getAuthorIdent(); b.setAuthor(authorIdent.getName()); b.setDate(authorIdent.getWhen()); historyBuilder.addCommit(b.build()); commitsAdded++; } } catch (Exception e) { throw new ScmException(ScmOperation.INFO, "Unable to retrieve the Git log history.", e); } return historyBuilder.build(); } private boolean isFilteredMessage(String message, Set<String> messageFilterPatterns) { for (String filter : messageFilterPatterns) { if (message.matches(filter)) { return true; } } return false; } private AnyObjectId getTagRevisionOrDefault(Optional<String> tag, String defaultRevision) { if (tag.isPresent()) { try { String tagName = GitUtil.TAG_NAME_PREFIX + tag.get(); for (Ref ref : this.git.tagList().call()) { if (Objects.equal(tagName, ref.getName())) { Ref peeledRef = this.git.getRepository().peel(ref); return MoreObjects.firstNonNull(peeledRef.getPeeledObjectId(), peeledRef.getObjectId()); } } throw new ScmException(ScmOperation.INFO, "Could not find a tag with name " + tag.get()); } catch (Exception e) { throw new ScmException(ScmOperation.INFO, "Unable to get the revision of the following tag: " + tag.get(), e); } } return defaultRevision != null ? ObjectId.fromString(defaultRevision) : null; } }
package com.jvm_bloggers.core.data_fetching.blogs; import com.jvm_bloggers.core.data_fetching.blogs.json_data.BloggerEntry; import com.jvm_bloggers.core.data_fetching.blogs.json_data.BloggersData; import com.jvm_bloggers.core.rss.SyndFeedProducer; import com.jvm_bloggers.entities.blog.Blog; import com.jvm_bloggers.entities.blog.BlogRepository; import com.jvm_bloggers.utils.NowProvider; import io.vavr.control.Option; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import static com.jvm_bloggers.entities.blog.BlogType.PERSONAL; @Component @Slf4j @RequiredArgsConstructor public class BloggersDataUpdater { private final BlogRepository blogRepository; private final NowProvider nowProvider; private final SyndFeedProducer syndFeedFactory; private final BloggerChangedVerifier bloggerChangedVerifier; public UpdateStatistic updateData(BloggersData data) { return data.getBloggers() .parallelStream() .filter(BloggerEntry::hasRss) .map(this::updateSingleEntry) .collect(UpdateStatistic.collector()); } private UpdateStatus updateSingleEntry(BloggerEntry bloggerEntry) { log.info("Parsing blogger entry {}", bloggerEntry.getBookmarkableId()); try { return blogRepository .findByBookmarkableId(bloggerEntry.getBookmarkableId()) .map(bloggerWithSameId -> updateBloggerIfThereAreAnyChanges(bloggerEntry, bloggerWithSameId)) .getOrElse(() -> createNewBlogger(bloggerEntry)); } catch (Exception ex) { log.warn("Problem when parsing blogger entry " + bloggerEntry.getBookmarkableId(), ex); return UpdateStatus.INVALID; } } private UpdateStatus updateBloggerIfThereAreAnyChanges(BloggerEntry bloggerEntry, Blog existingBlogger) { Option<String> validBlogUrl = extractValidBlogUrlFromFeed(bloggerEntry.getRss()); validBlogUrl.forEach(bloggerEntry::setUrl); if (bloggerChangedVerifier.pendingChanges(existingBlogger, bloggerEntry)) { existingBlogger.setBookmarkableId(bloggerEntry.getBookmarkableId()); existingBlogger.setAuthor(bloggerEntry.getName()); existingBlogger.setTwitter(bloggerEntry.getTwitter()); existingBlogger.setRss(bloggerEntry.getRss()); existingBlogger.setBlogType(bloggerEntry.getBlogType()); if (StringUtils.isNotBlank(bloggerEntry.getUrl())) { existingBlogger.setUrl(bloggerEntry.getUrl()); } blogRepository.save(existingBlogger); return UpdateStatus.UPDATED; } else { return UpdateStatus.NOT_CHANGED; } } private Option<String> extractValidBlogUrlFromFeed(String rss) { return syndFeedFactory.validUrlFromRss(rss); } private UpdateStatus createNewBlogger(BloggerEntry bloggerEntry) { Option<String> validBlogUrl = extractValidBlogUrlFromFeed(bloggerEntry.getRss()); if (validBlogUrl.isEmpty()) { log.warn("No url found for blog {}, Skipping", bloggerEntry.getRss()); return UpdateStatus.INVALID; } validBlogUrl.forEach(bloggerEntry::setUrl); Blog newBlog = Blog.builder() .bookmarkableId(bloggerEntry.getBookmarkableId()) .author(bloggerEntry.getName()) .rss(bloggerEntry.getRss()) .url(syndFeedFactory.validUrlFromRss( bloggerEntry.getRss()).getOrElse(() -> null) ) .twitter(bloggerEntry.getTwitter()) .url(bloggerEntry.getUrl()) .dateAdded(nowProvider.now()) .blogType(bloggerEntry.getBlogType()) .active(true) .moderationRequired(isModerationRequired(bloggerEntry)) .build(); blogRepository.save(newBlog); log.info("Added new blog: {} | {} | {}", newBlog.getAuthor(), newBlog.getBookmarkableId(), newBlog.getUrl()); return UpdateStatus.CREATED; } private boolean isModerationRequired(BloggerEntry bloggerEntry) { return bloggerEntry.getBlogType() != PERSONAL || bloggerEntry.getRss() != null && bloggerEntry.getRss().contains("//medium.com"); } }
package com.linkedpipes.etl.convert.uv.configuration; import com.linkedpipes.etl.convert.uv.pipeline.LpPipeline; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.openrdf.model.IRI; import org.openrdf.model.Statement; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.SimpleValueFactory; import org.openrdf.model.vocabulary.RDF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @XStreamAlias("cz.cuni.mff.xrg.uv.transformer.tabular.TabularConfig_V2") class TabularConfig_V2 implements Configuration { static final Logger LOG = LoggerFactory.getLogger(TabularConfig_V2.class); @XStreamAlias("cz.cuni.mff.xrg.uv.transformer.tabular.parser.ParserType") enum ParserType { CSV, DBF, XLS } @XStreamAlias("eu.unifiedviews.plugins.transformer.tabular.column.ColumnType") enum ColumnType { String, Integer, Long, Double, Float, Date, Boolean, gYear, Decimal, Auto } @XStreamAlias("cz.cuni.mff.xrg.uv.transformer.tabular.column.ColumnInfo_V1") static class ColumnInfo_V1 { String URI = null; ColumnType type = ColumnType.Auto; Boolean useTypeFromDfb = null; String language = null; ColumnInfo_V1() { } ColumnInfo_V1(String URI, ColumnType type) { this.URI = URI; this.type = type; } ColumnInfo_V1(String URI) { this.URI = URI; } } @XStreamAlias("cz.cuni.mff.xrg.uv.transformer.tabular.column.NamedCell_V1") static class NamedCell_V1 { String name = "A0"; Integer rowNumber = 0; Integer columnNumber = 0; NamedCell_V1() { } } @XStreamAlias("cz.cuni.mff.xrg.uv.transformer.tabular.TabularConfig_V2$AdvanceMapping") static class AdvanceMapping { String uri = ""; String template = ""; AdvanceMapping() { } AdvanceMapping(String uri, String template) { this.uri = uri; this.template = template; } } private String keyColumn = null; private String baseURI = "http://localhost"; private Map<String, ColumnInfo_V1> columnsInfo = new LinkedHashMap<>(); private List<AdvanceMapping> columnsInfoAdv = new LinkedList<>(); private List<NamedCell_V1> namedCells = new LinkedList<>(); private String quoteChar = "\""; private String delimiterChar = ","; private Integer linesToIgnore = 0; private String encoding = "UTF-8"; private Integer rowsLimit = null; private ParserType tableType = ParserType.CSV; private boolean hasHeader = true; private boolean generateNew = true; private boolean ignoreBlankCells = false; private boolean advancedKeyColumn = false; private String rowsClass = "http://unifiedviews.eu/ontology/t-tabular/Row"; private String xlsSheetName = null; private boolean staticRowCounter = false; private boolean generateRowTriple = true; private boolean useTableSubject = false; private boolean autoAsStrings = false; private boolean generateTableClass = false; private boolean generateLabels = false; private boolean stripHeader = false; private boolean dbfTrimString = false; private boolean xlsAdvancedDoubleParser = false; private boolean ignoreMissingColumn = false; @Override public void update(LpPipeline pipeline, LpPipeline.Component component, boolean asTemplate) { pipeline.renameInPort(component, "table", "InputFiles"); pipeline.renameOutPort(component, "triplifiedTable", "OutputRdf"); component.setTemplate("http://etl.linkedpipes.com/resources/components/t-tabularUv/0.0.0"); final ValueFactory vf = SimpleValueFactory.getInstance(); final List<Statement> st = new ArrayList<>(); Integer counter = 0; final IRI configResource = vf.createIRI("http://localhost/resources/configuration/t-tabularUv"); st.add(vf.createStatement( configResource, RDF.TYPE, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#Configuration"))); if (keyColumn != null) { st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#keyColumn"), vf.createLiteral(keyColumn))); } st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#baseUri"), vf.createLiteral(baseURI))); // columnsInfo for (Map.Entry<String, ColumnInfo_V1> item : columnsInfo.entrySet()) { IRI iri = vf.createIRI("http://localhost/resources/configuration/t-tabularUv/column_" + (++counter)); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#column"), iri)); st.add(vf.createStatement(iri, RDF.TYPE, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#ColumnInfo"))); final ColumnInfo_V1 itemValue = item.getValue(); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#name"), vf.createLiteral(item.getKey()))); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#uri"), vf.createLiteral(itemValue.URI))); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#type"), vf.createLiteral(itemValue.type.toString()))); if (itemValue.useTypeFromDfb != null) { st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#typeFromDbf"), vf.createLiteral(itemValue.useTypeFromDfb))); } if (itemValue.language != null) { st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#lang"), vf.createLiteral(itemValue.language))); } } // columnsInfoAdv for (AdvanceMapping item : columnsInfoAdv) { IRI iri = vf.createIRI("http://localhost/resources/configuration/t-tabularUv/advanced_" + (++counter)); st.add(vf.createStatement(configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#advancedMapping"), iri)); st.add(vf.createStatement(iri, RDF.TYPE, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#AdvancedMapping"))); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#uri"), vf.createLiteral(item.uri))); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#template"), vf.createLiteral(item.template))); } // namedCells for (NamedCell_V1 item : namedCells) { IRI iri = vf.createIRI("http://localhost/resources/configuration/t-tabularUv/named_" + (++counter)); st.add(vf.createStatement(configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#namedCell"), iri)); st.add(vf.createStatement(iri, RDF.TYPE, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#NamedCell"))); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#name"), vf.createLiteral(item.name))); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#rowNumber"), vf.createLiteral(item.rowNumber))); st.add(vf.createStatement(iri, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#columnNumber"), vf.createLiteral(item.columnNumber))); } st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#quote"), vf.createLiteral(quoteChar))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#delimeter"), vf.createLiteral(delimiterChar))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#linesToIgnore"), vf.createLiteral(linesToIgnore))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#encoding"), vf.createLiteral(encoding))); if (rowsLimit != null) { st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#rowsLimit"), vf.createLiteral(rowsLimit))); } st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#tableType"), vf.createLiteral(tableType.toString()))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#hasHeader"), vf.createLiteral(hasHeader))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#generateNew"), vf.createLiteral(generateNew))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#ignoreBlankCell"), vf.createLiteral(ignoreBlankCells))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#advancedKey"), vf.createLiteral(advancedKeyColumn))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#rowClass"), vf.createLiteral(rowsClass))); if (xlsSheetName != null) { st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#xlsSheetName"), vf.createLiteral(xlsSheetName))); } st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#staticRowCounter"), vf.createLiteral(staticRowCounter))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#rowTriple"), vf.createLiteral(generateRowTriple))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#useTableSubject"), vf.createLiteral(useTableSubject))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#autoAsString"), vf.createLiteral(autoAsStrings))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#tableClass"), vf.createLiteral(generateTableClass))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#generateLabels"), vf.createLiteral(generateLabels))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#stripHeader"), vf.createLiteral(stripHeader))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#trimString"), vf.createLiteral(dbfTrimString))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#xlsAdvancedParser"), vf.createLiteral(xlsAdvancedDoubleParser))); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#ignoreMissingColumn"), vf.createLiteral(ignoreMissingColumn))); if (asTemplate) { final IRI force = vf.createIRI( "http://plugins.linkedpipes.com/resource/configuration/Force"); st.add(vf.createStatement( configResource, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-tabularUv#control"), force)); } component.setLpConfiguration(st); // Insert t-graphMerger and reconnect edges. final LpPipeline.Component merger = new LpPipeline.Component( "rdf-graph-merger", "[I]", component); merger.setTemplate("http://etl.linkedpipes.com/resources/components/t-graphMerger/0.0.0"); pipeline.insertComponent(merger, 0, 60); pipeline.reconnectOutput(component, "OutputRdf", merger, "OutputRdf"); pipeline.addDataConnection(component, "OutputRdf", merger, "InputRdf"); } }
package com.skelril.skree.content.registry.item.zone; import com.google.common.collect.Lists; import com.skelril.skree.service.PlayerStateService; import com.skelril.skree.service.internal.playerstate.InventoryStorageStateException; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.projectile.Snowball; import org.spongepowered.api.entity.projectile.source.ProjectileSource; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.event.entity.CollideEntityEvent; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.chat.ChatTypes; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import java.util.*; import java.util.function.Supplier; import static com.skelril.nitro.item.ItemStackFactory.newItemStack; public class ZoneWaitingLobby { private Map<Player, Integer> playingPlayers = new WeakHashMap<>(); private Supplier<Location<World>> entryPointSupplier; public ZoneWaitingLobby(Supplier<Location<World>> entryPointSupplier) { this.entryPointSupplier = entryPointSupplier; } public void add(Player player) { Optional<PlayerStateService> optService = Sponge.getServiceManager().provide(PlayerStateService.class); if (optService.isPresent()) { PlayerStateService service = optService.get(); try { service.storeInventory(player); service.releaseInventory(player); player.getInventory().clear(); player.getInventory().offer(newItemStack(ItemTypes.COOKED_BEEF, 64)); } catch (InventoryStorageStateException e) { e.printStackTrace(); } } player.setLocation(entryPointSupplier.get()); player.sendMessage(Text.of(TextColors.YELLOW, "Your instance is building...")); player.sendMessage(Text.of(TextColors.YELLOW, "You will automatically be teleported when it's finished.")); player.sendMessage(Text.of(TextColors.YELLOW, "For now have a snowball fight!")); playingPlayers.put(player, 0); } public void remove(Collection<Player> players) { HashMap<Player, Integer> localCounts = new HashMap<>(); for (Player player : players) { localCounts.put(player, playingPlayers.remove(player)); } boolean hasSnowballs = false; for (int value : localCounts.values()) { if (value > 0) { hasSnowballs = true; break; } } List<Text> endMessage = new ArrayList<>(); if (hasSnowballs) { List<Map.Entry<Player, Integer>> results = Lists.newArrayList(localCounts.entrySet()); results.sort((a, b) -> b.getValue() - a.getValue()); endMessage.add(Text.of(TextColors.GOLD, "Top Snowball Fight Scores: ")); for (int i = 0; i < Math.min(results.size(), 3); ++i) { Map.Entry<Player, Integer> playerScore = results.get(i); endMessage.add(Text.of(TextColors.YELLOW, i + 1, ") ", playerScore.getKey().getName(), " - ", playerScore.getValue())); } } players.stream().forEach(p -> { if (!endMessage.isEmpty()) { p.sendMessages(endMessage); } restoreInventory(p); }); } private void restoreInventory(Player player) { Optional<PlayerStateService> optService = Sponge.getServiceManager().provide(PlayerStateService.class); if (optService.isPresent()) { PlayerStateService service = optService.get(); if (service.hasInventoryStored(player)) { try { service.loadInventory(player); } catch (InventoryStorageStateException e) { e.printStackTrace(); } } } } public boolean contains(Player player) { return playingPlayers.containsKey(player); } @Listener public void onBlockInteract(InteractBlockEvent event) { Optional<Player> optPlayer = event.getCause().first(Player.class); if (optPlayer.isPresent()) { Player player = optPlayer.get(); BlockType type = event.getTargetBlock().getState().getType(); if (type == BlockTypes.SNOW_LAYER && contains(player)) { player.getInventory().offer(newItemStack(ItemTypes.SNOWBALL, 16)); } } } @Listener public void onSnowballHit(CollideEntityEvent.Impact event) { Entity entity = event.getCause().first(Entity.class).get(); if (!(entity instanceof Snowball)) { return; } ProjectileSource source = ((Snowball) entity).getShooter(); if (!(source instanceof Player)) { return; } Player attacker = (Player) source; for (Entity anEntity : event.getEntities()) { if (anEntity instanceof Player) { Player defender = (Player) anEntity; playingPlayers.merge(attacker, 1, (a, b) -> a + b); attacker.sendMessage(ChatTypes.ACTION_BAR, Text.of("Total score: ", playingPlayers.get(attacker))); playingPlayers.merge(defender, 1, (a, b) -> Math.max(0, a - b)); defender.sendMessage(ChatTypes.ACTION_BAR, Text.of("Total score: ", playingPlayers.get(defender))); } } } }
package crate.elasticsearch.action.searchinto.parser; import crate.elasticsearch.action.searchinto.SearchIntoContext; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.fetch.FetchPhase; import org.elasticsearch.search.fetch.explain.ExplainParseElement; import org.elasticsearch.search.query.QueryPhase; import java.util.HashMap; import java.util.Map; /** * Parser for payload given to _export action. */ public class SearchIntoParser { private final ImmutableMap<String, SearchParseElement> elementParsers; @Inject public SearchIntoParser(QueryPhase queryPhase, FetchPhase fetchPhase) { Map<String, SearchParseElement> elementParsers = new HashMap<String, SearchParseElement>(); elementParsers.putAll(queryPhase.parseElements()); elementParsers.put("fields", new FieldsParseElement()); elementParsers.put("explain", new ExplainParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } /** * validate given payload * * @param context */ private void validate(SearchIntoContext context) { if (!context.hasFieldNames()) { throw new SearchParseException(context, "No fields defined"); } for (String field : context.fieldNames()) { FieldMapper mapper = context.mapperService().smartNameFieldMapper( field); if (mapper == null && !field.equals( "_version") && !field.startsWith( FieldsParseElement.SCRIPT_FIELD_PREFIX)) { throw new SearchParseException(context, "SearchInto field [" + field + "] does not exist in " + "the mapping"); } } } /** * Main method of this class to parse given payload of _export action * * @param context * @param source * @throws org.elasticsearch.search.SearchParseException * */ public void parseSource(SearchIntoContext context, BytesReference source) throws SearchParseException { XContentParser parser = null; try { if (source != null) { parser = XContentFactory.xContent(source).createParser(source); XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token .END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { String fieldName = parser.currentName(); parser.nextToken(); SearchParseElement element = elementParsers.get( fieldName); if (element == null) { throw new SearchParseException(context, "No parser for element [" + fieldName + "]"); } element.parse(parser, context); } else if (token == null) { break; } } } validate(context); } catch (Exception e) { String sSource = "_na_"; try { sSource = XContentHelper.convertToJson(source, false); } catch (Throwable e1) { // ignore } throw new SearchParseException(context, "Failed to parse source [" + sSource + "]", e); } finally { if (parser != null) { parser.close(); } } } }
package fi.otavanopisto.kuntaapi.server.controllers; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Instance; import javax.inject.Inject; import fi.otavanopisto.kuntaapi.server.id.ElectronicServiceChannelId; import fi.otavanopisto.kuntaapi.server.id.OrganizationId; import fi.otavanopisto.kuntaapi.server.id.PhoneServiceChannelId; import fi.otavanopisto.kuntaapi.server.id.PrintableFormServiceChannelId; import fi.otavanopisto.kuntaapi.server.id.ServiceId; import fi.otavanopisto.kuntaapi.server.id.ServiceLocationServiceChannelId; import fi.otavanopisto.kuntaapi.server.id.WebPageServiceChannelId; import fi.otavanopisto.kuntaapi.server.index.SearchResult; import fi.otavanopisto.kuntaapi.server.index.ServiceSearcher; import fi.otavanopisto.kuntaapi.server.integrations.ServiceChannelProvider; import fi.otavanopisto.kuntaapi.server.integrations.ServiceProvider; import fi.otavanopisto.kuntaapi.server.utils.ListUtils; import fi.metatavu.kuntaapi.server.rest.model.ElectronicServiceChannel; import fi.metatavu.kuntaapi.server.rest.model.PhoneServiceChannel; import fi.metatavu.kuntaapi.server.rest.model.PrintableFormServiceChannel; import fi.metatavu.kuntaapi.server.rest.model.Service; import fi.metatavu.kuntaapi.server.rest.model.ServiceLocationServiceChannel; import fi.metatavu.kuntaapi.server.rest.model.WebPageServiceChannel; @ApplicationScoped @SuppressWarnings ("squid:S3306") public class ServiceController { @Inject private EntityController entityController; @Inject private ServiceSearcher serviceSearcher; @Inject private Instance<ServiceProvider> serviceProviders; @Inject private Instance<ServiceChannelProvider> serviceChannelProviders; public Service findService(ServiceId serviceId) { for (ServiceProvider serviceProvider : getServiceProviders()) { Service service = serviceProvider.findService(serviceId); if (service != null) { return service; } } return null; } public List<Service> listServices(OrganizationId organizationId, Long firstResult, Long maxResults) { List<Service> result = new ArrayList<>(); for (ServiceProvider serviceProvider : getServiceProviders()) { result.addAll(serviceProvider.listServices(organizationId)); } return ListUtils.limit(entityController.sortEntitiesInNaturalOrder(result), firstResult, maxResults); } public List<Service> searchServices(OrganizationId organizationId, String search, Long firstResult, Long maxResults) { SearchResult<ServiceId> searchResult = serviceSearcher.searchServices(organizationId, search, firstResult, maxResults); if (searchResult != null) { List<Service> result = new ArrayList<>(searchResult.getResult().size()); for (ServiceId serviceId : searchResult.getResult()) { Service service = findService(serviceId); if (service != null) { result.add(service); } } return entityController.sortEntitiesInNaturalOrder(result); } return Collections.emptyList(); } public ElectronicServiceChannel findElectronicServiceChannel(ElectronicServiceChannelId electronicChannelId) { for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { ElectronicServiceChannel electronicChannel = serviceChannelProvider.findElectronicServiceChannel(electronicChannelId); if (electronicChannel != null) { return electronicChannel; } } return null; } public PhoneServiceChannel findPhoneServiceChannel(PhoneServiceChannelId phoneChannelId) { for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { PhoneServiceChannel phoneChannel = serviceChannelProvider.findPhoneServiceChannel(phoneChannelId); if (phoneChannel != null) { return phoneChannel; } } return null; } public PrintableFormServiceChannel findPrintableFormServiceChannel(PrintableFormServiceChannelId printableFormChannelId) { for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { PrintableFormServiceChannel printableFormChannel = serviceChannelProvider.findPrintableFormServiceChannel(printableFormChannelId); if (printableFormChannel != null) { return printableFormChannel; } } return null; } public ServiceLocationServiceChannel findServiceLocationServiceChannel(ServiceLocationServiceChannelId serviceLocationChannelId) { for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { ServiceLocationServiceChannel serviceLocationChannel = serviceChannelProvider.findServiceLocationServiceChannel(serviceLocationChannelId); if (serviceLocationChannel != null) { return serviceLocationChannel; } } return null; } public WebPageServiceChannel findWebPageServiceChannel(WebPageServiceChannelId webPageChannelId) { for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { WebPageServiceChannel webPageChannel = serviceChannelProvider.findWebPageServiceChannelChannel(webPageChannelId); if (webPageChannel != null) { return webPageChannel; } } return null; } public List<ElectronicServiceChannel> listElectronicServiceChannels(Long firstResult, Long maxResults) { List<ElectronicServiceChannel> result = new ArrayList<>(); for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { result.addAll(serviceChannelProvider.listElectronicServiceChannels()); } int resultCount = result.size(); int firstIndex = firstResult == null ? 0 : Math.min(firstResult.intValue(), resultCount); int toIndex = maxResults == null ? resultCount : Math.min(firstIndex + maxResults.intValue(), resultCount); return ListUtils.limit(entityController.sortEntitiesInNaturalOrder(result), firstIndex, toIndex); } public List<PhoneServiceChannel> listPhoneServiceChannels(Long firstResult, Long maxResults) { List<PhoneServiceChannel> result = new ArrayList<>(); for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { result.addAll(serviceChannelProvider.listPhoneServiceChannels()); } int resultCount = result.size(); int firstIndex = firstResult == null ? 0 : Math.min(firstResult.intValue(), resultCount); int toIndex = maxResults == null ? resultCount : Math.min(firstIndex + maxResults.intValue(), resultCount); return ListUtils.limit(entityController.sortEntitiesInNaturalOrder(result), firstIndex, toIndex); } public List<PrintableFormServiceChannel> listPrintableFormServiceChannels(Long firstResult, Long maxResults) { List<PrintableFormServiceChannel> result = new ArrayList<>(); for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { result.addAll(serviceChannelProvider.listPrintableFormServiceChannels()); } int resultCount = result.size(); int firstIndex = firstResult == null ? 0 : Math.min(firstResult.intValue(), resultCount); int toIndex = maxResults == null ? resultCount : Math.min(firstIndex + maxResults.intValue(), resultCount); return ListUtils.limit(entityController.sortEntitiesInNaturalOrder(result), firstIndex, toIndex); } public List<ServiceLocationServiceChannel> listServiceLocationServiceChannels(Long firstResult, Long maxResults) { List<ServiceLocationServiceChannel> result = new ArrayList<>(); for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { result.addAll(serviceChannelProvider.listServiceLocationServiceChannels()); } int resultCount = result.size(); int firstIndex = firstResult == null ? 0 : Math.min(firstResult.intValue(), resultCount); int toIndex = maxResults == null ? resultCount : Math.min(firstIndex + maxResults.intValue(), resultCount); return ListUtils.limit(entityController.sortEntitiesInNaturalOrder(result), firstIndex, toIndex); } public List<WebPageServiceChannel> listWebPageServiceChannels(Long firstResult, Long maxResults) { List<WebPageServiceChannel> result = new ArrayList<>(); for (ServiceChannelProvider serviceChannelProvider : getServiceChannelProviders()) { result.addAll(serviceChannelProvider.listWebPageServiceChannelsChannels()); } int resultCount = result.size(); int firstIndex = firstResult == null ? 0 : Math.min(firstResult.intValue(), resultCount); int toIndex = maxResults == null ? resultCount : Math.min(firstIndex + maxResults.intValue(), resultCount); return ListUtils.limit(entityController.sortEntitiesInNaturalOrder(result), firstIndex, toIndex); } private List<ServiceProvider> getServiceProviders() { List<ServiceProvider> result = new ArrayList<>(); Iterator<ServiceProvider> iterator = serviceProviders.iterator(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); } private List<ServiceChannelProvider> getServiceChannelProviders() { List<ServiceChannelProvider> result = new ArrayList<>(); Iterator<ServiceChannelProvider> iterator = serviceChannelProviders.iterator(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); } }
package io.smartcat.cassandra.diagnostics.report; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.aphyr.riemann.client.IRiemannClient; import com.aphyr.riemann.client.RiemannClient; import com.google.inject.Inject; import io.smartcat.cassandra.diagnostics.config.Configuration; /** * A Riemann based {@link QueryReporter} implementation. Query reports are sending towards the configured Riemann server * as Riemann events. */ public class RiemannQueryReporter implements QueryReporter { private static final String HOST_PROP = "riemannHost"; private static final String PORT_PROP = "riemannPort"; private static final String DEFAULT_PORT = "5555"; private static final String SERVICE_NAME_PROP = "riemannServiceName"; private static final String DEFAULT_SERVICE_NAME = "queryReport"; /** * Class logger. */ private static final Logger logger = LoggerFactory.getLogger(RiemannQueryReporter.class); private Configuration config; private String serviceName; private static IRiemannClient riemann; /** * Constructor. * * @param config configuration */ @Inject public RiemannQueryReporter(Configuration config) { this.config = config; } @Override public void report(QueryReport queryReport) { IRiemannClient client = riemannClient(); if (client == null) { logger.warn("Cannot report riemann event without initialized client."); return; } logger.debug("Sending QueryReport: execTime=" + queryReport.executionTimeInMilliseconds); riemannClient().event().service(serviceName).state("ok").metric(queryReport.executionTimeInMilliseconds) .attribute("client", queryReport.clientAddress).attribute("statement", queryReport.statement).ttl(10) .send(); } private IRiemannClient riemannClient() { if (riemann == null) { initRiemannClient(config); serviceName = config.reporterOptions.getOrDefault(SERVICE_NAME_PROP, DEFAULT_SERVICE_NAME); } return riemann; } private static synchronized void initRiemannClient(Configuration config) { if (riemann != null) { logger.debug("Riemann client already initialized"); return; } logger.debug("Initializing riemann client with config: " + config.toString()); if (!config.reporterOptions.containsKey(HOST_PROP)) { logger.warn("Tried to init Riemann client. Not properly configured. Aborting initialization."); return; } String host = config.reporterOptions.get(HOST_PROP); int port = Integer.parseInt(config.reporterOptions.getOrDefault(PORT_PROP, DEFAULT_PORT)); try { riemann = RiemannClient.tcp(host, port); riemann.connect(); } catch (IOException e) { logger.warn("Riemann client cannot be initialized", e); } } }
package org.cyclops.integrateddynamics.core.evaluate; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import org.cyclops.integrateddynamics.api.evaluate.EvaluationException; import org.cyclops.integrateddynamics.api.evaluate.variable.IValue; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueType; import org.cyclops.integrateddynamics.api.evaluate.variable.IValueTypeNumber; import org.cyclops.integrateddynamics.api.evaluate.variable.IVariable; import org.cyclops.integrateddynamics.api.logicprogrammer.IConfigRenderPattern; import org.cyclops.integrateddynamics.core.evaluate.build.OperatorBuilder; import org.cyclops.integrateddynamics.core.evaluate.operator.IterativeFunction; import org.cyclops.integrateddynamics.core.evaluate.operator.OperatorBase; import org.cyclops.integrateddynamics.core.evaluate.variable.*; /** * Collection of operator builders. * @author rubensworks */ public class OperatorBuilders { public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL = OperatorBuilder.forType(ValueTypes.BOOLEAN).appendKind("logical"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL_1_PREFIX = LOGICAL.inputTypes(1, ValueTypes.BOOLEAN).renderPattern(IConfigRenderPattern.PREFIX_1); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LOGICAL_2 = LOGICAL.inputTypes(2, ValueTypes.BOOLEAN).renderPattern(IConfigRenderPattern.INFIX); public static final IOperatorValuePropagator<Integer, IValue> PROPAGATOR_INTEGER_VALUE = new IOperatorValuePropagator<Integer, IValue>() { @Override public IValue getOutput(Integer input) throws EvaluationException { return ValueTypeInteger.ValueInteger.of(input); } }; public static final IOperatorValuePropagator<Boolean, IValue> PROPAGATOR_BOOLEAN_VALUE = new IOperatorValuePropagator<Boolean, IValue>() { @Override public IValue getOutput(Boolean input) throws EvaluationException { return ValueTypeBoolean.ValueBoolean.of(input); } }; public static final IOperatorValuePropagator<Double, IValue> PROPAGATOR_DOUBLE_VALUE = new IOperatorValuePropagator<Double, IValue>() { @Override public IValue getOutput(Double input) throws EvaluationException { return ValueTypeDouble.ValueDouble.of(input); } }; public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC = OperatorBuilder.forType(ValueTypes.CATEGORY_NUMBER).appendKind("arithmetic").conditionalOutputTypeDeriver(new OperatorBuilder.IConditionalOutputTypeDeriver() { @Override public IValueType getConditionalOutputType(OperatorBase operator, IVariable[] input) { IValueType[] original = ValueHelpers.from(input); IValueTypeNumber[] types = new IValueTypeNumber[original.length]; for(int i = 0; i < original.length; i++) { types[i] = (IValueTypeNumber) original[i]; } return ValueTypes.CATEGORY_NUMBER.getLowestType(types); } }); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC_2 = ARITHMETIC.inputTypes(2, ValueTypes.CATEGORY_NUMBER).renderPattern(IConfigRenderPattern.INFIX); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ARITHMETIC_2_PREFIX = ARITHMETIC.inputTypes(2, ValueTypes.CATEGORY_NUMBER).renderPattern(IConfigRenderPattern.PREFIX_2); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER = OperatorBuilder.forType(ValueTypes.INTEGER).appendKind("integer"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER_1_SUFFIX = INTEGER.inputTypes(1, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.SUFFIX_1); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> INTEGER_2 = INTEGER.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> RELATIONAL = OperatorBuilder.forType(ValueTypes.BOOLEAN).appendKind("relational"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> RELATIONAL_2 = RELATIONAL.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY = OperatorBuilder.forType(ValueTypes.INTEGER).appendKind("binary"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY_1_PREFIX = BINARY.inputTypes(1, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.PREFIX_1); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> BINARY_2 = BINARY.inputTypes(2, ValueTypes.INTEGER).renderPattern(IConfigRenderPattern.INFIX); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING = OperatorBuilder.forType(ValueTypes.STRING).appendKind("string"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING_1_PREFIX = STRING.inputTypes(1, ValueTypes.STRING).renderPattern(IConfigRenderPattern.PREFIX_1); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> STRING_2 = STRING.inputTypes(2, ValueTypes.STRING).renderPattern(IConfigRenderPattern.INFIX); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> DOUBLE = OperatorBuilder.forType(ValueTypes.DOUBLE).appendKind("double"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> DOUBLE_1_PREFIX = DOUBLE.inputTypes(1, ValueTypes.DOUBLE).renderPattern(IConfigRenderPattern.PREFIX_1); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LIST = OperatorBuilder.forType(ValueTypes.LIST).appendKind("list"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> LIST_1_PREFIX = LIST.inputTypes(1, ValueTypes.LIST).renderPattern(IConfigRenderPattern.PREFIX_1); public static final OperatorBuilder BLOCK = OperatorBuilder.forType(ValueTypes.OBJECT_BLOCK).appendKind("block"); public static final OperatorBuilder BLOCK_1_SUFFIX_LONG = BLOCK.inputTypes(1, ValueTypes.OBJECT_BLOCK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK = OperatorBuilder.forType(ValueTypes.OBJECT_ITEMSTACK).appendKind("itemstack"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_1_SUFFIX_LONG = ITEMSTACK.inputTypes(1, ValueTypes.OBJECT_ITEMSTACK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ITEMSTACK_2 = ITEMSTACK.inputTypes(2, ValueTypes.OBJECT_ITEMSTACK).renderPattern(IConfigRenderPattern.INFIX); public static final IterativeFunction.PrePostBuilder<ItemStack, IValue> FUNCTION_ITEMSTACK = IterativeFunction.PrePostBuilder.begin() .appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, ItemStack>() { @Override public ItemStack getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException { ValueObjectTypeItemStack.ValueItemStack a = input.getValue(0); return a.getRawValue().isPresent() ? a.getRawValue().get() : null; } }); public static final IterativeFunction.PrePostBuilder<ItemStack, Integer> FUNCTION_ITEMSTACK_TO_INT = FUNCTION_ITEMSTACK.appendPost(PROPAGATOR_INTEGER_VALUE); public static final IterativeFunction.PrePostBuilder<ItemStack, Boolean> FUNCTION_ITEMSTACK_TO_BOOLEAN = FUNCTION_ITEMSTACK.appendPost(PROPAGATOR_BOOLEAN_VALUE); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ENTITY = OperatorBuilder.forType(ValueTypes.OBJECT_ENTITY).appendKind("entity"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> ENTITY_1_SUFFIX_LONG = ENTITY.inputTypes(1, ValueTypes.OBJECT_ENTITY).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG); public static final IterativeFunction.PrePostBuilder<Entity, IValue> FUNCTION_ENTITY = IterativeFunction.PrePostBuilder.begin() .appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, Entity>() { @Override public Entity getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException { ValueObjectTypeEntity.ValueEntity a = input.getValue(0); return a.getRawValue().isPresent() ? a.getRawValue().get() : null; } }); public static final IterativeFunction.PrePostBuilder<Entity, Double> FUNCTION_ENTITY_TO_DOUBLE = FUNCTION_ENTITY.appendPost(PROPAGATOR_DOUBLE_VALUE); public static final IterativeFunction.PrePostBuilder<Entity, Boolean> FUNCTION_ENTITY_TO_BOOLEAN = FUNCTION_ENTITY.appendPost(PROPAGATOR_BOOLEAN_VALUE); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK = OperatorBuilder.forType(ValueTypes.OBJECT_FLUIDSTACK).appendKind("fluidstack"); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK_1_SUFFIX_LONG = FLUIDSTACK.inputTypes(1, ValueTypes.OBJECT_FLUIDSTACK).renderPattern(IConfigRenderPattern.SUFFIX_1_LONG); public static final OperatorBuilder<OperatorBase.SafeVariablesGetter> FLUIDSTACK_2 = FLUIDSTACK.inputTypes(2, ValueTypes.OBJECT_FLUIDSTACK).renderPattern(IConfigRenderPattern.INFIX); public static final IterativeFunction.PrePostBuilder<FluidStack, IValue> FUNCTION_FLUIDSTACK = IterativeFunction.PrePostBuilder.begin() .appendPre(new IOperatorValuePropagator<OperatorBase.SafeVariablesGetter, FluidStack>() { @Override public FluidStack getOutput(OperatorBase.SafeVariablesGetter input) throws EvaluationException { ValueObjectTypeFluidStack.ValueFluidStack a = input.getValue(0); return a.getRawValue().isPresent() ? a.getRawValue().get() : null; } }); public static final IterativeFunction.PrePostBuilder<FluidStack, Integer> FUNCTION_FLUIDSTACK_TO_INT = FUNCTION_FLUIDSTACK.appendPost(PROPAGATOR_INTEGER_VALUE); public static final IterativeFunction.PrePostBuilder<FluidStack, Boolean> FUNCTION_FLUIDSTACK_TO_BOOLEAN = FUNCTION_FLUIDSTACK.appendPost(PROPAGATOR_BOOLEAN_VALUE); }
package org.fxmisc.wellbehaved.event.experimental.internal; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; /** * Prefix tree (Trie) with an additional property that no data is stored in * internal nodes. * * @param <K> type of "strings" used to index values * @param <V> type of values (data) indexed by this trie */ public abstract class PrefixTree<K, V> { public static interface Ops<K, V> { boolean isPrefixOf(K k1, K k2); K commonPrefix(K k1, K k2); V promote(V v, K oldKey, K newKey); V squash(V v1, V v2); } private static class Empty<K, V> extends PrefixTree<K, V> { public Empty(Ops<K, V> ops) { super(ops); } @Override public Stream<Entry<K, V>> entries() { return Stream.empty(); } @Override public PrefixTree<K, V> insert(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine) { return insertInside(key, value, combine); } @Override PrefixTree<K, V> insertInside(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine) { return new Data<>(ops, key, value); } @Override public <W> PrefixTree<K, W> map( Function<? super V, ? extends W> f, Ops<K, W> ops) { return new Empty<>(ops); } } private static abstract class NonEmpty<K, V> extends PrefixTree<K, V> { public NonEmpty(Ops<K, V> ops) { super(ops); } abstract K getPrefix(); abstract Data<K, V> collapse(); @Override public abstract <W> NonEmpty<K, W> map(Function<? super V, ? extends W> f, Ops<K, W> ops); @Override abstract NonEmpty<K, V> insertInside(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine); @Override public PrefixTree<K, V> insert(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine) { if(ops.isPrefixOf(key, getPrefix())) { // key is a prefix of this tree return new Data<>(ops, key, value).insertInside(collapse(), flip(combine)); } else if(ops.isPrefixOf(getPrefix(), key)) { // key is inside this tree return insertInside(key, value, combine); } else { return new Branch<>(ops, this, new Data<>(ops, key, value)); } } } private static class Branch<K, V> extends NonEmpty<K, V> { private final K prefix; private final List<NonEmpty<K, V>> subTrees; Branch(Ops<K, V> ops, K prefix, List<NonEmpty<K, V>> subTrees) { super(ops); assert Objects.equals(prefix, subTrees.stream().map(NonEmpty::getPrefix).reduce(ops::commonPrefix).get()); assert subTrees.stream().noneMatch(tree -> Objects.equals(tree.getPrefix(), prefix)); this.prefix = prefix; this.subTrees = subTrees; } private Branch(Ops<K, V> ops, NonEmpty<K, V> t1, NonEmpty<K, V> t2) { this(ops, ops.commonPrefix(t1.getPrefix(), t2.getPrefix()), Arrays.asList(t1, t2)); } @Override K getPrefix() { return prefix; } @Override public Stream<Entry<K, V>> entries() { return subTrees.stream().flatMap(tree -> tree.entries()); } @Override Data<K, V> collapse() { return subTrees.stream() .map(tree -> tree.collapse().promote(prefix)) .reduce(Data::squash).get(); } @Override NonEmpty<K, V> insertInside(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine) { assert ops.isPrefixOf(prefix, key); if(Objects.equals(key, prefix)) { return new Data<>(ops, key, value).insertInside(collapse(), flip(combine)); } // try to find a sub-tree that has common prefix with key longer than this branch's prefix for(int i = 0; i < subTrees.size(); ++i) { NonEmpty<K, V> st = subTrees.get(i); K commonPrefix = ops.commonPrefix(key, st.getPrefix()); if(!Objects.equals(commonPrefix, prefix)) { if(Objects.equals(commonPrefix, st.getPrefix())) { // st contains key, insert inside st return replaceBranch(i, st.insertInside(key, value, combine)); } else if(Objects.equals(commonPrefix, key)) { // st is under key, insert st inside Data(key, value) return replaceBranch(i, new Data<>(ops, key, value).insertInside(st.collapse(), flip(combine))); } else { return replaceBranch(i, new Branch<>(ops, st, new Data<>(ops, key, value))); } } } // no branch intersects key, adjoin Data(key, value) to this branch List<NonEmpty<K, V>> branches = new ArrayList<>(subTrees.size() + 1); branches.addAll(subTrees); branches.add(new Data<>(ops, key, value)); return new Branch<>(ops, prefix, branches); } private Branch<K, V> replaceBranch(int i, NonEmpty<K, V> replacement) { assert ops.isPrefixOf(prefix, replacement.getPrefix()); assert ops.isPrefixOf(replacement.getPrefix(), subTrees.get(i).getPrefix()); ArrayList<NonEmpty<K, V>> branches = new ArrayList<>(subTrees); branches.set(i, replacement); return new Branch<>(ops, prefix, branches); } @Override public <W> NonEmpty<K, W> map( Function<? super V, ? extends W> f, Ops<K, W> ops) { List<NonEmpty<K, W>> mapped = new ArrayList<>(subTrees.size()); for(NonEmpty<K, V> tree: subTrees) { mapped.add(tree.map(f, ops)); } return new Branch<>(ops, prefix, mapped); } } private static class Data<K, V> extends NonEmpty<K, V> { private final K key; private final V value; Data(Ops<K, V> ops, K key, V value) { super(ops); this.key = key; this.value = value; } @Override K getPrefix() { return key; } @Override public Stream<Entry<K, V>> entries() { return Stream.of(new SimpleEntry<>(key, value)); } @Override Data<K, V> collapse() { return this; } @Override NonEmpty<K, V> insertInside(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine) { assert ops.isPrefixOf(this.key, key); return new Data<>( this.ops, this.key, combine.apply(this.value, ops.promote(value, key, this.key))); } NonEmpty<K, V> insertInside(NonEmpty<K, V> tree, BiFunction<? super V, ? super V, ? extends V> combine) { Data<K, V> d = tree.collapse(); return insertInside(d.key, d.value, combine); } Data<K, V> promote(K key) { assert ops.isPrefixOf(key, this.key); return new Data<>(ops, key, ops.promote(value, this.key, key)); } Data<K, V> squash(Data<K, V> that) { assert Objects.equals(this.key, that.key); return new Data<>(ops, key, ops.squash(this.value, that.value)); } @Override public <W> Data<K, W> map( Function<? super V, ? extends W> f, Ops<K, W> ops) { return new Data<>(ops, key, f.apply(value)); } } public static <K, V> PrefixTree<K, V> empty(Ops<K, V> ops) { return new Empty<>(ops); } private static <A, B, C> BiFunction<B, A, C> flip(BiFunction<A, B, C> f) { return (a, b) -> f.apply(b, a); } final Ops<K, V> ops; private PrefixTree(Ops<K, V> ops) { this.ops = ops; } public abstract Stream<Map.Entry<K, V>> entries(); public abstract PrefixTree<K, V> insert(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine); public abstract <W> PrefixTree<K, W> map(Function<? super V, ? extends W> f, Ops<K, W> ops); public final PrefixTree<K, V> map(Function<? super V, ? extends V> f) { return map(f, ops); } abstract PrefixTree<K, V> insertInside(K key, V value, BiFunction<? super V, ? super V, ? extends V> combine); }
package org.jboss.forge.addon.springboot.commands; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.ws.rs.client.Client; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.projects.ProjectFactory; import org.jboss.forge.addon.projects.facets.MetadataFacet; import org.jboss.forge.addon.resource.DirectoryResource; import org.jboss.forge.addon.rest.ClientFactory; import org.jboss.forge.addon.springboot.dto.SpringBootDependencyDTO; import org.jboss.forge.addon.springboot.utils.CollectionStringBuffer; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UIExecutionContext; import org.jboss.forge.addon.ui.input.UISelectMany; import org.jboss.forge.addon.ui.input.UISelectOne; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.metadata.WithAttributes; import org.jboss.forge.addon.ui.output.UIOutput; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.addon.ui.result.Results; import org.jboss.forge.addon.ui.util.Categories; import org.jboss.forge.addon.ui.util.Commands; import org.jboss.forge.addon.ui.util.Metadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import static org.jboss.forge.addon.maven.archetype.ArchetypeHelper.recursiveDelete; import static org.jboss.forge.addon.springboot.utils.ConvertHelper.jsonToMap; import static org.jboss.forge.addon.springboot.utils.IOHelper.close; import static org.jboss.forge.addon.springboot.utils.IOHelper.copyAndCloseInput; import static org.jboss.forge.addon.springboot.utils.UnzipHelper.unzip; public class SetupProjectCommand extends AbstractSpringBootCommand { private static final transient Logger LOG = LoggerFactory .getLogger(SetupProjectCommand.class); // lets use a different category for this command private static final String CATEGORY = "Spring Boot"; private static String SPRING_BOOT_DEFAULT_VERSION; private static String[] SPRING_BOOT_VERSIONS; private static String SPRING_BOOT_CONFIG_FILE; private static final String STARTER_ZIP_URL = "https://start.spring.io/starter.zip"; private static final String STARTER_URL = "https://start.spring.io"; private UIOutput uiOutput; public SetupProjectCommand() { SPRING_BOOT_DEFAULT_VERSION = System.getenv("SPRING_BOOT_DEFAULT_VERSION") != null ? System.getenv("SPRING_BOOT_DEFAULT_VERSION") : "1.4.1"; SPRING_BOOT_VERSIONS = System.getenv("SPRING_BOOT_VERSIONS") != null ? splitVersions(System.getenv("SPRING_BOOT_VERSIONS")) : new String[] { "1.3.8", "1.4.1", "1.4.3" }; SPRING_BOOT_CONFIG_FILE = System.getenv("SPRING_BOOT_CONFIG_FILE"); } @Inject @WithAttributes(label = "Spring Boot Version", description = "Spring Boot Version to use") private UISelectOne<String> springBootVersion; @Inject @WithAttributes(label = "Dependencies", description = "Add Spring Boot Starters and dependencies to your application") private UISelectMany<SpringBootDependencyDTO> dependencies; @Inject ProjectFactory projectFactory; @Inject private ClientFactory factory; private List<SpringBootDependencyDTO> choices; public static String[] splitVersions(String s) { return s.split(","); } public String getSpringBootDefaultVersion() { return SPRING_BOOT_DEFAULT_VERSION; } public String[] getSpringBootVersions() { return SPRING_BOOT_VERSIONS; } @Override public void initializeUI(UIBuilder builder) throws Exception { uiOutput = builder.getUIContext().getProvider().getOutput(); springBootVersion.setValueChoices(Arrays.asList(SPRING_BOOT_VERSIONS)); springBootVersion.setDefaultValue(SPRING_BOOT_DEFAULT_VERSION); try { choices = initDependencies(); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException( "Error loading dependencies from spring-boot-application.yaml due: " + e.getMessage(), e); } dependencies.setValueChoices(choices); if (builder.getUIContext().getProvider().isGUI()) { dependencies.setItemLabelConverter(SpringBootDependencyDTO::getGroupAndName); } else { // if in CLI mode then use shorter names so they are tab friendly in the shell dependencies.setItemLabelConverter( dto -> Commands.shellifyCommandName(dto.getName())); } dependencies.setValueConverter(s -> { for (SpringBootDependencyDTO dto : choices) { if (dto.getId().equals(s)) { return dto; } } return null; }); builder.add(springBootVersion).add(dependencies); } private List<SpringBootDependencyDTO> initDependencies() throws Exception { List<SpringBootDependencyDTO> list = new ArrayList<>(); for (Object dep : fetchDependencies()) { Map<String,Object> group = (Map) dep; String groupName = group.get("name").toString(); List<Map<String,String>> content; // Add this test as the json file & yaml file uses a different key if (group.get("content") != null) { content = (List) group.get("content"); } else { content = (List) group.get("values"); } for (Object row : content) { Map<String, Object> item = (Map) row; String id = item.get("id").toString(); String name = item.get("name").toString(); String description = item.get("description").toString(); list.add(new SpringBootDependencyDTO(groupName, id, name, description)); } } return list; } @Override protected boolean isProjectRequired() { return false; } @Override public UICommandMetadata getMetadata(UIContext context) { return Metadata.from(super.getMetadata(context), getClass()) .category(Categories.create(CATEGORY)).name(CATEGORY + ": Setup") .description("Create a new Spring Boot project"); } @Override public Result execute(UIExecutionContext context) throws Exception { UIContext uiContext = context.getUIContext(); Project project = (Project) uiContext.getAttributeMap().get(Project.class); if (project == null) { project = getSelectedProject(context.getUIContext()); } MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class); String projectName = metadataFacet.getProjectName(); String projectGroupId = metadataFacet.getProjectGroupName(); String projectVersion = metadataFacet.getProjectVersion(); File folder = project.getRoot().reify(DirectoryResource.class).getUnderlyingResourceObject(); Map<String, SpringBootDependencyDTO> selectedDTOs = new HashMap<>(); int[] selected = dependencies.getSelectedIndexes(); CollectionStringBuffer csbSpringBoot = new CollectionStringBuffer(","); for (int val : selected) { SpringBootDependencyDTO dto = choices.get(val); csbSpringBoot.append(dto.getId()); selectedDTOs.put(dto.getId(), dto); } String springBootDeps = csbSpringBoot.toString(); // boot version need the RELEASE suffix String bootVersion = springBootVersion.getValue() + ".RELEASE"; String url = String .format("%s?bootVersion=%s&groupId=%s&artifactId=%s&version=%s&packageName=%s&dependencies=%s", STARTER_ZIP_URL, bootVersion, projectGroupId, projectName, projectVersion, projectGroupId, springBootDeps); LOG.info("About to query url: " + url); uiOutput.info(uiOutput.out(), "About to query spring starter: " + url); Client client = factory.createClient(); InputStream is = client.target(url) .request() .get(InputStream.class); // some archetypes might not use maven or use the maven source layout so lets remove // the pom.xml and src folder if its already been pre-created // as these will be created if necessary via the archetype jar's contents File pom = new File(folder, "pom.xml"); if (pom.isFile() && pom.exists()) { pom.delete(); } File src = new File(folder, "src"); if (src.isDirectory() && src.exists()) { recursiveDelete(src); } File name = new File(folder, projectName + ".zip"); if (name.exists()) { name.delete(); } FileOutputStream fos = new FileOutputStream(name, false); copyAndCloseInput(is, fos); close(fos); // unzip the download from spring starter unzip(name, folder); LOG.info("Unzipped file to folder: {}", folder.getAbsolutePath()); uiOutput.info(uiOutput.out(), "Unzipped file to folder: " + folder.getAbsolutePath()); // and delete the zip file name.delete(); // are there any fabric8 dependencies to add afterwards? return Results.success( "Created new Spring Boot project in directory: " + folder.getName()); } private List fetchDependencies() throws Exception { List<Map> deps; // Check if we have a Spring Boot Config File if (SPRING_BOOT_CONFIG_FILE != null) { Yaml yaml = new Yaml(); InputStream input = new URL(SPRING_BOOT_CONFIG_FILE).openStream(); Map<String, Map> data = (Map) yaml.load(input); Map<String,List<Map>> initializer = (Map) data.get("initializr"); deps = (List) initializer.get("dependencies"); } else { // Fetch the dependencies list from the start.spring.io server Client client = factory.createClient(); String response = client.target(STARTER_URL) .request() .get(String.class); Map<String,Object> data = jsonToMap(response); Map<String,List<Map>> dependencies = (Map) data.get("dependencies"); deps = (List) dependencies.get("values"); } return deps; } }
package org.mariadb.jdbc.internal.failover.impl; import org.mariadb.jdbc.HostAddress; import org.mariadb.jdbc.UrlParser; import org.mariadb.jdbc.internal.failover.AbstractMastersSlavesListener; import org.mariadb.jdbc.internal.failover.HandleErrorResult; import org.mariadb.jdbc.internal.failover.thread.FailoverLoop; import org.mariadb.jdbc.internal.failover.tools.SearchFilter; import org.mariadb.jdbc.internal.logging.Logger; import org.mariadb.jdbc.internal.logging.LoggerFactory; import org.mariadb.jdbc.internal.protocol.MastersSlavesProtocol; import org.mariadb.jdbc.internal.protocol.Protocol; import org.mariadb.jdbc.internal.util.dao.ReconnectDuringTransactionException; import org.mariadb.jdbc.internal.util.dao.ServerPrepareResult; import org.mariadb.jdbc.internal.util.pool.GlobalStateInfo; import org.mariadb.jdbc.internal.util.scheduler.DynamicSizedSchedulerInterface; import org.mariadb.jdbc.internal.util.scheduler.SchedulerServiceProviderHolder; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * this class handle the operation when multiple hosts. */ public class MastersSlavesListener extends AbstractMastersSlavesListener { private static final DynamicSizedSchedulerInterface dynamicSizedScheduler; private static final AtomicInteger listenerCount = new AtomicInteger(); private static final Logger logger = LoggerFactory.getLogger(MastersSlavesListener.class); static { dynamicSizedScheduler = SchedulerServiceProviderHolder.getScheduler(1, "MariaDb-failover", 8); // fail loop scaling happens async and only from a single thread dynamicSizedScheduler.scheduleWithFixedDelay(new Runnable() { private final ArrayDeque<FailoverLoop> failoverLoops = new ArrayDeque<>(8); @Override public void run() { int desiredFailCount = Math.min(8, listenerCount.get() / 5 + 1); int countChange = desiredFailCount - failoverLoops.size(); if (countChange != 0) { dynamicSizedScheduler.setPoolSize(desiredFailCount); if (countChange > 0) { // start fail loops for (; countChange > 0; countChange // loop is started in constructor failoverLoops.add(new FailoverLoop(dynamicSizedScheduler)); } } else { // block on all removed loops after finished unscheduling to reduce blocking List<FailoverLoop> removedLoops = new ArrayList<>(-countChange); // terminate fail loops for (; countChange < 0; countChange++) { FailoverLoop failoverLoop = failoverLoops.remove(); failoverLoop.unscheduleTask(); removedLoops.add(failoverLoop); } for (FailoverLoop failoverLoop : removedLoops) { failoverLoop.blockTillTerminated(); } } } } }, 1, 2, TimeUnit.MINUTES); } protected Protocol masterProtocol; protected Protocol secondaryProtocol; /** * Initialisation. * * @param urlParser connection string object. * @param globalInfo server global variables information */ public MastersSlavesListener(final UrlParser urlParser, final GlobalStateInfo globalInfo) { super(urlParser, globalInfo); listenerCount.incrementAndGet(); masterProtocol = null; secondaryProtocol = null; setMasterHostFail(); setSecondaryHostFail(); } protected void removeListenerFromSchedulers() { super.removeListenerFromSchedulers(); FailoverLoop.removeListener(this); listenerCount.addAndGet(-1); } /** * Initialize connections. * * @throws SQLException if a connection error append. */ @Override public void initializeConnection() throws SQLException { super.initializeConnection(); try { reconnectFailedConnection(new SearchFilter(true)); } catch (SQLException e) { //initializeConnection failed checkInitialConnection(e); } } protected void checkInitialConnection(SQLException queryException) throws SQLException { if (this.secondaryProtocol == null || !this.secondaryProtocol.isConnected()) { setSecondaryHostFail(); } else { resetSecondaryFailoverData(); } if (this.masterProtocol == null || !this.masterProtocol.isConnected()) { setMasterHostFail(); if (!(urlParser.getOptions().allowMasterDownConnection && secondaryProtocol != null)) { throwFailoverMessage(masterProtocol != null ? masterProtocol.getHostAddress() : null, true, queryException, false); } } else { resetMasterFailoverData(); if (isSecondaryHostFail()) { //launched failLoop only if not throwing connection (connection will be closed). handleFailLoop(); } } } /** * Called after a call on Connection.close(). Will explicitly closed all connections. */ public void preClose() { if (explicitClosed.compareAndSet(false, true)) { proxy.lock.lock(); try { removeListenerFromSchedulers(); //closing connections closeConnection(waitNewSecondaryProtocol.getAndSet(null)); closeConnection(waitNewMasterProtocol.getAndSet(null)); closeConnection(masterProtocol); closeConnection(secondaryProtocol); } finally { proxy.lock.unlock(); } } } @Override public void preExecute() throws SQLException { lastQueryNanos = System.nanoTime(); checkWaitingConnection(); //if connection is closed or failed on slave if (this.currentProtocol != null && (this.currentProtocol.isClosed() || (!currentReadOnlyAsked && !currentProtocol.isMasterConnection()))) { preAutoReconnect(); } } /** * Verify that there is waiting connection that have to replace failing one. * If there is replace failed connection with new one. * * @throws SQLException if error occur */ public void checkWaitingConnection() throws SQLException { if (isSecondaryHostFail()) { proxy.lock.lock(); try { Protocol waitingProtocol = waitNewSecondaryProtocol.getAndSet(null); if (waitingProtocol != null && pingSecondaryProtocol(waitingProtocol)) { lockAndSwitchSecondary(waitingProtocol); } } finally { proxy.lock.unlock(); } } if (isMasterHostFail()) { proxy.lock.lock(); try { Protocol waitingProtocol = waitNewMasterProtocol.getAndSet(null); if (waitingProtocol != null && pingMasterProtocol(waitingProtocol)) { lockAndSwitchMaster(waitingProtocol); } } finally { proxy.lock.unlock(); } } } /** * Loop to connect. * * @throws SQLException if there is any error during reconnection */ public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLException { if (!searchFilter.isInitialConnection() && (isExplicitClosed() || (searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail())) { return; } //check if a connection has been retrieved by failoverLoop during lock if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); if ((searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail()) { return; } } catch (ReconnectDuringTransactionException e) { //don't throw an exception for this specific exception return; } } currentConnectionAttempts.incrementAndGet(); resetOldsBlackListHosts(); //put the list in the following order // - random order not blacklist and not connected host // - random order blacklist host // - connected host List<HostAddress> loopAddress = new LinkedList<>(urlParser.getHostAddresses()); loopAddress.removeAll(getBlacklistKeys()); Collections.shuffle(loopAddress); List<HostAddress> blacklistShuffle = new LinkedList<>(getBlacklistKeys()); blacklistShuffle.retainAll(urlParser.getHostAddresses()); Collections.shuffle(blacklistShuffle); loopAddress.addAll(blacklistShuffle); //put connected at end if (masterProtocol != null && !isMasterHostFail()) { loopAddress.remove(masterProtocol.getHostAddress()); loopAddress.add(masterProtocol.getHostAddress()); } if (secondaryProtocol != null && !isSecondaryHostFail()) { loopAddress.remove(secondaryProtocol.getHostAddress()); loopAddress.add(secondaryProtocol.getHostAddress()); } if ((isMasterHostFail() || isSecondaryHostFail()) || searchFilter.isInitialConnection()) { //while permit to avoid case when succeeded creating a new Master connection //and ping master connection fail a few millissecond after, //resulting a masterConnection not initialized. do { MastersSlavesProtocol.loop(this, globalInfo, loopAddress, searchFilter); //close loop if all connection are retrieved if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); } catch (ReconnectDuringTransactionException e) { //don't throw an exception for this specific exception } } } while (searchFilter.isInitialConnection() && !( masterProtocol != null || (urlParser.getOptions().allowMasterDownConnection && secondaryProtocol != null))); if (searchFilter.isInitialConnection() && masterProtocol == null && !currentReadOnlyAsked) { currentProtocol = this.secondaryProtocol; currentReadOnlyAsked = true; } } } /** * Method called when a new Master connection is found after a fallback. * * @param newMasterProtocol the new active connection */ public void foundActiveMaster(Protocol newMasterProtocol) { if (isMasterHostFail()) { if (isExplicitClosed()) { newMasterProtocol.close(); return; } if (!waitNewMasterProtocol.compareAndSet(null, newMasterProtocol)) { newMasterProtocol.close(); } } else { newMasterProtocol.close(); } } /** * Use the parameter newMasterProtocol as new current master connection. * <p> * <i>Lock must be set</i> * * @param newMasterProtocol new master connection * @throws ReconnectDuringTransactionException if there was an active transaction. */ public void lockAndSwitchMaster(Protocol newMasterProtocol) throws ReconnectDuringTransactionException { if (masterProtocol != null && !masterProtocol.isClosed()) { masterProtocol.close(); } if (!currentReadOnlyAsked || isSecondaryHostFail()) { //actually on a secondary read-only because master was unknown. //So select master as currentConnection try { syncConnection(currentProtocol, newMasterProtocol); } catch (Exception e) { //Some error append during connection parameter synchronisation } //switching current connection to master connection currentProtocol = newMasterProtocol; } boolean inTransaction = this.masterProtocol != null && this.masterProtocol.inTransaction(); this.masterProtocol = newMasterProtocol; resetMasterFailoverData(); if (inTransaction) { //master connection was down, so has been change for a new active connection //problem was there was an active connection -> must throw exception so client known it throw new ReconnectDuringTransactionException("Connection reconnect automatically during an active transaction", 1401, "25S03"); } } /** * Method called when a new secondary connection is found after a fallback. * * @param newSecondaryProtocol the new active connection * @throws SQLException if switch failed */ public void foundActiveSecondary(Protocol newSecondaryProtocol) throws SQLException { if (isSecondaryHostFail()) { if (isExplicitClosed()) { newSecondaryProtocol.close(); return; } if (proxy.lock.tryLock()) { try { lockAndSwitchSecondary(newSecondaryProtocol); } finally { proxy.lock.unlock(); } } else { if (!waitNewSecondaryProtocol.compareAndSet(null, newSecondaryProtocol)) { newSecondaryProtocol.close(); } } } else { newSecondaryProtocol.close(); } } /** * Use the parameter newSecondaryProtocol as new current secondary connection. * * @param newSecondaryProtocol new secondary connection * @throws SQLException if an error occur during setting session read-only */ public void lockAndSwitchSecondary(Protocol newSecondaryProtocol) throws SQLException { if (secondaryProtocol != null && !secondaryProtocol.isClosed()) { secondaryProtocol.close(); } //if asked to be on read only connection, switching to this new connection if (currentReadOnlyAsked || (urlParser.getOptions().failOnReadOnly && !currentReadOnlyAsked && isMasterHostFail())) { try { syncConnection(currentProtocol, newSecondaryProtocol); } catch (Exception e) { //Some error append during connection parameter synchronisation } currentProtocol = newSecondaryProtocol; } //set new found connection as slave connection. this.secondaryProtocol = newSecondaryProtocol; if (urlParser.getOptions().assureReadOnly) { setSessionReadOnly(true, this.secondaryProtocol); } resetSecondaryFailoverData(); } /** * Switch to a read-only(secondary) or read and write connection(master). * * @param mustBeReadOnly the read-only status asked * @throws SQLException if operation hasn't change protocol */ @Override public void switchReadOnlyConnection(Boolean mustBeReadOnly) throws SQLException { checkWaitingConnection(); if (currentReadOnlyAsked != mustBeReadOnly) { proxy.lock.lock(); try { // another thread updated state if (currentReadOnlyAsked == mustBeReadOnly) return; currentReadOnlyAsked = mustBeReadOnly; if (currentReadOnlyAsked) { if (currentProtocol.isMasterConnection()) { //must change to replica connection if (!isSecondaryHostFail()) { proxy.lock.lock(); try { //switching to secondary connection syncConnection(this.masterProtocol, this.secondaryProtocol); currentProtocol = this.secondaryProtocol; //current connection is now secondary return; } catch (SQLException e) { //switching to secondary connection failed if (setSecondaryHostFail()) { addToBlacklist(secondaryProtocol.getHostAddress()); } } finally { proxy.lock.unlock(); } } //stay on master connection, since slave connection is fail FailoverLoop.addListener(this); } } else { if (!currentProtocol.isMasterConnection()) { //must change to master connection if (!isMasterHostFail()) { try { //switching to master connection syncConnection(this.secondaryProtocol, this.masterProtocol); currentProtocol = this.masterProtocol; //current connection is now master return; } catch (SQLException e) { //switching to master connection failed if (setMasterHostFail()) { addToBlacklist(masterProtocol.getHostAddress()); } } } try { reconnectFailedConnection(new SearchFilter(true, false)); handleFailLoop(); //connection established, no need to send Exception ! //switching to master connection try { syncConnection(this.secondaryProtocol, this.masterProtocol); currentProtocol = this.masterProtocol; } catch (SQLException e) { //switching to master connection failed if (setMasterHostFail()) { addToBlacklist(masterProtocol.getHostAddress()); } } } catch (SQLException e) { //stop failover, since we will throw a connection exception that will close the connection. FailoverLoop.removeListener(this); HostAddress failHost = (this.masterProtocol != null) ? this.masterProtocol.getHostAddress() : null; throwFailoverMessage(failHost, true, new SQLException("master " + masterProtocol.getHostAddress() + " connection failed"), false); } } } } finally { proxy.lock.unlock(); } } } /** * To handle the newly detected failover on the master connection. * * @param method the initial called method * @param args the initial args * @param killCmd is the fail due to a KILL cmd * @return an object to indicate if the previous Exception must be thrown, or the object resulting if a failover worked * @throws Throwable if failover has not been catch */ public HandleErrorResult primaryFail(Method method, Object[] args, boolean killCmd) throws Throwable { boolean alreadyClosed = !masterProtocol.isConnected(); boolean inTransaction = masterProtocol != null && masterProtocol.inTransaction(); //in case of SocketTimeoutException due to having set socketTimeout, must force connection close if (masterProtocol.isConnected()) masterProtocol.close(); //fail on slave if parameter permit so if (urlParser.getOptions().failOnReadOnly && !isSecondaryHostFail()) { try { if (this.secondaryProtocol != null && this.secondaryProtocol.ping()) { //switching to secondary connection syncConnection(masterProtocol, this.secondaryProtocol); proxy.lock.lock(); try { currentProtocol = this.secondaryProtocol; } finally { proxy.lock.unlock(); } FailoverLoop.addListener(this); try { return relaunchOperation(method, args); } catch (Exception e) { //relaunchOperation failed } return new HandleErrorResult(); } } catch (Exception e) { if (setSecondaryHostFail()) { blackListAndCloseConnection(this.secondaryProtocol); } } } try { reconnectFailedConnection(new SearchFilter(true, urlParser.getOptions().failOnReadOnly)); handleFailLoop(); if (killCmd) return new HandleErrorResult(true, false); if (currentReadOnlyAsked || alreadyClosed || !inTransaction && isQueryRelaunchable(method, args)) { //connection was not in transaction //can relaunch query logger.info("Connection to master lost, new master {}, conn={} found" + ", query type permit to be re-execute on new server without throwing exception", currentProtocol.getHostAddress(), currentProtocol.getServerThreadId()); return relaunchOperation(method, args); } //throw Exception because must inform client, even if connection is reconnected return new HandleErrorResult(true); } catch (Exception e) { //we will throw a Connection exception that will close connection if (e.getCause() != null && proxy.hasToHandleFailover((SQLException) e.getCause()) && currentProtocol.isConnected()) { currentProtocol.close(); } setMasterHostFail(); FailoverLoop.removeListener(this); return new HandleErrorResult(); } } private void blackListAndCloseConnection(Protocol protocol) { addToBlacklist(protocol.getHostAddress()); if (protocol.isConnected()) { proxy.lock.lock(); try { protocol.close(); } finally { proxy.lock.unlock(); } } } /** * Reconnect failed connection. * * @throws SQLException if reconnection has failed */ public void reconnect() throws SQLException { SearchFilter filter; boolean inTransaction = false; if (currentReadOnlyAsked) { filter = new SearchFilter(true, true); } else { inTransaction = masterProtocol != null && masterProtocol.inTransaction(); filter = new SearchFilter(true, urlParser.getOptions().failOnReadOnly); } reconnectFailedConnection(filter); handleFailLoop(); if (inTransaction) { throw new ReconnectDuringTransactionException("Connection reconnect automatically during an active transaction", 1401, "25S03"); } } /** * Ping secondary protocol. * ! lock must be set ! * * @param protocol socket to ping * @return true if ping is valid. */ private boolean pingSecondaryProtocol(Protocol protocol) { try { if (protocol != null && protocol.isConnected() && protocol.ping()) { return true; } } catch (Exception e) { protocol.close(); if (setSecondaryHostFail()) { addToBlacklist(protocol.getHostAddress()); } } return false; } /** * To handle the newly detected failover on the secondary connection. * * @param method the initial called method * @param args the initial args * @param killCmd is fail due to a KILL command * @return an object to indicate if the previous Exception must be thrown, or the object resulting if a failover worked * @throws Throwable if failover has not catch error */ public HandleErrorResult secondaryFail(Method method, Object[] args, boolean killCmd) throws Throwable { proxy.lock.lock(); try { if (pingSecondaryProtocol(this.secondaryProtocol)) { return relaunchOperation(method, args); } } finally { proxy.lock.unlock(); } if (!isMasterHostFail()) { try { //check that master is on before switching to him if (masterProtocol != null && masterProtocol.isValid(1000)) { //switching to master connection syncConnection(secondaryProtocol, masterProtocol); proxy.lock.lock(); try { currentProtocol = masterProtocol; } finally { proxy.lock.unlock(); } FailoverLoop.addListener(this); logger.info("Connection to slave lost, using master connection" + ", query is re-execute on master server without throwing exception"); return relaunchOperation(method, args); //now that we are on master, relaunched result if the result was not crashing the master } } catch (Exception e) { //ping fail on master if (setMasterHostFail()) { blackListAndCloseConnection(masterProtocol); } } } try { reconnectFailedConnection(new SearchFilter(true, true)); handleFailLoop(); if (isSecondaryHostFail()) { syncConnection(this.secondaryProtocol, this.masterProtocol); proxy.lock.lock(); try { currentProtocol = this.masterProtocol; } finally { proxy.lock.unlock(); } } if (killCmd) return new HandleErrorResult(true, false); logger.info("Connection to slave lost, new slave {}, conn={} found" + ", query is re-execute on new server without throwing exception", currentProtocol.getHostAddress(), currentProtocol.getServerThreadId()); return relaunchOperation(method, args); //now that we are reconnect, relaunched result if the result was not crashing the node } catch (Exception ee) { //we will throw a Connection exception that will close connection FailoverLoop.removeListener(this); return new HandleErrorResult(); } } @Override public void handleFailLoop() { if (isMasterHostFail() || isSecondaryHostFail()) { if (!isExplicitClosed()) { FailoverLoop.addListener(this); } } else { FailoverLoop.removeListener(this); } } @Override public boolean isMasterConnected() { return masterProtocol != null && masterProtocol.isConnected(); } /** * Check master status. * * @param searchFilter search filter * @return has some status changed */ @Override public boolean checkMasterStatus(SearchFilter searchFilter) { if (masterProtocol != null) { pingMasterProtocol(masterProtocol); } return false; } @Override public void rePrepareOnSlave(ServerPrepareResult oldServerPrepareResult, boolean mustBeOnMaster) throws SQLException { if (isSecondaryHostFail()) { Protocol waitingProtocol = waitNewSecondaryProtocol.getAndSet(null); if (waitingProtocol != null) { proxy.lock.lock(); try { if (pingSecondaryProtocol(waitingProtocol)) { lockAndSwitchSecondary(waitingProtocol); } } finally { proxy.lock.unlock(); } } } if (secondaryProtocol != null && !isSecondaryHostFail()) { //prepare on slave ServerPrepareResult serverPrepareResult = secondaryProtocol.prepare(oldServerPrepareResult.getSql(), mustBeOnMaster); //release prepare on master try { serverPrepareResult.getUnProxiedProtocol().releasePrepareStatement(serverPrepareResult); } catch (SQLException exception) { //released failed. } //replace prepare data oldServerPrepareResult.failover(serverPrepareResult.getStatementId(), secondaryProtocol); } } /** * List current connected HostAddress. * * @return hostAddress List. */ public List<HostAddress> connectedHosts() { List<HostAddress> usedHost = new ArrayList<>(); if (isMasterHostFail()) { Protocol masterProtocol = waitNewMasterProtocol.get(); if (masterProtocol != null) usedHost.add(masterProtocol.getHostAddress()); } else usedHost.add(masterProtocol.getHostAddress()); if (isSecondaryHostFail()) { Protocol secondProtocol = waitNewSecondaryProtocol.get(); if (secondProtocol != null) usedHost.add(secondProtocol.getHostAddress()); } else usedHost.add(secondaryProtocol.getHostAddress()); return usedHost; } /** * Reset state of master and slave connection. * * @throws SQLException if command fail. */ public void reset() throws SQLException { if (!isMasterHostFail()) { masterProtocol.reset(); } if (!isSecondaryHostFail()) { secondaryProtocol.reset(); } } }
package org.opendaylight.controller.networkconfig.neutron; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.opendaylight.controller.configuration.ConfigurationObject; @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) public class Neutron_IPs extends ConfigurationObject implements Serializable { private static final long serialVersionUID = 1L; // See OpenStack Network API v2.0 Reference for description of // annotated attributes @XmlElement(name="ip_address") String ipAddress; @XmlElement(name="subnet_id") String subnetUUID; public Neutron_IPs() { } public Neutron_IPs(String uuid) { subnetUUID = uuid; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getSubnetUUID() { return subnetUUID; } public void setSubnetUUID(String subnetUUID) { this.subnetUUID = subnetUUID; } @Override public String toString() { return "Neutron_IPs{" + "ipAddress='" + ipAddress + '\'' + ", subnetUUID='" + subnetUUID + '\'' + "}"; } }
package org.squiddev.plethora.integration.vanilla.meta; import com.google.common.collect.Maps; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import org.squiddev.plethora.api.PlethoraAPI; import org.squiddev.plethora.api.meta.BaseMetaProvider; import org.squiddev.plethora.api.meta.IMetaProvider; import org.squiddev.plethora.api.method.IPartialContext; import javax.annotation.Nonnull; import java.util.HashMap; import java.util.Map; @IMetaProvider.Inject(value = IBlockState.class) public class MetaBlockState extends BaseMetaProvider<IBlockState> { @Nonnull @Override public Map<Object, Object> getMeta(@Nonnull IPartialContext<IBlockState> context) { HashMap<Object, Object> data = Maps.newHashMap(); IBlockState state = context.getTarget(); Block block = state.getBlock(); if (block != null) data.put("metadata", block.getMetaFromState(state)); HashMap<Object, Object> stateProperties = Maps.newHashMap(); data.put("state", stateProperties); for (Map.Entry<IProperty<?>, Comparable<?>> item : state.getProperties().entrySet()) { Object value = item.getValue(); if (!(value instanceof String) && !(value instanceof Number) && !(value instanceof Boolean)) { value = value.toString(); } stateProperties.put(item.getKey().getName(), value); } Material material = state.getMaterial(); data.put("material", PlethoraAPI.instance().metaRegistry().getMeta(context.makePartialChild(material))); int level = block.getHarvestLevel(state); if (level >= 0) data.put("harvestLevel", level); data.put("harvestTool", block.getHarvestTool(state)); MapColor mapCol = state.getMapColor(); if (mapCol != null) { int colour = mapCol.colorValue; data.put("colour", colour); data.put("color", colour); } return data; } }
package se.ivankrizsan.restexample.services; import io.reactivex.Observable; import org.springframework.transaction.annotation.Transactional; import se.ivankrizsan.restexample.domain.LongIdEntity; import se.ivankrizsan.restexample.repositories.customisation.JpaRepositoryCustomisations; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * Abstract base class for services that has operations for creating, reading, * updating and deleting entities. * This implementation uses RxJava. * * @param <E> Entity type. * @author Ivan Krizsan */ @Transactional public abstract class AbstractServiceBaseRxJava<E extends LongIdEntity> { /* Constant(s): */ /* Instance variable(s): */ protected JpaRepositoryCustomisations<E> mRepository; /** * Creates a mService instance that will use the supplied repository for entity persistence. * * @param inRepository Entity repository. */ public AbstractServiceBaseRxJava(final JpaRepositoryCustomisations<E> inRepository) { mRepository = inRepository; } /** * Saves the supplied entity. * * @param inEntity Entity to save. * @return Observable that will receive the saved entity, or exception if error occurs. */ public Observable<E> save(final E inEntity) { return Observable.create(inSource -> { try { final E theSavedEntity = mRepository.save(inEntity); inSource.onNext(theSavedEntity); inSource.onComplete(); } catch (final Exception theException) { inSource.onError(theException); } }); } /** * Updates the supplied entity. * * @param inEntity Entity to update. * @return Observable that will receive the updated entity, or exception if error occurs. */ public Observable<E> update(final E inEntity) { return Observable.create(inSource -> { try { final E theUpdatedEntity = mRepository.persist(inEntity); inSource.onNext(theUpdatedEntity); inSource.onComplete(); } catch (final Exception theException) { inSource.onError(theException); } }); } /** * Finds the entity having supplied id. * * @param inEntityId Id of entity to retrieve. * @return Observable that will receive the found entity, or exception if error occurs or no entity is found. */ @Transactional(readOnly = true) public Observable<E> find(final Long inEntityId) { return Observable.create(inSource -> { try { final E theEntity = mRepository.findOne(inEntityId); if (theEntity != null) { inSource.onNext(theEntity); inSource.onComplete(); } else { inSource.onError(new Error("Cannot find entity with id " + inEntityId)); } } catch (final Exception theException) { inSource.onError(theException); } }); } /** * Finds all the entities. * * @return Observable that will receive a list of entities, or exception if error occurs. */ @Transactional(readOnly = true) public Observable<List<E>> findAll() { return Observable.create(inSource -> { try { final List<E> theEntitiesList = StreamSupport.stream(mRepository.findAll().spliterator(), false) .collect(Collectors.toList()); inSource.onNext(theEntitiesList); inSource.onComplete(); } catch (final Exception theException) { inSource.onError(theException); } }); } /** * Deletes the entity having supplied id. * * @param inId Id of entity to delete. * @return Observable that will receive completion, or exception if error occurs. */ public Observable delete(final Long inId) { return Observable.create(inSource -> { try { mRepository.delete(inId); inSource.onComplete(); } catch (final Exception theException) { inSource.onError(theException); } }); } /** * Deletes all entities. * * @return Observable that will receive completion, or exception if error occurs. */ public Observable deleteAll() { return Observable.create(inSource -> { try { mRepository.deleteAll(); inSource.onComplete(); } catch (final Exception theException) { inSource.onError(theException); } }); } }
package japsadev.tools; import htsjdk.samtools.*; import japsa.bio.alignment.MultipleAlignment; import japsa.bio.alignment.ProfileDP; import japsa.bio.alignment.ProfileDP.EmissionState; import japsa.bio.np.ErrorCorrection; import japsa.bio.tr.TandemRepeat; import japsa.bio.tr.TandemRepeatVariant; import japsa.seq.*; import japsa.util.*; import japsa.util.deploy.Deployable; import japsa.xm.expert.Expert; import japsa.xm.expert.MarkovExpert; import japsadev.bio.hts.clustering.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * VNTR typing using long reads * */ @Deployable(scriptName = "jsa.dev.clusteringhmm", scriptDesc = "Clustring in the hmm framework") public class VNTRClusteringHmmCmd extends CommandLine { private static final Logger LOG = LoggerFactory.getLogger(VNTRClusteringHmmCmd.class); public VNTRClusteringHmmCmd(){ super(); Deployable annotation = getClass().getAnnotation(Deployable.class); setUsage(annotation.scriptName() + " [options]"); setDesc(annotation.scriptDesc()); Option referenceOpt = addString("reference", null, "Name of the reference genome ", true); ///addStdInputFile(); Option bamFileOpt = addString("bamFile", null, "Name of the bam file", true); Option outputOpt = addString("output", "-", "Name of the output file, - for stdout"); Option xafFileOpt = addString("xafFile", null, "Name of the regions file in xaf", true); Option flankingOpt = addInt("flanking", 30, "Size of the flanking regions"); Option minQualOpt = addInt("qual", 0, "Minimum quality"); addInt("iteration", 1, "Number of iteration"); addInt("nploidy",2, "The ploidy of the genome 1 = happloid, 2 = diploid. Currenly only support up to 2-ploidy"); addString("prefix", "", "Prefix of temporary files, if not specified, will be automatically generated"); ///////////////Adding galaxy support///////////// flankingOpt.setGalaxySetting(new GalaxySetting("integer", null,false)); minQualOpt.setGalaxySetting(new GalaxySetting("integer", null,false)); xafFileOpt.setGalaxySetting(new GalaxySetting("data", "tabular",false)); GalaxySetting galaxyOutput = new GalaxySetting("data", "text",true); galaxyOutput.setLabel("countRead.txt"); outputOpt.setGalaxySetting(galaxyOutput); bamFileOpt.setGalaxySetting(new GalaxySetting("data", "bam",false)); referenceOpt.setGalaxySetting(new GalaxySetting("data", "fasta",false)); setGalaxy(annotation.scriptName()); addStdHelp(); } static Alphabet dna = Alphabet.DNA16(); static IntArray profilePositions = new IntArray(); static IntArray seqPositions = new IntArray(); static DoubleArray costGeneration = new DoubleArray(); static ByteArray byteArray = new ByteArray(); public static void main(String[] args) throws Exception, InterruptedException { CommandLine cmdLine = new VNTRClusteringHmmCmd(); args = cmdLine.stdParseLine(args); int flanking = cmdLine.getIntVal("flanking"); if (flanking < 10) flanking = 10; int qual = cmdLine.getIntVal("qual"); int np = cmdLine.getIntVal("nploidy"); if (np > 2) { System.err.println("The program currenly only support haploid and diployd. Enter nploidy of 1 or 2"); System.exit(1); } String bamFile = cmdLine.getStringVal("bamFile"); String prefix = cmdLine.getStringVal("prefix"); if (prefix == null || prefix.length() == 0) { prefix = "p" + System.currentTimeMillis(); } SequenceOutputStream outOS = SequenceOutputStream .makeOutputStream(cmdLine.getStringVal("output")); String[] headers = TandemRepeatVariant.SIMPLE_HEADERS; if (np > 1) { headers = TandemRepeatVariant.SIMPLE_HEADERS2; } TandemRepeatVariant.printHeader(outOS, headers); String strFile = cmdLine.getStringVal("xafFile"); LOG.info("Read genome begins"); HashMap <String, Sequence> genome = new HashMap <String, Sequence>(); SequenceReader seqReader = SequenceReader.getReader(cmdLine.getStringVal("reference")); Sequence seq; while ((seq = seqReader.nextSequence(dna)) != null){ genome.put(seq.getName(), seq); } seqReader.close(); LOG.info("Read genome done"); XAFReader xafReader = new XAFReader(strFile); SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT); SamReader reader = SamReaderFactory.makeDefault().open(new File(bamFile)); Expert.setAlphabet(Alphabet.DNA4()); ArrayList<Sequence> readSequences = new ArrayList<Sequence>(); //Go through the list of repeats while (xafReader.next() != null){ TandemRepeat str = TandemRepeat.read(xafReader); //start,end = the start and end of the region (including flanks) int start = Integer.parseInt(xafReader.getField("start")) - flanking; int end = Integer.parseInt(xafReader.getField("end")) + flanking; String chrom = xafReader.getField("chrom"); if (seq == null || !seq.getName().equals(chrom)){ seq = genome.get(chrom); } if (seq == null){ xafReader.close(); LOG.error("Chrom in line " + xafReader.lineNo() + " not found!!!"); System.exit(1); } if (end > seq.length()) end = seq.length(); if (start < 1) start = 1; int hmmFlank = flanking; int period = str.getPeriod(); double fraction = str.getUnitNo() - Math.floor(str.getUnitNo()); int hmmPad = (int)(fraction * period ) ; //System.out.println("###" + str.getPeriod() + " " + str.getUnitNo() + " " + hmmPad); Sequence hmmSeq = new Sequence(dna, hmmFlank * 2 + hmmPad + str.getPeriod()); int i = 0; for (;i < hmmFlank + hmmPad + str.getPeriod(); i++) hmmSeq.setBase(i, seq.getBase(str.getStart() - hmmFlank + i -1)); for (;i < hmmSeq.length();i++){ byte base = seq.getBase(str.getEnd() + i - (hmmFlank + hmmPad + str.getPeriod()) );//no need to -1 hmmSeq.setBase(i,base); } ProfileDP dp = new ProfileDP(hmmSeq, hmmFlank + hmmPad, hmmFlank + hmmPad + str.getPeriod() - 1);//-1 for 0-index, inclusive //System.out.println("Lengths: " + hmmFlank + ", " + hmmPad + " " + str.getPeriod() + " " + hmmSeq.length() ); //System.out.println("CHECKING BEGIN"); outOS.print("##"+str.getID()+"\n## "); for (int x = 0; x < hmmSeq.length();x++){ outOS.print(hmmSeq.charAt(x)); if (x == hmmFlank + hmmPad -1 || x == hmmFlank + hmmPad + period - 1) outOS.print("=="); } outOS.println(); //run on the reference //if (1==0) { Sequence refRepeat = seq.subSequence(start, end); refRepeat.setName("reference"); processRead(refRepeat, dp, fraction, hmmFlank, hmmPad, period, outOS ); } SAMRecordIterator iter = reader.query(str.getParent(), start, end, false); String fileName = prefix + "_" + str.getID() + "_i.fasta"; String tempFile = str.getID(); SequenceOutputStream os = SequenceOutputStream.makeOutputStream(fileName); // double var = 0; TandemRepeatVariant trVar = new TandemRepeatVariant(); trVar.setTandemRepeat(str); int readIndex = 0; //Clear the list readSequences.clear(); while (iter.hasNext()) { SAMRecord rec = iter.next(); // Check qualilty if (rec.getMappingQuality() < qual) { continue; } // Only reads that fully span the repeat and flankings int currentRefPos = rec.getAlignmentStart(); if (currentRefPos > start) continue; if (rec.getAlignmentEnd() < end) continue; readIndex ++; //assert currentRefBase < start Sequence readSeq = getReadPosition(rec,start,end); if (readSeq == null) continue; String readName = readSeq.getName(); String [] toks = readName.split("/",4); String polymerageRead = (toks.length > 1) ? toks[1] : toks[0]; String subRead = (toks.length > 2) ? toks[2] : "_"; //String alignSubRead = (toks.length > 3) ? toks[3] : "_"; readSeq.setName(polymerageRead + "_" + subRead); readSeq.writeFasta(os); //processRead(readSeq, dp, fraction, hmmFlank, hmmPad, period, outOS ); readSequences.add(readSeq); }// while iter.close(); os.close(); //FIXME: readSequences: an array of reads //clustering of this array, HashMap<String, String> tempReadSequences = new HashMap<String, String>(); for(int x = 0;x<readSequences.size();x++){ Sequence temp = readSequences.get(x); tempReadSequences.put(temp.toString(), temp.getName()); } ArrayList<String> tempReads = new ArrayList<String>(tempReadSequences.keySet()); ArrayList<ArrayList<String>> clusterResult = new ArrayList<ArrayList<String>>(); KmeanClusteringWithReads clusterObj1 = new KmeanClusteringWithReads(); clusterResult = clusterObj1.Clustering(tempReads); ArrayList<String> cluster1String = clusterResult.get(1); ArrayList<String> cluster2String = clusterResult.get(2); ArrayList<Sequence> cluster1Sequence = new ArrayList<Sequence>(); ArrayList<Sequence> cluster2Sequence = new ArrayList<Sequence>(); Sequence tempSeq1;Sequence tempSeq2; //seq = new Sequence(Alphabet.DNA16(), sequenceString, sequenceName) if(cluster1String.size()>0){ for(int x=0; x<cluster1String.size();x++){ String str1 = cluster1String.get(x); tempSeq1 = new Sequence(dna, str1, tempReadSequences.get(str1)); cluster1Sequence.add(tempSeq1); } } if(cluster2String.size()>0){ for(int x=0; x<cluster2String.size();x++){ String str2 = cluster2String.get(x); tempSeq2 = new Sequence(dna, str2, tempReadSequences.get(str2)); cluster2Sequence.add(tempSeq2); } } Sequence cluster1Consensus = ErrorCorrection.consensusSequence(cluster1Sequence, prefix + "_cluster1_"+tempFile, "kalign"); cluster1Consensus.setName("consensus1"); Sequence cluster2Consensus = ErrorCorrection.consensusSequence(cluster2Sequence, prefix + "_cluster2_"+tempFile, "kalign"); cluster2Consensus.setName("consensus2"); //WriteClusterResultOnFile clusterObj2 = new WriteClusterResultOnFile(); //clusterObj2.writeOnFile(clusterResult, cluster1Consensus, cluster2Consensus, tempFile); //System.out.print("char seq: "+clusterResult.get(1).get(0)); //Get the consensus of each of them using the following command //ErrorCorrection.consensusSequence(clusterResult.get(index), "tmp", "kalign"); //ErrorCorrection.consensusSequence(readSequences, "tmp", "kalign"); //System.out.println("consensus" + ErrorCorrection.consensusSequence(readSequences, "tmp", "kalign")); //write to a file ProfileDP dpBatch = new ProfileDP(hmmSeq, hmmFlank + hmmPad, hmmFlank + hmmPad + str.getPeriod() - 1); //-1 for 0-index, inclusive outOS.print(" if (cluster1Consensus != null) processRead(cluster1Consensus, dpBatch, fraction, hmmFlank, hmmPad, period, outOS ); else outOS.print("##No consensus found for 1"); if (cluster1Sequence.size() >= 1) { processBatch(cluster1Sequence, dpBatch, fraction, hmmFlank, hmmPad, period, outOS); }else outOS.print("##No cluster found for 1"); outOS.print(" if (cluster2Consensus != null) processRead(cluster2Consensus, dpBatch, fraction, hmmFlank, hmmPad, period, outOS ); else outOS.print("##No consensus found for 2"); if (cluster2Sequence.size() >= 1) { processBatch(cluster2Sequence, dpBatch, fraction, hmmFlank, hmmPad, period, outOS); }else outOS.print("##No cluster found for 2"); //outOS.print(trVar.toString(headers)); //outOS.print('\n'); }// for reader.close(); outOS.close(); } static private void processBatch(ArrayList<Sequence> readBatch, ProfileDP dpBatch, double fraction, int hmmFlank, int hmmPad, int period, SequenceOutputStream outOS ) throws IOException{ for (int round = 0; round < 5;round ++){ double myCost = 0; int countIns = 0, countDel = 0, countMG = 0, countMB = 0; for (Sequence readSeq:readBatch){ EmissionState bestState = dpBatch.align(readSeq); //TODO: make a filter here: select only eligible alignment double alignScore = bestState.getScore(); countIns += bestState.getCountIns(); countDel += bestState.getCountDel(); countMG += bestState.getCountMG(); countMB += bestState.getCountMB(); //System.out.println("Score " + alignScore + " vs " + readSeq.length()*2 + " (" + alignScore/readSeq.length() +")"); double bestIter = bestState.getIter() + fraction; myCost += alignScore; }//for readSeq double sum = 3.0 + countMG + countMB + countIns + countDel; double insP = (countIns + 1.0) /sum; double delP = (countDel + 1.0) /sum; double matP = (countMG + countMB + 1.0) /sum; double matchP = (countMG + 1.0) / (countMG + countMB + 2.0); double misMatchP = 1 - matchP; outOS.print(String.format("Total: %3d %3d %3d %3d %8.4f %8.4f %8.4f %8.4f\n", countMG, countMB, countIns, countDel, insP, delP, misMatchP,myCost)); dpBatch.setTransitionProbability(matP, insP, delP); dpBatch.setMatchProbability(matchP); }//round for (Sequence readSeq:readBatch){ MarkovExpert expert = new MarkovExpert(1); double costM = 0; for (int x = 0; x< readSeq.length();x++){ int base = readSeq.getBase(x); costM -= JapsaMath.log2(expert.update(base)); } double backGround = costM / readSeq.length() - 0.1; boolean pass = true; outOS.print("Markov " + costM + "\t" + (costM / readSeq.length()) + "\n"); EmissionState bestState = dpBatch.align(readSeq); double alignScore = bestState.getScore(); //System.out.println("Score " + alignScore + " vs " + readSeq.length()*2 + " (" + alignScore/readSeq.length() +")"); double bestIter = bestState.getIter() + fraction; profilePositions.clear(); seqPositions.clear(); costGeneration.clear(); byteArray.clear(); EmissionState lastState = bestState; bestState = bestState.bwdState; while (bestState != null){ profilePositions.add(bestState.profilePos); seqPositions.add(bestState.profilePos); costGeneration.add(lastState.score - bestState.score); if (bestState.seqPos == lastState.seqPos) byteArray.add((byte)Alphabet.DNA.GAP); else byteArray.add(readSeq.getBase(lastState.seqPos)); lastState = bestState; bestState = bestState.bwdState; } double costL = 0, costR = 0, costCurrentRep = 0, costRep = 0; int stateL = 0, stateR = 0, stateCurrentRep = 0, stateRep = 0; int baseL = 0, baseR = 0, baseCurrentRep = 0, baseRep = 0; int bSeqL = 0, bSeqR = 0, bSeqCurrentRep = 0, bSeqRep = 0; int lastProfilePos = -1, lastSeqPos = -1; for (int x = profilePositions.size() - 1; x >=0; x outOS.print(Alphabet.DNA().int2char(byteArray.get(x))); int profilePos = profilePositions.get(x); int seqPos = seqPositions.get(x); if (profilePos < hmmFlank + hmmPad){ stateL ++; costL += costGeneration.get(x); if (lastProfilePos != profilePos) baseL ++; if (lastSeqPos != seqPos) bSeqL ++; }else if(profilePos > hmmFlank + hmmPad + period){ stateR ++; costR += costGeneration.get(x); if (lastProfilePos != profilePos) baseR ++; if (lastSeqPos != seqPos) bSeqR ++; }else{ stateCurrentRep ++; costCurrentRep += costGeneration.get(x); stateRep ++; costRep += costGeneration.get(x); if (lastProfilePos != profilePos){ baseRep ++; baseCurrentRep ++; } if (lastSeqPos != seqPos){ bSeqRep ++; bSeqCurrentRep ++; } } //end of a repeat cycle if (profilePos < lastProfilePos){ outOS.print("< + " " + stateCurrentRep + " " + (stateCurrentRep == 0?"inf": "" + (costCurrentRep/stateCurrentRep)) + " " + baseCurrentRep + " " + (baseCurrentRep == 0?"inf": "" + (costCurrentRep/baseCurrentRep)) + " " + bSeqCurrentRep + " " + (bSeqCurrentRep == 0?"inf": "" + (costCurrentRep/bSeqCurrentRep)) ); if (costCurrentRep/bSeqCurrentRep > backGround){ pass = false; outOS.print(" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } outOS.println(); costCurrentRep = 0;//restart stateCurrentRep = 0;//restart baseCurrentRep = 0; bSeqCurrentRep = 0; } //left if (profilePos >= hmmFlank + hmmPad && lastProfilePos < hmmFlank + hmmPad){ outOS.print("< + " " + stateL + " " + (stateL == 0?"inf": "" + (costL/stateL)) + " " + baseL + " " + (baseL == 0?"inf": "" + (costL/baseL)) + " " + bSeqL + " " + (bSeqL == 0?"inf": "" + (costL/bSeqL)) ); if (costL/bSeqL > backGround){ pass = false; outOS.print(" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } outOS.println(); } //right //if (profilePos < hmmFlank + hmmPad + period && lastProfilePos >= hmmFlank + hmmPad + period){ // + " " + stateR // + " " + (stateR == 0?"inf": "" + (costR/stateR)) // + " " + baseR // + " " + (baseR == 0?"inf": "" + (costR/baseR)) // + " " + bSeqR // + " " + (bSeqR == 0?"inf": "" + (costR/bSeqR)) // outOS.println(); lastProfilePos = profilePos; lastSeqPos = seqPos; }//for x //move to out of the loop outOS.print("< + " " + stateR + " " + (stateR == 0?"inf": "" + (costR/stateR)) + " " + baseR + " " + (baseR == 0?"inf": "" + (costR/baseR)) + " " + bSeqR + " " + (bSeqR == 0?"inf": "" + (costR/bSeqR)) ); if (costR/bSeqR > backGround){ pass = false; outOS.print(" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } //outOS.println(); outOS.println(); outOS.print ("L = " + (costL/(hmmFlank + hmmPad)) + " R = " + costR/(dpBatch.getProfileLength() - hmmFlank - hmmPad - period) + "\n"); outOS.print("##" + readSeq.getName() +"\t"+bestIter+"\t"+readSeq.length() +"\t" +alignScore+"\t" + alignScore/readSeq.length() + '\t' + costM + "\t" + costM / readSeq.length() + "\t" + costL + "\t" + stateL + "\t" + costR + "\t" + stateR + "\t" + (alignScore - costL - costR) + "\t" + stateRep + "\t" + pass + '\n'); outOS.print("==================================================================\n"); } } static private void processRead(Sequence readSeq, ProfileDP dp, double fraction, int hmmFlank, int hmmPad, int period, SequenceOutputStream outOS ) throws IOException{ MarkovExpert expert = new MarkovExpert(1); double costM = 0; for (int x = 0; x< readSeq.length();x++){ int base = readSeq.getBase(x); costM -= JapsaMath.log2(expert.update(base)); } double backGround = costM / readSeq.length() - 0.1; boolean pass = true; outOS.print("Markov " + costM + "\t" + (costM / readSeq.length()) + "\n"); EmissionState bestState = dp.align(readSeq); double alignScore = bestState.getScore(); //System.out.println("Score " + alignScore + " vs " + readSeq.length()*2 + " (" + alignScore/readSeq.length() +")"); double bestIter = bestState.getIter() + fraction; profilePositions.clear(); seqPositions.clear(); costGeneration.clear(); byteArray.clear(); //double oldCost = bestState.score; EmissionState lastState = bestState; bestState = bestState.bwdState; while (bestState != null){ profilePositions.add(bestState.profilePos); seqPositions.add(bestState.profilePos); costGeneration.add(lastState.score - bestState.score); if (bestState.seqPos == lastState.seqPos) byteArray.add((byte)Alphabet.DNA.GAP); else byteArray.add(readSeq.getBase(lastState.seqPos)); lastState = bestState; bestState = bestState.bwdState; } double costL = 0, costR = 0, costCurrentRep = 0, costRep = 0; int stateL = 0, stateR = 0, stateCurrentRep = 0, stateRep = 0; int baseL = 0, baseR = 0, baseCurrentRep = 0, baseRep = 0; int bSeqL = 0, bSeqR = 0, bSeqCurrentRep = 0, bSeqRep = 0; int lastProfilePos = -1, lastSeqPos = -1; for (int x = profilePositions.size() - 1; x >=0; x outOS.print(Alphabet.DNA().int2char(byteArray.get(x))); int profilePos = profilePositions.get(x); int seqPos = seqPositions.get(x); if (profilePos < hmmFlank + hmmPad){ stateL ++; costL += costGeneration.get(x); if (lastProfilePos != profilePos) baseL ++; if (lastSeqPos != seqPos) bSeqL ++; }else if(profilePos > hmmFlank + hmmPad + period){ stateR ++; costR += costGeneration.get(x); if (lastProfilePos != profilePos) baseR ++; if (lastSeqPos != seqPos) bSeqR ++; }else{ stateCurrentRep ++; costCurrentRep += costGeneration.get(x); stateRep ++; costRep += costGeneration.get(x); if (lastProfilePos != profilePos){ baseRep ++; baseCurrentRep ++; } if (lastSeqPos != seqPos){ bSeqRep ++; bSeqCurrentRep ++; } } //end of a repeat cycle if (profilePos < lastProfilePos){ outOS.print("< + " " + stateCurrentRep + " " + (stateCurrentRep == 0?"inf": "" + (costCurrentRep/stateCurrentRep)) + " " + baseCurrentRep + " " + (baseCurrentRep == 0?"inf": "" + (costCurrentRep/baseCurrentRep)) + " " + bSeqCurrentRep + " " + (bSeqCurrentRep == 0?"inf": "" + (costCurrentRep/bSeqCurrentRep)) ); if (costCurrentRep/bSeqCurrentRep > backGround){ pass = false; outOS.print(" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } outOS.println(); costCurrentRep = 0;//restart stateCurrentRep = 0;//restart baseCurrentRep = 0; bSeqCurrentRep = 0; } //left if (profilePos >= hmmFlank + hmmPad && lastProfilePos < hmmFlank + hmmPad){ outOS.print("< + " " + stateL + " " + (stateL == 0?"inf": "" + (costL/stateL)) + " " + baseL + " " + (baseL == 0?"inf": "" + (costL/baseL)) + " " + bSeqL + " " + (bSeqL == 0?"inf": "" + (costL/bSeqL)) ); if (costL/bSeqL > backGround){ pass = false; outOS.print(" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } outOS.println(); } //right //if (profilePos < hmmFlank + hmmPad + period && lastProfilePos >= hmmFlank + hmmPad + period){ // + " " + stateR // + " " + (stateR == 0?"inf": "" + (costR/stateR)) // + " " + baseR // + " " + (baseR == 0?"inf": "" + (costR/baseR)) // + " " + bSeqR // + " " + (bSeqR == 0?"inf": "" + (costR/bSeqR)) // outOS.println(); lastProfilePos = profilePos; lastSeqPos = seqPos; }//for x //move to out of the loop outOS.print("< + " " + stateR + " " + (stateR == 0?"inf": "" + (costR/stateR)) + " " + baseR + " " + (baseR == 0?"inf": "" + (costR/baseR)) + " " + bSeqR + " " + (bSeqR == 0?"inf": "" + (costR/bSeqR)) ); if (costR/bSeqR > backGround){ pass = false; outOS.print(" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); } //outOS.println(); outOS.println(); outOS.print ("L = " + (costL/(hmmFlank + hmmPad)) + " R = " + costR/(dp.getProfileLength() - hmmFlank - hmmPad - period) + "\n"); outOS.print("##" + readSeq.getName() +"\t"+bestIter+"\t"+readSeq.length() +"\t" +alignScore+"\t" + alignScore/readSeq.length() + '\t' + costM + "\t" + costM / readSeq.length() + "\t" + costL + "\t" + stateL + "\t" + costR + "\t" + stateR + "\t" + (alignScore - costL - costR) + "\t" + stateRep + "\t" + pass + '\n'); outOS.print("==================================================================\n"); } public static Sequence getReadPosition(SAMRecord rec, int startRef, int endRef){ byte[] seqRead = rec.getReadBases(); if (seqRead.length <= 1) return null; int startRead = -1, endRead = -1; int refPos = rec.getAlignmentStart(); int readPos = 0; //currentRefPos <= startRead for (final CigarElement e : rec.getCigar().getCigarElements()) { int length = e.getLength(); switch (e.getOperator()) { case H: break; // ignore hard clips case P: break; // ignore pads case S: readPos += e.getLength(); break; // soft clip read bases case N: // N ~ D case D: refPos += length; if (startRead < 0 && refPos >= startRef){ startRead = readPos; } if (endRead < 0 && refPos >= endRef){ endRead = readPos; } break;// case case I: readPos += length; break; case M: case EQ: case X: if ((startRead < 0) && refPos + length >= startRef) { startRead = readPos + startRef - refPos; } if ((endRead < 0) && (refPos + length >= endRef)){ endRead = readPos + endRef - refPos; } refPos += length; readPos += length; break; default: throw new IllegalStateException( "Case statement didn't deal with cigar op: " + e.getOperator()); }// case if (refPos >= endRef) break;//for }// for if (startRead < 0 || endRead < 0){ LOG.warn(" " + refPos + " " + readPos + " " + startRead + " " + endRead); return null; } Alphabet alphabet = Alphabet.DNA16(); Sequence retSeq = new Sequence(alphabet, endRead - startRead + 1, rec.getReadName() + "/" + startRead + "_" + endRead); for (int i = 0; i < retSeq.length();i++){ retSeq.setBase(i, alphabet.byte2index(seqRead[startRead + i])); } return retSeq; } }
package ucar.nc2.iosp.misc; import ucar.ma2.*; import ucar.nc2.*; import ucar.nc2.constants.AxisType; import ucar.nc2.constants.FeatureType; import ucar.nc2.constants._Coordinate; import ucar.nc2.iosp.AbstractIOServiceProvider; import ucar.nc2.util.CancelTask; import ucar.unidata.io.RandomAccessFile; import ucar.unidata.util.StringUtil; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.StringTokenizer; /** * IOSP for the USPLN/NAPLN original and extended formats. * <pre> * USPLN/NAPLN data format: * * Each 1 minute packet sent has an ASCII header, followed by a record for * each lightning detection during the past 1 minute. * * Header * The ASCII header provides information on the creation time of the one * minute packet and ending date and time of the file. * * Sample Header: * * (original format) * LIGHTNING-USPLN1,2004-10-11T20:45:02,2004-10-11T20:45:02 * * (extended format) * LIGHTNING-USPLN1EX,2004-10-11T20:45:02,2004-10-11T20:45:02 * * Description: * Name of Product: LIGHTNING-USPLN1 * Creation of 1 min Packet (yyyy-mm-ddThh:mm:ss): 2004-10-11T20:45:02 * Ending of 1 min Packet (yyyy-mm-ddThh:mm:ss): 2004-10-11T20:45:02 * * NOTE: All times in UTC * * Stroke Record Following the header, an individual record is provided for * each lightning stroke in a comma delimited format. * * Sample Stroke Records (original format): * 2004-10-11T20:44:02,32.6785331,-105.4344587,-96.1,1 * 2004-10-11T20:44:05,21.2628231,-86.9596634,53.1,1 * 2004-10-11T20:44:05,21.2967119,-86.9702106,50.3,1 * 2004-10-11T20:44:06,19.9044769,-100.7082608,43.1,1 * 2004-10-11T20:44:11,21.4523434,-82.5202274,-62.8,1 * 2004-10-11T20:44:11,21.8155306,-82.6708778,80.9,1 * * Sample Stroke Records (extended format): * 2004-10-11T20:44:02,32.6785331,-105.4344587,-96.1,0.5,0.25,0 * 2004-10-11T20:44:05,21.2628231,-86.9596634,53.1,0.25,0.25,41 * 2004-10-11T20:44:05,21.2967119,-86.9702106,50.3,0.25,0.25,78 * 2004-10-11T20:44:06,19.9044769,-100.7082608,43.1,0.75,0.25,-51 * 2004-10-11T20:44:11,21.4523434,-82.5202274,-62.8,0.25,0.25,-58 * 2004-10-11T20:44:11,21.8155306,-82.6708778,80.9,0.25,0.25,-86 * * Description: * * Stroke Date/Time (yyyy-mm-ddThh:mm:ss): 2004-10-11T20:44:02 * * Stroke Latitude (deg): 32.6785331 * Stroke Longitude (deg): -105.4344587 * Stroke Amplitude (kAmps, see note below): -96.1 * * (original format) * Stroke Count (number of strokes per flash): 1 * Note: At the present time USPLN data are only provided in stroke format, * so the stroke count will always be 1. * * (extended format) * Error Ellipse Major Axis (km): 0.5 * Error Ellipse Minor Axis (km): 0.25 * Error Ellipse Major Axis Orientation (degrees): 0 * * Notes about Decoding Stroke Amplitude * The amplitude field is utilized to indicate the amplitude of strokes and * polarity of strokes for all Cloud-to- Ground Strokes. * * For other types of detections this field is utilized to provide * information on the type of stroke detected. * * The amplitude number for Cloud-to-Ground strokes provides the amplitude * of the stroke and the sign (+/-) provides the polarity of the stroke. * * An amplitude of 0 indicates USPLN Cloud Flash Detections rather than * Cloud-to-Ground detections. * * Cloud flash detections include cloud-to-cloud, cloud-to-air, and * intra-cloud flashes. * * An amplitude of -999 or 999 indicates a valid cloud-to-ground stroke * detection in which an amplitude was not able to be determined. Typically * these are long-range detections. * </pre> * * @author caron, dmurray */ public class Uspln extends AbstractIOServiceProvider { /** Magic string for determining if this is my type of file. */ private static final String MAGIC = "LIGHTNING-..PLN1"; /** Magic string for determining if this is my type of file. */ private static final String MAGIC_OLD = "..PLN-LIGHTNING"; /** Magic string for determining if this is and extended type of file. */ private static final String MAGIC_EX = ".*PLN1EX.*"; /** original time format */ private static final String TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; /** extended time format */ private static final String TIME_FORMAT_EX = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** is this extended data */ private boolean isExtended = false; /** the date variable name */ private static final String DATE = "date"; /** the latitude variable name */ private static final String LAT = "lat"; /** the longitude variable name */ private static final String LON = "lon"; /** the stroke amplitude variable name */ private static final String AMP = "strokeAmplitude"; /** the number of strokes variable name */ private static final String NSTROKES = "strokeCount"; /** the number of error ellipse major axis variable name */ private static final String MAJOR_AXIS = "errorEllipseMajorAxis"; /** the number of error ellipse minor axis variable name */ private static final String MINOR_AXIS = "errorEllipseMinorAxis"; /** the number of error ellipse major axis orientation variable name */ private static final String AXIS_ORIENT = "majorAxisOrientation"; /** offsets int the file */ private long[] offsets; /** max/min latitude */ private double lat_min, lat_max; /** max/min longitude */ private double lon_min, lon_max; /** max/min time */ private double time_min, time_max; /** * Check if this is a valid file for this IOServiceProvider. * * @param raf RandomAccessFile * @return true if valid. * @throws IOException if read error */ public boolean isValidFile(RandomAccessFile raf) throws IOException { raf.seek(0); int n = MAGIC.length(); if (raf.length() < n) { return false; } byte[] b = new byte[n]; raf.read(b); String got = new String(b); return StringUtil.regexpMatch(got, MAGIC) || StringUtil.regexpMatch(got, MAGIC_OLD); } /** * Open existing file, and populate ncfile with it. This method is only * called by the NetcdfFile constructor on itself. The provided NetcdfFile * object will be empty except for the location String and the * IOServiceProvider associated with this NetcdfFile object. * * @param raf the file to work on, it has already passed the * isValidFile() test. * @param ncfile add objects to this empty NetcdfFile * @param cancelTask used to monitor user cancellation; may be null. * @throws IOException if read error */ public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException { this.raf = raf; int n; try { n = readAllData(raf); } catch (ParseException e) { e.printStackTrace(); throw new IOException("bad data"); } Dimension recordDim = new Dimension("record", n, true, true, false); ncfile.addDimension(null, recordDim); Structure struct = new Structure(ncfile, null, null, "record"); struct.setDimensions("record"); ncfile.addVariable(null, struct); Variable date = new Variable(ncfile, null, null, DATE); date.setDimensions(""); date.setDataType(DataType.DOUBLE); String timeUnit = "seconds since 1970-01-01 00:00:00"; date.addAttribute(new Attribute("long_name", "time of stroke")); date.addAttribute(new Attribute("units", timeUnit)); date.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString())); struct.addMemberVariable(date); date.setSPobject(new IospData(0)); Variable lat = new Variable(ncfile, null, null, LAT); lat.setDimensions(""); lat.setDataType(DataType.DOUBLE); lat.addAttribute(new Attribute("long_name", "latitude")); lat.addAttribute(new Attribute("units", "degrees_north")); lat.addAttribute(new Attribute("standard_name", "latitude")); lat.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Lat.toString())); struct.addMemberVariable(lat); lat.setSPobject(new IospData(1)); Variable lon = new Variable(ncfile, null, null, LON); lon.setDimensions(""); lon.setDataType(DataType.DOUBLE); lon.addAttribute(new Attribute("long_name", "longitude")); lon.addAttribute(new Attribute("standard_name", "longitude")); lon.addAttribute(new Attribute("units", "degrees_east")); lon.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Lon.toString())); struct.addMemberVariable(lon); lon.setSPobject(new IospData(2)); Variable amp = new Variable(ncfile, null, null, AMP); amp.setDimensions(""); amp.setDataType(DataType.DOUBLE); amp.addAttribute(new Attribute("long_name", "amplitude of stroke")); amp.addAttribute(new Attribute("units", "kAmps")); amp.addAttribute(new Attribute("missing_value", new Double(999))); struct.addMemberVariable(amp); amp.setSPobject(new IospData(3)); if (isExtended) { // major axis Variable majorAxis = new Variable(ncfile, null, null, MAJOR_AXIS); majorAxis.setDimensions(""); majorAxis.setDataType(DataType.DOUBLE); majorAxis.addAttribute(new Attribute("long_name", "error ellipse major axis")); majorAxis.addAttribute(new Attribute("units", "km")); struct.addMemberVariable(majorAxis); majorAxis.setSPobject(new IospData(4)); // minor axis Variable minorAxis = new Variable(ncfile, null, null, MINOR_AXIS); minorAxis.setDimensions(""); minorAxis.setDataType(DataType.DOUBLE); minorAxis.addAttribute(new Attribute("long_name", "error ellipse minor axis")); minorAxis.addAttribute(new Attribute("units", "km")); struct.addMemberVariable(minorAxis); minorAxis.setSPobject(new IospData(5)); // major axis orientation Variable axisOrient = new Variable(ncfile, null, null, AXIS_ORIENT); axisOrient.setDimensions(""); axisOrient.setDataType(DataType.INT); axisOrient.addAttribute(new Attribute("long_name", "orientation of error ellipse major axis")); axisOrient.addAttribute(new Attribute("units", "degrees")); struct.addMemberVariable(axisOrient); axisOrient.setSPobject(new IospData(6)); } else { // original format // number of strokes Variable nstrokes = new Variable(ncfile, null, null, NSTROKES); nstrokes.setDimensions(""); nstrokes.setDataType(DataType.INT); nstrokes.addAttribute(new Attribute("long_name", "number of strokes per flash")); nstrokes.addAttribute(new Attribute("units", "")); struct.addMemberVariable(nstrokes); nstrokes.setSPobject(new IospData(4)); } ncfile.addAttribute(null, new Attribute("title", "USPN Lightning Data")); ncfile.addAttribute( null, new Attribute("history", "Read directly by Netcdf Java IOSP")); ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.POINT.toString())); ncfile.addAttribute(null, new Attribute("observationDimension", "record")); ncfile.addAttribute(null, new Attribute("time_coverage_start", time_min + " " + timeUnit)); ncfile.addAttribute(null, new Attribute("time_coverage_end", time_max + " " + timeUnit)); ncfile.addAttribute(null, new Attribute("geospatial_lat_min", new Double(lat_min))); ncfile.addAttribute(null, new Attribute("geospatial_lat_max", new Double(lat_max))); ncfile.addAttribute(null, new Attribute("geospatial_lon_min", new Double(lon_min))); ncfile.addAttribute(null, new Attribute("geospatial_lon_max", new Double(lon_max))); ncfile.finish(); } // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,1 // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,0.25,0.5,80 /** * Read all the data and return the number of strokes * @param raf the file to read * @return the number of strokes * * @throws IOException if read error * @throws NumberFormatException if problem parsing data * @throws ParseException if parse problem */ int readAllData(RandomAccessFile raf) throws IOException, NumberFormatException, ParseException { ArrayList offsetList = new ArrayList(); java.text.SimpleDateFormat isoDateTimeFormat = new java.text.SimpleDateFormat(TIME_FORMAT); isoDateTimeFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); lat_min = 1000.0; lat_max = -1000.0; lon_min = 1000.0; lon_max = -1000.0; time_min = Double.POSITIVE_INFINITY; time_max = Double.NEGATIVE_INFINITY; raf.seek(0); int count = 0; boolean knowExtended = false; while (true) { long offset = raf.getFilePointer(); String line = raf.readLine(); if (line == null) { break; } if (StringUtil.regexpMatch(line, MAGIC) || StringUtil.regexpMatch(line, MAGIC_OLD)) { if ( !knowExtended) { isExtended = StringUtil.regexpMatch(line, MAGIC_EX); if (isExtended) { isoDateTimeFormat.applyPattern(TIME_FORMAT_EX); } knowExtended = true; } continue; } StringTokenizer stoker = new StringTokenizer(line, ",\r\n"); while (stoker.hasMoreTokens()) { Date date = isoDateTimeFormat.parse(stoker.nextToken()); double lat = Double.parseDouble(stoker.nextToken()); double lon = Double.parseDouble(stoker.nextToken()); double amp = Double.parseDouble(stoker.nextToken()); int nstrokes = 1; double axisMaj = Double.NaN; double axisMin = Double.NaN; int orient = 0; if (isExtended) { axisMaj = Double.parseDouble(stoker.nextToken()); axisMin = Double.parseDouble(stoker.nextToken()); orient = Integer.parseInt(stoker.nextToken()); } else { nstrokes = Integer.parseInt(stoker.nextToken()); } Stroke s = isExtended ? new Stroke(date, lat, lon, amp, axisMaj, axisMin, orient) : new Stroke(date, lat, lon, amp, nstrokes); lat_min = Math.min(lat_min, s.lat); lat_max = Math.max(lat_max, s.lat); lon_min = Math.min(lon_min, s.lon); lon_max = Math.max(lon_max, s.lon); time_min = Math.min(time_min, s.date); time_max = Math.max(time_max, s.date); } offsetList.add(new Long(offset)); count++; } offsets = new long[count]; for (int i = 0; i < offsetList.size(); i++) { Long off = (Long) offsetList.get(i); offsets[i] = off.longValue(); } //System.out.println("processed " + count + " records"); return count; } /** * Class to hold stroke information */ private class Stroke { /** the date as seconds since the epoch */ double date; /** lat, lon and amplitude */ double lat, lon, amp; /** number of strokes */ int n = 1; /** major axis */ double axisMajor; /** minor axis */ double axisMinor; /** major axis orientation */ int axisOrient; /** * Create a Stroke from the file data and time formatter * * @param offset offset into the file * @param isoDateTimeFormat the time formatter * * @throws IOException problem reading the file * @throws ParseException problem parsing the file */ Stroke(long offset, java.text.SimpleDateFormat isoDateTimeFormat) throws IOException, ParseException { raf.seek(offset); String line = raf.readLine(); if ((line == null) || StringUtil.regexpMatch(line, MAGIC) || StringUtil.regexpMatch(line, MAGIC_OLD)) { throw new IllegalStateException(); } StringTokenizer stoker = new StringTokenizer(line, ",\r\n"); Date date = isoDateTimeFormat.parse(stoker.nextToken()); makeDate(date); lat = Double.parseDouble(stoker.nextToken()); lon = Double.parseDouble(stoker.nextToken()); amp = Double.parseDouble(stoker.nextToken()); if (isExtended) { n = 1; axisMajor = Double.parseDouble(stoker.nextToken()); axisMinor = Double.parseDouble(stoker.nextToken()); axisOrient = Integer.parseInt(stoker.nextToken()); } else { n = Integer.parseInt(stoker.nextToken()); } } /** * Create a stroke from the info * * @param date The Date * @param lat the latitude * @param lon the longitude * @param amp the amplitude * @param n the number of strokes */ Stroke(Date date, double lat, double lon, double amp, int n) { makeDate(date); this.lat = lat; this.lon = lon; this.amp = amp; this.n = n; } /** * Create a stroke from the info * * @param date The Date * @param lat the latitude * @param lon the longitude * @param amp the amplitude * @param maj error ellipse major axis * @param min error ellipse minor axis * @param orient orientation of the major axis */ Stroke(Date date, double lat, double lon, double amp, double maj, double min, int orient) { makeDate(date); this.lat = lat; this.lon = lon; this.amp = amp; this.axisMajor = maj; this.axisMinor = min; this.axisOrient = orient; } /** * Make the date variable * * @param date the date */ void makeDate(Date date) { this.date = (int) (date.getTime() / 1000); } /** * Get a String representation of this object * * @return the String representation */ public String toString() { return (isExtended) ? lat + " " + lon + " " + amp + " " + axisMajor + "/" + axisMinor + " " + axisOrient : lat + " " + lon + " " + amp + " " + n; } } /** * Class to hold index information */ private class IospData { /** the variable number */ int varno; /** * Create a holder for the variable number * * @param varno the number */ IospData(int varno) { this.varno = varno; } } /** * Read nested data * * @param v2 the variable * @param section the data * * @return the array * * @throws IOException problem reading the data * @throws InvalidRangeException invalid range */ public Array readNestedData(Variable v2, Section section) throws IOException, InvalidRangeException { IospData iospd = (IospData) v2.getSPobject(); java.text.SimpleDateFormat isoDateTimeFormat = new java.text.SimpleDateFormat(); isoDateTimeFormat.applyPattern(isExtended ? TIME_FORMAT_EX : TIME_FORMAT); isoDateTimeFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); int[] sectionShape = section.getShape(); Array data = Array.factory(v2.getDataType(), sectionShape); Index ima = data.getIndex(); int count = 0; Range r = (Range) section.getRange(0); Range.Iterator riter = r.getIterator(); while (riter.hasNext()) { int index = riter.next(); long offset = offsets[index]; Stroke s; try { s = new Stroke(offset, isoDateTimeFormat); } catch (ParseException e) { throw new IOException(e.getMessage()); } ima.set(count); switch (iospd.varno) { case 0 : data.setDouble(ima, s.date); break; case 1 : data.setDouble(ima, s.lat); break; case 2 : data.setDouble(ima, s.lon); break; case 3 : data.setDouble(ima, s.amp); break; case 4 : if (isExtended) { data.setDouble(ima, s.axisMajor); } else { data.setInt(ima, s.n); } break; case 5 : data.setDouble(ima, s.axisMinor); break; case 6 : data.setInt(ima, s.axisOrient); break; } count++; } return data; } /** * Read data from a top level Variable and return a memory resident Array. * This Array has the same element type as the Variable, and the requested shape. * * @param v2 a top-level Variable * @param section the section of data to read. * There must be a Range for each Dimension in the variable, in order. * Note: no nulls allowed. IOSP may not modify. * @return the requested data in a memory-resident Array * @throws IOException if read error * @throws InvalidRangeException if invalid section * @see ucar.ma2.Range */ public Array readData(Variable v2, Section section) throws IOException, InvalidRangeException { java.text.SimpleDateFormat isoDateTimeFormat = new java.text.SimpleDateFormat(); isoDateTimeFormat.applyPattern(isExtended ? TIME_FORMAT_EX : TIME_FORMAT); isoDateTimeFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); Structure struct = (Structure) v2; int[] sectionShape = section.getShape(); ArrayStructureMA structData = new ArrayStructureMA(struct.makeStructureMembers(), sectionShape); ArrayDouble.D1 dateArray = (ArrayDouble.D1) Array.factory(DataType.DOUBLE, sectionShape); ArrayDouble.D1 latArray = (ArrayDouble.D1) Array.factory(DataType.DOUBLE, sectionShape); ArrayDouble.D1 lonArray = (ArrayDouble.D1) Array.factory(DataType.DOUBLE, sectionShape); ArrayDouble.D1 ampArray = (ArrayDouble.D1) Array.factory(DataType.DOUBLE, sectionShape); ArrayInt.D1 nstrokesArray = (ArrayInt.D1) Array.factory(DataType.INT, sectionShape); ArrayDouble.D1 majorAxisArray = (ArrayDouble.D1) Array.factory(DataType.DOUBLE, sectionShape); ArrayDouble.D1 minorAxisArray = (ArrayDouble.D1) Array.factory(DataType.DOUBLE, sectionShape); ArrayInt.D1 axisOrientArray = (ArrayInt.D1) Array.factory(DataType.INT, sectionShape); structData.setMemberArray(DATE, dateArray); structData.setMemberArray(LAT, latArray); structData.setMemberArray(LON, lonArray); structData.setMemberArray(AMP, ampArray); if (isExtended) { structData.setMemberArray(MAJOR_AXIS, majorAxisArray); structData.setMemberArray(MINOR_AXIS, minorAxisArray); structData.setMemberArray(AXIS_ORIENT, axisOrientArray); } else { structData.setMemberArray(NSTROKES, nstrokesArray); } int count = 0; Range r = section.getRange(0); Range.Iterator riter = r.getIterator(); while (riter.hasNext()) { int index = riter.next(); long offset = offsets[index]; try { Stroke s = new Stroke(offset, isoDateTimeFormat); dateArray.set(count, s.date); latArray.set(count, s.lat); lonArray.set(count, s.lon); ampArray.set(count, s.amp); if (isExtended) { majorAxisArray.set(count, s.axisMajor); minorAxisArray.set(count, s.axisMinor); axisOrientArray.set(count, s.axisOrient); } else { nstrokesArray.set(count, s.n); } count++; } catch (ParseException e) { throw new IOException(e.getMessage()); } } return structData; } public String getFileTypeId() { return "USPLN"; } public String getFileTypeDescription() { return "US Precision Lightning Network"; } public String getFileTypeVersion() { return "1"; } }
package uk.co.imallan.tuchongdaily; import android.test.AndroidTestCase; import android.util.Log; import uk.co.imallan.tuchongdaily.api.APIFactory; import uk.co.imallan.tuchongdaily.api.Response; import uk.co.imallan.tuchongdaily.api.data.DataPosts; public class APITest extends AndroidTestCase { private static final String LOG_TAG = APITest.class.getSimpleName(); public void testAPIGetPosts() throws Exception { Response<DataPosts> posts = APIFactory.instance().getPosts(); Log.v(LOG_TAG, String.valueOf(posts.getData().getPosts().size())); Log.v(LOG_TAG, posts.getData().getPosts().get(0).getTags()); } }
package cav.pdst.ui.fragments; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; 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.AdapterView; import android.widget.ListView; import java.text.SimpleDateFormat; import java.util.ArrayList; import cav.pdst.R; import cav.pdst.data.managers.DataManager; import cav.pdst.data.models.AbonementModel; import cav.pdst.data.models.SportsmanModel; import cav.pdst.services.AlarmTaskReciver; import cav.pdst.ui.activity.AbonementActivity; import cav.pdst.ui.adapters.AbonementAdapter; import cav.pdst.utils.ConstantManager; import cav.pdst.utils.Utils; public class SpAbonementFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener { private static final String TAG = "SPAB"; private static final String SPORTSMAN_ID = "SP_ID"; private static final String MODE = "SP_MODE"; private static final String SPORTSMAN_NAME = "SP_NAME"; private ListView mListView; private AbonementAdapter mAbonementAdapter; private FloatingActionButton mFab; private DataManager mDataManager; private int sp_id; private String sp_name; private int mode; private int last_ab = 1; private AbonementCallback mAbonementCallback; public interface AbonementCallback { void updateData(AbonementModel model); } public static SpAbonementFragment newInstance(SportsmanModel model, int mode){ Bundle args = new Bundle(); if (model != null) { args.putSerializable(SPORTSMAN_ID, model.getId()); args.putString(SPORTSMAN_NAME, model.getName()); } else { args.putSerializable(SPORTSMAN_ID,-1); args.putString(SPORTSMAN_NAME,""); } args.putSerializable(MODE,mode); SpAbonementFragment fragment = new SpAbonementFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDataManager = DataManager.getInstance(); this.sp_id = getArguments().getInt(SPORTSMAN_ID); this.mode = getArguments().getInt(MODE); this.sp_name = getArguments().getString(SPORTSMAN_NAME); setHasOptionsMenu(true); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mAbonementCallback = (AbonementCallback) activity; } @Override public void onDetach() { super.onDetach(); mAbonementCallback = null; } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sp_abonement, container, false); mListView = (ListView) rootView.findViewById(R.id.sp_abom_list_view); mListView.setOnItemClickListener(this); mFab = (FloatingActionButton) rootView.findViewById(R.id.frm_abonement_fab); mFab.setOnClickListener(this); if (mode != ConstantManager.VIEW_SPORTSMAN) { mListView.setOnItemLongClickListener(this); }else { mFab.setEnabled(false); mFab.setVisibility(View.GONE); } updateUI(); return rootView; //return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.save_item: return false; case R.id.edit_tr_item: this.mode = ConstantManager.EDIT_SPORTSMAN; mFab.setVisibility(View.VISIBLE); mFab.setEnabled(true); //mFab.setOnClickListener(this); mListView.setOnItemLongClickListener(this); //mFab.setFocusableInTouchMode(true); // mFab.requestFocus(); return true; } return false; } public void updateUI(){ ArrayList<AbonementModel> data = mDataManager.getAbonement(sp_id); if (data.size()!= 0) { last_ab = data.get(data.size()-1).getId(); last_ab = last_ab + 1; } if (mAbonementAdapter == null){ mAbonementAdapter = new AbonementAdapter(this.getContext(),R.layout.abinement_item,data); mListView.setAdapter(mAbonementAdapter); }else { mAbonementAdapter.setData(data); mAbonementAdapter.notifyDataSetChanged(); mListView.setAdapter(mAbonementAdapter); } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { final AbonementModel model = (AbonementModel) adapterView.getItemAtPosition(position); int lmode = ConstantManager.VIEW_ABONEMENT; Intent intent = new Intent(SpAbonementFragment.this.getContext(), AbonementActivity.class); intent.putExtra(ConstantManager.AB_DETAIL_DATA,model); switch (mode){ case ConstantManager.EDIT_SPORTSMAN: lmode = ConstantManager.EDIT_ABONEMENT; intent.putExtra(ConstantManager.MODE_ABONEMENT,ConstantManager.EDIT_ABONEMENT); break; case ConstantManager.VIEW_SPORTSMAN: lmode = ConstantManager.VIEW_ABONEMENT; } intent.putExtra(ConstantManager.MODE_ABONEMENT,lmode); if (lmode == ConstantManager.VIEW_ABONEMENT) { startActivity(intent); }else { startActivityForResult(intent, ConstantManager.EDIT_ABONEMENT); } } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { final AbonementModel model = (AbonementModel) adapterView.getItemAtPosition(position); /* EditDeleteDialog dialog = EditDeleteDialog.newInstance(); dialog.setEditDeleteDialogListener(new EditDeleteDialog.EditDeleteDialogListener() { @Override public void onDialogItemClick(int selectItem) { if (selectItem==R.id.dialog_del_item) { mDataManager.delAbonememet(model.getId(),model.getSpId()); mAbonementAdapter.remove(model); } if (selectItem == R.id.dialog_edit_item){ Intent intent = new Intent(SpAbonementFragment.this.getContext(), AbonementActivity.class); intent.putExtra(ConstantManager.MODE_ABONEMENT,ConstantManager.EDIT_ABONEMENT); intent.putExtra(ConstantManager.AB_DETAIL_DATA,model); startActivityForResult(intent,ConstantManager.EDIT_ABONEMENT); } } }); FragmentManager fm = getChildFragmentManager(); dialog.show(fm,ConstantManager.DIALOG_EDIT_DEL); */ AlertDialog.Builder dialog = new AlertDialog.Builder(this.getContext()); dialog.setTitle("Удаление").setMessage("Вы уверены что хотите удалить ?"); dialog.setIcon(android.R.drawable.ic_dialog_info); dialog.setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int i) { if (mDataManager.getDB().isUseAbomenet(model.getId(),model.getSpId())) { showInfoDialog(); } else { mDataManager.delAbonememet(model.getId(), model.getSpId()); mAbonementAdapter.remove(model); } } }); dialog.setNegativeButton(R.string.dialog_no, null); //dialog.create(); dialog.show(); return true; } private void showInfoDialog(){ AlertDialog.Builder dialog = new AlertDialog.Builder(this.getContext()); dialog.setTitle("Внимание !") .setMessage("По данному абонементу есть тренировки ! Удаление запрещено !") .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(R.string.dialog_yes,null).create(); dialog.show(); } @Override public void onClick(View view) { Intent intent = new Intent(this.getContext(), AbonementActivity.class); intent.putExtra(ConstantManager.MODE_ABONEMENT,ConstantManager.NEW_ABONEMENT); startActivityForResult(intent,ConstantManager.NEW_ABONEMENT); } @Override public void onResume() { super.onResume(); //updateUI(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data!=null){ String createDate; String startDate; String endDate; int countTr; float pay; String comment; switch (requestCode){ case ConstantManager.NEW_ABONEMENT: createDate = data.getStringExtra(ConstantManager.AB_CREATEDATE); startDate = data.getStringExtra(ConstantManager.AB_STARTDATE); endDate = data.getStringExtra(ConstantManager.AB_ENDDATE); countTr = data.getIntExtra(ConstantManager.AB_COUNT_TR,0); pay = data.getFloatExtra(ConstantManager.AB_PAY,0.0f); comment = data.getStringExtra(ConstantManager.AB_COMMENT); int type = data.getIntExtra(ConstantManager.AB_TYPE,0); float debit = data.getFloatExtra(ConstantManager.AB_DEBIT,0.0f); String sDateDebit = data.getStringExtra(ConstantManager.AB_DEBIT_DATETIME); AbonementModel model = Utils.getConvertModel(sp_id,last_ab,createDate,startDate,endDate,countTr,pay,comment); model.setType(type); model.setDebit(debit); if (sDateDebit.length()!=0) { model.setDebitDate(Utils.getSteToDate(sDateDebit, "dd.MM.yyyy HH:mm")); } mAbonementAdapter.add(model); mDataManager.addUpdateAbonement(model); last_ab = last_ab + 1; /* if (sp_id != -1){ mDataManager.addUpdateAbonement(model); last_ab = last_ab + 1; }else { mAbonementAdapter.add(model); } */ if (model.getDebitDate()!=null){ Utils.startAlarm(this.getContext(),model.getDebitDate(), sp_name+" : ("+model.getDebit()+")" +new SimpleDateFormat("dd.MM.yy HH:mm").format(model.getDebitDate()), model.getSpId()); } updateUI(); break; case ConstantManager.EDIT_ABONEMENT: AbonementModel model2= data.getParcelableExtra(ConstantManager.AB_DETAIL_DATA); mDataManager.addUpdateAbonement(model2); mAbonementAdapter.add(model2); if (model2.getDebitDate()!=null){ Utils.startAlarm(this.getContext(),model2.getDebitDate(), sp_name+" : ("+model2.getDebit()+")" + new SimpleDateFormat("dd.MM.yy HH:mm").format(model2.getDebitDate()), model2.getSpId()); } updateUI(); break; } } } }
package com.apps.adrcotfas.goodtime; import android.app.IntentService; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import android.text.format.DateFormat; import java.util.Calendar; import static android.app.PendingIntent.FLAG_ONE_SHOT; import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; import static android.app.PendingIntent.getActivity; import static android.graphics.Color.WHITE; import static android.media.AudioAttributes.USAGE_ALARM; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.support.v4.app.NotificationCompat.PRIORITY_HIGH; import static android.support.v4.app.NotificationCompat.VISIBILITY_PUBLIC; import static com.apps.adrcotfas.goodtime.TimerState.PAUSED; public final class Notifications { final static String ACTION_PAUSE_UI = "com.apps.adrcotfas.goodtime.PAUSE_UI"; final static String ACTION_STOP_UI = "com.apps.adrcotfas.goodtime.STOP_UI"; final static String ACTION_START_BREAK_UI = "com.apps.adrcotfas.goodtime.START_BREAK_UI"; final static String ACTION_SKIP_BREAK_UI = "com.apps.adrcotfas.goodtime.SKIP_BREAK_UI"; final static String ACTION_START_WORK_UI = "com.apps.adrcotfas.goodtime.START_WORK_UI"; private final static String ACTION_PAUSE = "com.apps.adrcotfas.goodtime.PAUSE"; private final static String ACTION_STOP = "com.apps.adrcotfas.goodtime.STOP"; private final static String ACTION_START_BREAK = "com.apps.adrcotfas.goodtime.START_BREAK"; private final static String ACTION_SKIP_BREAK = "com.apps.adrcotfas.goodtime.SKIP_BREAK"; private final static String ACTION_START_WORK = "com.apps.adrcotfas.goodtime.START_WORK"; static Notification createCompletionNotification( Context context, SessionType sessionType, String notificationSound, boolean vibrate, boolean addButtons ) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(R.drawable.ic_status_goodtime) .setPriority(PRIORITY_HIGH) .setVisibility(VISIBILITY_PUBLIC) .setLights(WHITE, 250, 750) .setContentTitle(buildCompletedNotificationTitle(context, sessionType)) .setContentText(buildCompletedNotificationText(context, sessionType)) .setContentIntent( getActivity( context, 0, new Intent(context.getApplicationContext(), TimerActivity.class), FLAG_ONE_SHOT )) .setAutoCancel(true); if(addButtons) { NotificationCompat.WearableExtender extender = new NotificationCompat.WearableExtender(); if (isWorkingSession(sessionType)) { NotificationCompat.Action startBreakAction = createStartBreakAction(context); NotificationCompat.Action skipBreakAction = createSkipBreakAction(context); builder.addAction(startBreakAction) .addAction(skipBreakAction); extender.addAction(startBreakAction) .addAction(skipBreakAction); } else { NotificationCompat.Action startWorkAction = createStartWorkAction(context); builder.addAction(startWorkAction); extender.addAction(startWorkAction); } builder.extend(extender); } if (vibrate) { builder.setVibrate(new long[]{0, 300, 700, 300}); } if (!notificationSound.equals("")) { if (SDK_INT >= LOLLIPOP) { builder.setSound(Uri.parse(notificationSound), USAGE_ALARM); } else { builder.setSound(Uri.parse(notificationSound), AudioManager.STREAM_ALARM); } } return builder.build(); } private static CharSequence buildCompletedNotificationTitle(Context context, SessionType sessionType) { switch (sessionType) { case BREAK: case LONG_BREAK: return context.getString(R.string.dialog_break_message); case WORK: default: return context.getString(R.string.dialog_session_message); } } private static CharSequence buildCompletedNotificationText(Context context, SessionType sessionType) { switch (sessionType) { case BREAK: case LONG_BREAK: return context.getString(R.string.notification_break_complete); case WORK: default: return context.getString(R.string.notification_work_complete); } } static Notification createForegroundNotification( Context context, SessionType sessionType, TimerState timerState, int remainingTime ) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(R.drawable.ic_status_goodtime) .setAutoCancel(false) .setContentTitle(context.getString(R.string.app_name)) .setContentText(buildForegroundNotificationText(context, sessionType, timerState, remainingTime)) .setVisibility(VISIBILITY_PUBLIC) .setOngoing(isTimerActive(timerState)) .setShowWhen(false) .setContentIntent( getActivity( context, 0, new Intent(context.getApplicationContext(), TimerActivity.class), FLAG_UPDATE_CURRENT )); builder.addAction(createStopAction(context)); if (isWorkingSession(sessionType)) { builder.addAction( isTimerActive(timerState) ? createPauseAction(context) : createResumeAction(context)); } return builder.build(); } private static CharSequence buildForegroundNotificationText( Context context, SessionType sessionType, TimerState timerState, int remainingTime ) { switch (sessionType) { case BREAK: case LONG_BREAK: return context.getString(R.string.notification_break) + buildNotificationCountdownTime(context, remainingTime); case WORK: default: if (timerState == PAUSED) { return context.getString(R.string.notification_pause); } else { return context.getString(R.string.notification_session) + buildNotificationCountdownTime(context, remainingTime); } } } private static CharSequence buildNotificationCountdownTime(Context context, int remainingTime) { boolean is24HourFormat = android.text.format.DateFormat.is24HourFormat(context); String inFormat = is24HourFormat ? " k:mm" : " h:mm aa"; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, remainingTime); return DateFormat.format(inFormat, calendar) + "."; } private static boolean isTimerActive(TimerState timerState) { switch (timerState) { case INACTIVE: case PAUSED: return false; case ACTIVE: default: return true; } } private static boolean isWorkingSession(SessionType sessionType) { return sessionType.equals(SessionType.WORK); } private static NotificationCompat.Action createStartBreakAction(Context context) { Intent startBreakIntent = new Intent(context, NotificationActionService.class) .setAction(ACTION_START_BREAK); PendingIntent startBreakPendingIntent = PendingIntent.getService( context, 0, startBreakIntent, PendingIntent.FLAG_CANCEL_CURRENT); return new NotificationCompat.Action.Builder( R.drawable.ic_notification_resume, context.getString(R.string.dialog_session_break), startBreakPendingIntent).build(); } private static NotificationCompat.Action createSkipBreakAction(Context context) { Intent skipBreakIntent = new Intent(context, NotificationActionService.class) .setAction(ACTION_SKIP_BREAK); PendingIntent skipBreakPendingIntent = PendingIntent.getService( context, 0, skipBreakIntent, PendingIntent.FLAG_CANCEL_CURRENT); return new NotificationCompat.Action.Builder( R.drawable.ic_notification_skip, context.getString(R.string.dialog_session_skip), skipBreakPendingIntent).build(); } private static NotificationCompat.Action createStartWorkAction(Context context) { Intent startWorkIntent = new Intent(context, NotificationActionService.class) .setAction(ACTION_START_WORK); PendingIntent startWorkPendingIntent = PendingIntent.getService( context, 0, startWorkIntent, PendingIntent.FLAG_CANCEL_CURRENT); return new NotificationCompat.Action.Builder( R.drawable.ic_notification_resume, context.getString(R.string.dialog_break_session), startWorkPendingIntent).build(); } private static NotificationCompat.Action createPauseAction(Context context) { Intent pauseIntent = new Intent(context, NotificationActionService.class) .setAction(ACTION_PAUSE); PendingIntent pausePendingIntent = PendingIntent.getService( context, 0, pauseIntent, PendingIntent.FLAG_CANCEL_CURRENT); return new NotificationCompat.Action.Builder( R.drawable.ic_notification_pause, context.getString(R.string.pause), pausePendingIntent).build(); } private static NotificationCompat.Action createResumeAction(Context context) { Intent pauseIntent = new Intent(context, NotificationActionService.class) .setAction(ACTION_PAUSE); PendingIntent pausePendingIntent = PendingIntent.getService( context, 0, pauseIntent, PendingIntent.FLAG_CANCEL_CURRENT); return new NotificationCompat.Action.Builder( R.drawable.ic_notification_resume, context.getString(R.string.resume), pausePendingIntent).build(); } private static NotificationCompat.Action createStopAction(Context context) { Intent stopIntent = new Intent(context, NotificationActionService.class) .setAction(ACTION_STOP); PendingIntent stopPendingIntent = PendingIntent.getService( context, 0, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT); return new NotificationCompat.Action.Builder( R.drawable.ic_notification_stop, context.getString(R.string.stop), stopPendingIntent).build(); } public static class NotificationActionService extends IntentService { public NotificationActionService() { super(NotificationActionService.class.getSimpleName()); } @Override protected void onHandleIntent(Intent intent) { switch (intent.getAction()) { case ACTION_PAUSE: LocalBroadcastManager.getInstance(this).sendBroadcast( new Intent(ACTION_PAUSE_UI)); break; case ACTION_STOP: LocalBroadcastManager.getInstance(this).sendBroadcast( new Intent(ACTION_STOP_UI)); break; case ACTION_SKIP_BREAK: LocalBroadcastManager.getInstance(this).sendBroadcast( new Intent(ACTION_SKIP_BREAK_UI)); break; case ACTION_START_BREAK: LocalBroadcastManager.getInstance(this).sendBroadcast( new Intent(ACTION_START_BREAK_UI)); break; case ACTION_START_WORK: LocalBroadcastManager.getInstance(this).sendBroadcast( new Intent(ACTION_START_WORK_UI)); break; } } } }
package com.gcw.sapienza.places; import android.app.Application; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import com.cgw.sapienza.places.model.Flag; import com.parse.LogInCallback; import com.parse.Parse; import com.parse.ParseObject; import com.parse.ParseUser; import com.parse.ParseException; public class PlacesApplication extends Application{ //just the tag for logging private static final String TAG = "PlacesApplication"; //Parse.com app key private static final String PARSE_COM_APP_KEY = "BWtqN9x6uyr935MKAROcWkc6mzv8KLQMMVnFGHps"; //Parse.com client key private static final String PARSE_COM_CLIENT_KEY = "Gr1g8Z2kfv3AOZqToZ30hyMyNzH24vj4yudNoKfb"; //Shared location manager //fixme find a better way to handle GPS private LocationManager locationManager; //current location private Location currentLocation = null; //method called when the app is launched @Override public void onCreate() { super.onCreate(); //initialize the location manager this.initLocationManager(); // initialize Parse.com ParseObject.registerSubclass(Flag.class); Parse.initialize(this, PARSE_COM_APP_KEY , PARSE_COM_CLIENT_KEY); //todo when we will have login/signup screen we can remove this. It is just for simulating a logged in user if(ParseUser.getCurrentUser() != null){ Log.d(TAG, "Already logged in as: " + ParseUser.getCurrentUser().getUsername()); } else{ ParseUser.logInInBackground("test_user", "test_pwd", new LogInCallback() { @Override public void done(ParseUser user, ParseException e) { if (user != null) { Log.d(TAG, "Logged in as: " + ParseUser.getCurrentUser().getUsername()); } else { Log.d(TAG, "Login failed: " + e.getMessage()); } } }); } Log.d(TAG, "Hi"); } private void initLocationManager(){ this.locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { PlacesApplication.this.currentLocation = location; } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } public Location getCurrentLocation(){ return this.currentLocation; } }
package com.github.beraboris.boxes.app; import android.content.Context; import android.content.res.TypedArray; import android.graphics.*; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * A view the user can draw on. Allows for saving of the drawing at a later time. */ public class CanvasView extends View { private Paint paint; private Path path; private Bitmap bitmap; private Canvas canvas; private float canvasX; private float canvasY; private float canvasWidth; private float canvasHeight; private RectF canvasBox; private OnTouchListener touchListener = new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: path.moveTo(event.getX() - canvasX, event.getY() - canvasY); break; case MotionEvent.ACTION_MOVE: path.lineTo(event.getX() - canvasX, event.getY() - canvasY); break; case MotionEvent.ACTION_UP: canvas.drawPath(path, paint); path.reset(); break; default: return false; } invalidate(); return true; } }; public CanvasView(Context context) { super(context); init(context, null, 0); } public CanvasView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public CanvasView(Context context, AttributeSet attrs, int style) { super(context, attrs, style); init(context, attrs, style); } private void init(Context context, AttributeSet attrs, int style) { canvasWidth = 640; canvasHeight = 480; int brushColor = Color.BLACK; float brushWidth = 20; if (attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CanvasView, style, 0); try { brushWidth = a.getDimension(R.styleable.CanvasView_brushWidth, brushWidth); brushColor = a.getColor(R.styleable.CanvasView_brushColor, brushColor); canvasHeight = a.getDimension(R.styleable.CanvasView_canvasHeight, canvasHeight); canvasWidth = a.getDimension(R.styleable.CanvasView_canvasWidth, canvasWidth); } finally { a.recycle(); } } bitmap = Bitmap.createBitmap( (int) Math.ceil(canvasWidth), (int) Math.ceil(canvasHeight), Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); canvas.drawColor(Color.WHITE); path = new Path(); paint = new Paint(Paint.DITHER_FLAG); paint.setStyle(Paint.Style.STROKE); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeJoin(Paint.Join.ROUND); paint.setColor(brushColor); paint.setStrokeWidth(brushWidth); this.setOnTouchListener(touchListener); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { canvasX = (w / 2) - canvasWidth / 2; canvasY = (h / 2) - canvasHeight / 2; canvasBox = new RectF(canvasX, canvasY, canvasX + canvasWidth, canvasY + canvasHeight); super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.clipRect(canvasBox); canvas.translate(canvasX, canvasY); canvas.drawBitmap(this.bitmap, 0, 0, paint); canvas.drawPath(path, paint); } public int getBrushColor() { return paint.getColor(); } public void setBrushColor(int color) { paint.setColor(color); } public float getBrushSize() { return paint.getStrokeWidth(); } public void setBrushSize(float size) { paint.setStrokeWidth(size); } }
package com.github.deckyfx.httprequest; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.github.deckyfx.persistentcookiejar.ClearableCookieJar; import java.net.URI; import java.util.HashMap; import java.util.List; import okhttp3.CacheControl; import okhttp3.Call; import okhttp3.Cookie; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; public class HTTPClient { private HttpUrl mBaseURL; private DBHelper DB; private CacheControl mCacheControl; private ClearableCookieJar mCookieStore; private OkHttpClient client; public HTTPClient() { this(new HTTPClient.ClientBuilder()); } public HTTPClient(HTTPClient client) { this(client.newClientBuilder()); } public HTTPClient(OkHttpClient.Builder builder) { this(new HTTPClient.ClientBuilder(builder)); } public HTTPClient(OkHttpClient client) { this(new HTTPClient.ClientBuilder(client.newBuilder())); } public HTTPClient(ClientBuilder clientBuilder) { this.setClientBuilder(clientBuilder); } public HTTPClient setClientBuilder(ClientBuilder clientBuilder) { this.client = clientBuilder.getBuilder().build(); this.mBaseURL = clientBuilder.mBaseURL; this.mCacheControl = clientBuilder.mCacheControl; this.mCookieStore = clientBuilder.mCookieStore; return this; } public ClientBuilder newClientBuilder() { return new ClientBuilder(this); } public static final class ClientBuilder { private OkHttpClient.Builder builder; private HttpUrl mBaseURL; private DBHelper DB; private CacheControl mCacheControl; private ClearableCookieJar mCookieStore; private ClientListener mClientistener; public ClientBuilder() { this.builder = new OkHttpClient.Builder(); } ClientBuilder(HTTPClient client) { this.builder = client.client.newBuilder(); } ClientBuilder(OkHttpClient client) { this.builder = client.newBuilder(); } ClientBuilder(ClientBuilder builder) { this.builder = builder.getBuilder(); } ClientBuilder(OkHttpClient.Builder builder) { this.setBuilder(builder); } public OkHttpClient.Builder getBuilder() { return this.builder; } public ClientBuilder setBuilder(OkHttpClient.Builder builder) { this.builder = builder; return this; } public HTTPClient build() { this.builder.eventListener(new PrintingEventListener(this.mClientistener)); return new HTTPClient(this); } public ClientBuilder setBaseURL(HttpUrl baseURL) { if (baseURL == null) throw new NullPointerException("url == null"); this.mBaseURL = baseURL; return this; } public ClientBuilder setBaseURL(String baseURL){ HttpUrl parsed = HttpUrl.parse(baseURL); if (parsed == null) throw new IllegalArgumentException("unexpected url: " + baseURL); this.setBaseURL(parsed); return this; } public ClientBuilder setCacheControl(CacheControl cacheControl){ this.mCacheControl = cacheControl; return this; } public ClientBuilder setCookieStore(ClearableCookieJar cookieStore){ this.mCookieStore = cookieStore; return this; } public ClientBuilder setDBCache(DBHelper dbhelper){ this.DB = dbhelper; return this; } public ClientBuilder setClientListener(ClientListener listener){ this.mClientistener = listener; return this; } } public void send(Request request) { Request.Builder builder = request.newBuilder(); if (request.url() == null && request.path() != null && this.mBaseURL != null) builder.url(this.mBaseURL).path(request.path()); if (this.DB != null) builder.dbHelper(this.DB); if (this.mCacheControl != null && request.cacheControl() == null) builder.cacheControl(this.mCacheControl); request = builder.build(true); // Final check url can not be empty if (request.url() == null) throw new NullPointerException("url == null"); okhttp3.Request req = new okhttp3.Request.Builder() .url(request.url()) .cacheControl(request.cacheControl()) .tag(request.tag()) .method(request.method(), request.body()) .headers(request.headers()) .build(); Call call = this.client.newCall(req); request.onStart(); if (!this.isNetworkAvailable(request.context())) { request.onNetworkError(); return; } call.enqueue(request); } public void cancelRequests(){ // Should watch this two line bellow! a dangerous method // Likely will trigger crash when type for suggestion search this.client.dispatcher().cancelAll(); for (Call call : this.client.dispatcher().queuedCalls()) { call.cancel(); } for (Call call : this.client.dispatcher().runningCalls()) { call.cancel(); } } public boolean isNetworkAvailable(Context ctx) { NetworkInfo localNetworkInfo = ((ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); return (localNetworkInfo != null) && (localNetworkInfo.isConnected()); } public HashMap<String, Cookie> getCookies(){ HashMap<String, Cookie> result = new HashMap<String, Cookie>(); List<Cookie> cookielist = this.mCookieStore.loadForRequest(this.mBaseURL); URI uri = this.mBaseURL.uri(); String domain = uri.getHost(); domain = domain.startsWith("www.") ? domain.substring(4) : domain; for (Cookie cookie : cookielist) { if (cookie.domain().equals(domain)) { result.put(cookie.name(), cookie); } } return result; } public HttpUrl getBaseURL(){ return this.mBaseURL; } public CacheControl getCacheControl(){ return this.mCacheControl; } public ClearableCookieJar getCookieStore(){ return this.mCookieStore; } public DBHelper getDBCache(){ return this.DB; } }
package com.google.samples.mysample; import android.service.headless.HomeService; import android.util.Log; import android.view.InputEvent; /** * Implement your device logic here. */ public class MyHomeService extends HomeService { private static final String TAG = "MyHomeService"; @Override public void onCreate() { Log.d(TAG, "Headless service created"); } @Override public void onInputEvent(InputEvent event) { Log.d(TAG, "Input event received: " + event); } }
package com.noprestige.kanaquiz.logs; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.TextView; import com.noprestige.kanaquiz.R; import java.text.DecimalFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import static java.util.Calendar.DAY_OF_MONTH; import static java.util.Calendar.DAY_OF_WEEK; import static java.util.Calendar.LONG; import static java.util.Calendar.MONTH; import static java.util.Calendar.YEAR; public class DailyLogItem extends LinearLayout { private TextView lblDate; private TextView lblCorrect; private TextView lblTotal; private TextView lblPercentage; private int correctAnswers = -1; private int totalAnswers = -1; private static final DecimalFormat PERCENT_FORMATTER = new DecimalFormat(" public DailyLogItem(Context context) { super(context); init(null, 0); } public DailyLogItem(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public DailyLogItem(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } private void init(AttributeSet attrs, int defStyle) { // Set up initial objects LayoutInflater.from(getContext()).inflate(R.layout.daily_log_item, this); lblDate = findViewById(R.id.lblDate); lblCorrect = findViewById(R.id.lblCorrect); lblTotal = findViewById(R.id.lblTotal); lblPercentage = findViewById(R.id.lblPercentage); } public void setFromRecord(DailyRecord record) { setDate(record.date); setCorrectAnswers(record.correct_answers); setTotalAnswers(record.correct_answers + record.incorrect_answers); } public void setDate(Date date) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); lblDate.setText(calendar.getDisplayName(DAY_OF_WEEK, LONG, Locale.getDefault())); lblDate.append(System.getProperty("line.separator")); lblDate.append(calendar.getDisplayName(MONTH, LONG, Locale.getDefault())); lblDate.append(" "); lblDate.append(Integer.toString(calendar.get(DAY_OF_MONTH))); lblDate.append(System.getProperty("line.separator")); lblDate.append(Integer.toString(calendar.get(YEAR))); } public void setCorrectAnswers(int correctAnswers) { this.correctAnswers = correctAnswers; updateAnswers(); } public void setTotalAnswers(int totalAnswers) { this.totalAnswers = totalAnswers; updateAnswers(); } private void updateAnswers() { if (correctAnswers >= 0 && totalAnswers >= 0) { lblCorrect.setText(Integer.toString(correctAnswers) + "/"); lblTotal.setText(Integer.toString(totalAnswers)); float percentage = (float) correctAnswers / (float) totalAnswers; lblPercentage.setText(PERCENT_FORMATTER.format(percentage)); if (percentage < 0.6) lblPercentage.setTextColor(getResources().getColor(R.color.below_sixty)); else if (percentage < 0.7) lblPercentage.setTextColor(getResources().getColor(R.color.sixty_to_seventy)); else if (percentage < 0.8) lblPercentage.setTextColor(getResources().getColor(R.color.seventy_to_eighty)); else if (percentage < 0.9) lblPercentage.setTextColor(getResources().getColor(R.color.eighty_to_ninty)); else lblPercentage.setTextColor(getResources().getColor(R.color.above_ninty)); } } }
package de.s_paarmann.homeworkapp.ui; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.os.PersistableBundle; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import com.bugsnag.android.Bugsnag; import de.s_paarmann.homeworkapp.Log; import de.s_paarmann.homeworkapp.R; import de.s_paarmann.homeworkapp.network.LoginManager; import de.s_paarmann.homeworkapp.ui.login.LoginActivity; public class MainActivity extends AppCompatActivity { public static final String TAG = "MainActivity"; public static final String ACTION_REMIND = "de.s_paarmann.homeworkapp.action.REMIND"; public static final String ACTION_UPDATEHOMEWORK = "de.s_paarmann.homeworkapp.action.UPDATEHOMEWORK"; public static final String PREF_NAME = "de.s_paarmann.homeworkapp.sharedprefs"; public static final String PREF_UPDATED = "de.s_paarmann.homeworkapp.updated"; public static final String PREF_SETREMINDERS = "de.s_paarmann.homeworkapp.reminders"; public static final String PREF_DELETEDREMINDERS = "de.s_paarmann.homeworkapp.deletedreminders"; public static final String PREF_LASTUPDATED = "de.s_paarmann.homeworkapp.lastupdated"; public static final String PREF_DONEITEMS = "de.s_paarmann.homeworkapp.doneitems"; public static final String PREF_DONEITEMS2 = "de.s_paarmann.homeworkapp.doneitems2"; public static final String PREF_FILTERSUBJECTS = "de.s_paarmann.homeworkapp.FilterSubjects"; public static final String PREF_CHOSENSUBJECTS = "de.s_paarmann.homeworkapp.ChosenSubjects"; public static final String PREF_HOMEWORKTODAY = "de.s_paarmann.homeworkapp.HomeworkToday"; public static final String PREF_AUTOUPDATES = "de.s_paarmann.homeworkapp.AutomaticUpdates"; public static final String PREF_AUTOREMINDERS = "de.s_paarmann.homeworkapp.AutomaticReminders"; public static final String PREF_REMINDERTIME = "de.s_paarmann.homeworkapp.ReminderTime"; public static final String PREF_REMINDERDAY = "de.s_paarmann.homeworkapp.ReminderDay"; public static final String PREF_AUTOREMINDERSINSTANT = "de.s_paarmann.homeworkapp.InstantAutomaticReminders"; public static final String PREF_MOBILEDATA = "de.s_paarmann.homeworkapp.UseMobileData"; public static final String PREF_CRED_GROUP = "de.s_paarmann.homeworkapp.credgroup"; public static final String PREF_CRED_USER = "de.s_paarmann.homeworkapp.creduser"; public static final String PREF_CRED_AUTH = "de.s_paarmann.homeworkapp.credauth"; public static final String PREF_CRED_TOKEN = "de.s_paarmann.homeworkapp.credtoken"; public static final String PREF_PROVIDER = "de.s_paarmann.homeworkapp.provider"; public static final String EXTRA_OPEN_VIEW = "de.s_paarmann.homeworkapp.extra.openview"; private static final String STATE_VIEW = "view"; public enum Views { MAIN, HOMEWORK_DETAIL, ADD_HOMEWORK, MANAGE_REMINDERS, SETTINGS } private Views currentView; public Fragment fragment; private DrawerLayout drawerLayout; private NavigationView navigationView; private ActionBarDrawerToggle drawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { Bugsnag.init(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_drawer); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); navigationView = (NavigationView) findViewById(R.id.navigation); drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); navigationView.setNavigationItemSelectedListener(item -> { switch (item.getItemId()) { case R.id.nav_home: showView(Views.MAIN); drawerLayout.closeDrawer(GravityCompat.START); return true; case R.id.nav_add_homework: showView(Views.ADD_HOMEWORK); drawerLayout.closeDrawer(GravityCompat.START); return true; case R.id.nav_reminders: showView(Views.MANAGE_REMINDERS); drawerLayout.closeDrawer(GravityCompat.START); return true; case R.id.nav_logout: LoginManager.removeCredentials(this); startActivity(new Intent(this, LoginActivity.class)); drawerLayout.closeDrawer(GravityCompat.START); return true; case R.id.nav_settings: showView(Views.SETTINGS); drawerLayout.closeDrawer(GravityCompat.START); return true; default: return false; } }); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { invalidateOptionsMenu(); } }; drawerLayout.addDrawerListener(drawerToggle); getFragmentManager().addOnBackStackChangedListener(this::onBackStackChanged); if (getIntent().hasExtra(EXTRA_OPEN_VIEW)) { showView(Views.valueOf(getIntent().getStringExtra(EXTRA_OPEN_VIEW))); } else if (savedInstanceState != null && savedInstanceState.containsKey(STATE_VIEW)) { showView(Views.valueOf(savedInstanceState.getString(STATE_VIEW))); } else { showMainView(); } PreferenceManager.setDefaultValues(this, R.xml.preferences, false); if (!LoginManager.loadCredentials(this)) { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putString(STATE_VIEW, currentView.name()); super.onSaveInstanceState(outState); } @Override public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onPostCreate(savedInstanceState, persistentState); drawerToggle.syncState(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. switch (currentView) { case MAIN: getMenuInflater().inflate(R.menu.main, menu); break; case HOMEWORK_DETAIL: getMenuInflater().inflate(R.menu.homework_detail, menu); break; case ADD_HOMEWORK: case MANAGE_REMINDERS: case SETTINGS: // No menu super.onCreateOptionsMenu(menu); break; } 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. if (drawerToggle.onOptionsItemSelected(item)) { return true; } int id = item.getItemId(); switch (id) { case R.id.action_update: if (currentView == Views.MAIN) { ((MainFragment) fragment).checkForUpdates(true); } return true; default: return super.onOptionsItemSelected(item); } } private void onBackStackChanged() { Fragment frag = getFragmentManager().findFragmentById(R.id.content_frame); if (frag instanceof MainFragment) currentView = Views.MAIN; else if (frag instanceof HomeworkDetailFragment) currentView = Views.HOMEWORK_DETAIL; else if (frag instanceof AddHomeworkFragment) currentView = Views.ADD_HOMEWORK; else if (frag instanceof ManagerRemindersFragment) currentView = Views.MANAGE_REMINDERS; else if (frag instanceof SettingsFragment) currentView = Views.SETTINGS; else Log.w(TAG, "Fragment displayed not recognized!"); updateNavDrawerSelection(currentView); } private void showView(Fragment frag, Views view) { if (getCurrentFocus() != null) { InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } fragment = frag; FragmentManager manager = getFragmentManager(); FragmentTransaction transaction = manager.beginTransaction().replace(R.id.content_frame, fragment); if ((currentView == Views.MAIN || view == Views.ADD_HOMEWORK || view == Views.MANAGE_REMINDERS || view == Views.SETTINGS) && view != Views.MAIN && currentView != view) { transaction.addToBackStack(null); } transaction.commit(); currentView = view; invalidateOptionsMenu(); updateNavDrawerSelection(view); } private void updateNavDrawerSelection(Views view) { switch (view) { case MAIN: navigationView.setCheckedItem(R.id.nav_home); break; case HOMEWORK_DETAIL: navigationView.setCheckedItem(R.id.nav_home); break; case ADD_HOMEWORK: navigationView.setCheckedItem(R.id.nav_add_homework); break; case MANAGE_REMINDERS: navigationView.setCheckedItem(R.id.nav_reminders); break; case SETTINGS: navigationView.setCheckedItem(R.id.nav_settings); break; } } private void showView(Views view) { switch (view) { case MAIN: showMainView(); break; case HOMEWORK_DETAIL: showHomeworkDetailView(getIntent().getStringExtra(HomeworkDetailFragment.EXTRA_DATE)); break; case ADD_HOMEWORK: showAddHomeworkView(); break; case MANAGE_REMINDERS: showRemindersView(); break; case SETTINGS: showSettingsView(); break; } } public void showMainView() { showView(new MainFragment(), Views.MAIN); } public void showHomeworkDetailView(String strDate) { Fragment frag = new HomeworkDetailFragment(); Bundle args = new Bundle(); if (strDate == null) { args.putString(HomeworkDetailFragment.EXTRA_DATE, "all"); } else { args.putString(HomeworkDetailFragment.EXTRA_DATE, strDate); } frag.setArguments(args); showView(frag, Views.HOMEWORK_DETAIL); } public void showAddHomeworkView() { showView(new AddHomeworkFragment(), Views.ADD_HOMEWORK); } public void showRemindersView() { showView(new ManagerRemindersFragment(), Views.MANAGE_REMINDERS); } public void showSettingsView() { showView(new SettingsFragment(), Views.SETTINGS); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } }
package dimitris.android.chessviews; import android.graphics.Canvas; import android.graphics.Typeface; import dimitris.android.chessviews.Pieces.FenParser; public class DrawableBoard extends MoveSubject{ private int squareSize; private SquareView lastSelectedSquareView; private SquareView[][] squareViews; // private MoveExecutor moveExecutor; // private MoveFilterer moveFilterer; public DrawableBoard(int squareSize) { super(); this.squareSize = squareSize; // moveExecutor = new MoveExecutor(this); // TurnArbiter arbiter = new TurnArbiter(this); // moveFilterer = new MoveFilterer(); // moveFilterer.addFilter(arbiter); // moveFilterer.addFilter(new KingCaptureFilter()); // moveFilterer.addFilter(new SelfCaptureFilter()); } public void draw(Canvas canvas) { if (squareViews == null) return; for (int row = 0; row < 8; row++) for (int col = 0; col < 8; col++) squareViews[row][col].draw(canvas); } protected void squareSelectedAt(int row, int col) { System.out.println("Clicked at square "+ squareViews[row][col].getName() ); if (lastSelectedSquareView == null) { selectSquareIfNotEmpty(row, col); } else if (lastSelectedSquareView == squareViews[row][col]) { clearSelection(); } else { dispatchNewMoveIfPassesFilters(row, col); clearSelection(); } } private void dispatchNewMoveIfPassesFilters(int row, int col) { Move toMake = new Move(lastSelectedSquareView, squareViews[row][col]); doMove(toMake); } private void selectSquareIfNotEmpty(int row, int col) { if (!squareIsEmpty(row, col)) { lastSelectedSquareView = squareViews[row][col]; lastSelectedSquareView.setSelected(true); } } private boolean squareIsEmpty(int row, int col) { return squareViews[row][col].isEmpty(); } private void clearSelection() { lastSelectedSquareView.setSelected(false); lastSelectedSquareView = null; } public void setUpBoard(Typeface font) { try { squareViews = new BoardViewFactory(squareSize).createInitialBoard(font); } catch (FenParser.BadFenException e) { e.printStackTrace(); } } public void doMove(Move toDo) { toDo.execute(); broadcastNewMoveToObservers(toDo); } // public void undoMove() { // broadcastUndoToObservers(); // public void redoMove() { // broadcastRedoToObservers(); // public Square getSquare(String squareName) { // return getSquare(getSquareCoords(squareName)); // public Square getSquare(BoardCoords coords) { // return squareViews[coords.row][coords.column]; // public BoardCoords getBoardCoordsOfSquare(String squareName) { // return getSquareCoords(squareName); // public String printMoves() { // return moveExecutor.printMoves(); @Override public void broadcastUndoToObservers() { for (MoveObserver o : moveObservers) o.undoMove(); } @Override public void broadcastRedoToObservers() { for (MoveObserver o : moveObservers) o.redoMove(); } @Override public void broadcastNewMoveToObservers(Move move) { for (MoveObserver o : moveObservers) o.doMove(move); } }
package fi.jyu.ln.luontonurkka; import android.content.Context; import android.content.Intent; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class TabbedListActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tabbed); //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //setSupportActionBar(toolbar); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.list_pager); mViewPager.setAdapter(mSectionsPagerAdapter); } /** * Fragment creating species list */ public static class ListFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SPECIES_LIST = "species_list"; public ListFragment() { } /** * Returns a new instance of this fragment for the given section * number. */ public static ListFragment newInstance(int sectionNumber, ArrayList<Species> speciesList) { ListFragment fragment = new ListFragment(); Bundle args = new Bundle(); args.putSerializable(ARG_SPECIES_LIST, speciesList); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_list, container, false); // get list of species from the arguments ArrayList<Species> speciesList = (ArrayList<Species>) getArguments().getSerializable(ARG_SPECIES_LIST); SpeciesListAdapter sla = new SpeciesListAdapter(container.getContext(), speciesList); ListView listView = (ListView)rootView.findViewById(R.id.species_list); listView.setAdapter(sla); return rootView; } private class SpeciesListAdapter extends ArrayAdapter { ArrayList<Species> speciesList; Context context; public SpeciesListAdapter(Context context, ArrayList<Species> speciesList) { super(context,R.layout.specieslistobject_layout,speciesList); this.speciesList = speciesList; this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { final Species species = (Species)getItem(position); LayoutInflater inflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE); final View row = inflater.inflate(R.layout.specieslistobject_layout, null, true); TextView textView = (TextView)row.findViewById(R.id.list_name); textView.setText(species.getName()); Button button = (Button)row.findViewById(R.id.list_button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((TabbedListActivity)row.getContext()).openSpeciesView(species); } }); return row; } } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a ListFragment (defined as a static inner class below). // TODO create lists in a method ArrayList<Species> testiLista = new ArrayList<Species>(10); for (int i = 0;i < 10; i++) { if(i > 5) { Species.SpeciesBuilder sb = new Species.SpeciesBuilder("Koira", 1); sb.descr("Koira on myös kovis"); Species s = sb.build(); testiLista.add(i,s); } else { Species.SpeciesBuilder sb = new Species.SpeciesBuilder("Kissa", 1); sb.descr("Kissa on kovis"); Species s = sb.build(); testiLista.add(i, s); } } return ListFragment.newInstance(position + 1, testiLista); } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Kaikki"; case 1: return "Linnut"; case 2: return "Kasvit"; } return null; } } /** * Opens the species view activity. * @param species Species object on which more info will be shown */ protected void openSpeciesView(Species species) { Intent intent = new Intent(this, SpeciesActivity.class); intent.putExtra("Species", species); startActivity(intent); } /** * Shows settings drawer. Called from three vertical lines button. * @param view View that calling the method */ public void showDrawer(View view) { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (!drawer.isDrawerOpen(GravityCompat.START)) { drawer.openDrawer(GravityCompat.START); } } public void showAllTab(View view) { showTab(0); } public void showBirdsTab(View view) { showTab(1); } public void showPlantsTab(View view) { showTab(2); } public void showTab(int index) { ViewPager pager = (ViewPager)findViewById(R.id.list_pager); pager.setCurrentItem(index); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @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); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_share) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
package me.ryanpetschek.gatekeeper; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.spec.ECParameterSpec; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; public class SignInActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle("Sign up"); final Button button = (Button) findViewById(R.id.signup); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(SignInActivity.this, MainActivity.class); startActivity(intent); } }); } protected KeyPair generateKeys() { ECParameterSpec specs = ECNamedCurveTable.getParameterSpec("secp256k1"); try { KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC"); g.initialize(specs, new SecureRandom()); KeyPair pair = g.generateKeyPair(); return pair; } catch (java.security.NoSuchAlgorithmException err) { } catch (java.security.NoSuchProviderException err) { } catch (java.security.InvalidAlgorithmParameterException err) { } finally { return null; } } }
package me.sinziana.vanilla.screens; import android.app.Fragment; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.RippleDrawable; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.HashMap; import me.sinziana.vanilla.PunCategoryList; import me.sinziana.vanilla.R; public class PunCategories extends Fragment{ public PunCategories() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onStart() { super.onStart(); ActionBar ab = ((AppCompatActivity)getActivity()).getSupportActionBar(); if (ab != null) { ab.setTitle(R.string.pun_categories); ab.invalidateOptionsMenu(); ab.setDisplayHomeAsUpEnabled(true); } } @SuppressWarnings("UnnecessaryLocalVariable") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.pun_categories, container, false); final ListView listview = (ListView) view.findViewById(R.id.listview); final PunCategories.StableArrayAdapter adapter = new PunCategories.StableArrayAdapter(this.getActivity(), R.layout.pun_category, PunCategoryList.categories); listview.setAdapter(adapter); listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { final String item = (String) parent.getItemAtPosition(position); System.out.println("Pressed on: " + item); } }); return view; } /** * Adapter for the List View */ private class StableArrayAdapter extends ArrayAdapter<String> { final HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); private final Context context; private final String[] values; public StableArrayAdapter(Context context, int textViewResourceId, String[] values) { super(context, -1, values); this.context = context; this.values = values; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); TextView rowView = (TextView)inflater.inflate(R.layout.pun_category, parent, false); rowView.setText(values[position]); // rowView.setBackgroundColor(Color.parseColor("#14A697")); RippleDrawable newImage = new RippleDrawable( new ColorStateList( new int[][]{ new int[]{android.R.attr.state_pressed}, new int[]{} }, new int[]{ ContextCompat.getColor(context, R.color.ripple_material_light), ContextCompat.getColor(context, R.color.ripple_material_dark), }), new ColorDrawable(Color.parseColor("#14A697")), null); rowView.setBackground(newImage); // TODO - Refactor this! return rowView; } } }
package org.azavea.lists; import org.azavea.lists.data.DisplayableModel; import android.content.Context; public interface InfoList { public DisplayableModel[] getDisplayValues(); public Object[] getListValues(); public void addObserver(ListObserver o); public void setupLocationUpdating(Context applicationContext); public void removeLocationUpdating(); }
package self.premi.sanjeev.nayati.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import java.util.ArrayList; import java.util.List; import self.premi.sanjeev.nayati.model.TrackItem; import self.premi.sanjeev.nayati.model.TrackItemView; /** * 'Database Access Object' for the item being tracked. */ public class DaoTrackItem extends DbAccess { /** * Constructor */ public DaoTrackItem(Context ctx) { super(ctx); } /** * Adds an item to be tracked. * * When item is being added: * - the state is expected to be unknown. * - the sync time is empty. */ public long add(String tnum, String name, long cat) { long id = -1; ContentValues cv = new ContentValues(); cv.put(DbConst.ITEM_TNUM, tnum); cv.put(DbConst.ITEM_NAME, name); cv.put(DbConst.ITEM_ICAT, cat); cv.put(DbConst.ITEM_STATE, DbConst.ITEM_STATE_NONE); cv.put(DbConst.ITEM_SYNC, ""); db.beginTransaction(); try { id = db.insert(DbConst.TABLE_ITEMS, null, cv); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return id; } /** * Deletes an item being tracked. */ public int delete(long id) { int rows = 0; db.beginTransaction(); try { rows = db.delete(DbConst.TABLE_ITEMS, DbConst.ITEM_ID + "=" + id, null); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return rows; } /** * Updates an item being tracked. */ public boolean update(TrackItem item) { long id = item.getId(); long ret; ContentValues cv = new ContentValues(); cv.put(DbConst.ITEM_TNUM, item.getTrackNum()); cv.put(DbConst.ITEM_NAME, item.getName()); cv.put(DbConst.ITEM_ICAT, item.getCategory()); cv.put(DbConst.ITEM_STATE, item.getState()); cv.put(DbConst.ITEM_SYNC, item.getSync()); db.beginTransaction(); try { ret = db.update(DbConst.TABLE_ITEMS, cv, DbConst.ITEM_ID + "=" + id, null); db.setTransactionSuccessful(); } finally { db.endTransaction(); } if (ret == 0) return false; return true; } /** * List all items. */ public List<TrackItem> list() { List<TrackItem> items = new ArrayList<>(); Cursor c; db.beginTransaction(); try { c = db.query(DbConst.TABLE_ITEMS, null, null, null, null, null, null); db.setTransactionSuccessful(); if (c != null) { if (c.moveToFirst()) { do { long id = c.getLong(c.getColumnIndex(DbConst.ITEM_ID)); String tnum = c.getString(c.getColumnIndex(DbConst.ITEM_TNUM)); String name = c.getString(c.getColumnIndex(DbConst.ITEM_NAME)); long cat = c.getLong(c.getColumnIndex(DbConst.ITEM_ICAT)); int state = c.getInt(c.getColumnIndex(DbConst.ITEM_STATE)); String sync = c.getString(c.getColumnIndex(DbConst.ITEM_SYNC)); items.add(new TrackItem(id, tnum, name, cat, state, sync)); } while (c.moveToNext()); } } } finally { db.endTransaction(); } c.close(); return items; } /** * List all items with resolved (joined) data across the tables. */ public List<TrackItemView> listResolved() { List<TrackItemView> items = new ArrayList<>(); Cursor c; String query = "SELECT " + "ITEM" + "." + DbConst.ITEM_ID + " AS iid, " + "ITEM" + "." + DbConst.ITEM_TNUM + ", " + "ITEM" + "." + DbConst.ITEM_NAME + ", " + "ITEM" + "." + DbConst.ITEM_STATE + ", " + "ITEM" + "." + DbConst.ITEM_SYNC + ", " + "CAT" + "." + DbConst.ITEMCAT_SYMBOL + " FROM " + DbConst.TABLE_ITEMS + " ITEM " + " INNER JOIN " + DbConst.TABLE_ITEMCATS + " CAT " + " ON " + "ITEM" + "." + DbConst.ITEM_ICAT + " = " + "CAT" + "." + DbConst.ITEMCAT_ID; db.beginTransaction(); try { c = db.rawQuery(query, null); db.setTransactionSuccessful(); if (c != null) { if (c.moveToFirst()) { do { long id = c.getLong(0); String tnum = c.getString(1); String name = c.getString(2); int state = c.getInt(3); String sync = c.getString(4); String cat = c.getString(5); items.add(new TrackItemView(id, tnum, name, cat, state, sync)); } while (c.moveToNext()); } } } finally { db.endTransaction(); } c.close(); return items; } /** * Get an item. */ public TrackItem get(String tnum) { TrackItem item = null; Cursor c; db.beginTransaction(); try { c = db.query(DbConst.TABLE_ITEMS, null, DbConst.ITEM_TNUM + " = " + "\"" + tnum + "\"", null, null, null, null); db.setTransactionSuccessful(); if (c != null) { if (c.moveToFirst()) { long id = c.getLong(c.getColumnIndex(DbConst.ITEM_ID)); String name = c.getString(c.getColumnIndex(DbConst.ITEM_NAME)); long cat = c.getLong(c.getColumnIndex(DbConst.ITEM_ICAT)); int state = c.getInt(c.getColumnIndex(DbConst.ITEM_STATE)); String sync = c.getString(c.getColumnIndex(DbConst.ITEM_SYNC)); item = new TrackItem(id, tnum, name, cat, state, sync); } } } finally { db.endTransaction(); } c.close(); return item; } }
package org.commcare.dalvik.application; import android.annotation.SuppressLint; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.preference.PreferenceManager; import android.provider.Settings.Secure; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import android.util.Log; import android.util.Pair; import android.widget.Toast; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteException; import org.acra.annotation.ReportsCrashes; import org.commcare.android.database.DbHelper; import org.commcare.android.database.SqlStorage; import org.commcare.android.database.UserStorageClosedException; import org.commcare.android.database.app.DatabaseAppOpenHelper; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.android.database.global.DatabaseGlobalOpenHelper; import org.commcare.android.database.global.models.ApplicationRecord; import org.commcare.android.database.user.CommCareUserOpenHelper; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.database.user.models.User; import org.commcare.android.db.legacy.LegacyInstallUtils; import org.commcare.android.framework.SessionActivityRegistration; import org.commcare.android.javarosa.AndroidLogEntry; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.javarosa.PreInitLogger; import org.commcare.android.logic.GlobalConstants; import org.commcare.android.models.AndroidSessionWrapper; import org.commcare.android.models.notifications.NotificationClearReceiver; import org.commcare.android.models.notifications.NotificationMessage; import org.commcare.android.references.ArchiveFileRoot; import org.commcare.android.references.AssetFileRoot; import org.commcare.android.references.JavaHttpRoot; import org.commcare.android.storage.framework.Table; import org.commcare.android.tasks.DataSubmissionListener; import org.commcare.android.tasks.ExceptionReportTask; import org.commcare.android.tasks.FormRecordCleanupTask; import org.commcare.android.tasks.LogSubmissionTask; import org.commcare.android.tasks.templates.ManagedAsyncTask; import org.commcare.android.util.ACRAUtil; import org.commcare.android.util.AndroidCommCarePlatform; import org.commcare.android.util.AndroidUtil; import org.commcare.android.util.CallInPhoneListener; import org.commcare.android.util.CommCareExceptionHandler; import org.commcare.android.util.FileUtil; import org.commcare.android.util.ODKPropertyManager; import org.commcare.android.util.SessionStateUninitException; import org.commcare.android.util.SessionUnavailableException; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.LoginActivity; import org.commcare.dalvik.activities.MessageActivity; import org.commcare.dalvik.activities.UnrecoverableErrorActivity; import org.commcare.dalvik.odk.provider.FormsProvider; import org.commcare.dalvik.odk.provider.ProviderUtils; import org.commcare.dalvik.preferences.CommCarePreferences; import org.commcare.dalvik.services.CommCareSessionService; import org.commcare.suite.model.Profile; import org.commcare.util.CommCareSession; import org.commcare.util.externalizable.AndroidClassHasher; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.reference.RootTranslator; import org.javarosa.core.services.Logger; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.storage.EntityFilter; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.services.storage.StorageFullException; import org.javarosa.core.util.PropertyUtils; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.StethoInitializer; import java.io.File; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.Vector; import javax.crypto.SecretKey; /** * @author ctsims */ @ReportsCrashes( formUri = "https://your/cloudant/report", formUriBasicAuthLogin="your_username", formUriBasicAuthPassword="your_password", reportType = org.acra.sender.HttpSender.Type.JSON, httpMethod = org.acra.sender.HttpSender.Method.PUT) public class CommCareApplication extends Application { private static final String TAG = CommCareApplication.class.getSimpleName(); public static final int STATE_UNINSTALLED = 0; public static final int STATE_UPGRADE = 1; public static final int STATE_READY = 2; public static final int STATE_CORRUPTED = 4; public static final int STATE_DELETE_REQUESTED = 8; public static final String ACTION_PURGE_NOTIFICATIONS = "CommCareApplication_purge"; private int dbState; private static CommCareApplication app; private CommCareApp currentApp; private CommCareApp appBeingInstalled; // stores current state of application: the session, form private AndroidSessionWrapper sessionWrapper; private final Object globalDbHandleLock = new Object(); private SQLiteDatabase globalDatabase; private boolean updatePending = false; private ArchiveFileRoot mArchiveFileRoot; // Fields for managing a connection to the CommCareSessionService // A bound service is created out of the CommCareSessionService to ensure // it stays in memory. private CommCareSessionService mBoundService; private ServiceConnection mConnection; private final Object serviceLock = new Object(); // Has the CommCareSessionService been bound? private boolean mIsBound = false; // Has CommCareSessionService initilization finished? // Important so we don't use the service before the db is initialized. private boolean mIsBinding = false; //Milliseconds to wait for bind private static final int MAX_BIND_TIMEOUT = 5000; private int mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT; private CallInPhoneListener listener = null; /** * Handler to receive notifications and show them the user using toast. */ private final PopupHandler toaster = new PopupHandler(this); @Override public void onCreate() { super.onCreate(); StethoInitializer.initStetho(this); Collect.setStaticApplicationContext(this); //Sets the static strategy for the deserializtion code to be //based on an optimized md5 hasher. Major speed improvements. AndroidClassHasher.registerAndroidClassHashStrategy(); AndroidUtil.initializeStaticHandlers(); CommCareApplication.app = this; //TODO: Make this robust PreInitLogger pil = new PreInitLogger(); Logger.registerLogger(pil); //Workaround because android is written by 7 year olds. //(reuses http connection pool improperly, so the second https //request in a short time period will flop) System.setProperty("http.keepAlive", "false"); Thread.setDefaultUncaughtExceptionHandler(new CommCareExceptionHandler(Thread.getDefaultUncaughtExceptionHandler())); PropertyManager.setPropertyManager(new ODKPropertyManager()); SQLiteDatabase.loadLibs(this); setRoots(); prepareTemporaryStorage(); //Init global storage (Just application records, logs, etc) dbState = initGlobalDb(); //This is where we go through and check for updates between major transitions. //Soon we should start doing this differently, and actually go to an activity //first which tells the user what's going on. //The rule about this transition is that if the user had logs pending, we still want them in order, so //we aren't going to dump our logs from the Pre-init logger until after this transition occurs. try { LegacyInstallUtils.checkForLegacyInstall(this, this.getGlobalStorage(ApplicationRecord.class)); } catch(SessionUnavailableException | StorageFullException sfe) { throw new RuntimeException(sfe); } finally { //No matter what happens, set up our new logger, we want those logs! Logger.registerLogger(new AndroidLogger(this.getGlobalStorage(AndroidLogEntry.STORAGE_KEY, AndroidLogEntry.class))); pil.dumpToNewLogger(); } intializeDefaultLocalizerData(); //The fallback in case the db isn't installed initializeAppResourcesOnStartup(); ACRAUtil.initACRA(this); } public void triggerHandledAppExit(Context c, String message) { triggerHandledAppExit(c, message, Localization.get("app.handled.error.title")); } public void triggerHandledAppExit(Context c, String message, String title) { Intent i = new Intent(c, UnrecoverableErrorActivity.class); i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_TITLE, title); i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_MESSAGE, message); // start a new stack and forget where we were (so we don't restart the // app from there) i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_CLEAR_TOP); c.startActivity(i); } public void startUserSession(byte[] symetricKey, UserKeyRecord record) { synchronized(serviceLock) { // if we already have a connection established to // CommCareSessionService, close it and open a new one if(this.mIsBound) { releaseUserResourcesAndServices(); } bindUserSessionService(symetricKey, record); } } /** * Closes down the user service, resources, and background tasks. Used for * manual user log-outs. */ public void closeUserSession() { synchronized(serviceLock) { // Cancel any running tasks before closing down the user databse. ManagedAsyncTask.cancelTasks(); releaseUserResourcesAndServices(); } } /** * Closes down the user service, resources, and background tasks, * broadcasting an intent to redirect the user to the login screen. Used * for session-expiration related user logouts. */ public void expireUserSession() { synchronized(serviceLock) { closeUserSession(); SessionActivityRegistration.registerSessionExpiration(); sendBroadcast(new Intent(SessionActivityRegistration.USER_SESSION_EXPIRED)); } } public void releaseUserResourcesAndServices() { try { CommCareApplication._().getSession().closeServiceResources(); } catch (SessionUnavailableException e) { Log.w(TAG, "User's session services have unexpectedly already " + "been closed down. Proceeding to close the session."); } unbindUserSessionService(); } public SecretKey createNewSymetricKey() throws SessionUnavailableException { return getSession().createNewSymetricKey(); } private void attachCallListener() { TelephonyManager tManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); listener = new CallInPhoneListener(this, this.getCommCarePlatform()); listener.startCache(); tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); } public CallInPhoneListener getCallListener() { return listener; } public int[] getCommCareVersion() { return this.getResources().getIntArray(R.array.commcare_version); } public AndroidCommCarePlatform getCommCarePlatform() { if (this.currentApp == null) { throw new RuntimeException("No App installed!!!"); } else { return this.currentApp.getCommCarePlatform(); } } public void setAppBeingInstalled(CommCareApp app) { this.appBeingInstalled = app; } public CommCareApp getAppBeingInstalled() { return this.appBeingInstalled; } public CommCareApp getCurrentApp() { return this.currentApp; } /** * Get the current CommCare session that's being executed */ public CommCareSession getCurrentSession() { return getCurrentSessionWrapper().getSession(); } public AndroidSessionWrapper getCurrentSessionWrapper() { if (sessionWrapper == null) { // TODO PLM: should be able to init this so it is never null. // Need to find the correct place after the currentApp is set. throw new SessionStateUninitException("CommCare user session isn't available"); } return sessionWrapper; } public int getDatabaseState() { return dbState; } public void initializeGlobalResources(CommCareApp app) { if (dbState != STATE_UNINSTALLED) { initializeAppResources(app); } } public String getPhoneId() { TelephonyManager manager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); String imei = manager.getDeviceId(); if (imei == null) { imei = Secure.getString(getContentResolver(), Secure.ANDROID_ID); } return imei; } public void intializeDefaultLocalizerData() { Localization.init(true); Localization.registerLanguageReference("default", "jr://asset/locales/messages_ccodk_default.txt"); Localization.setDefaultLocale("default"); //For now. Possibly handle this better in the future Localization.setLocale("default"); } private void setRoots() { JavaHttpRoot http = new JavaHttpRoot(); AssetFileRoot afr = new AssetFileRoot(this); ArchiveFileRoot arfr = new ArchiveFileRoot(); mArchiveFileRoot = arfr; ReferenceManager._().addReferenceFactory(http); ReferenceManager._().addReferenceFactory(afr); ReferenceManager._().addReferenceFactory(arfr); ReferenceManager._().addRootTranslator(new RootTranslator("jr://media/", GlobalConstants.MEDIA_REF)); } /** * Performs the appropriate initialization of an application when this CommCareApplication is * first launched */ private void initializeAppResourcesOnStartup() { // Before we try to initialize a new app, check if any existing apps were left in a // partially deleted state, and finish uninstalling them if so for (ApplicationRecord record : getGlobalStorage(ApplicationRecord.class)) { if (record.getStatus() == ApplicationRecord.STATUS_DELETE_REQUESTED) { try { uninstall(record); } catch (RuntimeException e) { Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Unable to uninstall an app " + "during startup that was previously left partially-deleted"); } } } // There may now be multiple app records in storage, because of multiple apps support. We // want to initialize one of them to start, so that there will be currently-seated app when // the login screen starts up // If there is a 'last app' set in shared preferences, try to initialize that application. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String lastAppId = prefs.getString(LoginActivity.KEY_LAST_APP, ""); if (!"".equals(lastAppId)){ ApplicationRecord lastApp = getAppById(lastAppId); if (lastApp == null || !lastApp.isUsable()) { // This app record could be null if it has since been uninstalled, or unusable if // it has since been archived, etc. In either case, just revert to picking the // first app initFirstUsableAppRecord(); } else { initializeAppResources(new CommCareApp(lastApp)); } } // Otherwise, just pick the first app in the list to initialize initFirstUsableAppRecord(); } /** * Initializes the first "usable" application from the list of globally installed app records, * if there is one */ public void initFirstUsableAppRecord() { for(ApplicationRecord record : getUsableAppRecords()) { initializeAppResources(new CommCareApp(record)); break; } } /** * Initialize all of the given app's resources, and set the state of its resources accordingly * * @param app the CC app to initialize */ public void initializeAppResources(CommCareApp app) { int resourceState; try { currentApp = app; if (currentApp.initializeApplication()) { resourceState = STATE_READY; this.sessionWrapper = new AndroidSessionWrapper(this.getCommCarePlatform()); } else { resourceState = STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ExceptionReportTask ert = new ExceptionReportTask(); ert.execute(e); resourceState = STATE_CORRUPTED; } app.setAppResourceState(resourceState); } /** * @return all ApplicationRecords in storage, regardless of their status, in alphabetical order */ public ArrayList<ApplicationRecord> getInstalledAppRecords() { ArrayList<ApplicationRecord> records = new ArrayList<>(); for (ApplicationRecord r : getGlobalStorage(ApplicationRecord.class)) { records.add(r); } Collections.sort(records, new Comparator<ApplicationRecord>() { @Override public int compare(ApplicationRecord lhs, ApplicationRecord rhs) { return lhs.getDisplayName().compareTo(rhs.getDisplayName()); } }); return records; } /** * @return all ApplicationRecords that have status installed and are NOT archived */ public ArrayList<ApplicationRecord> getVisibleAppRecords() { ArrayList<ApplicationRecord> visible = new ArrayList<>(); for (ApplicationRecord r : getInstalledAppRecords()) { if (r.isVisible()) { visible.add(r); } } return visible; } /** * @return all ApplicationRecords that are installed AND are not archived AND have MM verified */ public ArrayList<ApplicationRecord> getUsableAppRecords() { ArrayList<ApplicationRecord> ready = new ArrayList<>(); for (ApplicationRecord r : getInstalledAppRecords()) { if (r.isUsable()) { ready.add(r); } } return ready; } /** * @return whether the user should be sent to CommCareVerificationActivity. Current logic is * that this should occur only if there is exactly one visible app and it is missing its MM * (because we are then assuming the user is not currently using multiple apps functionality) */ public boolean shouldSeeMMVerification() { return (CommCareApplication._().getVisibleAppRecords().size() == 1 && CommCareApplication._().getUsableAppRecords().size() == 0); } public boolean usableAppsPresent() { return getUsableAppRecords().size() > 0; } /** * @return the list of all installed apps as an array */ public ApplicationRecord[] appRecordArray() { ArrayList<ApplicationRecord> appList = CommCareApplication._().getInstalledAppRecords(); ApplicationRecord[] appArray = new ApplicationRecord[appList.size()]; int index = 0; for (ApplicationRecord r : appList) { appArray[index++] = r; } return appArray; } /** * @param uniqueId - the uniqueId of the ApplicationRecord being sought * @return the ApplicationRecord corresponding to the given id, if it exists. Otherwise, * return null */ public ApplicationRecord getAppById(String uniqueId) { for (ApplicationRecord r : getInstalledAppRecords()) { if (r.getUniqueId().equals(uniqueId)) { return r; } } return null; } /** * @return if the given ApplicationRecord is the currently seated one */ public boolean isSeated(ApplicationRecord record) { return currentApp != null && currentApp.getUniqueId().equals(record.getUniqueId()); } /** * If the given record is the currently seated app, unseat it */ public void unseat(ApplicationRecord record) { if (isSeated(record)) { this.currentApp.teardownSandbox(); this.currentApp = null; } } /** * Completes a full uninstall of the CC app that the given ApplicationRecord represents. * This method should be idempotent and should be capable of completing an uninstall * regardless of previous failures */ public void uninstall(ApplicationRecord record) { CommCareApp app = new CommCareApp(record); // 1) If the app we are uninstalling is the currently-seated app, tear down its sandbox if (isSeated(record)) { getCurrentApp().teardownSandbox(); } // 2) Set record's status to delete requested, so we know if we have left it in a bad // state later record.setStatus(ApplicationRecord.STATUS_DELETE_REQUESTED); getGlobalStorage(ApplicationRecord.class).write(record); // 3) Delete the directory containing all of this app's resources if (!FileUtil.deleteFileOrDir(app.storageRoot())) { Logger.log(AndroidLogger.TYPE_RESOURCES, "App storage root was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); return; } // 3) Delete all the user databases associated with this app SqlStorage<UserKeyRecord> userDatabase = app.getStorage(UserKeyRecord.class); for (UserKeyRecord user : userDatabase) { File f = getDatabasePath(CommCareUserOpenHelper.getDbName(user.getUuid())); if (!FileUtil.deleteFileOrDir(f)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "A user database was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); // If we failed to delete a file, it is likely because there is an open pointer // to that db still in use, so stop the uninstall for now, and rely on it to // complete the next time the app starts up return; } } // 4) Delete the forms database for this app File formsDb = getDatabasePath(ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.TYPE_FORMS, app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(formsDb)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's forms database was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); return; } // 5) Delete the instances database for this app File instancesDb = getDatabasePath(ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.TYPE_INSTANCES, app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(instancesDb)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's instances database was unable to" + " be deleted during app uninstall. Aborting uninstall process for now."); return; } // 6) Delete the app database File f = getDatabasePath(DatabaseAppOpenHelper.getDbName(app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(f)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app database was unable to be deleted" + "during app uninstall. Aborting uninstall process for now."); return; } // 7) Delete the ApplicationRecord getGlobalStorage(ApplicationRecord.class).remove(record.getID()); } private int initGlobalDb() { SQLiteDatabase database; try { database = new DatabaseGlobalOpenHelper(this).getWritableDatabase("null"); database.close(); return STATE_READY; } catch (SQLiteException e) { //Only thrown if DB isn't there return STATE_UNINSTALLED; } } public SQLiteDatabase getUserDbHandle() throws SessionUnavailableException { return this.getSession().getUserDbHandle(); } public <T extends Persistable> SqlStorage<T> getGlobalStorage(Class<T> c) { return getGlobalStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getGlobalStorage(String table, Class<T> c) { return new SqlStorage<T>(table, c, new DbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() { synchronized (globalDbHandleLock) { if (globalDatabase == null || !globalDatabase.isOpen()) { globalDatabase = new DatabaseGlobalOpenHelper(this.c).getWritableDatabase("null"); } return globalDatabase; } } }); } public <T extends Persistable> SqlStorage<T> getAppStorage(Class<T> c) { return getAppStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getAppStorage(String name, Class<T> c) { return currentApp.getStorage(name, c); } public <T extends Persistable> SqlStorage<T> getUserStorage(Class<T> c) { return getUserStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getUserStorage(String storage, Class<T> c) { return new SqlStorage<T>(storage, c, new DbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() throws SessionUnavailableException { SQLiteDatabase database = getUserDbHandle(); if (database == null) { throw new SessionUnavailableException("The user database has been closed!"); } return database; } }); } public <T extends Persistable> SqlStorage<T> getRawStorage(String storage, Class<T> c, final SQLiteDatabase handle) { return new SqlStorage<T>(storage, c, new DbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() { return handle; } }); } public static CommCareApplication _() { return app; } /** * This method wipes out all local user data (users, referrals, etc) but leaves * application resources in place. * * It makes no attempt to make sure this is a safe operation when called, so * it shouldn't be used lightly. */ public void clearUserData() { // //First clear anything that will require the user's key, since we're going to wipe it out! // getStorage(ACase.STORAGE_KEY, ACase.class).removeAll(); // //TODO: We should really be wiping out the _stored_ instances here, too // getStorage(FormRecord.STORAGE_KEY, FormRecord.class).removeAll(); // //Also, any of the sessions we've got saved // getStorage(SessionStateDescriptor.STORAGE_KEY, SessionStateDescriptor.class).removeAll(); // //Now we wipe out the user entirely // getStorage(User.STORAGE_KEY, User.class).removeAll(); // //Get rid of any user fixtures // getStorage("fixture", FormInstance.class).removeAll(); // getStorage(GeocodeCacheModel.STORAGE_KEY, GeocodeCacheModel.class).removeAll(); final String username; try { username = this.getSession().getLoggedInUser().getUsername(); } catch (SessionUnavailableException e) { return; } final Set<String> dbIdsToRemove = new HashSet<String>(); this.getAppStorage(UserKeyRecord.class).removeAll(new EntityFilter<UserKeyRecord>() { @Override public boolean matches(UserKeyRecord ukr) { if (ukr.getUsername().equalsIgnoreCase(username.toLowerCase())) { dbIdsToRemove.add(ukr.getUuid()); return true; } return false; } }); //TODO: We can just delete the db entirely. Editor sharedPreferencesEditor = CommCareApplication._().getCurrentApp().getAppPreferences().edit(); sharedPreferencesEditor.putString(CommCarePreferences.LAST_LOGGED_IN_USER, null); sharedPreferencesEditor.commit(); for (String id : dbIdsToRemove) { //TODO: We only wanna do this if the user is the _last_ one with a key to this id, actually. //(Eventually) this.getDatabasePath(CommCareUserOpenHelper.getDbName(id)).delete(); } CommCareApplication._().closeUserSession(); } public void prepareTemporaryStorage() { String tempRoot = this.getAndroidFsTemp(); FileUtil.deleteFileOrDir(tempRoot); boolean success = FileUtil.createFolder(tempRoot); if (!success) { Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Couldn't create temp folder"); } } public String getCurrentVersionString() { PackageManager pm = this.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { e.printStackTrace(); return "ERROR! Incorrect package version requested"; } int[] versions = this.getCommCareVersion(); String ccv = ""; for (int vn : versions) { if (!"".equals(ccv)) { ccv += "."; } ccv += vn; } String profileVersion = ""; Profile p = this.currentApp == null ? null : this.getCommCarePlatform().getCurrentProfile(); if (p != null) { profileVersion = String.valueOf(p.getVersion()); } String buildDate = getString(R.string.app_build_date); String buildNumber = getString(R.string.app_build_number); return Localization.get(getString(R.string.app_version_string), new String[]{pi.versionName, String.valueOf(pi.versionCode), ccv, buildNumber, buildDate, profileVersion}); } /** * Allows something within the current service binding to update the app to let it * know that the bind may take longer than the current timeout can allow */ public void setCustomServiceBindTimeout(int timeout) { synchronized (serviceLock) { this.mCurrentServiceBindTimeout = timeout; } } private void bindUserSessionService(final byte[] key, final UserKeyRecord record) { mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. User user = null; synchronized (serviceLock) { mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT; mBoundService = ((CommCareSessionService.LocalBinder) service).getService(); //Don't let anyone touch this until it's logged in // Open user database mBoundService.prepareStorage(key, record); if (record != null) { //Ok, so we have a login that was successful, but do we have a user model in the DB? //We need to check before we're logged in, so we get the handle raw, here for (User u : getRawStorage("USER", User.class, mBoundService.getUserDbHandle())) { if (record.getUsername().equals(u.getUsername())) { user = u; } } } //service available mIsBound = true; //Don't signal bind completion until the db is initialized. mIsBinding = false; if (user != null) { mBoundService.startSession(user); attachCallListener(); CommCareApplication.this.sessionWrapper = new AndroidSessionWrapper(CommCareApplication.this.getCommCarePlatform()); //See if there's an auto-update pending. We only want to be able to turn this //to "True" on login, not any other time //TODO: this should be associated with the app itself, not the global settings updatePending = getPendingUpdateStatus(); syncPending = getPendingSyncStatus(); doReportMaintenance(false); //Register that this user was the last to successfully log in if it's a real user if (!User.TYPE_DEMO.equals(user.getUserType())) { getCurrentApp().getAppPreferences().edit().putString(CommCarePreferences.LAST_LOGGED_IN_USER, record.getUsername()).commit(); performArchivedFormPurge(getCurrentApp()); } } } } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; } }; // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). bindService(new Intent(this, CommCareSessionService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBinding = true; } @SuppressLint("NewApi") protected void doReportMaintenance(boolean force) { //OK. So for now we're going to daily report sends and not bother with any of the frequency properties. //Create a new submission task no matter what. If nothing is pending, it'll see if there are unsent reports //and try to send them. Otherwise, it'll create the report SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences(); String url = settings.getString("PostURL", null); if (url == null) { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "PostURL isn't set. This should never happen"); return; } DataSubmissionListener dataListener = null; try { dataListener = CommCareApplication.this.getSession().startDataSubmissionListener(R.string.submission_logs_title); } catch (SessionUnavailableException sue) { // abort since it looks like the session expired return; } LogSubmissionTask task = new LogSubmissionTask( force || isPending(settings.getLong(CommCarePreferences.LOG_LAST_DAILY_SUBMIT, 0), DateUtils.DAY_IN_MILLIS), dataListener, url); //Execute on a true multithreaded chain, since this is an asynchronous process if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { task.execute(); } } private boolean getPendingUpdateStatus() { SharedPreferences preferences = getCurrentApp().getAppPreferences(); //Establish whether or not an AutoUpdate is Pending String autoUpdateFreq = preferences.getString(CommCarePreferences.AUTO_UPDATE_FREQUENCY, CommCarePreferences.FREQUENCY_NEVER); //See if auto update is even turned on if (!autoUpdateFreq.equals(CommCarePreferences.FREQUENCY_NEVER)) { long lastUpdateCheck = preferences.getLong(CommCarePreferences.LAST_UPDATE_ATTEMPT, 0); long duration = (24 * 60 * 60 * 100) * (CommCarePreferences.FREQUENCY_DAILY.equals(autoUpdateFreq) ? 1 : 7); return isPending(lastUpdateCheck, duration); } return false; } /** * Check through user storage and identify whether there are any forms * which can be purged from the device. * * @param app The current app */ private void performArchivedFormPurge(CommCareApp app) { int daysForReview = -1; String daysToPurge = app.getAppPreferences().getString("cc-days-form-retain", "-1"); try { daysForReview = Integer.parseInt(daysToPurge); } catch (NumberFormatException nfe) { Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, "Invalid days to purge: " + daysToPurge); } //If we don't define a days for review flag, we should just keep the forms around //indefinitely if (daysForReview == -1) { return; } SqlStorage<FormRecord> forms = this.getUserStorage(FormRecord.class); //Get the last date for froms to be valid (n days prior to today) long lastValidDate = new Date().getTime() - daysForReview * 24 * 60 * 60 * 1000; Vector<Integer> toPurge = new Vector<Integer>(); //Get all saved forms currently in storage for (int id : forms.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_SAVED)) { String date = forms.getMetaDataFieldForRecord(id, FormRecord.META_LAST_MODIFIED); try { //If the date the form was saved is before the last valid date, we can purge it if (lastValidDate > Date.parse(date)) { toPurge.add(id); } } catch (Exception e) { //Catch all for now, we know that at least "" and null //are causing problems (neither of which should be acceptable //but if we see them, we should consider the form //purgable. toPurge.add(id); } } if (toPurge.size() > 0) { Logger.log(AndroidLogger.TYPE_MAINTENANCE, "Purging " + toPurge.size() + " archived forms for being before the last valid date " + new Date(lastValidDate).toString()); //Actually purge the old forms for (int formRecord : toPurge) { FormRecordCleanupTask.wipeRecord(this, formRecord); } } } private boolean isPending(long last, long period) { Date current = new Date(); //There are a couple of conditions in which we want to trigger pending maintenance ops. long now = current.getTime(); //1) Straightforward - Time is greater than last + duration long diff = now - last; if (diff > period) { return true; } Calendar lastRestoreCalendar = Calendar.getInstance(); lastRestoreCalendar.setTimeInMillis(last); //2) For daily stuff, we want it to be the case that if the last time you synced was the day prior, //you still sync, so people can get into the cycle of doing it once in the morning, which //is more valuable than syncing mid-day. if (period == DateUtils.DAY_IN_MILLIS && (lastRestoreCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.getInstance().get(Calendar.DAY_OF_WEEK))) { return true; } //3) Major time change - (Phone might have had its calendar day manipulated). //for now we'll simply say that if last was more than a day in the future (timezone blur) //we should also trigger if (now < (last - DateUtils.DAY_IN_MILLIS)) { return true; } //TODO: maaaaybe trigger all if there's a substantial time difference //noted between calls to a server //Otherwise we're fine return false; } /** * Whether automated stuff like auto-updates/syncing are valid and should * be triggered. */ private boolean areAutomatedActionsInvalid() { try { if (User.TYPE_DEMO.equals(getSession().getLoggedInUser().getUserType())) { return true; } } catch (SessionUnavailableException sue) { return true; } return false; } public boolean isUpdatePending() { if (areAutomatedActionsInvalid()) { return false; } // We only set this to true occasionally, but in theory it could be set // to false from other factors, so turn it off if it is. if (!getPendingUpdateStatus()) { updatePending = false; } return updatePending; } private void unbindUserSessionService() { synchronized (serviceLock) { if (mIsBound) { if (sessionWrapper != null) { sessionWrapper.reset(); } mIsBound = false; // Detach our existing connection. unbindService(mConnection); } } } public CommCareSessionService getSession() throws SessionUnavailableException { long started = System.currentTimeMillis(); //If binding is currently in process, just wait for it. while (mIsBinding) { if (System.currentTimeMillis() - started > mCurrentServiceBindTimeout) { //Something bad happened unbindUserSessionService(); throw new SessionUnavailableException("Timeout binding to session service"); } } if (mIsBound) { synchronized (serviceLock) { return mBoundService; } } else { throw new SessionUnavailableException(); } } /** * @return A pair comprised of last sync time and an array with unsent and * incomplete form counts. If the user storage isn't open, return 0 vals * for unsent/incomplete forms. */ public Pair<Long, int[]> getSyncDisplayParameters() { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); long lastSync = prefs.getLong("last-succesful-sync", 0); SqlStorage<FormRecord> formsStorage = this.getUserStorage(FormRecord.class); try { int unsentForms = formsStorage.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_UNSENT).size(); int incompleteForms = formsStorage.getIDsForValue(FormRecord.META_STATUS, FormRecord.STATUS_INCOMPLETE).size(); return new Pair<>(lastSync, new int[]{unsentForms, incompleteForms}); } catch (UserStorageClosedException e) { return new Pair<>(lastSync, new int[]{0, 0}); } } // Start - Error message Hooks private final int MESSAGE_NOTIFICATION = org.commcare.dalvik.R.string.notification_message_title; private final ArrayList<NotificationMessage> pendingMessages = new ArrayList<NotificationMessage>(); public void reportNotificationMessage(NotificationMessage message) { reportNotificationMessage(message, false); } public void reportNotificationMessage(final NotificationMessage message, boolean notifyUser) { synchronized (pendingMessages) { //make sure there is no matching message pending for (NotificationMessage msg : pendingMessages) { if (msg.equals(message)) { //If so, bail. return; } } if (notifyUser) { Bundle b = new Bundle(); b.putParcelable("message", message); Message m = Message.obtain(toaster); m.setData(b); toaster.sendMessage(m); } //Otherwise, add it to the queue, and update the notification pendingMessages.add(message); updateMessageNotification(); } } public void updateMessageNotification() { NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); synchronized (pendingMessages) { if (pendingMessages.size() == 0) { mNM.cancel(MESSAGE_NOTIFICATION); return; } String title = pendingMessages.get(0).getTitle(); Notification messageNotification = new Notification(org.commcare.dalvik.R.drawable.notification, title, System.currentTimeMillis()); messageNotification.number = pendingMessages.size(); // The PendingIntent to launch our activity if the user selects this notification Intent i = new Intent(this, MessageActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0); String additional = pendingMessages.size() > 1 ? Localization.get("notifications.prompt.more", new String[]{String.valueOf(pendingMessages.size() - 1)}) : ""; // Set the info for the views that show in the notification panel. messageNotification.setLatestEventInfo(this, title, Localization.get("notifications.prompt.details", new String[]{additional}), contentIntent); messageNotification.deleteIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, NotificationClearReceiver.class), 0); //Send the notification. mNM.notify(MESSAGE_NOTIFICATION, messageNotification); } } public ArrayList<NotificationMessage> purgeNotifications() { synchronized (pendingMessages) { this.sendBroadcast(new Intent(ACTION_PURGE_NOTIFICATIONS)); ArrayList<NotificationMessage> cloned = (ArrayList<NotificationMessage>) pendingMessages.clone(); clearNotifications(null); return cloned; } } public void clearNotifications(String category) { synchronized (pendingMessages) { NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Vector<NotificationMessage> toRemove = new Vector<NotificationMessage>(); for (NotificationMessage message : pendingMessages) { if (category == null || category.equals(message.getCategory())) { toRemove.add(message); } } for (NotificationMessage message : toRemove) { pendingMessages.remove(message); } if (pendingMessages.size() == 0) { mNM.cancel(MESSAGE_NOTIFICATION); } else { updateMessageNotification(); } } } private boolean syncPending = false; /** * @return True if there is a sync action pending. */ private boolean getPendingSyncStatus() { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); long period = -1; //Old flag, use a day by default if ("true".equals(prefs.getString("cc-auto-update", "false"))) { period = DateUtils.DAY_IN_MILLIS; } //new flag, read what it is. String periodic = prefs.getString(CommCarePreferences.AUTO_SYNC_FREQUENCY, CommCarePreferences.FREQUENCY_NEVER); if (!periodic.equals(CommCarePreferences.FREQUENCY_NEVER)) { period = DateUtils.DAY_IN_MILLIS * (periodic.equals(CommCarePreferences.FREQUENCY_DAILY) ? 1 : 7); } //If we didn't find a period, bail if (period == -1) { return false; } long lastRestore = prefs.getLong(CommCarePreferences.LAST_SYNC_ATTEMPT, 0); return (isPending(lastRestore, period)); } public synchronized boolean isSyncPending(boolean clearFlag) { if (areAutomatedActionsInvalid()) { return false; } //We only set this to true occasionally, but in theory it could be set to false //from other factors, so turn it off if it is. if (!getPendingSyncStatus()) { syncPending = false; } if (!syncPending) { return false; } if (clearFlag) { syncPending = false; } return true; } public boolean isStorageAvailable() { try { File storageRoot = new File(getAndroidFsRoot()); return storageRoot.exists(); } catch (Exception e) { return false; } } /** * Notify the application that something has occurred which has been * logged, and which should cause log submission to occur as soon as * possible. */ public void notifyLogsPending() { doReportMaintenance(true); } public String getAndroidFsRoot() { return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/files/"; } public String getAndroidFsTemp() { return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/temp/"; } /** * @return a path to a file location that can be used to store a file * temporarily and will be cleaned up as part of CommCare's application * lifecycle */ public String getTempFilePath() { return getAndroidFsTemp() + PropertyUtils.genUUID(); } public ArchiveFileRoot getArchiveFileRoot() { return mArchiveFileRoot; } /** * Message handler that pops-up notifications to the user via toast. */ private static class PopupHandler extends Handler { /** * Reference to the context used to show pop-ups (the parent class). * Reference is weak to avoid memory leaks. */ private final WeakReference<CommCareApplication> mActivity; /** * @param activity Is the context used to pop-up the toast message. */ public PopupHandler(CommCareApplication activity) { mActivity = new WeakReference<CommCareApplication>(activity); } /** * Pops up the message to the user by way of toast * * @param m Has a 'message' parcel storing pop-up message text */ @Override public void handleMessage(Message m) { NotificationMessage message = m.getData().getParcelable("message"); CommCareApplication activity = mActivity.get(); if (activity != null) { Toast.makeText(activity, Localization.get("notification.for.details.wrapper", new String[]{message.getTitle()}), Toast.LENGTH_LONG).show(); } } } }
package dr.evomodel.coalescent; import dr.evolution.coalescent.ConstantPopulation; import dr.evolution.tree.Tree; import dr.evolution.util.Units; import dr.evomodel.tree.TreeModel; import dr.inference.model.Likelihood; import dr.inference.model.Parameter; import dr.xml.*; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.NotConvergedException; import no.uib.cipr.matrix.SymmTridiagEVD; import no.uib.cipr.matrix.SymmTridiagMatrix; /** * A likelihood function for the Gaussian Markov random field population trajectory. * * * * @author Erik Bloomquist * @author Vladimir Minin * @author Marc Suchard * @version $Id: GMRFSkylineLikelihood.java,v 1.3 2007/03/20 22:40:04 msuchard Exp $ */ public class GMRFSkylineLikelihood extends CoalescentLikelihood { // PUBLIC STUFF public static final String SKYLINE_LIKELIHOOD = "gmrfSkyLineLikelihood"; public static final String POPULATION_PARAMETER = "populationSizes"; public static final String PRECISION_PARAMETER = "precisionParameter"; public static final String POPULATION_TREE = "populationTree"; public static final String LAMBDA_PARAMETER = "lambdaParameter"; // PRIVATE STUFF protected Parameter popSizeParameter; protected Parameter precisionParameter; protected Parameter lambdaParameter; protected double[] gmrfWeights; protected int fieldLength; protected double[] coalescentIntervals; protected double[] storedCoalescentIntervals; protected double[] sufficientStatistics; protected double[] storedSufficientStatistics; protected SymmTridiagMatrix weightMatrix; protected SymmTridiagMatrix storedWeightMatrix; public GMRFSkylineLikelihood() { super(SKYLINE_LIKELIHOOD); } public GMRFSkylineLikelihood(Tree tree, Parameter popParameter, Parameter precParameter, Parameter lambda) { super(SKYLINE_LIKELIHOOD); this.popSizeParameter = popParameter; this.precisionParameter = precParameter; this.lambdaParameter = lambda; int tips = tree.getExternalNodeCount(); fieldLength = popSizeParameter.getDimension(); if (tips - fieldLength != 1) { throw new IllegalArgumentException("Number of tips (" + tips + ") must be one greater than number of pop sizes (" + fieldLength + ")"); } this.tree = tree; if (tree instanceof TreeModel) { addModel((TreeModel) tree); } addParameter(popSizeParameter); addParameter(precisionParameter); addParameter(lambdaParameter); setupIntervals(); coalescentIntervals = new double[fieldLength]; storedCoalescentIntervals = new double[fieldLength]; sufficientStatistics = new double[fieldLength]; storedSufficientStatistics = new double[fieldLength]; setupGMRFWeights(); addStatistic(new DeltaStatistic()); } // Likelihood IMPLEMENTATION public double getLogLikelihood() { if (!likelihoodKnown) { logLikelihood = calculateLogLikelihood(); likelihoodKnown = true; } return logLikelihood; } public double[] getSufficientStatistics() { return sufficientStatistics; } protected void setupGMRFWeights() { int index = 0; double length = 0; double weight = 0; for (int i = 0; i < getIntervalCount(); i++) { length += getInterval(i); weight += getInterval(i) * getLineageCount(i) * (getLineageCount(i) - 1); if (getIntervalType(i) == CoalescentEventType.COALESCENT) { coalescentIntervals[index] = length; sufficientStatistics[index] = weight / 2.0; index++; length = 0; weight = 0; } } //Set up the weight Matrix double[] offdiag = new double[fieldLength - 1]; double[] diag = new double[fieldLength]; // double precision = precisionParameter.getParameterValue(0); //First set up the offdiagonal entries; for (int i = 0; i < fieldLength - 1; i++) { offdiag[i] = -2.0 / (coalescentIntervals[i] + coalescentIntervals[i + 1]); } //Then set up the diagonal entries; for (int i = 1; i < fieldLength - 1; i++) diag[i] = -(offdiag[i] + offdiag[i - 1]); //Take care of the endpoints diag[0] = -offdiag[0]; diag[fieldLength - 1] = -offdiag[fieldLength - 2]; weightMatrix = new SymmTridiagMatrix(diag, offdiag); } public SymmTridiagMatrix getScaledWeightMatrix(double precision) { SymmTridiagMatrix a = weightMatrix.copy(); for (int i = 0; i < a.numRows() - 1; i++) { a.set(i, i, a.get(i, i) * precision); a.set(i + 1, i, a.get(i + 1, i) * precision); } a.set(fieldLength - 1, fieldLength - 1, a.get(fieldLength - 1, fieldLength - 1) * precision); return a; } public SymmTridiagMatrix getCopyWeightMatrix() { return weightMatrix.copy(); } protected void storeState() { super.storeState(); System.arraycopy(coalescentIntervals, 0, storedCoalescentIntervals, 0, coalescentIntervals.length); System.arraycopy(sufficientStatistics, 0, storedSufficientStatistics, 0, sufficientStatistics.length); storedWeightMatrix = weightMatrix.copy(); } protected void restoreState() { super.restoreState(); System.arraycopy(storedCoalescentIntervals, 0, coalescentIntervals, 0, storedCoalescentIntervals.length); System.arraycopy(storedSufficientStatistics, 0, sufficientStatistics, 0, storedSufficientStatistics.length); weightMatrix = storedWeightMatrix; } protected void handleParameterChangedEvent(Parameter parameter, int index) { likelihoodKnown = false; // Parameters (precision and popsizes do not change intervals or GMRF sufficient statistics // todo precision and lambda both change Q } /** * Calculates the log likelihood of this set of coalescent intervals, * given a demographic model. */ public double calculateLogLikelihood() { if (!intervalsKnown) { // intervalsKnown -> false when handleModelChanged event occurs in super. setupIntervals(); setupGMRFWeights(); } double logL = 0.0; double currentTime = 0.0; int popIndex = 0; ConstantPopulation cp = new ConstantPopulation(Units.Type.YEARS); for (int j = 0; j < intervalCount; j++) { cp.setN0(Math.exp(popSizeParameter.getParameterValue(popIndex))); if (getIntervalType(j) == CoalescentEventType.COALESCENT) { popIndex += 1; } logL += calculateIntervalLikelihood(cp, intervals[j], currentTime, lineageCounts[j], getIntervalType(j)); // insert zero-length coalescent intervals // int diff = getCoalescentEvents(j) - 1; // System.err.println("Diff = "+diff); // for (int k = 0; k < diff; k++) { // cp.setN0(popSizeParameter.getParameterValue(popIndex)); // logL += calculateIntervalLikelihood(cp, 0.0, currentTime, lineageCounts[j] - k - 1, CoalescentEventType.COALESCENT); // popIndex += 1; currentTime += intervals[j]; } // Calculate GMRF density; here GMRF = RW(1) logL += -0.5 * calculateWeightedSSE() * precisionParameter.getParameterValue(0); // Matrix operations taken from block update sampler to calculate data likelihood and field prior double currentLike = 0; DenseVector diagonal1 = new DenseVector(fieldLength); DenseVector currentGamma = new DenseVector(popSizeParameter.getParameterValues()); for (int i = 0; i < fieldLength; i++) { currentLike += -currentGamma.get(i) - sufficientStatistics[i] * Math.exp(-currentGamma.get(i)); } SymmTridiagMatrix currentQ = getScaledWeightMatrix(precisionParameter.getParameterValue(0)); currentQ.mult(currentGamma, diagonal1); currentLike -= 0.5 * logGeneralizedDeterminant(currentQ) - 0.5 * currentGamma.dot(diagonal1); // todo the line above is missing a normalizing constant involving factors of 2*pi /* WinBUGS code to fixed tree: (A:4.0,(B:2.0,(C:0.5,D:1.0):1.0):2.0) model { stat1 ~ dexp(rate[1]) stat2 ~ dexp(rate[2]) stat3 ~ dexp(rate[3]) rate[1] <- 1 / exp(theta[1]) rate[2] <- 1 / exp(theta[2]) rate[3] <- 1 / exp(theta[3]) theta[1] ~ dnorm(0, 0.001) theta[2] ~ dnorm(theta[1], weight[1]) theta[3] ~ dnorm(theta[2], weight[2]) weight[1] <- tau / 1.0 weight[2] <- tau / 1.5 tau ~ dgamma(1,0.3333) stat1 <- 9 / 2 stat2 <- 6 / 2 stat3 <- 4 / 2 } */ // return logL; return 0; } public static double logGeneralizedDeterminant(SymmTridiagMatrix X) { //Set up the eigenvalue solver SymmTridiagEVD eigen = new SymmTridiagEVD(X.numRows(), false); //Solve for the eigenvalues try { eigen.factor(X); } catch (NotConvergedException e) { throw new RuntimeException("Not converged error in generalized determinate calculation.\n" + e.getMessage()); } //Get the eigenvalues double[] x = eigen.getEigenvalues(); double a = 0; for (int i = 0; i < x.length; i++) { if (x[i] > 0.00001) a += Math.log(x[i]); } return a; } public Parameter getPrecisionParameter() { return precisionParameter; } public Parameter getPopSizeParameter() { return popSizeParameter; } public Parameter getLambdaParameter() { return lambdaParameter; } public SymmTridiagMatrix getWeightMatrix() { return weightMatrix.copy(); } public double calculateWeightedSSE() { double weightedSSE = 0; double currentPopSize = popSizeParameter.getParameterValue(0); double currentInterval = coalescentIntervals[0]; for (int j = 1; j < fieldLength; j++) { double nextPopSize = popSizeParameter.getParameterValue(j); double nextInterval = coalescentIntervals[j]; double delta = nextPopSize - currentPopSize; double weight = (currentInterval + nextInterval) / 2.0; weightedSSE += delta * delta / weight; currentPopSize = nextPopSize; currentInterval = nextInterval; } return weightedSSE; } // Private and protected stuff public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return SKYLINE_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { XMLObject cxo = (XMLObject) xo.getChild(POPULATION_PARAMETER); Parameter popParameter = (Parameter) cxo.getChild(Parameter.class); cxo = (XMLObject) xo.getChild(PRECISION_PARAMETER); Parameter precParameter = (Parameter) cxo.getChild(Parameter.class); cxo = (XMLObject) xo.getChild(POPULATION_TREE); TreeModel treeModel = (TreeModel) cxo.getChild(TreeModel.class); cxo = (XMLObject) xo.getChild(LAMBDA_PARAMETER); Parameter lambda = (Parameter) cxo.getChild(Parameter.class); return new GMRFSkylineLikelihood(treeModel, popParameter, precParameter, lambda); }
package org.ccnx.ccn.io.content; import java.io.IOException; import java.util.EnumSet; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.impl.CCNFlowControl.SaveType; import org.ccnx.ccn.impl.encoding.GenericXMLEncodable; import org.ccnx.ccn.impl.encoding.XMLDecoder; import org.ccnx.ccn.impl.encoding.XMLEncodable; import org.ccnx.ccn.impl.encoding.XMLEncoder; import org.ccnx.ccn.io.ErrorStateException; import org.ccnx.ccn.io.CCNAbstractInputStream.FlagTypes; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.KeyLocator; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.SignedInfo.ContentType; /** * Represents a secure, authenticatable link from one part of the CCN namespace to another. * * CCN links are very flexible and can be used to represent a wide variety of application-level * structures. A link can point to a specific content object (an individual block of content), * the collection of "segments" making up a specific version of a stream or document, an aggregated * "document" object consisting of multiple versions and their associated metadata, or to an arbitrary * point in the name tree -- essentially saying "treat the children of this node as if they * were my children". * * CCN links have authentication information associated with them, and can be made highly secure -- * by specifying who should have published (signed) the target of a given link, one can say effectively * "what I mean by name N is whatever Tom means by name N'". The authentication information * associated with a Link is called a LinkAuthenticator; its form and capabilities are still * evolving, but it will at least have the ability to offer indirection -- "trust anyone whose * key is signed by key K to have signed a valid target for this link". * * Links also play an important role in making up Collections, the CCN notion of a container full * of objects or names. */ public class Link extends GenericXMLEncodable implements XMLEncodable, Cloneable { /** * A CCNNetworkObject wrapper around Link, used for easily saving and retrieving * versioned Links to CCN. A typical pattern for using network objects to save * objects that happen to be encodable or serializable is to incorporate such a static * member wrapper class subclassing CCNEncodableObject, CCNSerializableObject, or * CCNNetworkObject itself inside the main class definition. */ public static class LinkObject extends CCNEncodableObject<Link> { public LinkObject(ContentName name, Link data, SaveType saveType, CCNHandle handle) throws IOException { super(Link.class, true, name, data, saveType, handle); } public LinkObject(ContentName name, Link data, SaveType saveType, PublisherPublicKeyDigest publisher, KeyLocator keyLocator, CCNHandle handle) throws IOException { super(Link.class, true, name, data, saveType, publisher, keyLocator, handle); } public LinkObject(ContentName name, CCNHandle handle) throws ContentDecodingException, IOException { super(Link.class, true, name, (PublisherPublicKeyDigest)null, handle); } public LinkObject(ContentName name, PublisherPublicKeyDigest publisher, CCNHandle handle) throws ContentDecodingException, IOException { super(Link.class, true, name, publisher, handle); } public LinkObject(ContentObject firstBlock, CCNHandle handle) throws ContentDecodingException, IOException { super(Link.class, true, firstBlock, handle); } public LinkObject(CCNEncodableObject<? extends Link> other) { super(Link.class, other); } /** * Subclasses that need to write an object of a particular type can override. * @return Content type to use. */ @Override public ContentType contentType() { return ContentType.LINK; } public ContentName getTargetName() throws ContentGoneException, ContentNotReadyException, ErrorStateException { Link lr = link(); if (null == lr) return null; return lr.targetName(); } public LinkAuthenticator getTargetAuthenticator() throws ContentNotReadyException, ContentGoneException, ErrorStateException { Link lr = link(); if (null == lr) return null; return lr.targetAuthenticator(); } public Link link() throws ContentNotReadyException, ContentGoneException, ErrorStateException { if (null == data()) return null; return data(); } public ContentObject dereference(long timeout) throws IOException { if (null == data()) return null; return link().dereference(timeout, _handle); } /** * Modify the properties of the input streams we read to read links themselves, * rather than dereferencing them and causing an infinite loop; must modify * in constructor to handle passed in content objects.. */ @Override protected EnumSet<FlagTypes> getInputStreamFlags() { return EnumSet.of(FlagTypes.DONT_DEREFERENCE); } } protected static final String LINK_ELEMENT = "Link"; protected static final String LABEL_ELEMENT = "Label"; // overlaps with WrappedKey.LABEL_ELEMENT, // shared dictionary entry protected ContentName _targetName; protected String _targetLabel; protected LinkAuthenticator _targetAuthenticator = null; public Link(ContentName targetName, String targetLabel, LinkAuthenticator targetAuthenticator) { _targetName = targetName; if ((null != targetLabel) && (targetLabel.length() == 0)) targetLabel = null; _targetLabel = targetLabel; _targetAuthenticator = targetAuthenticator; } public Link(ContentName targetName, LinkAuthenticator targetAuthenticator) { _targetName = targetName; _targetAuthenticator = targetAuthenticator; } public Link(ContentName targetName) { this(targetName, null); } /** * Decoding constructor. */ public Link() {} public Link(Link other) { _targetName = other.targetName(); _targetLabel = other.targetLabel(); _targetAuthenticator = other.targetAuthenticator(); } public ContentName targetName() { return _targetName; } public String targetLabel() { return _targetLabel; } public LinkAuthenticator targetAuthenticator() { return _targetAuthenticator; } /** * A stab at a dereference() method. Dereferencing is not well-defined in this * general setting -- we don't know what we'll find down below this name. A link may * link to anything in the tree, including an intermediate node, or a name qualified * down to the digest, and we need a way of distinguishing these things (TODO). Usually * you'll read the target of the link using a method that knows something about what * kind of data to find there. This is a brute-force method that hands you back a block * underneath the link target name that meets the authentication criteria; at minimum * it should pull an exact match if the link fully specifies digests and so on (TODO -- TBD), * and otherwise it'll probably assume that what is below here is either a version and * segments (get latest version) or that this is versioned and it wants segments. * * @param timeout How long to try for, in milliseconds. * @param handle Handle to use. Should not be null. * @return Returns a child object. Verifies that it meets the requirement of the link, * and that it is signed by who it claims. Could allow caller to pass in verifier * to verify higher-level trust and go look for another block on failure. * @throws IOException */ public ContentObject dereference(long timeout, CCNHandle handle) throws IOException { // getLatestVersion will return the latest version of an unversioned name, or the // latest version after a given version. So if given a specific version, get that one. if (VersioningProfile.hasTerminalVersion(targetName())) { return handle.get(targetName(), (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null, timeout); } // Don't know if we are referencing a particular object, so don't look for segments. PublisherPublicKeyDigest desiredPublisher = (null != targetAuthenticator()) ? targetAuthenticator().publisher() : null; return VersioningProfile.getLatestVersion(targetName(), desiredPublisher, timeout, new ContentObject.SimpleVerifier(desiredPublisher), handle); } @Override public void decode(XMLDecoder decoder) throws ContentDecodingException { decoder.readStartElement(getElementLabel()); _targetName = new ContentName(); _targetName.decode(decoder); if (decoder.peekStartElement(LABEL_ELEMENT)) { _targetLabel = decoder.readUTF8Element(LABEL_ELEMENT); } if (decoder.peekStartElement(LinkAuthenticator.LINK_AUTHENTICATOR_ELEMENT)) { _targetAuthenticator = new LinkAuthenticator(); _targetAuthenticator.decode(decoder); } decoder.readEndElement(); } @Override public void encode(XMLEncoder encoder) throws ContentEncodingException { if (!validate()) throw new ContentEncodingException("Link failed to validate!"); encoder.writeStartElement(getElementLabel()); _targetName.encode(encoder); if (null != targetLabel()) { encoder.writeElement(LABEL_ELEMENT, targetLabel()); } if (null != _targetAuthenticator) _targetAuthenticator.encode(encoder); encoder.writeEndElement(); } @Override public String getElementLabel() { return LINK_ELEMENT; } @Override public boolean validate() { return (null != targetName()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_targetAuthenticator == null) ? 0 : _targetAuthenticator .hashCode()); result = prime * result + ((_targetLabel == null) ? 0 : _targetLabel.hashCode()); result = prime * result + ((_targetName == null) ? 0 : _targetName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Link other = (Link) obj; if (_targetAuthenticator == null) { if (other._targetAuthenticator != null) return false; } else if (!_targetAuthenticator.equals(other._targetAuthenticator)) return false; if (_targetLabel == null) { if (other._targetLabel != null) return false; } else if (!_targetLabel.equals(other._targetLabel)) return false; if (_targetName == null) { if (other._targetName != null) return false; } else if (!_targetName.equals(other._targetName)) return false; return true; } @Override public Object clone() throws CloneNotSupportedException { return new Link(this); } @Override public String toString() { return "Link [targetName=" + targetName() + ", targetLabel=" + targetLabel() + ", targetAuthenticator=" + targetAuthenticator() + "]"; } }
package burp; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.nio.*; import java.nio.charset.*; import java.util.*; import java.util.regex.*; import javax.swing.*; import javax.swing.tree.*; import mjson.Json; public class JsonJTree extends MouseAdapter implements IMessageEditorTab, ClipboardOwner { private final JPanel panel = new JPanel(new BorderLayout()); private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); private final JTree tree = new JTree(root); private final JComboBox<Part> comboBox = new JComboBox<>(); private final DefaultTreeModel model = (DefaultTreeModel)tree.getModel(); private byte[] content; private final IExtensionHelpers helpers; private final IBurpExtenderCallbacks callbacks; private static final Pattern JWT_RE = Pattern.compile( "(?:[-_A-Z0-9]+\\.){2}[-_A-Z0-9]+", Pattern.CASE_INSENSITIVE); JsonJTree(IBurpExtenderCallbacks callbacks) { tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addMouseListener(this); this.callbacks = callbacks; this.helpers = callbacks.getHelpers(); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { root.removeAllChildren(); Part part = comboBox.getItemAt(comboBox.getSelectedIndex()); Json node = Json.read(part.decode()); root.setUserObject(new Node(null, node)); if (node.isObject()) { dumpObjectNode(root, node); } else if (node.isArray()) { dumpArrayNode(root, node); } model.reload(root); expandAllNodes(tree, 0, tree.getRowCount()); } }); panel.add(comboBox, BorderLayout.NORTH); panel.add(new JScrollPane(tree), BorderLayout.CENTER); } @Override public void mousePressed (MouseEvent e) { if (e.isPopupTrigger()) doPop(e); } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) doPop(e); } private void doPop(MouseEvent e) { final JPopupMenu popup = new JPopupMenu(); final TreePath sp = tree.getSelectionPath(); if (sp == null) return; // nothing was selected final DefaultMutableTreeNode node = (DefaultMutableTreeNode)sp.getLastPathComponent(); final Node item = (Node)node.getUserObject(); if (node != root) { addToPopup(popup, "Copy key", new ActionListener() { public void actionPerformed(ActionEvent e) { copyString(item.asKeyString()); } }); } if (!item.isArrayOrObject()) { final String value = item.asValueString(); addToPopup(popup, "Copy value as string", new ActionListener() { public void actionPerformed(ActionEvent e) { copyString(value); } }); if (mayBeJwt(value)) { addToPopup(popup, "Convert JWT to EsPReSSO format", new ActionListener() { public void actionPerformed(ActionEvent e) { convertJwt(value); } }); } } addToPopup(popup, "Copy value as JSON", new ActionListener() { public void actionPerformed(ActionEvent e) { copyString(item.asJsonString()); } }); popup.addSeparator(); addToPopup(popup, "Collapse full tree", new ActionListener() { public void actionPerformed(ActionEvent e) { collapseChildren(root); } }); if (node != root) { addToPopup(popup, "Collapse subtree below this node", new ActionListener() { public void actionPerformed(ActionEvent e) { collapseChildren(node); } }); } popup.show(e.getComponent(), e.getX(), e.getY()); } private void collapseChildren(DefaultMutableTreeNode node) { final ArrayList<DefaultMutableTreeNode> list = Collections.list(node.children()); for (DefaultMutableTreeNode child : list) collapseChildren(child); if (node.isRoot()) return; tree.collapsePath(new TreePath(node.getPath())); } private static boolean mayBeJwt(final String value) { return JWT_RE.matcher(value).matches(); } private void convertJwt(final String jwt) { final java.util.List<String> headers = Arrays.asList( "GET / HTTP/1.0", "Content-Type: application/x-www-form-urlencoded", "X-Message: dummy request, do not send!"); final byte[] body = helpers.stringToBytes("access_token=" + jwt); final byte[] request = helpers.buildHttpMessage(headers, body); callbacks.sendToRepeater("example.com", 80, false, request, "JWT"); } private static void addToPopup(JPopupMenu pm, String title, ActionListener al) { final JMenuItem mi = new JMenuItem(title); mi.addActionListener(al); pm.add(mi); } private void copyString(final String value) { Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(new StringSelection(value), this); } public boolean isEnabled(byte[] content, boolean isRequest) { if (content.length == 0) { root.removeAllChildren(); model.reload(root); return false; } return !parse(content, isRequest).isEmpty(); // TODO try parsing at this stage } private final static byte[] BOM_UTF8 = {(byte)0xEF, (byte)0xBB, (byte)0xBF}; private final static int MIN_LEN = 2; private void detectRawJson(Vector<Part> dest, byte[] content, int bodyOffset, IRequestInfo req) { final int len = content.length; final int bodyLen = len - bodyOffset; if (bodyLen < MIN_LEN) return; byte[] firstThreeBytes = Arrays.copyOfRange(content, bodyOffset, bodyOffset + BOM_UTF8.length); if (Arrays.equals(firstThreeBytes, BOM_UTF8) && bodyLen > BOM_UTF8.length + MIN_LEN) bodyOffset += BOM_UTF8.length; addIfJson(dest, bytesToString(Arrays.copyOfRange(content, bodyOffset, len)), null); } private final CharsetDecoder utfDecoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput( CodingErrorAction.REPORT); private String bytesToString(byte[] source) { try { return utfDecoder.decode(ByteBuffer.wrap(source)).toString(); } catch (CharacterCodingException e) { return helpers.bytesToString(source); } } private enum Base64Variant { STANDARD("/+"), URL_SAFE("_-") { private String decode(IExtensionHelpers helpers, String value) { String c14n = value; for (int i = 0; i < nonAlNums.length(); i++) { c14n = c14n.replace(nonAlNums.charAt(i), STANDARD.nonAlNums.charAt(i)); } return super.decode(helpers, c14n); } }; protected final String nonAlNums; private final Pattern pattern; private Base64Variant(String nonAlNums) { this.nonAlNums = nonAlNums; pattern = Pattern.compile("[a-zA-Z0-9" + nonAlNums + "]+"); } public static void tryAll(IExtensionHelpers helpers, Set<String> matches, String value) { for (Base64Variant variant : Base64Variant.values()) { variant.tryMatch(helpers, matches, value); } } private void tryMatch(IExtensionHelpers helpers, Set<String> matches, String value) { Matcher m = pattern.matcher(value); int start = 0; while (m.find(start)) { matches.add(decode(helpers, m.group())); start = m.end(); } } private String decode(IExtensionHelpers helpers, String value) { return helpers.bytesToString(helpers.base64Decode(value)); } } private void detectParamJson(Vector<Part> dest, byte[] content, int bodyOffset, IRequestInfo req) { if (req == null) return; java.util.List<IParameter> params = req.getParameters(); ArrayList<Part> parts = new ArrayList<>(params.size()); for (IParameter param : params) { String value = param.getValue(); Set<String> candidates = new HashSet<String>( Arrays.asList(value, helpers.urlDecode(value))); Base64Variant.tryAll(helpers, candidates, value); for (final String s : candidates) { addIfJson(dest, s, param); } } } public interface Part { public String decode(); } private static void addIfJson(Vector<Part> dest, String value, IParameter param) { if (mightBeJson(value)) { dest.add(new Part() { public String decode() { return value; } @Override public String toString() { if (param == null) return "HTTP body"; return parameterTypeToString(param.getType()) + " \"" + param.getName() + '"'; } }); } } private static boolean mightBeJson(final String value) { final int len = value.length(); if (len < MIN_LEN) return false; final char firstChar = value.charAt(0); return ((firstChar | (byte)0x20) == (byte)0x7b) && // '[' = 0x5b, '{' = 0x7b, former missing bit 0x20 (value.charAt(len - 1) == firstChar + 2); // ']' = 0x5d, '}' = 0x7d, offset is 2 for both } private static String parameterTypeToString(final byte type) { switch (type) { case IParameter.PARAM_URL: return "URL parameter"; case IParameter.PARAM_BODY: return "Body parameter"; case IParameter.PARAM_COOKIE: return "HTTP cookie"; case IParameter.PARAM_XML: return "XML element"; case IParameter.PARAM_XML_ATTR: return "XML attribute"; case IParameter.PARAM_MULTIPART_ATTR: return "MIME multipart attribute"; case IParameter.PARAM_JSON: return "JSON item"; default: return "Unknown parameter"; } } private Vector<Part> parse(byte[] content, boolean isRequest) { IRequestInfo req = null; int bodyOffset; if (isRequest) { req = helpers.analyzeRequest(content); bodyOffset = req.getBodyOffset(); } else { IResponseInfo i = helpers.analyzeResponse(content); bodyOffset = i.getBodyOffset(); } Vector<Part> parts = new Vector<>(); detectRawJson(parts, content, bodyOffset, req); detectParamJson(parts, content, bodyOffset, req); return parts; } public void setMessage(byte[] content, boolean isRequest) { this.content = content; root.removeAllChildren(); if (content != null) { Vector<Part> parts = parse(content, isRequest); if (parts.size() == 1) { Json node = Json.read(parts.get(0).decode()); root.setUserObject(new Node(null, node)); if (node.isObject()) { dumpObjectNode(root, node); } else if (node.isArray()) { dumpArrayNode(root, node); } comboBox.setVisible(false); } else { comboBox.setModel(new DefaultComboBoxModel<>(parts)); comboBox.setSelectedIndex(0); comboBox.setVisible(true); } } else { root.setUserObject(new Node(null, null)); } model.reload(root); expandAllNodes(tree, 0, tree.getRowCount()); } private static class Node { private final String key; private final Json value; Node(String key, Json value) { this.key = key; this.value = value; } public boolean isArrayOrObject() { return value.isArray() || value.isObject(); } public String asValueString() { return value.asString(); } public String asJsonString() { return value.toString(); } public String asKeyString() { return key; } @Override public String toString() { if (key == null) return "(JSON root)"; if (value.isNull()) { return key + ": null"; } else if (value.isString()) { return key + ": \"" + value.asString() + '"'; } else if (value.isNumber() || value.isBoolean()) { return key + ": " + value.toString(); } return key; } } private static void dumpObjectNode(DefaultMutableTreeNode dst, Json src) { Map<String, Json> tm = new TreeMap(String.CASE_INSENSITIVE_ORDER); tm.putAll(src.asJsonMap()); for (Map.Entry<String, Json> e : tm.entrySet()) { processNode(dst, e.getKey(), e.getValue()); } } private static void dumpArrayNode(DefaultMutableTreeNode dst, Json src) { int i = 0; for (Json value : src.asJsonList()) { String key = '[' + String.valueOf(i++) + ']'; processNode(dst, key, value); } } private static void processNode(DefaultMutableTreeNode dst, String key, Json value) { final DefaultMutableTreeNode node = new DefaultMutableTreeNode(new Node(key, value)); dst.add(node); // check if `value` is actually JSON serialized data "embedded" as string if (value.isString()) { // if so, deserialize and treat the result as first-class content final String stringValue = value.asString(); if (mightBeJson(stringValue)) { try { value = Json.read(stringValue); } catch (Exception e) { // ignore false positive } } } if (value.isObject()) { dumpObjectNode(node, value); } else if (value.isArray()) { dumpArrayNode(node, value); } } private static void expandAllNodes(JTree tree, int startingIndex, int rowCount) { for (int i = startingIndex; i < rowCount; i++) { tree.expandRow(i); } if (tree.getRowCount() != rowCount) { expandAllNodes(tree, rowCount, tree.getRowCount()); } } public String getTabCaption() { return "JSON JTree"; } public Component getUiComponent() { return panel; } public byte[] getMessage() { return content; } public boolean isModified() { return false; } public byte[] getSelectedData() { return null; } public void lostOwnership(Clipboard aClipboard, Transferable aContents) {} }
package org.funcj.data; import org.funcj.util.Functions.*; import java.util.*; import java.util.function.Consumer; import java.util.stream.*; /** * Simple recursive, immutable linked list. * <p> * Each {code IList} is either {code Empty} or it is {@code NonEmpty}, * in which case it has a head element value and a tail. * The tail is itself an {@code IList}. * Null elements are not allowed. * @param <T> element type */ public abstract class IList<T> implements Iterable<T> { /** * Construct an empty list. * @param <T> element type * @return empty list */ public static <T> IList<T> nil() { return (IList<T>)Empty.EMPTY; } /** * Construct an empty list. * @param <T> element type * @return empty list */ public static <T> IList<T> of() { return nil(); } /** * Construct a list with one element. * @param elem element * @param <T> element type * @return list with one element */ public static <T> NonEmpty<T> of(T elem) { return IList.<T>nil().add(elem); } /** * Construct a list with one or more elements. * @param elem first element * @param elems remaining elements * @param <T> element type * @return list with one or more element */ public static <T> NonEmpty<T> of(T elem, T... elems) { return ofArray(elems).add(elem); } /** * Construct a list from an {@link java.lang.Iterable} collection of elements. * @param elems iterable collection of elements * @param <T> element type * @return list with multiple elements */ public static <T> IList<T> ofIterable(Iterable<T> elems) { IList<T> r = nil(); for (T elem : elems) { r = r.add(elem); } return r.reverse(); } /** * Construct a list from an array. * @param elems array of elements * @param <T> element type * @return list with multiple elements */ public static <T> IList<T> ofArray(T[] elems) { IList<T> r = nil(); for (int i = elems.length-1; i >= 0; --i) { r = r.add(elems[i]); } return r; } /** * Concatenate two lists to form a new list * @param l1 first list * @param l2 second list * @param <T> element type * @return concatenated list */ public static <T> IList<T> concat(IList<? extends T> l1, IList<? extends T> l2) { IList<T> r = (IList<T>)l2; for (T elem : l1.reverse()) { r = r.add(elem); } return r; } /** * Convert a list of {@link java.lang.Character}s into a {@link java.lang.String}. * @param l list of {@code Character}s * @return a {@code String} */ public static String listToString(IList<Character> l) { final StringBuilder sb = new StringBuilder(); for (; !l.isEmpty(); l = l.tail()) { sb.append(l.head()); } return sb.toString(); } /** * Convert a {@link java.lang.String} into a list of {@link java.lang.Character}s. * @param s {@code String} * @return a list of {@code Character}s */ public static IList<Character> stringToList(String s) { IList<Character> r = nil(); for (int i = s.length() - 1; i >= 0; --i) { r = r.add(s.charAt(i)); } return r; } /** * Create a new list by adding an element to the head of this list. * @param head element to add onto head of this list * @return new list */ public NonEmpty<T> add(T head) { return new NonEmpty<T>(head, this); } /** * Create a new list by adding multiple elements to the head of this list. * @param l list to be added to the head of this list * @param <S> list element type * @return new list */ public <S extends T> IList<T> addAll(IList<S> l) { IList<T> r = this; for(IList<S> next = l.reverse(); !next.isEmpty(); next = next.tail()) { r = r.add(next.head()); } return r; } /** * Return true if this list is empty otherwise false * @return true if this list is empty otherwise false */ public abstract boolean isEmpty(); /** * Returns Optional.empty() if this list is empty, * otherwise it returns an {@link java.util.Optional} which wraps the non-empty list. * @return Optional.empty() if this list is empty, otherwise an {@code Optional} which wraps the * non-empty list. */ public abstract Optional<NonEmpty<T>> nonEmptyOpt(); /** * Return the head element of this list. * @return the head of this list. * @throws UnsupportedOperationException if the list is empty. */ public abstract T head(); /** * Return the tail of this list. * @return the tail of this list. * @throws UnsupportedOperationException if the list is empty. */ public abstract IList<T> tail(); /** * Returns the element at the specified position in this list. * @param index the position of the element to return * @return the element of this list at the specified position. * @throws IndexOutOfBoundsException if the index is out of bounds. */ public abstract T get(int index); /** * Append the contents of this list to a {@link java.lang.StringBuilder}. * @param sb the StringBuilder to be appended to * @return the StringBuilder */ public abstract StringBuilder append(StringBuilder sb); /** * List equality. * @return true if this list and rhs are equal in terms of their size and elements. */ @Override public boolean equals(Object rhs) { return this == rhs || (rhs != null && getClass() == rhs.getClass() && equals((IList<T>) rhs)); } /** * Type-safe list equality. * @param rhs list to be cpmpared * @return true if this list and rhs are equal in terms of their elements. */ public abstract boolean equals(IList<T> rhs); /** * Apply one of two functions depending on whether this list is empty or not. * @param nonEmptyF function to be applied if the list is non-empty * @param emptyF function to be applied if the list is empty * @param <S> return type of both functions * @return the result of applying the appropriate function. */ public abstract <S> S match(F<NonEmpty<T>, S> nonEmptyF, F<Empty<T>, S> emptyF); /** * Create a new list by appending an element to the end of this list. * @param l list to be appended to the end of this list * @return new list */ public abstract IList<T> appendAll(IList<T> l); /** * @return the length of this list. */ public abstract int size(); /** * @return this list in reverse. */ public abstract IList<T> reverse(); /** * Apply the function {code f} to each element in this list, * and store the results in a new list. * @param f function to be applied to each element * @param <U> function return type * @return the new list */ public abstract <U> IList<U> map(F<? super T, ? extends U> f); /** * Apply a function that returns an {@code IList} to each element * in this list and concatenate the results into a single list. * @param f function to be applied * @param <U> element type for the list returned by the function * @return the new list */ public abstract <U> IList<U> flatMap(F<? super T, IList<? extends U>> f); /** * Right-fold a function over this list. * @param f function to be folded * @param z initial value for the fold (typically the identity value of {@code f}) * @param <U> fold result type * @return folded result */ public abstract <U> U foldRight(F2<T, U, U> f, U z); /** * Left-fold a function over this list. * @param f function to be folded * @param z initial value for the fold (typically the identity value of {@code f}) * @param <U> fold result type * @return folded result */ public abstract <U> U foldLeft(F2<U, T, U> f, U z); /** * Right-fold a function over this non-empty list. * @param f function to be folded * @return folded result */ public abstract T foldRight1(Op2<T> f); /** * Left-fold a function over this non-empty list. * @param f function to be folded * @return folded result */ public abstract T foldLeft1(Op2<T> f); /** * Create a {@link java.util.Spliterator}. * @return the spliterator */ public abstract Spliterator<T> spliterator(); /** * Create a {@link java.util.stream.Stream} onto this list. * @return the new stream */ public Stream<T> stream() { return StreamSupport.stream(spliterator(), false); } /** * Create a parallel {@link java.util.stream.Stream} onto this list. * @return the new stream */ public Stream<T> parallelStream() { return StreamSupport.stream(spliterator(), true); } /** * Create an {@link java.util.Iterator} over this list. * @return the iterator */ public abstract Iterator<T> iterator(); /** * Convert to a Java List implementation, albeit an immutable one. * @return Java List. */ public abstract List<T> toList(); public static final class Empty<T> extends IList<T> { static final Empty EMPTY = new Empty(); private Empty() { } @Override public boolean isEmpty() { return true; } @Override public Optional<NonEmpty<T>> nonEmptyOpt() { return Optional.empty(); } @Override public T head() { throw new UnsupportedOperationException("Cannot take the head of an empty list"); } @Override public IList<T> tail() { throw new UnsupportedOperationException("Cannot take the tail of an empty list"); } @Override public T get(int index) { throw new IndexOutOfBoundsException( "Index " + index + " out of bounds for an " + size() + " element list"); } @Override public String toString() { return "[]"; } @Override public boolean equals(IList<T> rhs) { return rhs.isEmpty(); } public int hashCode() { return 0; } @Override public StringBuilder append(StringBuilder sb) { return sb; } @Override public <S> S match(F<NonEmpty<T>, S> nonEmptyF, F<Empty<T>, S> emptyF) { return emptyF.apply(this); } @Override public IList<T> appendAll(IList<T> l) { return l; } @Override public int size() { return 0; } @Override public IList<T> reverse() { return EMPTY; } @Override public <U> IList<U> map(F<? super T, ? extends U> f) { return EMPTY; } @Override public <U> IList<U> flatMap(F<? super T, IList<? extends U>> f) { return EMPTY; } @Override public <U> U foldRight(F2<T, U, U> f, U z) { return z; } @Override public <U> U foldLeft(F2<U, T, U> f, U z) { return z; } @Override public T foldRight1(Op2<T> f) { throw new UnsupportedOperationException("Cannot call foldRight1(f) on an empty list"); } @Override public T foldLeft1(Op2<T> f) { throw new UnsupportedOperationException("Cannot call foldLeft1(f) on an empty list"); } @Override public Spliterator<T> spliterator() { return new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { return false; } @Override public Spliterator<T> trySplit() { return null; } @Override public long estimateSize() { return size(); } @Override public int characteristics() { return Spliterator.IMMUTABLE + Spliterator.SIZED; } }; } @Override public Iterator<T> iterator() { return new Iterator<T>(){ @Override public boolean hasNext() { return false; } @Override public T next() { throw new NoSuchElementException(); } }; } @Override public List<T> toList() { return Collections.emptyList(); } } public static final class NonEmpty<T> extends IList<T> { private final T head; private final IList<T> tail; NonEmpty(T head, IList<T> tail) { this.head = Objects.requireNonNull(head); this.tail = Objects.requireNonNull(tail); } @Override public boolean isEmpty() { return false; } @Override public Optional<NonEmpty<T>> nonEmptyOpt() { return Optional.of(this); } @Override public T head() { return head; } @Override public IList<T> tail() { return tail; } @Override public T get(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index " + index + " out of bounds"); } else if (index == 0) { return head; } else { IList<T> next = tail; for (int i = 1; i < index; ++i) { if (next.isEmpty()) { throw new IndexOutOfBoundsException("Index " + index + " out of bounds"); } else { next = ((NonEmpty<T>)next).tail; } } if (next.isEmpty()) { throw new IndexOutOfBoundsException("Index " + index + " out of bounds"); } else { return ((NonEmpty<T>)next).head; } } } @Override public String toString() { final StringBuilder r = new StringBuilder("["); append(r).setCharAt(r.length() - 1, ']'); return r.toString(); } @Override public StringBuilder append(StringBuilder sb) { return tail.append(sb.append(head).append(',')); } @Override public boolean equals(IList<T> rhs) { if (rhs.isEmpty()) { return false; } else { for (T lhs : this) { if (rhs.isEmpty() || !lhs.equals(rhs.head())) { return false; } rhs = rhs.tail(); } return rhs.isEmpty(); } } public int hashCode() { int hashCode = 1; for(IList<T> next = this; !next.isEmpty(); next = next.tail()) { hashCode = 31 * hashCode + next.head().hashCode(); } return hashCode; } @Override public <S> S match(F<NonEmpty<T>, S> nonEmptyF, F<Empty<T>, S> emptyF) { return nonEmptyF.apply(this); } @Override public IList<T> appendAll(IList<T> l) { return new NonEmpty<T>(head, tail.appendAll(l)); } @Override public int size() { IList<T> pos = this; int length = 0; while (!pos.isEmpty()) { ++length; pos = pos.tail(); } return length; } @Override public NonEmpty<T> reverse() { IList<T> r = IList.of(); for (IList<T> n = this; !n.isEmpty(); n = n.tail()) { r = r.add(n.head()); } return (NonEmpty<T>)r; } @Override public <U> IList<U> map(F<? super T, ? extends U> f) { IList<U> r = nil(); for (IList<T> n = this; !n.isEmpty(); n = n.tail()) { r = r.add(f.apply(n.head())); } return r.reverse(); } @Override public <U> IList<U> flatMap(F<? super T, IList<? extends U>> f) { final IList<U> r = nil(); for (IList<T> n = this; !n.isEmpty(); n = n.tail()) { r.addAll(f.apply(n.head())); } return r; } @Override public <U> U foldRight(F2<T, U, U> f, U z) { return reverse().foldLeft(f.flip(), z); } @Override public <U> U foldLeft(F2<U, T, U> f, U z) { U r = z; for (IList<T> n = this; !n.isEmpty(); n = n.tail()) { r = f.apply(r, n.head()); } return r; } @Override public T foldRight1(Op2<T> f) { return reverse().foldLeft1(f.flip()); } @Override public T foldLeft1(Op2<T> f) { T r = head; for (IList<T> n = tail; !n.isEmpty(); n = n.tail()) { r = f.apply(r, n.head()); } return r; } @Override public Spliterator<T> spliterator() { return Spliterators.spliterator( this.iterator(), size(), Spliterator.IMMUTABLE + Spliterator.SIZED ); } @Override public Iterator<T> iterator() { return new Iterator<T>(){ IList<T> n = NonEmpty.this; @Override public boolean hasNext() { return !n.isEmpty(); } @Override public T next() { final T head = n.head(); n = n.tail(); return head; } }; } @Override public List<T> toList() { return new ListAdaptor<T>(this); } } } class ListAdaptor<T> extends AbstractSequentialList<T> { private final IList<T> impl; private final int size; ListAdaptor(IList<T> impl) { this.impl = impl; size = impl.size(); } @Override public ListIterator<T> listIterator(int index) { return new ListIterator<T>() { private IList<T> move(IList<T> node, int count) { for (int i = 0; i < count; ++i) { node = node.tail(); } return node; } private int pos = index; private IList<T> node = move(impl, index); @Override public boolean hasNext() { return pos < size; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } else { final T ret = node.head(); node = node.tail(); ++pos; return ret; } } @Override public boolean hasPrevious() { return pos >= 0; } @Override public T previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } else { --pos; node = move(impl, pos); ++pos; return node.head(); } } @Override public int nextIndex() { return pos; } @Override public int previousIndex() { return pos - 1; } @Override public void remove() { throw modError(); } @Override public void set(T t) { throw modError(); } @Override public void add(T t) { throw modError(); } private UnsupportedOperationException modError() { return new UnsupportedOperationException("IList can not be modified"); } }; } @Override public int size() { return size; } }
package org.jeo.data; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.jeo.feature.Schema; import org.jeo.util.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Driver utility class. * * @author Justin Deoliveira, OpenGeo */ public class Drivers { /** logger */ static final Logger LOG = LoggerFactory.getLogger(Drivers.class); /** driver registry */ static final DriverRegistry REGISTRY = new ServiceLoaderDriverRegistry(); /** * Lists all registered drivers. */ public static Iterator<Driver<?>> list() { return list(REGISTRY); } /** * Lists all registered drivers from the specified registry. */ public static Iterator<Driver<?>> list(DriverRegistry registry) { return list(Driver.class, registry); } /** * Lists all registered drivers that extend from the specified class. */ public static Iterator<Driver<?>> list(final Class<?> filter) { return list(filter, REGISTRY); } /** * Lists all registered drivers from the specified registry that extend from the specified class. */ public static Iterator<Driver<?>> list(final Class<?> filter, DriverRegistry registry) { final Iterator<? extends Driver<?>> it = registry.list(); return new Iterator<Driver<?>>() { Driver<?> next; @Override public boolean hasNext() { while(next == null && it.hasNext()) { next = it.next(); if (filter == null || !filter.isInstance(next)) { next = null; } } return next != null; } @Override public Driver<?> next() { try { return next; } finally { next = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } /** * Looks up a driver by name. * * @see Drivers#find(String, DriverRegistry) */ public static Driver<?> find(String name) { return find(name, REGISTRY); } /** * Looks up a driver by name from the specified registry. * <p> * This method does a case-insensitive comparison. * </p> * * @param name The driver name. * * @return The matching driver, or <code>null</code> if no match was found. * * @see Driver#getName() */ public static Driver<?> find(String name, DriverRegistry registry) { for (Iterator<Driver<?>> it = list(registry); it.hasNext();) { Driver<?> d = it.next(); if (name.equalsIgnoreCase(d.getName()) || d.getAliases().contains(name)) { return d; } } return null; } /** * Looks up a driver from a data uri. * * @see Drivers#find(URI, DriverRegistry)}. */ public static Driver<?> find(URI uri) { return find(uri, REGISTRY); } /** * Looks up a driver from a data uri. * * @param uri A uri defining a data source, as described by * {@link #open(URI, Class, DriverRegistry)}. * * @return The matching driver, or <code>null</code> if no match was found. */ public static <T> Driver<T> find(URI uri, DriverRegistry registry) { uri = convertFileURI(uri); String scheme = uri.getScheme(); if (scheme == null) { LOG.debug("URI must have scheme: " + uri); return null; } Driver<T> d = (Driver<T>) find(scheme, registry); if (d == null) { LOG.debug("No matching driver for " + scheme); return null; } return d; } /** * Opens a connection to data specified by a file. * * @see Drivers#open(File, Class, DriverRegistry) */ public static Object open(File file) throws IOException { return open(file, REGISTRY); } /** * Opens a connection to data specified by a file using the specified driver registry. * * @see Drivers#open(File, Class, DriverRegistry) */ public static Object open(File file, DriverRegistry registry) throws IOException { return open(file, Object.class, registry); } /** * Opens a connection to data specified by a file expecting an object of the specified class. * * @see Drivers#open(File, Class, DriverRegistry) */ public static <T> T open(File file, Class<T> clazz) throws IOException { return open(file, clazz, REGISTRY); } /** * Opens a connection to data specified by a file. * <p> * The optional <tt>class</tt> parameter is used to filter the candidate driver set. For * example to constrain to workspace drivers. * <pre><code> * Workspace ws = Drivers.open(..., Workspace.class); * </code></pre> * </p> * @param file The file to open. * @param clazz Class used to filter registered drivers, may be <code>null</code>. * * @return The data object, or <code>null</code> if no suitable driver could be found for the * specified file. * * @throws IOException Any connection errors, such as a file system error or * database connection failure. */ public static <T> T open(File file, Class<T> clazz, DriverRegistry registry) throws IOException { return open(file.toURI(), clazz, registry); } /** * Opens a connection to data described by the specified options. * <p> * The optional <tt>class</tt> parameter is used to filter the candidate driver set. For * example to constrain to workspace drivers. * <pre><code> * Workspace ws = Drivers.open(..., Workspace.class); * </code></pre> * </p> * @param opts Connection options. * @param clazz Class used to filter registered drivers, may be <code>null</code>. * * @return The data object, or <code>null</code> if no suitable driver could be found for the * specified options. * * @throws IOException Any connection errors, such as a file system error or * database connection failure. */ public static <T> T open(Map<?, Object> opts, Class<T> clazz) throws IOException { return open(opts, clazz, REGISTRY); } public static <T> T open(Map<?, Object> opts, Class<T> clazz, DriverRegistry registry) throws IOException { return open(opts, clazz, list(registry)); } /** * Opens a connection to data described by the specified uri. * * @see Drivers#open(URI, Class, DriverRegistry) */ public static Object open(URI uri) throws IOException { return open(uri, REGISTRY); } /** * Opens a connection to data described by the specified uri with the specified driver * registry. * * @see Drivers#open(URI, Class, DriverRegistry) */ public static Object open(URI uri, DriverRegistry registry) throws IOException { return open(uri, Object.class, registry); } /** * Opens a connection to data described by the specified uri. * <p> * The <tt>uri</tt> can take one of two forms. The first is a file uri: * <pre> * file:&lt;path> * </pre> * For example <tt>file:/Users/jdeolive/foo.json</tt> specifies a connection to a GeoJSON file. * </p> * <p> * The second form uses the uri components to describe different aspect of the connection: * <pre> * [&lt;driver>://][&lt;primary-option>][?&lt;secondary-options>]*][#&lt;dataset>] * </pre> * Where: * <ul> * <li><tt>driver</tt> is the driver name or alias * <li><tt>primary-option</tt> is the "main" option for that driver, for example in the case * of file based drivers this would be the file path, in the case of database based drivers * this would be the database name. * <li><tt>secondary-options</tt> are additional driver options * <li><tt>dataset</tt> is the name of a dataset within a workspace * </ul> * For example <tt>pg://jeo?host=locahost&port=5432&user=bob#states</tt> specifies a * connection to a PostGIS table named "states", in a database named "jeo", as user "bob", to * a server running on localhost, port 5432. * </p> * <p> * The optional <tt>class</tt> parameter is used to filter the candidate driver set. For * example to constrain to workspace drivers. * <pre><code> * Workspace ws = Drivers.open(..., Workspace.class); * </code></pre> * </p> * @param uri uri specifying connection options. * @param clazz Class used to filter registered drivers, may be <code>null</code>. * * @return The data object, or <code>null</code> if no suitable driver could be found for the * specified options. * * @throws IOException Any connection errors, such as a file system error or * database connection failure. */ public static <T> T open(URI uri, Class<T> clazz, DriverRegistry registry) throws IOException { uri = convertFileURI(uri); Driver<?> d = find(uri, registry); if (d == null) { return null; } Map<String,Object> opts = parseURI(uri, d); if (!d.canOpen(opts, null)) { throw new IllegalArgumentException(d.getName() + " driver can't open " + opts); } Object data = d.open(opts); if (data instanceof Workspace && uri.getFragment() != null) { data = ((Workspace)data).get(uri.getFragment()); } return clazz.cast(data); } public static <T extends VectorDataset> T create(Schema schema, URI uri, Class<T> clazz) throws IOException { return create(schema, uri, clazz, REGISTRY); } public static <T extends VectorDataset> T create(Schema schema, URI uri, Class<T> clazz, DriverRegistry registry) throws IOException { uri = convertFileURI(uri); Driver<T> d = find(uri, registry); if (d == null) { throw new IllegalArgumentException("No driver for " + uri); } if (!(d instanceof VectorDriver)) { throw new IllegalArgumentException(d.getName() + " not a vector driver"); } VectorDriver<?> vd = (VectorDriver<?>) d; Map<String,Object> opts = parseURI(uri, d); if (!vd.canCreate(opts, null)) { throw new IllegalArgumentException(d.getName() + " driver can't open " + opts); } Object obj = vd.create(opts, schema); if (obj instanceof VectorDataset) { return (T) obj; } else if (obj instanceof Workspace) { Workspace ws = (Workspace) obj; return (T) ws.get(schema.getName()); } throw new IllegalArgumentException(d.getName() + " driver returned " + obj); } static Map<String,Object> parseURI(URI uri, Driver<?> d) { Map<String,Object> opts = new HashMap<String, Object>(); // parse host / path String first = uri.getHost() != null ? uri.getHost() : uri.getPath(); if (first != null) { //use the first key if (!d.getKeys().isEmpty()) { opts.put(d.getKeys().get(0).getName(), first); } } // parse query string if (uri.getQuery() != null) { String[] kvps = uri.getQuery().split("&"); for (String kvp : kvps) { String[] kv = kvp.split("="); if (kv.length != 2) { throw new IllegalArgumentException("Illegal key value pair: " + kvp); } opts.put(kv[0], kv[1]); } } return opts; } static <T> T open(Map<?, Object> opts, Class<T> clazz, Iterator<Driver<?>> it) throws IOException { while (it.hasNext()) { Driver<?> drv = it.next(); if (clazz != null && !clazz.isAssignableFrom(drv.getType())) { continue; } if (drv.canOpen(opts, null)) { Object data = drv.open(opts); if (data != null) { return (T) data; } } } return null; } static URI convertFileURI(URI uri) { if ("file".equalsIgnoreCase(uri.getScheme())) { //hack for files, turn file extension String ext = Util.extension(uri.getPath()); if (ext != null) { try { uri = new URI(String.format("%s://?file=%s%s", ext, uri.getPath(), uri.getFragment() != null ? "#"+uri.getFragment() : "")); } catch (URISyntaxException e) { } } } return uri; } }
package ru.job4j.max; public class Max { public int max(int first, int second) { return first > second ? first : second; } }
package ru.pro.tree; import java.util.*; class Tree<E extends Comparable<E>> implements SimpleTree<E> { private Node<E> root; public Tree(Node<E> root) { this.root = root; } private Node<E> find(List<Node<E>> children, E parent) { Node<E> result = null; for (Node<E> child : children) { if (child.getValue().compareTo(parent) == 0) { if (checkRepeat(child.getValue(),children)) { result = child; break; } } result = find(child.getChildren(), parent); } return result; } private boolean checkRepeat(E child,List<Node<E>> children){ boolean result = true; int count = 0; for (Node<E> childall : children) { if (child.equals(childall.getValue())) { if (count > 0 & count <= 1) { result = false; break; } count++; } } return result; } public boolean isBinary(){ return isBinary(root); } private boolean isBinary(Node<E> node) { boolean result; if (node.getChildren().size() > 2){ return false; } else { for (Node<E> noda: node.getChildren()) { result = isBinary(noda); if (!result) { return result; } } } return true; } @Override public boolean add(E parent, E child) { Node<E> resultAdd = root; if (!root.getValue().equals(parent)) { resultAdd = find(root.getChildren(), parent); } boolean parentExists = resultAdd != null; if (parentExists) { Node<E> node = new Node<>(child); resultAdd.getChildren().add(node); } return parentExists; } @Override public Iterator<E> iterator() { return new TreeIterator(); } private class TreeIterator implements Iterator<E> { private Queue<Node<E>> queue; private TreeIterator() { queue = new LinkedList<>(); queue.add(root); } @Override public boolean hasNext() { return !queue.isEmpty(); } @Override public E next() { Node<E> result = queue.poll(); queue.addAll(result.getChildren()); return result.getValue(); } } }
package arez; import arez.component.TypeBasedLocator; import arez.spy.ActionCompleteEvent; import arez.spy.ActionStartEvent; import arez.spy.ComponentCreateStartEvent; import arez.spy.ComponentInfo; import arez.spy.ComputableValueCreateEvent; import arez.spy.ComputeCompleteEvent; import arez.spy.ComputeStartEvent; import arez.spy.ObservableValueChangeEvent; import arez.spy.ObservableValueCreateEvent; import arez.spy.ObserveCompleteEvent; import arez.spy.ObserveScheduleEvent; import arez.spy.ObserveStartEvent; import arez.spy.ObserverCreateEvent; import arez.spy.ObserverErrorEvent; import arez.spy.ObserverInfo; import arez.spy.Priority; import arez.spy.PropertyAccessor; import arez.spy.PropertyMutator; import arez.spy.TaskCompleteEvent; import arez.spy.TaskStartEvent; import arez.spy.TransactionCompleteEvent; import arez.spy.TransactionStartEvent; import java.io.IOException; import java.security.AccessControlException; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; @SuppressWarnings( "Duplicates" ) public class ArezContextTest extends AbstractArezTest { @Test public void generateName() { final ArezContext context = Arez.context(); // Use passed in name assertEquals( context.generateName( "ComputableValue", "MyName" ), "MyName" ); //synthesize name context.setNextNodeId( 1 ); assertEquals( context.generateName( "ComputableValue", null ), "ComputableValue@1" ); assertEquals( context.getNextNodeId(), 2 ); ArezTestUtil.disableNames(); //Ignore name assertNull( context.generateName( "ComputableValue", "MyName" ) ); //Null name also fine assertNull( context.generateName( "ComputableValue", null ) ); } @Test public void triggerScheduler() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); context.observer( () -> { observeADependency(); callCount.incrementAndGet(); }, Flags.RUN_LATER ); assertEquals( callCount.get(), 0 ); context.triggerScheduler(); assertEquals( callCount.get(), 1 ); } @Test public void triggerScheduler_alreadyActive() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); context.observer( () -> { observeADependency(); callCount.incrementAndGet(); }, Flags.RUN_LATER ); assertEquals( callCount.get(), 0 ); context.markSchedulerAsActive(); context.triggerScheduler(); assertEquals( callCount.get(), 0 ); } @Test public void triggerScheduler_inEnvironment() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final AtomicReference<String> environment = new AtomicReference<>(); context.setEnvironment( new Environment() { @Override public <T> T run( @Nonnull final SafeFunction<T> function ) { environment.set( "RED" ); try { return function.call(); } finally { environment.set( null ); } } @Override public <T> T run( @Nonnull final Function<T> function ) throws Throwable { environment.set( "RED" ); try { return function.call(); } finally { environment.set( null ); } } } ); context.observer( () -> { observeADependency(); callCount.incrementAndGet(); assertEquals( environment.get(), "RED" ); }, Flags.RUN_LATER ); assertEquals( callCount.get(), 0 ); assertNull( environment.get() ); context.triggerScheduler(); assertEquals( callCount.get(), 1 ); assertNull( environment.get() ); } @Test public void triggerScheduler_inEnvironment_whereEnvironmentSchedulesActions() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final AtomicReference<String> environment = new AtomicReference<>(); final AtomicInteger count = new AtomicInteger( 3 ); final AtomicReference<Observer> observerReference = new AtomicReference<>(); context.setEnvironment( new Environment() { @Override public <T> T run( @Nonnull final SafeFunction<T> function ) { environment.set( "RED" ); T result = function.call(); /* * This simulates the scenario where something like react4j has only scheduler that will * react to changes in arez and potentially re-schedule arez events. */ if ( count.decrementAndGet() > 0 ) { context.safeAction( () -> observerReference.get().setState( Flags.STATE_STALE ), Flags.NO_VERIFY_ACTION_REQUIRED ); } environment.set( null ); return result; } @Override public <T> T run( @Nonnull final Function<T> function ) throws Throwable { environment.set( "RED" ); T result = function.call(); /* * This simulates the scenario where something like react4j has only scheduler that will * react to changes in arez and potentially re-schedule arez events. */ if ( count.decrementAndGet() > 0 ) { context.safeAction( () -> observerReference.get().setState( Flags.STATE_STALE ), Flags.NO_VERIFY_ACTION_REQUIRED ); } environment.set( null ); return result; } } ); final Observer observer = context.observer( () -> { final ObservableValue<Object> observableValue = Arez.context().observable(); observableValue.reportObserved(); callCount.incrementAndGet(); assertEquals( environment.get(), "RED" ); }, Flags.RUN_LATER ); observerReference.set( observer ); assertEquals( callCount.get(), 0 ); assertNull( environment.get() ); context.triggerScheduler(); assertEquals( callCount.get(), 3 ); assertEquals( count.get(), 0 ); assertNull( environment.get() ); } @Test public void isReadOnlyTransactionActive() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); context.action( () -> { assertTrue( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); observeADependency(); context.action( () -> { assertTrue( context.isTransactionActive() ); assertTrue( context.isReadOnlyTransactionActive() ); observeADependency(); }, Flags.READ_ONLY ); } ); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); } @Test public void isWriteTransactionActive() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadWriteTransactionActive() ); context.action( () -> { assertTrue( context.isTransactionActive() ); assertTrue( context.isReadWriteTransactionActive() ); observeADependency(); context.action( () -> { assertTrue( context.isTransactionActive() ); assertFalse( context.isReadWriteTransactionActive() ); observeADependency(); }, Flags.READ_ONLY ); } ); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadWriteTransactionActive() ); } @Test public void isTrackingTransactionActive() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); assertFalse( context.isReadWriteTransactionActive() ); assertFalse( context.isTrackingTransactionActive() ); context.action( () -> { assertTrue( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); assertTrue( context.isReadWriteTransactionActive() ); observeADependency(); } ); final Observer tracker = context.tracker( () -> assertFalse( context.isTrackingTransactionActive() ) ); context.observe( tracker, () -> { observeADependency(); assertTrue( context.isTransactionActive() ); assertTrue( context.isReadOnlyTransactionActive() ); assertFalse( context.isReadWriteTransactionActive() ); assertTrue( context.isTrackingTransactionActive() ); } ); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); assertFalse( context.isReadWriteTransactionActive() ); assertFalse( context.isTrackingTransactionActive() ); } @SuppressWarnings( "unused" ) @Test public void requireNewTransaction_false() throws Throwable { final ArezContext context = Arez.context(); context.action( () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); context.action( () -> assertNotEquals( context.getTransaction(), transaction ), Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); final int result1 = context.action( () -> { assertNotEquals( context.getTransaction(), transaction ); return 0; }, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); context.safeAction( () -> assertNotEquals( context.getTransaction(), transaction ), Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); final int result2 = context.safeAction( () -> { assertNotEquals( context.getTransaction(), transaction ); return 0; }, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); context.action( () -> assertEquals( context.getTransaction(), transaction ), Flags.NO_VERIFY_ACTION_REQUIRED ); final int result3 = context.action( () -> { assertEquals( context.getTransaction(), transaction ); return 0; }, Flags.NO_VERIFY_ACTION_REQUIRED ); context.safeAction( () -> assertEquals( context.getTransaction(), transaction ), Flags.NO_VERIFY_ACTION_REQUIRED ); final int result4 = context.safeAction( () -> { assertEquals( context.getTransaction(), transaction ); return 0; }, Flags.NO_VERIFY_ACTION_REQUIRED ); }, Flags.NO_VERIFY_ACTION_REQUIRED ); } @SuppressWarnings( "unused" ) @Test public void nestedAction_allowed() throws Throwable { final ArezContext context = Arez.context(); final AtomicInteger updateCalled = new AtomicInteger(); final Observer tracker = context.tracker( updateCalled::incrementAndGet, Flags.READ_WRITE | Flags.NESTED_ACTIONS_ALLOWED ); context.observe( tracker, () -> { observeADependency(); assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); context.action( () -> assertNotEquals( context.getTransaction(), transaction ), Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); final int result1 = context.action( () -> { assertNotEquals( context.getTransaction(), transaction ); return 0; }, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); context.safeAction( () -> assertNotEquals( context.getTransaction(), transaction ), Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); final int result2 = context.safeAction( () -> { assertNotEquals( context.getTransaction(), transaction ); return 0; }, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ); context.action( () -> assertEquals( context.getTransaction(), transaction ), Flags.NO_VERIFY_ACTION_REQUIRED ); } ); } @SuppressWarnings( "unused" ) @Test public void nestedAction_notAllowed() throws Throwable { final ArezContext context = Arez.context(); final AtomicInteger updateCalled = new AtomicInteger(); final Observer tracker = context.tracker( updateCalled::incrementAndGet, Flags.READ_WRITE | Flags.NESTED_ACTIONS_DISALLOWED ); context.observe( tracker, () -> { observeADependency(); assertInvariantFailure( () -> context.action( "A1", AbstractArezTest::observeADependency, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ), "Arez-0187: Attempting to nest action named 'A1' inside transaction named 'Observer@1' created by an observer that does not allow nested actions." ); assertInvariantFailure( () -> context.action( "A2", () -> 1, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ), "Arez-0187: Attempting to nest action named 'A2' inside transaction named 'Observer@1' created by an observer that does not allow nested actions." ); assertInvariantFailure( () -> context.safeAction( "A3", AbstractArezTest::observeADependency, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ), "Arez-0187: Attempting to nest action named 'A3' inside transaction named 'Observer@1' created by an observer that does not allow nested actions." ); assertInvariantFailure( () -> context.safeAction( "A4", () -> 1, Flags.NO_VERIFY_ACTION_REQUIRED | Flags.REQUIRE_NEW_TRANSACTION ), "Arez-0187: Attempting to nest action named 'A4' inside transaction named 'Observer@1' created by an observer that does not allow nested actions." ); } ); } @Test public void verifyActionFlags() { final Procedure executable = () -> { }; assertInvariantFailure( () -> Arez.context().action( executable, Flags.DEACTIVATE_ON_UNOBSERVE ), "Arez-0212: Flags passed to action 'Action@1' include some " + "unexpected flags set: " + Flags.DEACTIVATE_ON_UNOBSERVE ); } @Test public void verifyActionFlags_badEnvironmentFlags() { final Procedure executable = () -> { }; assertInvariantFailure( () -> Arez.context() .action( executable, Flags.ENVIRONMENT_REQUIRED | Flags.ENVIRONMENT_NOT_REQUIRED ), "Arez-0125: Flags passed to action 'Action@1' include both ENVIRONMENT_REQUIRED and ENVIRONMENT_NOT_REQUIRED." ); } @Test public void verifyActionFlags_badTransactionFlags() { final Procedure executable = () -> { }; assertInvariantFailure( () -> Arez.context() .action( executable, Flags.READ_ONLY | Flags.READ_WRITE ), "Arez-0126: Flags passed to action 'Action@1' include both READ_ONLY and READ_WRITE." ); } @Test public void verifyActionFlags_badVerifyAction() { final Procedure executable = () -> { }; assertInvariantFailure( () -> Arez.context() .action( executable, Flags.VERIFY_ACTION_REQUIRED | Flags.NO_VERIFY_ACTION_REQUIRED ), "Arez-0127: Flags passed to action 'Action@1' include both VERIFY_ACTION_REQUIRED and NO_VERIFY_ACTION_REQUIRED." ); } @Test public void action_function() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final String expectedValue = ValueUtil.randomString(); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); final String name = ValueUtil.randomString(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String v0 = context.action( name, () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), name ); assertNull( transaction.getPrevious() ); assertEquals( transaction.getContext(), context ); assertEquals( transaction.getId(), nextNodeId ); assertFalse( transaction.isMutation() ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); //Not tracking so no state updated assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); return expectedValue; }, Flags.READ_ONLY, new Object[]{ param1, param2, param3 } ); assertFalse( context.isTransactionActive() ); assertEquals( v0, expectedValue ); //ObservableValue still not updated assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); assertEquals( observableValue.getObservers().size(), 0 ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertNull( e.getThrowable() ); assertTrue( e.returnsResult() ); assertEquals( e.getResult(), v0 ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void action_NO_REPORT_RESULT() throws Throwable { final ArezContext context = Arez.context(); final ObservableValue<?> observableValue = context.observable(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.action( () -> { observableValue.reportObserved(); return ValueUtil.randomString(); }, Flags.NO_REPORT_RESULT ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class ); handler.assertNextEvent( TransactionStartEvent.class ); handler.assertNextEvent( TransactionCompleteEvent.class ); handler.assertNextEvent( ActionCompleteEvent.class, e -> assertNull( e.getResult() ) ); } @Test public void safeAction_NO_REPORT_RESULT() { final ArezContext context = Arez.context(); final ObservableValue<?> observableValue = context.observable(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.safeAction( () -> { observableValue.reportObserved(); return ValueUtil.randomString(); }, Flags.NO_REPORT_RESULT ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class ); handler.assertNextEvent( TransactionStartEvent.class ); handler.assertNextEvent( TransactionCompleteEvent.class ); handler.assertNextEvent( ActionCompleteEvent.class, e -> assertNull( e.getResult() ) ); } @Test public void action_function_throwsException() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final String name = ValueUtil.randomString(); final IOException ioException = new IOException(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); assertThrows( IOException.class, () -> context.action( name, () -> { throw ioException; }, 0, new Object[]{ param1, param2, param3 } ) ); assertFalse( context.isTransactionActive() ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertTrue( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertTrue( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertEquals( e.getThrowable(), ioException ); assertTrue( e.returnsResult() ); assertNull( e.getResult() ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void action_Environment_Required() throws Throwable { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.action( AbstractArezTest::observeADependency, Flags.ENVIRONMENT_REQUIRED ); assertEquals( inEnvironmentCallCount.get(), 1 ); } @Test public void action_Environment_Not_Required() throws Throwable { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.action( AbstractArezTest::observeADependency, Flags.ENVIRONMENT_NOT_REQUIRED ); assertEquals( inEnvironmentCallCount.get(), 0 ); } @Test public void action_Environment_Default() throws Throwable { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.action( AbstractArezTest::observeADependency ); assertEquals( inEnvironmentCallCount.get(), 0 ); } @Test public void safeAction_Environment_Required() { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.safeAction( AbstractArezTest::observeADependency, Flags.ENVIRONMENT_REQUIRED ); assertEquals( inEnvironmentCallCount.get(), 1 ); } @Test public void safeAction_Environment_Not_Required() { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.safeAction( AbstractArezTest::observeADependency, Flags.ENVIRONMENT_NOT_REQUIRED ); assertEquals( inEnvironmentCallCount.get(), 0 ); } @Test public void safeAction_Environment_Default() { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.safeAction( AbstractArezTest::observeADependency ); assertEquals( inEnvironmentCallCount.get(), 0 ); } @Test public void action_function_NameButNoMutationVariant() throws Throwable { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); context.action( name, () -> { observeADependency(); assertTrue( context.getTransaction().isMutation() ); assertEquals( context.getTransaction().getName(), name ); return ValueUtil.randomString(); } ); } @Test public void action_procedure_verifyActionRequired_false() throws Throwable { final Procedure executable = ValueUtil::randomString; Arez.context().action( executable, Flags.NO_VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void action_procedure_verifyActionRequired_true_butInvariantsDisabled() throws Throwable { ArezTestUtil.noCheckInvariants(); final Procedure executable = ValueUtil::randomString; Arez.context().action( executable, Flags.VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void action_procedure_verifyActionRequired_true() { final Procedure procedure = ValueUtil::randomString; assertInvariantFailure( () -> Arez.context().action( "X", procedure, Flags.VERIFY_ACTION_REQUIRED ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void action_procedure_verifyActionRequired_true_is_default() { assertInvariantFailure( () -> Arez.context().action( "X", (Procedure) ValueUtil::randomString ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void action_function_verifyActionRequired_false() throws Throwable { Arez.context().action( (Function<String>) ValueUtil::randomString, Flags.NO_VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void action_function_verifyActionRequired_true_butInvariantsDisabled() throws Throwable { ArezTestUtil.noCheckInvariants(); Arez.context().action( (Function<String>) ValueUtil::randomString, Flags.VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void action_function_verifyActionRequired_true() { final Function<String> function = ValueUtil::randomString; assertInvariantFailure( () -> Arez.context().action( "X", function, Flags.VERIFY_ACTION_REQUIRED ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void action_function_verifyActionRequired_true_is_default() { final Function<String> function = ValueUtil::randomString; assertInvariantFailure( () -> Arez.context().action( "X", function ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void safeAction_procedure_verifyActionRequired_false() { final SafeProcedure procedure = ValueUtil::randomString; Arez.context().safeAction( ValueUtil.randomString(), procedure, Flags.NO_VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void safeAction_procedure_verifyActionRequired_true_butInvariantsDisabled() { ArezTestUtil.noCheckInvariants(); final SafeProcedure executable = ValueUtil::randomString; Arez.context().safeAction( ValueUtil.randomString(), executable, Flags.VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void safeAction_procedure_verifyActionRequired_true() { final SafeProcedure procedure = ValueUtil::randomString; assertInvariantFailure( () -> Arez.context().safeAction( "X", procedure, Flags.VERIFY_ACTION_REQUIRED ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void safeAction_procedure_verifyActionRequired_true_is_default() { assertInvariantFailure( () -> Arez.context().safeAction( "X", (SafeProcedure) ValueUtil::randomString ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void safeAction_function_verifyActionRequired_false() { Arez.context().safeAction( (SafeFunction<String>) ValueUtil::randomString, Flags.NO_VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void safeAction_function_verifyActionRequired_true_butInvariantsDisabled() { ArezTestUtil.noCheckInvariants(); Arez.context().safeAction( (SafeFunction<String>) ValueUtil::randomString, Flags.VERIFY_ACTION_REQUIRED ); // If we get to here then we performed an action where no read or write occurred } @Test public void safeAction_function_verifyActionRequired_true() { final SafeFunction<String> function = ValueUtil::randomString; assertInvariantFailure( () -> Arez.context().safeAction( "X", function, Flags.VERIFY_ACTION_REQUIRED ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void safeAction_function_verifyActionRequired_true_is_default() { assertInvariantFailure( () -> Arez.context().safeAction( "X", (SafeFunction<String>) ValueUtil::randomString ), "Arez-0185: Action named 'X' completed but no reads, writes, schedules, reportStales or reportPossiblyChanged occurred within the scope of the action." ); } @Test public void action_function_minimalParameters() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final String expectedValue = ValueUtil.randomString(); final ObservableValue<Object> observableValue = context.observable(); final int nextNodeId = context.getNextNodeId(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String v0 = context.action( () -> { observableValue.reportObserved(); assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), "Action@" + nextNodeId ); assertTrue( transaction.isMutation() ); return expectedValue; } ); assertFalse( context.isTransactionActive() ); assertEquals( v0, expectedValue ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 0 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertTrue( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertTrue( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertNull( e.getThrowable() ); assertTrue( e.returnsResult() ); assertEquals( e.getResult(), v0 ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 0 ); } ); } @Test public void track_function() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final String expectedValue = ValueUtil.randomString(); final AtomicInteger callCount = new AtomicInteger(); final Observer tracker = context.tracker( callCount::incrementAndGet, Flags.READ_WRITE ); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String v0 = context.observe( tracker, () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), tracker.getName() ); assertEquals( transaction.isMutation(), tracker.isMutation() ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); // Tracking so state updated final ArrayList<ObservableValue<?>> observableValues = transaction.getObservableValues(); assertNotNull( observableValues ); assertEquals( observableValues.size(), 1 ); assertEquals( observableValue.getObservers().size(), 0 ); assertEquals( observableValue.getLastTrackerTransactionId(), nextNodeId ); return expectedValue; }, new Object[]{ param1, param2, param3 } ); assertFalse( context.isTransactionActive() ); context.getSpy().removeSpyEventHandler( handler ); assertEquals( v0, expectedValue ); assertEquals( observableValue.getLastTrackerTransactionId(), 0 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); // Reaction not called as the function sets up initial tracking assertEquals( callCount.get(), 0 ); context.action( observableValue::reportChanged ); assertEquals( callCount.get(), 1 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertTrue( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertTrue( e.isMutation() ); final ObserverInfo info = e.getTracker(); assertNotNull( info ); assertEquals( info.getName(), tracker.getName() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertTrue( e.isMutation() ); final ObserverInfo info = e.getTracker(); assertNotNull( info ); assertEquals( info.getName(), tracker.getName() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertNull( e.getThrowable() ); assertTrue( e.returnsResult() ); assertEquals( e.getResult(), v0 ); assertTrue( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void observe_function_no_parameters() throws Throwable { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger callCount = new AtomicInteger(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); final Observer observer = context.tracker( callCount::incrementAndGet, Flags.AREZ_OR_NO_DEPENDENCIES | Flags.READ_WRITE ); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final int result = context.observe( observer, () -> { final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), observer.getName() ); return 23; } ); assertEquals( inEnvironmentCallCount.get(), 0 ); assertEquals( result, 23 ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertTrue( e.isTracked() ); assertEquals( e.getParameters().length, 0 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertTrue( e.isMutation() ); final ObserverInfo info = e.getTracker(); assertNotNull( info ); assertEquals( info.getName(), observer.getName() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertTrue( e.isMutation() ); final ObserverInfo info = e.getTracker(); assertNotNull( info ); assertEquals( info.getName(), observer.getName() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertNull( e.getThrowable() ); assertTrue( e.returnsResult() ); assertEquals( e.getResult(), result ); assertTrue( e.isTracked() ); assertEquals( e.getParameters().length, 0 ); } ); } @Test public void observe_NO_REPORT_RESULT() throws Throwable { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.tracker( callCount::incrementAndGet, Flags.AREZ_OR_NO_DEPENDENCIES | Flags.NO_REPORT_RESULT ); assertTrue( observer.noReportResults() ); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final int result = context.observe( observer, () -> 23 ); assertEquals( result, 23 ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class ); handler.assertNextEvent( TransactionStartEvent.class ); handler.assertNextEvent( TransactionCompleteEvent.class ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertTrue( e.returnsResult() ); assertNull( e.getResult() ); } ); } @Test public void observe_environment_Required() throws Throwable { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger callCount = new AtomicInteger(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); final Observer observer = context.tracker( callCount::incrementAndGet, Flags.AREZ_OR_NO_DEPENDENCIES | Flags.ENVIRONMENT_REQUIRED ); context.observe( observer, () -> 23 ); assertEquals( inEnvironmentCallCount.get(), 1 ); } @Test public void track_function_passingNonTracker() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.observer( new CountAndObserveProcedure() ); assertInvariantFailure( () -> context.observe( observer, callCount::incrementAndGet ), "Arez-0017: Attempted to invoke observe(..) on observer named '" + observer.getName() + "' but observer is not configured to use an application executor." ); assertEquals( callCount.get(), 0 ); } @Test public void action_safeFunction() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final String expectedValue = ValueUtil.randomString(); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); final String name = ValueUtil.randomString(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String v0 = context.safeAction( name, () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), name ); assertNull( transaction.getPrevious() ); assertEquals( transaction.getContext(), context ); assertEquals( transaction.getId(), nextNodeId ); assertFalse( transaction.isMutation() ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); //Not tracking so no state updated assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); return expectedValue; }, Flags.READ_ONLY, new Object[]{ param1, param2, param3 } ); assertFalse( context.isTransactionActive() ); assertEquals( v0, expectedValue ); //ObservableValue still not updated assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); assertEquals( observableValue.getObservers().size(), 0 ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertNull( e.getThrowable() ); assertTrue( e.returnsResult() ); assertEquals( e.getResult(), v0 ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void action_safeFunction_throws_Exception() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final AccessControlException secException = new AccessControlException( "" ); final String name = ValueUtil.randomString(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); assertThrows( AccessControlException.class, () -> context.safeAction( name, () -> { throw secException; }, Flags.READ_ONLY, new Object[]{ param1, param2, param3 } ) ); assertFalse( context.isTransactionActive() ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertEquals( e.getThrowable(), secException ); assertTrue( e.returnsResult() ); assertNull( e.getResult() ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void action_safeFunction_minimalParameters() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final int nextNodeId = context.currentNextTransactionId(); final String expectedValue = ValueUtil.randomString(); final String v0 = context.safeAction( () -> { observeADependency(); assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), "Action@" + nextNodeId ); assertTrue( transaction.isMutation() ); return expectedValue; } ); assertFalse( context.isTransactionActive() ); assertEquals( v0, expectedValue ); } @Test public void action_safeFunction_NameButNoMutationVariant() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); context.safeAction( name, () -> { observeADependency(); assertTrue( context.getTransaction().isMutation() ); assertEquals( context.getTransaction().getName(), name ); return ValueUtil.randomString(); } ); } @Test public void track_safeFunction() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final String expectedValue = ValueUtil.randomString(); final AtomicInteger callCount = new AtomicInteger(); final Observer tracker = context.tracker( callCount::incrementAndGet ); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); final String v0 = context.safeObserve( tracker, () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), tracker.getName() ); assertEquals( transaction.isMutation(), tracker.isMutation() ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); // Tracking so state updated final ArrayList<ObservableValue<?>> observableValues = transaction.getObservableValues(); assertNotNull( observableValues ); assertEquals( observableValues.size(), 1 ); assertEquals( observableValue.getObservers().size(), 0 ); assertEquals( observableValue.getLastTrackerTransactionId(), nextNodeId ); return expectedValue; } ); assertFalse( context.isTransactionActive() ); assertEquals( v0, expectedValue ); assertEquals( observableValue.getLastTrackerTransactionId(), 0 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); // Reaction not called as the function sets up initial tracking assertEquals( callCount.get(), 0 ); context.action( observableValue::reportChanged ); assertEquals( callCount.get(), 1 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); } @Test public void track_safeFunction_passingNonTracker() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.observer( new CountAndObserveProcedure() ); assertInvariantFailure( () -> context.safeObserve( observer, callCount::incrementAndGet ), "Arez-0018: Attempted to invoke safeObserve(..) on observer named '" + observer.getName() + "' but observer is not configured to use an application executor." ); assertEquals( callCount.get(), 0 ); } @Test public void safeAction_safeProcedure_minimalParameters() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final int nextNodeId = context.getNextNodeId(); context.safeAction( () -> { observeADependency(); assertTrue( context.isTransactionActive() ); assertTrue( context.getTransaction().isMutation() ); assertEquals( context.getTransaction().getName(), "Action@" + nextNodeId ); } ); assertFalse( context.isTransactionActive() ); } @Test public void safeAction_safeProcedure_NameButNoMutationVariant() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); context.safeAction( name, () -> { observeADependency(); assertTrue( context.getTransaction().isMutation() ); assertEquals( context.getTransaction().getName(), name ); } ); } @Test public void action_safeProcedure_throws_Exception() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final AccessControlException secException = new AccessControlException( "" ); final String name = ValueUtil.randomString(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final SafeProcedure procedure = () -> { throw secException; }; assertThrows( AccessControlException.class, () -> context.safeAction( name, procedure, 0, new Object[]{ param1, param2, param3 } ) ); assertFalse( context.isTransactionActive() ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertTrue( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertTrue( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertEquals( e.getThrowable(), secException ); assertFalse( e.returnsResult() ); assertNull( e.getResult() ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void track_safeProcedure() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final AtomicInteger callCount = new AtomicInteger(); final Observer tracker = context.tracker( callCount::incrementAndGet ); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); context.safeObserve( tracker, () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), tracker.getName() ); assertEquals( transaction.isMutation(), tracker.isMutation() ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); // Tracking so state updated final ArrayList<ObservableValue<?>> observableValues = transaction.getObservableValues(); assertNotNull( observableValues ); assertEquals( observableValues.size(), 1 ); assertEquals( observableValue.getObservers().size(), 0 ); assertEquals( observableValue.getLastTrackerTransactionId(), nextNodeId ); } ); assertFalse( context.isTransactionActive() ); assertEquals( observableValue.getLastTrackerTransactionId(), 0 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); // Reaction not called as the function sets up initial tracking assertEquals( callCount.get(), 0 ); context.action( observableValue::reportChanged ); assertEquals( callCount.get(), 1 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); } @Test public void track_safeProcedure_passingNonTracker() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.observer( new CountAndObserveProcedure() ); final SafeProcedure procedure = callCount::incrementAndGet; assertInvariantFailure( () -> context.safeObserve( observer, procedure ), "Arez-0020: Attempted to invoke safeObserve(..) on observer named '" + observer.getName() + "' but observer is not configured to use an application executor." ); assertEquals( callCount.get(), 0 ); } @Test public void action_procedure_NameButNoMutationVariant() throws Throwable { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); context.action( name, () -> { observeADependency(); assertTrue( context.getTransaction().isMutation() ); assertEquals( context.getTransaction().getName(), name ); } ); } @Test public void action_procedure_minimalParameters() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final int nextNodeId = context.currentNextTransactionId(); context.action( () -> { observeADependency(); assertTrue( context.isTransactionActive() ); assertTrue( context.getTransaction().isMutation() ); assertEquals( context.getTransaction().getName(), "Action@" + nextNodeId ); } ); assertFalse( context.isTransactionActive() ); } @Test public void track_procedure_passingNonTracker() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.observer( new CountAndObserveProcedure() ); final Procedure procedure = callCount::incrementAndGet; assertInvariantFailure( () -> context.observe( observer, procedure ), "Arez-0019: Attempted to invoke observe(..) on observer named '" + observer.getName() + "' but observer is not configured to use an application executor." ); assertEquals( callCount.get(), 0 ); } @Test public void track_procedure() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); final AtomicInteger callCount = new AtomicInteger(); final Observer tracker = context.tracker( callCount::incrementAndGet ); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); context.observe( tracker, () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), tracker.getName() ); assertEquals( transaction.isMutation(), tracker.isMutation() ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); // Tracking so state updated final ArrayList<ObservableValue<?>> observableValues = transaction.getObservableValues(); assertNotNull( observableValues ); assertEquals( observableValues.size(), 1 ); assertEquals( observableValue.getObservers().size(), 0 ); assertEquals( observableValue.getLastTrackerTransactionId(), nextNodeId ); } ); assertFalse( context.isTransactionActive() ); assertEquals( observableValue.getLastTrackerTransactionId(), 0 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); // Reaction not called as the function sets up initial tracking assertEquals( callCount.get(), 0 ); context.action( observableValue::reportChanged ); assertEquals( callCount.get(), 1 ); assertEquals( observableValue.getObservers().size(), 1 ); assertEquals( tracker.getDependencies().size(), 1 ); } @Test public void nonTrackingSafeProcedureObservingSingleObservable() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); final String name = ValueUtil.randomString(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.safeAction( name, () -> { assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), name ); assertNull( transaction.getPrevious() ); assertEquals( transaction.getContext(), context ); assertEquals( transaction.getId(), nextNodeId ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); //Not tracking so no state updated assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); }, Flags.READ_ONLY, new Object[]{ param1, param2, param3 } ); assertFalse( context.isTransactionActive() ); //ObservableValue still not updated assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); assertEquals( observableValue.getObservers().size(), 0 ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertNull( e.getThrowable() ); assertFalse( e.returnsResult() ); assertNull( e.getResult() ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void action_procedure() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final ObservableValue<?> observableValue = context.observable(); assertEquals( observableValue.getObservers().size(), 0 ); final int nextNodeId = context.currentNextTransactionId(); final String name = ValueUtil.randomString(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final ObservableValue<Object> observableValue1 = Arez.context().observable(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.action( name, () -> { observableValue1.reportObserved(); assertTrue( context.isTransactionActive() ); final Transaction transaction = context.getTransaction(); assertEquals( transaction.getName(), name ); assertNull( transaction.getPrevious() ); assertEquals( transaction.getContext(), context ); assertEquals( transaction.getId(), nextNodeId ); assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); observableValue.reportObserved(); //Not tracking so no state updated assertEquals( observableValue.getObservers().size(), 0 ); assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); }, Flags.READ_ONLY, new Object[]{ param1, param2, param3 } ); assertFalse( context.isTransactionActive() ); //ObservableValue still not updated assertNotEquals( nextNodeId, observableValue.getLastTrackerTransactionId() ); assertEquals( observableValue.getObservers().size(), 0 ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertNull( e.getThrowable() ); assertFalse( e.returnsResult() ); assertNull( e.getResult() ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void action_procedure_throwsException() { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertInvariantFailure( context::getTransaction, "Arez-0117: Attempting to get current transaction but no transaction is active." ); final String name = ValueUtil.randomString(); final IOException ioException = new IOException(); final String param1 = ""; final Object param2 = null; final int param3 = 3; final ObservableValue observableValue = Arez.context().observable(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final Procedure procedure = () -> { observableValue.reportObserved(); throw ioException; }; assertThrows( IOException.class, () -> context.action( name, procedure, Flags.READ_ONLY, new Object[]{ param1, param2, param3 } ) ); assertFalse( context.isTransactionActive() ); handler.assertEventCount( 4 ); handler.assertNextEvent( ActionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); handler.assertNextEvent( TransactionStartEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertFalse( e.isMutation() ); assertNull( e.getTracker() ); } ); handler.assertNextEvent( ActionCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertEquals( e.getThrowable(), ioException ); assertFalse( e.returnsResult() ); assertNull( e.getResult() ); assertFalse( e.isTracked() ); final Object[] parameters = e.getParameters(); assertEquals( parameters.length, 3 ); assertEquals( parameters[ 0 ], param1 ); assertEquals( parameters[ 1 ], param2 ); assertEquals( parameters[ 2 ], param3 ); } ); } @Test public void nestedProceduresAccessingSameObservable() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertThrows( context::getTransaction ); final int nextNodeId = context.currentNextTransactionId(); final String name = ValueUtil.randomString(); final String name2 = ValueUtil.randomString(); context.action( name, () -> { observeADependency(); assertTrue( context.isTransactionActive() ); final Transaction transaction1 = context.getTransaction(); assertEquals( transaction1.getName(), name ); assertNull( transaction1.getPrevious() ); assertEquals( transaction1.getContext(), context ); assertEquals( transaction1.getId(), nextNodeId ); assertTrue( transaction1.isRootTransaction() ); assertEquals( transaction1.getRootTransaction(), transaction1 ); context.action( name2, () -> { observeADependency(); assertTrue( context.isTransactionActive() ); final Transaction transaction2 = context.getTransaction(); assertEquals( transaction2.getName(), name2 ); assertEquals( transaction2.getPrevious(), transaction1 ); assertEquals( transaction2.getContext(), context ); assertEquals( transaction2.getId(), nextNodeId + 1 ); assertFalse( transaction2.isRootTransaction() ); assertEquals( transaction2.getRootTransaction(), transaction1 ); }, Flags.REQUIRE_NEW_TRANSACTION ); final Transaction transaction1b = context.getTransaction(); assertEquals( transaction1b.getName(), name ); assertNull( transaction1b.getPrevious() ); assertEquals( transaction1b.getContext(), context ); assertEquals( transaction1b.getId(), nextNodeId ); assertTrue( transaction1b.isRootTransaction() ); assertEquals( transaction1b.getRootTransaction(), transaction1b ); } ); assertFalse( context.isTransactionActive() ); } @Test public void nextNodeId() { final ArezContext context = Arez.context(); assertEquals( context.currentNextTransactionId(), 1 ); assertEquals( context.nextTransactionId(), 1 ); assertEquals( context.currentNextTransactionId(), 2 ); } @Test public void observer_with_onDepsUpdated() { final ArezContext context = Arez.context(); final ObservableValue<Object> observable = context.observable(); final AtomicInteger observedCallCount = new AtomicInteger(); final AtomicInteger onDepsChangeCallCount = new AtomicInteger(); final String name = ValueUtil.randomString(); context.observer( name, () -> { observedCallCount.incrementAndGet(); observable.reportObserved(); assertEquals( context.getTransaction().getName(), name ); }, onDepsChangeCallCount::incrementAndGet ); assertEquals( onDepsChangeCallCount.get(), 0 ); context.safeAction( observable::reportChanged ); assertEquals( onDepsChangeCallCount.get(), 1 ); } @Test public void observer_withComponent_and_onDepsUpdated() { final ArezContext context = Arez.context(); final ObservableValue<Object> observable = context.observable(); final AtomicInteger observeCallCount = new AtomicInteger(); final AtomicInteger onDepsChangeCallCount = new AtomicInteger(); final Component component = context.component( ValueUtil.randomString(), 22 ); final String name = ValueUtil.randomString(); final Observer observer = context.observer( component, name, () -> { observeCallCount.incrementAndGet(); observable.reportObserved(); assertEquals( context.getTransaction().getName(), name ); }, onDepsChangeCallCount::incrementAndGet ); assertEquals( onDepsChangeCallCount.get(), 0 ); final ComponentInfo componentInfo = observer.asInfo().getComponent(); assertNotNull( componentInfo ); assertEquals( componentInfo.getName(), component.getName() ); context.safeAction( observable::reportChanged ); assertEquals( onDepsChangeCallCount.get(), 1 ); } @Test public void observerErrorHandler() { final ArezContext context = Arez.context(); // Clear out handler added as part of test infrastructure context.getObserverErrorHandlerSupport().getObserverErrorHandlers().clear(); final ObserverError observerError = ObserverError.REACTION_ERROR; final Throwable throwable = new Throwable(); final Procedure action = new NoopProcedure(); final Observer observer = context.observer( ValueUtil.randomString(), action, Flags.READ_WRITE ); final AtomicInteger callCount = new AtomicInteger(); final ObserverErrorHandler handler = ( o, e, t ) -> { callCount.incrementAndGet(); assertEquals( o, observer ); assertEquals( e, observerError ); assertEquals( t, throwable ); }; context.addObserverErrorHandler( handler ); assertEquals( context.getObserverErrorHandlerSupport().getObserverErrorHandlers().size(), 1 ); assertTrue( context.getObserverErrorHandlerSupport().getObserverErrorHandlers().contains( handler ) ); assertEquals( callCount.get(), 0 ); context.reportObserverError( observer, observerError, throwable ); assertEquals( callCount.get(), 1 ); context.removeObserverErrorHandler( handler ); assertEquals( context.getObserverErrorHandlerSupport().getObserverErrorHandlers().size(), 0 ); context.reportObserverError( observer, observerError, throwable ); assertEquals( callCount.get(), 1 ); } @Test public void reportObserverError_when_spyEventHandler_present() { final ArezContext context = Arez.context(); // Clear out handler added as part of test infrastructure context.getObserverErrorHandlerSupport().getObserverErrorHandlers().clear(); final ObserverError observerError = ObserverError.REACTION_ERROR; final Throwable throwable = new Throwable(); final Procedure action = new NoopProcedure(); final Observer observer = context.observer( action ); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.reportObserverError( observer, observerError, throwable ); handler.assertEventCount( 1 ); handler.assertNextEvent( ObserverErrorEvent.class, event -> { assertEquals( event.getObserver().getName(), observer.getName() ); assertEquals( event.getError(), observerError ); assertEquals( event.getThrowable(), throwable ); } ); } @Test public void addObserverErrorHandler_whenDisabled() { ArezTestUtil.disableObserverErrorHandlers(); final ObserverErrorHandler handler = ( o, e, t ) -> { }; assertInvariantFailure( () -> Arez.context().addObserverErrorHandler( handler ), "Arez-0182: ArezContext.addObserverErrorHandler() invoked when Arez.areObserverErrorHandlersEnabled() returns false." ); } @Test public void removeObserverErrorHandler_whenDisabled() { ArezTestUtil.disableObserverErrorHandlers(); final ArezContext context = Arez.context(); final ObserverErrorHandler handler = ( o, e, t ) -> { }; assertInvariantFailure( () -> context.removeObserverErrorHandler( handler ), "Arez-0181: ArezContext.removeObserverErrorHandler() invoked when Arez.areObserverErrorHandlersEnabled() returns false." ); } @Test public void getSpy_whenSpiesDisabled() { ArezTestUtil.disableSpies(); final ArezContext context = Arez.context(); assertInvariantFailure( context::getSpy, "Arez-0021: Attempting to get Spy but spies are not enabled." ); } @Test public void scheduleReaction() { final ArezContext context = Arez.context(); final Observer observer = context.observer( new CountAndObserveProcedure() ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 0L ); context.scheduleReaction( observer ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 1L ); assertTrue( context.getTaskQueue().getOrderedTasks().anyMatch( o -> o == observer.getTask() ) ); } @Test public void scheduleReaction_shouldAbortInReadOnlyTransaction() { final ArezContext context = Arez.context(); final Observer observer = context.observer( new CountAndObserveProcedure() ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 0L ); assertInvariantFailure( () -> { final Procedure executable = () -> context.scheduleReaction( observer ); context.action( executable, Flags.READ_ONLY ); }, "Arez-0013: Observer named '" + observer.getName() + "' attempted to be scheduled " + "during read-only transaction." ); } @Test public void scheduleReaction_shouldAbortInReadWriteOwnedTransaction() { final ArezContext context = Arez.context(); final Observer derivation = context.computable( () -> "" ).getObserver(); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 0L ); setCurrentTransaction( derivation ); assertInvariantFailure( () -> context.scheduleReaction( derivation ), "Arez-0014: Observer named '" + derivation.getName() + "' attempted to schedule itself " + "during read-only tracking transaction. Observers that are supporting ComputableValue " + "instances must not schedule self." ); } @Test public void scheduleReaction_generates_spyEvent() { final ArezContext context = Arez.context(); final Observer observer = context.observer( new CountAndObserveProcedure() ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 0L ); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.scheduleReaction( observer ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 1L ); handler.assertEventCount( 1 ); handler.assertNextEvent( ObserveScheduleEvent.class, event -> assertEquals( event.getObserver().getName(), observer.getName() ) ); } @Test public void computableValue() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final SafeFunction<String> function = () -> { observeADependency(); return ""; }; final Procedure onActivate = ValueUtil::randomString; final Procedure onDeactivate = ValueUtil::randomString; final Procedure onStale = ValueUtil::randomString; final ComputableValue<String> computableValue = context.computable( null, name, function, onActivate, onDeactivate, onStale, Flags.PRIORITY_HIGH ); assertEquals( computableValue.getName(), name ); assertEquals( computableValue.getContext(), context ); assertFalse( computableValue.getObserver().isKeepAlive() ); assertTrue( computableValue.getObserver().areArezDependenciesRequired() ); assertFalse( computableValue.getObserver().isEnvironmentRequired() ); assertEquals( computableValue.getObservableValue().getName(), name ); assertEquals( computableValue.getOnActivate(), onActivate ); assertEquals( computableValue.getOnDeactivate(), onDeactivate ); assertEquals( computableValue.getOnStale(), onStale ); assertEquals( computableValue.getObserver().getName(), name ); assertEquals( computableValue.getObserver().getTask().getPriority(), Priority.HIGH ); assertFalse( computableValue.getObserver().canObserveLowerPriorityDependencies() ); } @Test public void computable_with_NO_REPORT_RESULT() { final ArezContext context = Arez.context(); final ObservableValue<Object> observable = Arez.context().observable(); final SafeFunction<String> function = () -> { observable.reportObserved(); return ""; }; final ComputableValue<String> computableValue = context.computable( function, Flags.NO_REPORT_RESULT ); assertTrue( computableValue.getObserver().noReportResults() ); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.safeAction( computableValue::get ); handler.assertEventCount( 9 ); handler.assertNextEvent( ActionStartEvent.class ); handler.assertNextEvent( TransactionStartEvent.class ); handler.assertNextEvent( ComputeStartEvent.class ); handler.assertNextEvent( TransactionStartEvent.class ); handler.assertNextEvent( ObservableValueChangeEvent.class ); handler.assertNextEvent( TransactionCompleteEvent.class ); handler.assertNextEvent( ComputeCompleteEvent.class, e -> assertNull( e.getResult() ) ); handler.assertNextEvent( TransactionCompleteEvent.class ); handler.assertNextEvent( ActionCompleteEvent.class ); } @Test public void computableValue_withComponent() { final ArezContext context = Arez.context(); final Component component = context.component( ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString() ); final String name = ValueUtil.randomString(); final ComputableValue<String> computableValue = context.computable( component, name, () -> "", null, null, null ); assertEquals( computableValue.getName(), name ); assertEquals( computableValue.getComponent(), component ); } @Test public void computableValue_Environment_Required() { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); final SafeFunction<String> function = () -> { observeADependency(); return ""; }; final ComputableValue<String> computableValue = context.computable( function, Flags.ENVIRONMENT_REQUIRED ); assertTrue( computableValue.getObserver().isEnvironmentRequired() ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.safeAction( computableValue::get ); assertEquals( inEnvironmentCallCount.get(), 1 ); } @Test public void computableValue_Environment_NotRequired() { final ArezContext context = Arez.context(); // Scheduler paused otherwise reactions will run in environment and upset our environment call count context.pauseScheduler(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); final SafeFunction<String> function = () -> { observeADependency(); return ""; }; final ComputableValue<String> computableValue = context.computable( function, Flags.ENVIRONMENT_NOT_REQUIRED ); assertFalse( computableValue.getObserver().isEnvironmentRequired() ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.safeAction( computableValue::get ); assertEquals( inEnvironmentCallCount.get(), 0 ); } @Test public void computableValue_canObserveLowerPriorityDependencies() { final ComputableValue<String> computableValue = Arez.context().computable( () -> "", Flags.OBSERVE_LOWER_PRIORITY_DEPENDENCIES ); assertTrue( computableValue.getObserver().canObserveLowerPriorityDependencies() ); } @Test public void computableValue_mayNotAccessArezState() { final ArezContext context = Arez.context(); assertFalse( context.computable( () -> "", Flags.AREZ_OR_NO_DEPENDENCIES ) .getObserver() .areArezDependenciesRequired() ); assertFalse( context.computable( () -> "", Flags.AREZ_OR_EXTERNAL_DEPENDENCIES ) .getObserver() .areArezDependenciesRequired() ); } @Test public void computableValue_withKeepAliveAndRunImmediately() { final ArezContext context = Arez.context(); final AtomicInteger calls = new AtomicInteger(); final SafeFunction<String> action = () -> { observeADependency(); calls.incrementAndGet(); return ""; }; final ComputableValue<String> computableValue = context.computable( action, Flags.KEEPALIVE | Flags.RUN_NOW ); assertTrue( computableValue.getObserver().isKeepAlive() ); assertEquals( calls.get(), 1 ); } @Test public void computableValue_withKeepAliveAndNoRunImmediately() { final ArezContext context = Arez.context(); final AtomicInteger calls = new AtomicInteger(); final SafeFunction<String> action = () -> { observeADependency(); calls.incrementAndGet(); return ""; }; final ComputableValue<String> computableValue = context.computable( action, Flags.KEEPALIVE | Flags.RUN_LATER ); assertTrue( computableValue.getObserver().isKeepAlive() ); assertEquals( calls.get(), 0 ); context.triggerScheduler(); assertEquals( calls.get(), 1 ); } @Test public void computableValue_pass_no_hooks() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final SafeFunction<String> function = () -> { observeADependency(); return ""; }; final ComputableValue<String> computableValue = context.computable( name, function ); assertEquals( computableValue.getName(), name ); assertEquals( computableValue.getContext(), context ); assertEquals( computableValue.getObserver().getName(), name ); assertEquals( computableValue.getObservableValue().getName(), name ); assertNull( computableValue.getOnActivate() ); assertNull( computableValue.getOnDeactivate() ); assertNull( computableValue.getOnStale() ); assertEquals( computableValue.getObserver().getTask().getPriority(), Priority.NORMAL ); } @Test public void computableValue_minimumParameters() { final ArezContext context = Arez.context(); context.setNextNodeId( 22 ); final SafeFunction<String> function = () -> { observeADependency(); return ""; }; final ComputableValue<String> computableValue = context.computable( function ); final String name = "ComputableValue@22"; assertEquals( computableValue.getName(), name ); assertEquals( computableValue.getContext(), context ); assertEquals( computableValue.getObserver().getName(), name ); assertEquals( computableValue.getObservableValue().getName(), name ); assertNull( computableValue.getOnActivate() ); assertNull( computableValue.getOnDeactivate() ); assertNull( computableValue.getOnStale() ); assertEquals( computableValue.getObserver().getTask().getPriority(), Priority.NORMAL ); assertFalse( computableValue.getObserver().canObserveLowerPriorityDependencies() ); } @Test public void computableValue_generates_spyEvent() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final ComputableValue<String> computableValue = context.computable( ValueUtil.randomString(), () -> { observeADependency(); return ""; } ); handler.assertEventCount( 1 ); handler.assertNextEvent( ComputableValueCreateEvent.class, event -> assertEquals( event.getComputableValue().getName(), computableValue.getName() ) ); } @Test public void observer_noObservers() { setIgnoreObserverErrors( true ); Arez.context().setNextNodeId( 22 ); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = Arez.context().observer( callCount::incrementAndGet ); assertEquals( observer.getName(), "Observer@22" ); assertFalse( observer.isMutation() ); assertEquals( observer.getState(), Flags.STATE_UP_TO_DATE ); assertEquals( observer.getTask().getPriority(), Priority.NORMAL ); assertEquals( callCount.get(), 1 ); assertEquals( getObserverErrors().size(), 1 ); assertEquals( getObserverErrors().get( 0 ), "Observer: Observer@22 Error: REACTION_ERROR java.lang.IllegalStateException: Arez-0172: Observer named 'Observer@22' that does not use an external executor completed observe function but is not observing any properties. As a result the observer will never be rescheduled." ); } @Test public void autorun_noObservers_manualReportStaleAllowed() { setIgnoreObserverErrors( true ); final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); context.observer( callCount::incrementAndGet, Flags.AREZ_OR_EXTERNAL_DEPENDENCIES ); assertEquals( callCount.get(), 1 ); // No observer errors even though the executable accesses no arez dependencies assertEquals( getObserverErrors().size(), 0 ); } @Test public void observer_minimumParameters() { final ArezContext context = Arez.context(); context.setNextNodeId( 22 ); final AtomicInteger callCount = new AtomicInteger(); final Procedure observe = () -> { observeADependency(); callCount.incrementAndGet(); }; final Observer observer = context.observer( observe ); assertNull( observer.getComponent() ); assertEquals( observer.getName(), "Observer@22" ); assertFalse( observer.isMutation() ); assertEquals( observer.getState(), Flags.STATE_UP_TO_DATE ); assertEquals( observer.getTask().getPriority(), Priority.NORMAL ); assertFalse( observer.isComputableValue() ); assertFalse( observer.canObserveLowerPriorityDependencies() ); assertTrue( observer.isKeepAlive() ); assertFalse( observer.nestedActionsAllowed() ); assertNull( observer.getOnDepsChange() ); assertFalse( observer.isApplicationExecutor() ); assertEquals( observer.getObserve(), observe ); assertEquals( callCount.get(), 1 ); } @Test public void autorun_withComponent() { final ArezContext context = Arez.context(); final Component component = context.component( ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString() ); final String name = ValueUtil.randomString(); final Observer observer = context.observer( component, name, AbstractArezTest::observeADependency ); assertEquals( observer.getName(), name ); assertEquals( observer.getComponent(), component ); } @Test public void autorun_minimumParametersForMutation() { final ArezContext context = Arez.context(); context.setNextNodeId( 22 ); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.observer( () -> { observeADependency(); callCount.incrementAndGet(); }, Flags.READ_WRITE ); assertEquals( observer.getName(), "Observer@22" ); assertTrue( observer.isMutation() ); assertEquals( observer.getState(), Flags.STATE_UP_TO_DATE ); assertEquals( observer.getTask().getPriority(), Priority.NORMAL ); assertFalse( observer.nestedActionsAllowed() ); assertFalse( observer.supportsManualSchedule() ); assertEquals( callCount.get(), 1 ); } @SuppressWarnings( "ConstantConditions" ) @Test public void autorun_runImmediately() { final ArezContext context = Arez.context(); final ObservableValue<Object> observableValue = Arez.context().observable(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String name = ValueUtil.randomString(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.observer( name, () -> { observableValue.reportObserved(); callCount.incrementAndGet(); }, Flags.READ_WRITE ); assertEquals( observer.getName(), name ); assertTrue( observer.isMutation() ); assertEquals( observer.getState(), Flags.STATE_UP_TO_DATE ); assertEquals( observer.getTask().getPriority(), Priority.NORMAL ); assertFalse( observer.isApplicationExecutor() ); assertEquals( callCount.get(), 1 ); handler.assertEventCount( 8 ); handler.assertNextEvent( ObserverCreateEvent.class, e -> assertEquals( e.getObserver().getName(), name ) ); handler.assertNextEvent( ObserveScheduleEvent.class, e -> assertEquals( e.getObserver().getName(), name ) ); assertObserverReaction( handler, name ); } @SuppressWarnings( "ConstantConditions" ) @Test public void autorun_runImmediately_will_obeyNormalSchedulingPriorities() { final ArezContext context = Arez.context(); final ObservableValue<Object> observableValue = Arez.context().observable(); final Observer observer1 = context.observer( "O1", observableValue::reportObserved ); final Observer observer2 = context.observer( "O2", observableValue::reportObserved, Flags.PRIORITY_HIGH ); final Disposable schedulerLock = context.pauseScheduler(); // Trigger change that should schedule above observers context.safeAction( observableValue::reportChanged ); final Observer observer3 = context.observer( "O3", observableValue::reportObserved ); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); schedulerLock.dispose(); handler.assertEventCount( 6 * 3 ); assertObserverReaction( handler, observer2.getName() ); assertObserverReaction( handler, observer1.getName() ); assertObserverReaction( handler, observer3.getName() ); } private void assertObserverReaction( @Nonnull final TestSpyEventHandler handler, @Nonnull final String name ) { handler.assertNextEvent( ObserveStartEvent.class, e -> assertEquals( e.getObserver().getName(), name ) ); handler.assertNextEvent( ActionStartEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( TransactionStartEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( TransactionCompleteEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( ActionCompleteEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( ObserveCompleteEvent.class, e -> assertEquals( e.getObserver().getName(), name ) ); } @Test public void autorun_highPriority() { final ArezContext context = Arez.context(); final Observer observer = context.observer( AbstractArezTest::observeADependency, Flags.PRIORITY_HIGH ); assertEquals( observer.getTask().getPriority(), Priority.HIGH ); } @Test public void autorun_canObserveLowerPriorityDependencies() { final ArezContext context = Arez.context(); final Observer observer = context.observer( AbstractArezTest::observeADependency, Flags.OBSERVE_LOWER_PRIORITY_DEPENDENCIES ); assertTrue( observer.canObserveLowerPriorityDependencies() ); } @Test public void autorun_nestedActionsAllowed() { final ArezContext context = Arez.context(); final Observer observer = context.observer( AbstractArezTest::observeADependency, Flags.NESTED_ACTIONS_ALLOWED ); assertTrue( observer.nestedActionsAllowed() ); } @Test public void observer_areArezDependenciesRequired() { final ArezContext context = Arez.context(); final Procedure observe = AbstractArezTest::observeADependency; assertFalse( context.observer( observe, Flags.AREZ_OR_EXTERNAL_DEPENDENCIES ).areArezDependenciesRequired() ); assertFalse( context.observer( observe, Flags.AREZ_OR_NO_DEPENDENCIES ).areArezDependenciesRequired() ); assertTrue( context.observer( observe, Flags.AREZ_DEPENDENCIES ).areArezDependenciesRequired() ); } @Test public void autorun_supportsManualSchedule() { final ArezContext context = Arez.context(); final Observer observer = context.observer( AbstractArezTest::observeADependency, ValueUtil::randomString ); assertTrue( observer.supportsManualSchedule() ); } @Test public void autorun_notRunImmediately() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String name = ValueUtil.randomString(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.observer( name, () -> { observeADependency(); callCount.incrementAndGet(); }, Flags.RUN_LATER ); assertEquals( observer.getName(), name ); assertFalse( observer.isMutation() ); assertEquals( observer.getState(), Flags.STATE_INACTIVE ); assertEquals( observer.getTask().getPriority(), Priority.NORMAL ); assertFalse( observer.isApplicationExecutor() ); assertEquals( callCount.get(), 0 ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 1L ); handler.assertEventCount( 2 ); handler.assertNextEvent( ObserverCreateEvent.class, e -> assertEquals( e.getObserver().getName(), observer.getName() ) ); handler.assertNextEvent( ObserveScheduleEvent.class, e -> assertEquals( e.getObserver().getName(), observer.getName() ) ); } @Test public void tracker() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String name = ValueUtil.randomString(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.tracker( null, name, callCount::incrementAndGet, Flags.PRIORITY_HIGH | Flags.OBSERVE_LOWER_PRIORITY_DEPENDENCIES | Flags.NESTED_ACTIONS_ALLOWED | Flags.AREZ_OR_NO_DEPENDENCIES ); assertEquals( observer.getName(), name ); assertFalse( observer.isMutation() ); assertEquals( observer.getState(), Flags.STATE_INACTIVE ); assertNull( observer.getComponent() ); assertEquals( observer.getTask().getPriority(), Priority.HIGH ); assertTrue( observer.canObserveLowerPriorityDependencies() ); assertTrue( observer.isApplicationExecutor() ); assertTrue( observer.nestedActionsAllowed() ); assertFalse( observer.areArezDependenciesRequired() ); assertFalse( observer.supportsManualSchedule() ); assertEquals( callCount.get(), 0 ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 0L ); handler.assertEventCount( 1 ); handler.assertNextEvent( ObserverCreateEvent.class, e -> assertEquals( e.getObserver().getName(), observer.getName() ) ); } @Test public void tracker_withComponent() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final AtomicInteger callCount = new AtomicInteger(); final Component component = context.component( ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString() ); final Observer observer = context.tracker( component, name, callCount::incrementAndGet ); assertEquals( observer.getName(), name ); assertEquals( observer.getComponent(), component ); assertEquals( observer.getTask().getPriority(), Priority.NORMAL ); assertFalse( observer.canObserveLowerPriorityDependencies() ); assertTrue( observer.isApplicationExecutor() ); } @Test public void tracker_minimalParameters() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final int nextNodeId = context.getNextNodeId(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.tracker( callCount::incrementAndGet ); assertEquals( observer.getName(), "Observer@" + nextNodeId ); assertFalse( observer.isMutation() ); assertEquals( observer.getState(), Flags.STATE_INACTIVE ); assertFalse( observer.canObserveLowerPriorityDependencies() ); assertTrue( observer.isApplicationExecutor() ); assertFalse( observer.nestedActionsAllowed() ); assertTrue( observer.areArezDependenciesRequired() ); assertFalse( observer.supportsManualSchedule() ); assertEquals( callCount.get(), 0 ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 0L ); handler.assertEventCount( 1 ); handler.assertNextEvent( ObserverCreateEvent.class, e -> assertEquals( e.getObserver().getName(), observer.getName() ) ); } @Test public void observer_generates_spyEvent() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); context.pauseScheduler(); final Observer observer = context.observer( new CountingProcedure() ); handler.assertEventCount( 2 ); handler.assertNextEvent( ObserverCreateEvent.class, e -> assertEquals( e.getObserver().getName(), observer.getName() ) ); handler.assertNextEvent( ObserveScheduleEvent.class, e -> assertEquals( e.getObserver().getName(), observer.getName() ) ); } @Test public void createObservable_no_parameters() { final ArezContext context = Arez.context(); context.setNextNodeId( 22 ); final ObservableValue<?> observableValue = context.observable(); assertNotNull( observableValue.getName() ); assertEquals( observableValue.getName(), "ObservableValue@22" ); assertNull( observableValue.getAccessor() ); assertNull( observableValue.getMutator() ); } @Test public void createObservable() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final ObservableValue<?> observableValue = context.observable( name ); assertEquals( observableValue.getName(), name ); assertNull( observableValue.getAccessor() ); assertNull( observableValue.getMutator() ); } @Test public void createObservable_withIntrospectors() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final PropertyAccessor<String> accessor = () -> ""; final PropertyMutator<String> mutator = v -> { }; final ObservableValue<?> observableValue = context.observable( name, accessor, mutator ); assertEquals( observableValue.getName(), name ); assertEquals( observableValue.getAccessor(), accessor ); assertEquals( observableValue.getMutator(), mutator ); } @Test public void createObservable_withComponent() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final Component component = context.component( ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString() ); final ObservableValue<String> observableValue = context.observable( component, name ); assertEquals( observableValue.getName(), name ); assertEquals( observableValue.getComponent(), component ); } @Test public void createObservable_spyEventHandlerPresent() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String name = ValueUtil.randomString(); final ObservableValue<?> observableValue = context.observable( name ); assertEquals( observableValue.getName(), name ); handler.assertEventCount( 1 ); handler.assertNextEvent( ObservableValueCreateEvent.class, e -> assertEquals( e.getObservableValue().getName(), observableValue.getName() ) ); } @Test public void createObservable_name_Null() { ArezTestUtil.disableNames(); final ArezContext context = Arez.context(); final ObservableValue<?> observableValue = context.observable( null ); assertNotNull( observableValue ); } @Test public void pauseScheduler() { final ArezContext context = Arez.context(); assertFalse( context.isSchedulerPaused() ); assertEquals( context.getSchedulerLockCount(), 0 ); final Disposable lock1 = context.pauseScheduler(); assertEquals( context.getSchedulerLockCount(), 1 ); assertTrue( context.isSchedulerPaused() ); final AtomicInteger callCount = new AtomicInteger(); // This would normally be scheduled and run now but scheduler should be paused context.observer( () -> { observeADependency(); callCount.incrementAndGet(); }, Flags.RUN_LATER ); context.triggerScheduler(); assertEquals( callCount.get(), 0 ); final Disposable lock2 = context.pauseScheduler(); assertEquals( context.getSchedulerLockCount(), 2 ); assertTrue( context.isSchedulerPaused() ); lock2.dispose(); assertEquals( context.getSchedulerLockCount(), 1 ); // Already disposed so this is a noop lock2.dispose(); assertEquals( context.getSchedulerLockCount(), 1 ); assertTrue( context.isSchedulerPaused() ); assertEquals( callCount.get(), 0 ); lock1.dispose(); assertEquals( context.getSchedulerLockCount(), 0 ); assertEquals( callCount.get(), 1 ); assertFalse( context.isSchedulerPaused() ); } @Test public void releaseSchedulerLock_whenNoLock() { assertInvariantFailure( () -> Arez.context().releaseSchedulerLock(), "Arez-0016: releaseSchedulerLock() reduced schedulerLockCount below 0." ); } @Test public void createComponent() { final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); final String name = ValueUtil.randomString(); assertFalse( context.isComponentPresent( type, id ) ); final Component component = context.component( type, id, name ); assertTrue( context.isComponentPresent( type, id ) ); assertEquals( component.getType(), type ); assertEquals( component.getId(), id ); assertEquals( component.getName(), name ); assertNull( component.getPreDispose() ); assertNull( component.getPostDispose() ); } @Test public void createComponent_includeDisposeHooks() { final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); final String name = ValueUtil.randomString(); assertFalse( context.isComponentPresent( type, id ) ); final SafeProcedure preDispose = () -> { }; final SafeProcedure postDispose = () -> { }; final Component component = context.component( type, id, name, preDispose, postDispose ); assertTrue( context.isComponentPresent( type, id ) ); assertEquals( component.getType(), type ); assertEquals( component.getId(), id ); assertEquals( component.getName(), name ); assertEquals( component.getPreDispose(), preDispose ); assertEquals( component.getPostDispose(), postDispose ); } @Test public void createComponent_synthesizeNameIfRequired() { final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); assertFalse( context.isComponentPresent( type, id ) ); final Component component = context.component( type, id ); assertTrue( context.isComponentPresent( type, id ) ); assertEquals( component.getType(), type ); assertEquals( component.getId(), id ); assertEquals( component.getName(), type + "@" + id ); } @Test public void createComponent_spyEventHandlerPresent() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final Component component = context.component( ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString() ); handler.assertEventCount( 1 ); handler.assertNextEvent( ComponentCreateStartEvent.class, event -> assertEquals( event.getComponentInfo().getName(), component.getName() ) ); } @Test public void createComponent_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); final String name = ValueUtil.randomString(); assertInvariantFailure( () -> context.component( type, id, name ), "Arez-0008: ArezContext.component() invoked when Arez.areNativeComponentsEnabled() returns false." ); } @Test public void createComponent_duplicateComponent() { final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); context.component( type, id, ValueUtil.randomString() ); assertTrue( context.isComponentPresent( type, id ) ); assertInvariantFailure( () -> context.component( type, id, ValueUtil.randomString() ), "Arez-0009: ArezContext.component() invoked for type '" + type + "' and id '" + id + "' but a component already exists for specified type+id." ); } @Test public void isComponentPresent_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); assertInvariantFailure( () -> context.isComponentPresent( type, id ), "Arez-0135: ArezContext.isComponentPresent() invoked when Arez.areNativeComponentsEnabled() returns false." ); } @Test public void deregisterComponent_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final Component component = new Component( context, ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString(), null, null ); assertInvariantFailure( () -> context.deregisterComponent( component ), "Arez-0006: ArezContext.deregisterComponent() invoked when Arez.areNativeComponentsEnabled() returns false." ); } @Test public void deregisterComponent_componentMisalignment() { final ArezContext context = Arez.context(); final Component component = new Component( context, ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString(), null, null ); final Component component2 = context.component( component.getType(), component.getId(), ValueUtil.randomString() ); assertInvariantFailure( () -> context.deregisterComponent( component ), "Arez-0007: ArezContext.deregisterComponent() invoked for '" + component + "' but was unable to remove specified component from registry. " + "Actual component removed: " + component2 ); } @Test public void deregisterComponent_removesTypeIfLastOfType() { final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final Component component = context.component( type, ValueUtil.randomString(), ValueUtil.randomString() ); final Component component2 = context.component( type, ValueUtil.randomString(), ValueUtil.randomString() ); assertEquals( context.findAllComponentTypes().size(), 1 ); assertTrue( context.findAllComponentTypes().contains( type ) ); context.deregisterComponent( component ); assertEquals( context.findAllComponentTypes().size(), 1 ); assertTrue( context.findAllComponentTypes().contains( type ) ); context.deregisterComponent( component2 ); assertEquals( context.findAllComponentTypes().size(), 0 ); } @Test public void component_finders() { final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id1 = ValueUtil.randomString(); final String id2 = ValueUtil.randomString(); assertEquals( context.findAllComponentTypes().size(), 0 ); assertEquals( context.findAllComponentsByType( type ).size(), 0 ); final Component component = context.component( type, id1, ValueUtil.randomString() ); assertEquals( context.findAllComponentTypes().size(), 1 ); assertTrue( context.findAllComponentTypes().contains( type ) ); assertEquals( context.findAllComponentsByType( ValueUtil.randomString() ).size(), 0 ); assertEquals( context.findAllComponentsByType( type ).size(), 1 ); assertTrue( context.findAllComponentsByType( type ).contains( component ) ); final Component component2 = context.component( type, id2, ValueUtil.randomString() ); assertEquals( context.findAllComponentTypes().size(), 1 ); assertTrue( context.findAllComponentTypes().contains( type ) ); assertEquals( context.findAllComponentsByType( ValueUtil.randomString() ).size(), 0 ); assertEquals( context.findAllComponentsByType( type ).size(), 2 ); assertTrue( context.findAllComponentsByType( type ).contains( component ) ); assertTrue( context.findAllComponentsByType( type ).contains( component2 ) ); assertEquals( context.findComponent( type, id1 ), component ); assertEquals( context.findComponent( type, id2 ), component2 ); assertNull( context.findComponent( type, ValueUtil.randomString() ) ); assertNull( context.findComponent( ValueUtil.randomString(), id2 ) ); } @Test public void findComponent_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); assertInvariantFailure( () -> context.findComponent( type, id ), "Arez-0010: ArezContext.findComponent() invoked when Arez.areNativeComponentsEnabled() returns false." ); } @Test public void findAllComponentsByType_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); assertInvariantFailure( () -> context.findAllComponentsByType( type ), "Arez-0011: ArezContext.findAllComponentsByType() invoked when Arez.areNativeComponentsEnabled() returns false." ); } @Test public void findAllComponentTypes_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); assertInvariantFailure( context::findAllComponentTypes, "Arez-0012: ArezContext.findAllComponentTypes() invoked when Arez.areNativeComponentsEnabled() returns false." ); } @Test public void registryAccessWhenDisabled() { ArezTestUtil.disableRegistries(); final ArezContext context = Arez.context(); final ObservableValue<Object> observableValue = context.observable(); final ComputableValue<String> computableValue = context.computable( () -> "" ); final Observer observer = context.observer( AbstractArezTest::observeADependency ); final Task task = context.task( ValueUtil::randomString ); assertInvariantFailure( () -> context.registerObservableValue( observableValue ), "Arez-0022: ArezContext.registerObservableValue invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( () -> context.deregisterObservableValue( observableValue ), "Arez-0024: ArezContext.deregisterObservableValue invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( context::getTopLevelObservables, "Arez-0026: ArezContext.getTopLevelObservables() invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( () -> context.registerObserver( observer ), "Arez-0027: ArezContext.registerObserver invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( () -> context.deregisterObserver( observer ), "Arez-0029: ArezContext.deregisterObserver invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( context::getTopLevelObservers, "Arez-0031: ArezContext.getTopLevelObservers() invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( () -> context.registerComputableValue( computableValue ), "Arez-0032: ArezContext.registerComputableValue invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( () -> context.deregisterComputableValue( computableValue ), "Arez-0034: ArezContext.deregisterComputableValue invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( context::getTopLevelComputableValues, "Arez-0036: ArezContext.getTopLevelComputableValues() invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( () -> context.registerTask( task ), "Arez-0214: ArezContext.registerTask invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( () -> context.deregisterTask( task ), "Arez-0226: ArezContext.deregisterTask invoked when Arez.areRegistriesEnabled() returns false." ); assertInvariantFailure( context::getTopLevelTasks, "Arez-0228: ArezContext.getTopLevelTasks() invoked when Arez.areRegistriesEnabled() returns false." ); } @Test public void observableRegistry() { final ArezContext context = Arez.context(); final ObservableValue<Object> observableValue = context.observable(); assertEquals( context.getTopLevelObservables().size(), 1 ); assertEquals( context.getTopLevelObservables().get( observableValue.getName() ), observableValue ); assertInvariantFailure( () -> context.registerObservableValue( observableValue ), "Arez-0023: ArezContext.registerObservableValue invoked with observableValue named '" + observableValue.getName() + "' but an existing observableValue with that name is " + "already registered." ); assertEquals( context.getTopLevelObservables().size(), 1 ); context.getTopLevelObservables().clear(); assertEquals( context.getTopLevelObservables().size(), 0 ); assertInvariantFailure( () -> context.deregisterObservableValue( observableValue ), "Arez-0025: ArezContext.deregisterObservableValue invoked with observableValue named '" + observableValue.getName() + "' but no observableValue with that name is registered." ); } @Test public void observerRegistry() { final ArezContext context = Arez.context(); final Observer observer = context.observer( AbstractArezTest::observeADependency ); assertEquals( context.getTopLevelObservers().size(), 1 ); assertEquals( context.getTopLevelObservers().get( observer.getName() ), observer ); assertInvariantFailure( () -> context.registerObserver( observer ), "Arez-0028: ArezContext.registerObserver invoked with observer named '" + observer.getName() + "' but an existing observer with that name is " + "already registered." ); assertEquals( context.getTopLevelObservers().size(), 1 ); context.getTopLevelObservers().clear(); assertEquals( context.getTopLevelObservers().size(), 0 ); assertInvariantFailure( () -> context.deregisterObserver( observer ), "Arez-0030: ArezContext.deregisterObserver invoked with observer named '" + observer.getName() + "' but no observer with that name is registered." ); } @Test public void computableValueRegistry() { final ArezContext context = Arez.context(); final ComputableValue computableValue = context.computable( () -> "" ); assertEquals( context.getTopLevelComputableValues().size(), 1 ); assertEquals( context.getTopLevelComputableValues().get( computableValue.getName() ), computableValue ); assertInvariantFailure( () -> context.registerComputableValue( computableValue ), "Arez-0033: ArezContext.registerComputableValue invoked with ComputableValue " + "named '" + computableValue.getName() + "' but an existing ComputableValue with that " + "name is already registered." ); assertEquals( context.getTopLevelComputableValues().size(), 1 ); context.getTopLevelComputableValues().clear(); assertEquals( context.getTopLevelComputableValues().size(), 0 ); assertInvariantFailure( () -> context.deregisterComputableValue( computableValue ), "Arez-0035: ArezContext.deregisterComputableValue invoked with " + "ComputableValue named '" + computableValue.getName() + "' but no ComputableValue " + "with that name is registered." ); } @Test public void taskRegistry() { final ArezContext context = Arez.context(); final Task task = context.task( ValueUtil::randomString ); assertEquals( context.getTopLevelTasks().size(), 1 ); assertEquals( context.getTopLevelTasks().get( task.getName() ), task ); assertInvariantFailure( () -> context.registerTask( task ), "Arez-0225: ArezContext.registerTask invoked with Task named '" + task.getName() + "' but an existing Task with that name is already registered." ); assertEquals( context.getTopLevelTasks().size(), 1 ); context.getTopLevelTasks().clear(); assertEquals( context.getTopLevelTasks().size(), 0 ); assertInvariantFailure( () -> context.deregisterTask( task ), "Arez-0227: ArezContext.deregisterTask invoked with Task named '" + task.getName() + "' but no Task with that name is registered." ); } @Test public void computedValueNotPopulateOtherTopLevelRegistries() { final ArezContext context = Arez.context(); final ComputableValue computableValue = context.computable( () -> "" ); assertEquals( context.getTopLevelComputableValues().size(), 1 ); assertEquals( context.getTopLevelComputableValues().get( computableValue.getName() ), computableValue ); assertEquals( context.getTopLevelTasks().size(), 0 ); assertEquals( context.getTopLevelObservers().size(), 0 ); assertEquals( context.getTopLevelObservables().size(), 0 ); } @Test public void observersNotPopulateOtherTopLevelRegistries() { final ArezContext context = Arez.context(); final Observer observer = context.observer( ValueUtil::randomString, Flags.AREZ_OR_NO_DEPENDENCIES ); assertEquals( context.getTopLevelObservers().size(), 1 ); assertEquals( context.getTopLevelObservers().get( observer.getName() ), observer ); assertEquals( context.getTopLevelTasks().size(), 0 ); assertEquals( context.getTopLevelComputableValues().size(), 0 ); assertEquals( context.getTopLevelObservables().size(), 0 ); } @Test public void scheduleDispose() { final ArezContext context = Arez.context(); final MultiPriorityTaskQueue queue = context.getTaskQueue(); final Observer observer = Arez.context().observer( new CountAndObserveProcedure() ); assertEquals( queue.getOrderedTasks().count(), 0L ); // Pause scheduler so that the task is not invoked immediately final Disposable schedulerLock = context.pauseScheduler(); final String name = observer.getName() + ".dispose"; context.scheduleDispose( name, observer ); assertEquals( queue.getOrderedTasks().count(), 1L ); final CircularBuffer<Task> buffer = queue.getBufferByPriority( 0 ); assertEquals( buffer.size(), 1 ); final Task task = buffer.get( 0 ); assertNotNull( task ); assertEquals( task.getName(), name ); assertFalse( task.isDisposed() ); assertFalse( observer.isDisposed() ); schedulerLock.dispose(); assertTrue( task.isDisposed() ); assertTrue( observer.isDisposed() ); } @Test public void scheduleDispose_withNoNameWhenNamesEnabled() { final ArezContext context = Arez.context(); final MultiPriorityTaskQueue queue = context.getTaskQueue(); final Observer observer = Arez.context().observer( new CountAndObserveProcedure() ); assertEquals( queue.getOrderedTasks().count(), 0L ); // Pause scheduler so that the task stays in the queue context.pauseScheduler(); context.scheduleDispose( null, observer ); assertEquals( queue.getOrderedTasks().count(), 1L ); final CircularBuffer<Task> buffer = queue.getBufferByPriority( 0 ); assertEquals( buffer.size(), 1 ); final Task task = buffer.get( 0 ); assertNotNull( task ); assertEquals( task.getName(), "Dispose@3" ); } @Test public void locator() { final ArezContext context = Arez.context(); final Locator locator = context.locator(); assertNotNull( locator ); assertNull( locator.findById( String.class, "21" ) ); final TypeBasedLocator worker = new TypeBasedLocator(); worker.registerLookup( String.class, String::valueOf ); final Disposable disposable = context.registerLocator( worker ); assertEquals( locator.findById( String.class, "21" ), "21" ); disposable.dispose(); assertNull( locator.findById( String.class, "21" ) ); } @Test public void locator_referencesDisabled() { ArezTestUtil.disableReferences(); ArezTestUtil.resetState(); assertInvariantFailure( () -> Arez.context().locator(), "Arez-0192: ArezContext.locator() invoked but Arez.areReferencesEnabled() returned false." ); } @Test public void registerLocator_referencesDisabled() { ArezTestUtil.disableReferences(); ArezTestUtil.resetState(); assertInvariantFailure( () -> Arez.context().registerLocator( new TypeBasedLocator() ), "Arez-0191: ArezContext.registerLocator invoked but Arez.areReferencesEnabled() returned false." ); } @Test public void runInEnvironment() { final ArezContext context = Arez.context(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); final ObservableValue<Object> observable = context.observable(); final AtomicInteger observerCallCount = new AtomicInteger(); context.observer( () -> { observerCallCount.incrementAndGet(); observable.reportObserved(); } ); assertEquals( inEnvironmentCallCount.get(), 1 ); assertEquals( observerCallCount.get(), 1 ); } @Test public void runInEnvironment_nestedCallIgnored() throws Throwable { final ArezContext context = Arez.context(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); final ObservableValue<Object> observable = context.observable(); final AtomicInteger observer1CallCount = new AtomicInteger(); final AtomicInteger observer2CallCount = new AtomicInteger(); context.runInEnvironment( () -> { context.observer( () -> { observer1CallCount.incrementAndGet(); observable.reportObserved(); } ); context.observer( () -> { observer2CallCount.incrementAndGet(); observable.reportObserved(); } ); return null; } ); assertEquals( inEnvironmentCallCount.get(), 1 ); assertEquals( observer1CallCount.get(), 1 ); assertEquals( observer2CallCount.get(), 1 ); } @Test public void runInEnvironment_directNested() throws Throwable { final ArezContext context = Arez.context(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.runInEnvironment( () -> context.runInEnvironment( () -> context.runInEnvironment( () -> "" ) ) ); assertEquals( inEnvironmentCallCount.get(), 1 ); } @Test public void setEnvironment_whenEnvironmentsDisabled() { ArezTestUtil.disableEnvironments(); final ArezContext context = Arez.context(); assertInvariantFailure( () -> context.setEnvironment( new CountingEnvironment( new AtomicInteger() ) ), "Arez-0124: ArezContext.setEnvironment() invoked but Arez.areEnvironmentsEnabled() returned false." ); } @Test public void safeRunInEnvironment_directNested() { final ArezContext context = Arez.context(); final AtomicInteger inEnvironmentCallCount = new AtomicInteger(); context.setEnvironment( new CountingEnvironment( inEnvironmentCallCount ) ); assertEquals( inEnvironmentCallCount.get(), 0 ); context.safeRunInEnvironment( () -> context.safeRunInEnvironment( () -> context.safeRunInEnvironment( () -> "" ) ) ); assertEquals( inEnvironmentCallCount.get(), 1 ); } @Test public void runInEnvironment_noEnvironment() throws Throwable { final ArezContext context = Arez.context(); context.runInEnvironment( () -> context.runInEnvironment( () -> context.runInEnvironment( () -> "" ) ) ); } @Test public void safeRunInEnvironment_noEnvironment() { final ArezContext context = Arez.context(); context.safeRunInEnvironment( () -> context.safeRunInEnvironment( () -> context.safeRunInEnvironment( () -> "" ) ) ); } @Test public void task() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final String name = ValueUtil.randomString(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final Disposable task = context.task( name, callCount::incrementAndGet, 0 ); assertEquals( ( (Task) task ).getName(), name ); assertEquals( callCount.get(), 1 ); assertFalse( ( (Task) task ).isQueued() ); assertFalse( task.isDisposed() ); handler.assertEventCount( 2 ); handler.assertNextEvent( TaskStartEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( TaskCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertNull( e.getThrowable() ); } ); handler.reset(); // This does nothing but just to make sure task.dispose(); assertEquals( callCount.get(), 1 ); assertFalse( ( (Task) task ).isQueued() ); assertTrue( task.isDisposed() ); handler.assertEventCount( 0 ); } @Test public void task_throwsException() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final String name = ValueUtil.randomString(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final String errorMessage = "Blah Error!"; final SafeProcedure work = () -> { callCount.incrementAndGet(); throw new RuntimeException( errorMessage ); }; final Disposable task = context.task( name, work, 0 ); assertEquals( ( (Task) task ).getName(), name ); assertEquals( callCount.get(), 1 ); assertFalse( ( (Task) task ).isQueued() ); assertFalse( task.isDisposed() ); handler.assertEventCount( 2 ); handler.assertNextEvent( TaskStartEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( TaskCompleteEvent.class, e -> { assertEquals( e.getName(), name ); assertNotNull( e.getThrowable() ); assertEquals( e.getThrowable().getMessage(), errorMessage ); } ); } @Test public void task_minimalParameters() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final Disposable task = context.task( callCount::incrementAndGet ); final String name = "Task@1"; assertEquals( ( (Task) task ).getName(), name ); assertEquals( callCount.get(), 1 ); assertFalse( ( (Task) task ).isQueued() ); assertFalse( task.isDisposed() ); handler.assertEventCount( 2 ); handler.assertNextEvent( TaskStartEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( TaskCompleteEvent.class, e -> assertEquals( e.getName(), name ) ); } @Test public void task_RUN_LATER() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final TestSpyEventHandler handler = new TestSpyEventHandler(); context.getSpy().addSpyEventHandler( handler ); final Disposable task = context.task( null, callCount::incrementAndGet, Flags.RUN_LATER ); final String name = "Task@1"; assertEquals( ( (Task) task ).getName(), name ); assertEquals( callCount.get(), 0 ); assertTrue( ( (Task) task ).isQueued() ); assertFalse( task.isDisposed() ); handler.assertEventCount( 0 ); // Trigger scheduler and allow task to run context.triggerScheduler(); assertEquals( callCount.get(), 1 ); assertFalse( ( (Task) task ).isQueued() ); assertFalse( task.isDisposed() ); handler.assertEventCount( 2 ); handler.assertNextEvent( TaskStartEvent.class, e -> assertEquals( e.getName(), name ) ); handler.assertNextEvent( TaskCompleteEvent.class, e -> assertEquals( e.getName(), name ) ); } @Test public void task_different_PRIORITY() { final ArezContext context = Arez.context(); final ArrayList<String> calls = new ArrayList<>(); context.task( null, () -> calls.add( "1" ), Flags.RUN_LATER | Flags.PRIORITY_LOW ); context.task( null, () -> calls.add( "2" ), Flags.RUN_LATER | Flags.PRIORITY_HIGH ); context.task( null, () -> calls.add( "3" ), Flags.RUN_LATER ); context.task( null, () -> calls.add( "4" ), Flags.RUN_LATER | Flags.PRIORITY_HIGH ); context.task( null, () -> calls.add( "5" ), Flags.RUN_LATER | Flags.PRIORITY_HIGHEST ); context.task( null, () -> calls.add( "6" ), Flags.RUN_LATER | Flags.PRIORITY_LOWEST ); context.task( null, () -> calls.add( "7" ), Flags.RUN_LATER | Flags.PRIORITY_NORMAL ); // Trigger scheduler and allow tasks to run according to priority context.triggerScheduler(); assertEquals( String.join( ",", calls ), "5,2,4,3,7,1,6" ); } @Test public void task_bad_flags() { final ArezContext context = Arez.context(); assertInvariantFailure( () -> context.task( "MyTask", ValueUtil::randomString, Flags.REQUIRE_NEW_TRANSACTION ), "Arez-0224: Task named 'MyTask' passed invalid flags: " + Flags.REQUIRE_NEW_TRANSACTION ); } }
package polytheque.view; import javax.swing.JLabel; import javax.swing.JTabbedPane; @SuppressWarnings("serial") public class HomePage extends JTabbedPane { /** * Une tache d'affichage de l'application. */ private TacheDAffichage tacheDAffichageDeLApplication; public HomePage(TacheDAffichage afficheAppli){ this.tacheDAffichageDeLApplication = afficheAppli; this.addTab("Jeux", this.tacheDAffichageDeLApplication.afficherListeJeux()); this.addTab("Extensions", this.tacheDAffichageDeLApplication.afficherListeExtensions()); this.addTab("Réserver", this.tacheDAffichageDeLApplication.afficherEcranReservation()); this.addTab("Profil", this.tacheDAffichageDeLApplication.afficherMonCompte()); if (this.tacheDAffichageDeLApplication.adherentAdmin()) { this.addTab("Emprunt", new JLabel("Fonctionnalité à venir !")); this.addTab("Adhérents", this.tacheDAffichageDeLApplication.afficherGestionAdherent()); //this.addTab("Reservations", this.tacheDAffichageDeLApplication.afficherListeReservations()); } } }
package com.RoboWars; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import robowars.server.controller.ClientCommand; import robowars.server.controller.LobbyChatEvent; import robowars.server.controller.LobbyGameEvent; import robowars.server.controller.LobbyRobotEvent; import robowars.server.controller.LobbyUserEvent; import robowars.server.controller.ServerLobbyEvent; import robowars.shared.model.CameraPosition; import robowars.shared.model.GameEvent; import android.util.Log; /** * @author Steve Legere * @version 5/11/2010 * * Handles TCP connection to the server. * @see robowars.server.controller */ public class TcpClient extends Thread { private static final int ERROR = 0; private static final int CHAT = 1; private static final int EVENT = 2; private LobbyModel lobbyModel; private GameModel gameModel; private String IPAddress; private int port; private Socket socket; private ObjectInputStream in; private ObjectOutputStream out; private boolean connected; public TcpClient(LobbyModel lobbyModel, GameModel gameModel) { this.lobbyModel = lobbyModel; this.gameModel = gameModel; this.connected = false; } public void run() { if (!handshake()) return; Object response; /* Run forever, handling incoming messages. */ try { while (true) { response = in.readObject(); if(response == null) break; // Log.i("RoboWars", "Read object."); if(response instanceof String) { Log.i("RoboWars", "Read string: " + (String)response); printMessage(EVENT, (String)response); } else if (response instanceof ServerLobbyEvent) { Log.i("RoboWars", "Read lobby event."); handle((ServerLobbyEvent)response); } else if (response instanceof GameEvent) { Log.i("RoboWars", "Read game event."); handle((GameEvent)response); } Thread.yield(); } } catch (IOException e) { printMessage(ERROR, "Lost connection to the server."); } catch (ClassNotFoundException e) { printMessage(ERROR, "Could not deserialize message from server."); } finally { try { sendClientCommand(new ClientCommand(ClientCommand.DISCONNECT)); out.close(); in.close(); socket.close(); printMessage(EVENT, "Socket Disconnected!"); } catch (IOException e) { printMessage(ERROR, "Could not close socket."); } } } public void connect(String IPAddress, int port) { this.IPAddress = IPAddress; this.port = port; printMessage(EVENT, "Connecting..."); try { socket = new Socket(IPAddress, port); out = new ObjectOutputStream(socket.getOutputStream()); in = new ObjectInputStream(socket.getInputStream()); connected = true; printMessage(EVENT, "Connected!"); } catch (UnknownHostException e1) { printMessage(ERROR, "Could not resolve host."); printMessage(ERROR, "Address: " + IPAddress + ":" + port); } catch (IOException e2) { printMessage(ERROR, "Could not get I/O for the connection."); printMessage(ERROR, "Address: " + IPAddress + ":" + port); } if (connected) this.start(); } /** * Sends a string to the server in UTF format. This should only be used * for the connection handshake (protocol string and username), as all * further communication should used RoboWars protocol * (Serialized ServerLobbyEvents and ClientCommands). * @param message The string to be sent to the server. */ public void sendUTFString(String message) { if (connected) { synchronized(out) { try { out.writeUTF(message); out.reset(); } catch (IOException e) { // TODO: Properly log / notify user of error e.printStackTrace(); } } } } public void sendClientCommand(ClientCommand cmd) { if (connected) { synchronized(out) { try { out.writeObject(cmd); out.reset(); } catch (IOException e) { // TODO: Properly log / notify user of error e.printStackTrace(); } } } } /** * Provide initial information to the server. */ private boolean handshake() { String version = lobbyModel.getVersion(); User user = lobbyModel.getMyUser(); if (user != null) { sendUTFString(version); sendUTFString(user.getName()); return true; } else { printMessage(ERROR, "No username set."); return false; } } private void handle(GameEvent event) { switch (event.getEventType()) { case GameEvent.GAME_START: gameModel.startGame(); break; //TODO: Start up the OpenGL engine and start the game. case GameEvent.GAME_OVER: gameModel.endGame(); break; //TODO: End the game, show the winner. case GameEvent.ROBOT_MOVED: break; //TODO: Which robot moved? Update appropriate position. default: // Unhandled GameEvent. } } /** * @param message * Determines what to do, given an input message. */ private void handle(ServerLobbyEvent event) { // User events if(event instanceof LobbyUserEvent) { LobbyUserEvent userEvent = (LobbyUserEvent)event; switch(userEvent.getEventType()) { case ServerLobbyEvent.EVENT_PLAYER_JOINED: // Player joined lobbyModel.userJoined(userEvent.getUser().getUsername()); printMessage(EVENT, event.toString()); return; case ServerLobbyEvent.EVENT_PLAYER_LEFT: // Player left lobbyModel.userLeft(userEvent.getUser().getUsername()); printMessage(EVENT, event.toString()); return; case ServerLobbyEvent.EVENT_PLAYER_STATE_CHANGE: // Player state changed lobbyModel.printMessage(EVENT, event.toString()); return; default: return; } } // Robot events if(event instanceof LobbyRobotEvent) { LobbyRobotEvent robotEvent = (LobbyRobotEvent)event; lobbyModel.printMessage(EVENT, event.toString()); } // Game events if(event instanceof LobbyGameEvent) { LobbyGameEvent gameEvent = (LobbyGameEvent)event; if(gameEvent.getCameraPosition() != null) { CameraPosition cam = gameEvent.getCameraPosition(); lobbyModel.printMessage(EVENT, "Got camera information: <X:" + cam.getxPos() + "|Y:" + cam.getyPos() + "|X:" + cam.getzPos() +"|HorOrien:" + cam.getHorOrientation() + "|VerOrien:" + cam.getVerOrientation() + "|FOV:" + cam.getFov()+ ">"); } lobbyModel.printMessage(EVENT, event.toString()); } // Chat events if(event instanceof LobbyChatEvent) { LobbyChatEvent chatEvent = (LobbyChatEvent)event; lobbyModel.printMessage(EVENT, event.toString()); } } private void printMessage(int type, String message) { lobbyModel.printMessage(type, message); } }
/* * Largest prime factor * * Problem 3 * * The prime factors of 13195 are 5, 7, 13 and 29. * What is the largest prime factor of the number 600851475143 ? * * Expected result: 6857 */ public class Euler3{ public static void main(String[] args){ long factor = 2; long number = 600851475143L; for(long i = 2; i<=number; i++){ while(number%i == 0){ factor = i; number /= i; } } System.out.println(factor); } }
package com.nebby.grandmadown; import java.util.ArrayList; import java.util.List; import javax.mail.internet.ContentType; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import com.amazon.speech.slu.Intent; import com.amazon.speech.speechlet.Session; import com.amazon.speech.speechlet.SpeechletResponse; import com.amazon.speech.ui.Reprompt; import com.amazon.speech.ui.SsmlOutputSpeech; public class IntentHandler { private Medication pill; public SpeechletResponse addPill(Intent intent, Session session) { SpeechOutput output = new SpeechOutput(); output.text("Okay, I will add it to your list of medication. What type of medication is it"); pill = new Medication(); SpeechOutput reprompt = new SpeechOutput(); reprompt.text("What type of medication is it"); return newAskResponse(output.toString(), reprompt.toString()); } public SpeechletResponse namePill(Intent intent, Session session) { SpeechOutput output = new SpeechOutput(); output.text("Okay, I've update your medication list. What time would you like to take it"); if (pill == null) { pill = new Medication(); } pill.setName(intent.getSlot("Name").getValue()); SpeechOutput reprompt = new SpeechOutput(); reprompt.text("What time would you like to take it"); return newAskResponse(output.toString(), reprompt.toString()); } public SpeechletResponse timePill(Intent intent, Session session) { if(pill == null) return newTellResponse("<speak></speak>"); SpeechOutput output = new SpeechOutput(); pill.setTime(intent.getSlot("Time").getValue()); try { String url = "http://ec2-54-172-226-18.compute-1.amazonaws.com:8888/addPill"; HttpClient client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("name", pill.getName())); params.add(new BasicNameValuePair("time", pill.getTime())); request.setEntity(new StringEntity(pill.getName() + ":" + pill.getTime(), "UTF-8")); HttpResponse res = client.execute(request); String response = EntityUtils.toString(res.getEntity(), "UTF-8"); output.text("Ok, adding " + pill.getName() + " at " + pill.getTime() + " to your pill list. I will do my best to remind you!"); } catch(Exception e) { output.text("I'm sorry, I couldn't get your information to the cloud."); } pill = null; return newTellResponse(output.toString()); } public SpeechletResponse takePills(Intent intent, Session session) { SpeechOutput output = new SpeechOutput(); try { String url = "http://ec2-54-172-226-18.compute-1.amazonaws.com:8888/takePill"; HttpClient client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); HttpResponse res = client.execute(request); String response = EntityUtils.toString(res.getEntity(), "UTF-8"); output.text("Glad to hear, remember that you'll need to take it again at " + response); } catch(Exception e) { output.text("I'm sorry, I couldn't get your information to the cloud. Please repeat."); } try { String url = "http://ec2-54-172-226-18.compute-1.amazonaws.com:8888/clear"; HttpClient client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); HttpResponse res = client.execute(request); //output.text("Cleared"); } catch(Exception e) { //output.text("I'm sorry, I couldn't get your information to the cloud."); } return newTellResponse(output.toString()); } public SpeechletResponse pillsTaken(Intent intent, Session session) { SpeechOutput output = new SpeechOutput(); try { String url = "http://ec2-54-172-226-18.compute-1.amazonaws.com:8888/pillsTaken"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse res = client.execute(request); String response = EntityUtils.toString(res.getEntity(), "UTF-8"); if(response.length() > 0) { output.text("You still need to take " + response); } else output.text("You have taken all your pills so far."); } catch(Exception e) { output.text("I'm sorry, I couldn't get your information to the cloud."); } return newTellResponse(output.toString()); } public SpeechletResponse clear(Intent intent, Session session) { SpeechOutput output = new SpeechOutput(); try { String url = "http://ec2-54-172-226-18.compute-1.amazonaws.com:8888/clear"; HttpClient client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); HttpResponse res = client.execute(request); output.text("Cleared"); } catch(Exception e) { output.text("I'm sorry, I couldn't get your information to the cloud."); } return newTellResponse(output.toString()); } public SpeechletResponse checkup (Intent intent, Session session) { SpeechOutput output = new SpeechOutput(); try { String url = "http://ec2-54-172-226-18.compute-1.amazonaws.com:8888/checkup"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); HttpResponse res = client.execute(request); output.text("Checking up on " + intent.getSlot("Person")); } catch(Exception e) { output.text("I'm sorry, we couldn't connect but I am sure everything is fine"); } return newTellResponse(output.toString()); } public SpeechletResponse newTellResponse(String output) { SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech(); outputSpeech.setSsml(output); return SpeechletResponse.newTellResponse(outputSpeech); } public SpeechletResponse newAskResponse(String output, String reprompt) { SsmlOutputSpeech outputSpeech, repromptOutputSpeech; outputSpeech = new SsmlOutputSpeech(); outputSpeech.setSsml(output); repromptOutputSpeech = new SsmlOutputSpeech(); repromptOutputSpeech.setSsml(reprompt); Reprompt r = new Reprompt(); r.setOutputSpeech(repromptOutputSpeech); return SpeechletResponse.newAskResponse(outputSpeech, r); } }
package mlga.ui; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontFormatException; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.IOException; import java.io.InputStream; import java.net.Inet4Address; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.JPanel; import javax.swing.JWindow; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import mlga.Boot; import mlga.io.FileUtil; import mlga.io.Settings; public class Overlay extends JPanel { private static final long serialVersionUID = -470849574354121503L; private boolean frameMove = false; private CopyOnWriteArrayList<Peer> peers = new CopyOnWriteArrayList<Peer>(); private Font roboto; /** idx & fh are updated by listener and rendering events. <br>They track hovered index and font height. */ private int idx = -1, fh = 0; private final JWindow frame; public Overlay() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, FontFormatException, IOException { InputStream is = FileUtil.localResource("Roboto-Medium.ttf"); roboto = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(15f); is.close(); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); this.setOpaque(false); frame = new JWindow(); frame.setBackground(new Color(0, 0, 0, 0)); frame.setFocusableWindowState(false); frame.add(this); frame.setAlwaysOnTop(true); frame.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (!SwingUtilities.isRightMouseButton(e)) { if (e.isShiftDown()) { if (idx < 0 || idx >= peers.size() || peers.isEmpty() || e.getX() < 0 || e.getY() < 0) return; Peer p = peers.get(idx); if (!p.saved()) { p.rate(true); } else if (p.blocked()) { p.rate(false); } else { p.unsave(); } } else if (e.getClickCount() >= 2) { frameMove = !frameMove; Settings.set("frame_x", frame.getLocationOnScreen().x); Settings.set("frame_y", frame.getLocationOnScreen().y); } } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { idx = -1; } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }); frame.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { if (frameMove) frame.setLocation(e.getXOnScreen() - (getPreferredSize().width / 2), e.getYOnScreen() - 6); } @Override public void mouseMoved(MouseEvent e) { idx = Math.min(peers.size() - 1, (int) Math.floor(e.getY() / (fh))); } }); frame.pack(); frame.setLocation((int) Settings.getDouble("frame_x", 5), (int) Settings.getDouble("frame_y", 400)); frame.setVisible(true); Timer cleanTime = new Timer(); cleanTime.scheduleAtFixedRate(new TimerTask() { @Override public void run() { peers.stream().filter(p -> p.age() >= 5000).forEach(p -> { Boot.active.remove(p.getID().hashCode()); peers.remove(p); }); } }, 0, 2500); Thread t = new Thread("UIPainter") { public void run() { try { while (true) { frame.toFront(); //Fix for window sometime hiding behind others if (!frameMove) { Thread.sleep(400); } else { Thread.sleep(10); } Overlay.this.repaint(); } } catch (Exception e) { e.printStackTrace(); } } }; t.setDaemon(true); t.start(); } private void addPeer(Inet4Address addr, long rtt) { peers.add(new Peer(addr, rtt)); } /** Sets a peer's ping, or creates their object. */ public void setPing(Inet4Address id, long ping) { Peer p = this.getPeer(id); if (p != null) { p.setPing(ping); } else { this.addPeer(id, ping); } } /** Finds a Peer connection by its ID. */ private Peer getPeer(Inet4Address id) { return peers.stream().filter(p -> p.getID().equals(id)).findFirst().orElse(null); } /** Dispose this Overlay's Window. */ public void close() { this.frame.dispose(); } @Override public Dimension getPreferredSize() { return new Dimension(110, 100); } @Override protected void paintComponent(Graphics gr) { super.paintComponent(gr); Graphics2D g = (Graphics2D) gr.create(); g.setColor(getBackground()); g.setFont(roboto); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, getWidth(), getHeight()); if (!frameMove) { g.setColor(new Color(0f, 0f, 0f, .5f)); } else { g.setColor(new Color(0f, 0f, 0f, 1f)); } fh = g.getFontMetrics().getAscent();//line height. Can use getHeight() for more padding between. g.fillRect(0, 0, getPreferredSize().width, fh * Math.max(1, peers.size()) + 2); if (!peers.isEmpty()) { short i = 0; for (Peer p : peers) { if (idx == i) { g.setColor(new Color(0f, 0f, 0f)); g.fillRect(1, fh * i + 1, getPreferredSize().width, fh + 1);//Pronounce hovered Peer. } long rtt = p.getPing(); if (rtt <= 140) { g.setColor(Color.GREEN); } else if (rtt > 140 && rtt <= 190) { g.setColor(Color.YELLOW); } else { g.setColor(Color.RED); } String render = "Ping: " + rtt; if (p.saved()) render = (p.blocked() ? "BLOCKED: " : "LOVED: ") + rtt; g.drawString(render, 1, fh * (i + 1)); ++i; } } else { g.setColor(Color.RED); g.drawString("No Players", 1, fh); } g.dispose(); } }
//This code is developed as part of the Java CoG Kit project //This message may not be removed or altered. package org.globus.cog.karajan.workflow.nodes.restartLog; import java.io.File; import java.io.IOException; import org.globus.cog.karajan.workflow.KarajanRuntimeException; import org.globus.cog.karajan.workflow.nodes.functions.VariableArgumentsOperator; public class LogVargOperator extends VariableArgumentsOperator { private final FlushableLockedFileWriter writer; private boolean closed; public LogVargOperator(FlushableLockedFileWriter writer) { this.writer = writer; } protected Object initialValue() { return null; } protected synchronized Object update(Object oldvalue, Object item) { if (closed) { return null; } try { String str = (String) item; writer.write(str); if (!str.endsWith("\n")) { writer.write('\n'); } writer.flush(); } catch (IOException e) { throw new KarajanRuntimeException("Exception caught while writing to log file", e); } return null; } public boolean isCommutative() { return true; } public synchronized void close() throws IOException { if (!closed) { writer.close(); closed = true; } } public File getFile() { return writer.getFile(); } }
package ca.corefacility.bioinformatics.irida.config.services; import java.time.Duration; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.concurrent.DelegatingSecurityContextScheduledExecutorService; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFileSnapshot; import ca.corefacility.bioinformatics.irida.model.user.Role; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.AnalysisSubmissionRepository; import ca.corefacility.bioinformatics.irida.service.AnalysisExecutionScheduledTask; import ca.corefacility.bioinformatics.irida.service.CleanupAnalysisSubmissionCondition; import ca.corefacility.bioinformatics.irida.service.ProjectEventEmailScheduledTask; import ca.corefacility.bioinformatics.irida.service.analysis.execution.AnalysisExecutionService; import ca.corefacility.bioinformatics.irida.service.impl.AnalysisExecutionScheduledTaskImpl; import ca.corefacility.bioinformatics.irida.service.impl.analysis.submission.CleanupAnalysisSubmissionConditionAge; import ca.corefacility.bioinformatics.irida.service.user.UserService; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; /** * Config for only activating scheduled tasks in certain profiles. * * */ @Profile({ "prod" }) @Configuration @EnableScheduling public class IridaScheduledTasksConfig implements SchedulingConfigurer { private static final Logger logger = LoggerFactory.getLogger(IridaScheduledTasksConfig.class); @Autowired private AnalysisSubmissionRepository analysisSubmissionRepository; @Autowired private AnalysisExecutionService analysisExecutionService; @Autowired private UserService userService; @Autowired private ProjectEventEmailScheduledTask eventEmailTask; /** * Rate in milliseconds of the analysis execution tasks. */ private static final long ANALYSIS_EXECUTION_TASK_RATE = 15000; // 15 seconds /** * Rate in milliseconds of the cleanup task. */ private static final long CLEANUP_TASK_RATE = 60*60*1000; // 1 hour /** * Defines the time to clean up in number of days a submission must exist before it is cleaned up. */ @Value("${irida.analysis.cleanup.days}") private Double daysToCleanup; /** * Cycle through any newly created submissions and download any required * {@link SequenceFileSnapshot}s. */ @Scheduled(initialDelay = 1000, fixedRate = ANALYSIS_EXECUTION_TASK_RATE) public void downloadFiles() { analysisExecutionScheduledTask().downloadFiles(); } /** * Cycle through any submissions and prepare them for execution. */ @Scheduled(initialDelay = 2000, fixedRate = ANALYSIS_EXECUTION_TASK_RATE) public void prepareAnalyses() { analysisExecutionScheduledTask().prepareAnalyses(); } /** * Cycle through any outstanding submissions and execute them. */ @Scheduled(initialDelay = 3000, fixedRate = ANALYSIS_EXECUTION_TASK_RATE) public void executeAnalyses() { analysisExecutionScheduledTask().executeAnalyses(); } /** * Cycle through any submissions running in Galaxy and monitor the status. */ @Scheduled(initialDelay = 4000, fixedRate = ANALYSIS_EXECUTION_TASK_RATE) public void monitorRunningAnalyses() { analysisExecutionScheduledTask().monitorRunningAnalyses(); } /** * Cycle through any completed submissions and transfer the results. */ @Scheduled(initialDelay = 5000, fixedRate = ANALYSIS_EXECUTION_TASK_RATE) public void transferAnalysesResults() { analysisExecutionScheduledTask().transferAnalysesResults(); } /** * Cycle through any completed or error submissions and clean up results from the execution manager. */ @Scheduled(initialDelay = 10000, fixedRate = CLEANUP_TASK_RATE) public void cleanupAnalysisSubmissions() { analysisExecutionScheduledTask().cleanupAnalysisSubmissions(); } /** * Check for any new events for users who are subscribed to projects and * email them */ @Scheduled(cron = "${irida.scheduled.subscription.cron}") public void emailProjectEvents() { eventEmailTask.emailUserTasks(); } /** * Creates a new bean with a AnalysisExecutionScheduledTask for performing * the analysis tasks. * * @return A AnalysisExecutionScheduledTask bean. */ @DependsOn("analysisSubmissionCleanupService") @Bean public AnalysisExecutionScheduledTask analysisExecutionScheduledTask() { return new AnalysisExecutionScheduledTaskImpl(analysisSubmissionRepository, analysisExecutionService, cleanupAnalysisSubmissionCondition()); } /** * Builds a condition object defining the conditions under which an analysis * submission should be cleaned up. * * @return A {@link CleanupAnalysisSubmissionConditionAge}. */ @Bean public CleanupAnalysisSubmissionCondition cleanupAnalysisSubmissionCondition() { if (daysToCleanup == null) { logger.info("No irida.analysis.cleanup.days set, defaulting to no cleanup"); return CleanupAnalysisSubmissionCondition.NEVER_CLEANUP; } else { logger.info("Setting daysToCleanup to be irida.analysis.cleanup.time=" + daysToCleanup); // Converts fraction of day to a millisecond value long millisToCleanup = Math.round(daysToCleanup * TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); return new CleanupAnalysisSubmissionConditionAge(Duration.ofMillis(millisToCleanup)); } } /** * {@inheritDoc} */ @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } /** * Builds a new Executor for scheduled tasks. * @return A new Executor for scheduled tasks. */ private Executor taskExecutor() { ScheduledExecutorService delegateExecutor = Executors .newSingleThreadScheduledExecutor(); SecurityContext schedulerContext = createSchedulerSecurityContext(); return new DelegatingSecurityContextScheduledExecutorService( delegateExecutor, schedulerContext); } /** * Creates a security context object for the scheduled tasks. * * @return A {@link SecurityContext} for the scheduled tasks. */ private SecurityContext createSchedulerSecurityContext() { SecurityContext context = SecurityContextHolder.createEmptyContext(); Authentication anonymousToken = new AnonymousAuthenticationToken( "nobody", "nobody", ImmutableList.of(Role.ROLE_ANONYMOUS)); Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication(); SecurityContextHolder.getContext().setAuthentication(anonymousToken); User admin = userService.getUserByUsername("admin"); SecurityContextHolder.getContext().setAuthentication(oldAuthentication); Authentication adminAuthentication = new PreAuthenticatedAuthenticationToken( admin, null, Lists.newArrayList(Role.ROLE_ADMIN)); context.setAuthentication(adminAuthentication); return context; } }
package com.github.theholywaffle.teamspeak3.api.exception; public class TS3ConnectionFailedException extends TS3Exception { private static final long serialVersionUID = 6849777544299282019L; public TS3ConnectionFailedException(Throwable c) { super("Could not connect to the TeamSpeak3 server", c); } }
package cz.zajezdy.data.bengine.engine.internal.scriptengine.impl; import java.util.Map; import javax.script.Compilable; import javax.script.CompiledScript; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptException; import cz.zajezdy.data.bengine.engine.internal.scriptengine.JavaScriptEngine; public class JavaScriptEngineImpl implements JavaScriptEngine { ScriptEngine engine = null; public JavaScriptEngineImpl(ScriptEngine engine) { this.engine = engine; } @Override public Object eval(String scriptToEval) throws ScriptException { return engine.eval(scriptToEval); } @Override public void put(String varName, Map<String, Object> varValue) { engine.put(varName, varValue); } @Override public CompiledScript getCompiledScript(String script) throws ScriptException { final Compilable compilable = (Compilable) engine; CompiledScript compiledScript = compilable.compile(script); compiledScript.eval(); return compiledScript; } @Override public Object invokeFunction(String functionName, Object... arguments) throws NoSuchMethodException, ScriptException { final Invocable invocable = (Invocable) engine; return invocable.invokeFunction(functionName, arguments); } }
package io.github.mzmine.modules.visualization.neutralloss; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JMenuBar; import com.google.common.collect.Range; import io.github.mzmine.datamodel.RawDataFile; import io.github.mzmine.main.MZmineCore; import io.github.mzmine.modules.visualization.spectra.simplespectra.SpectraVisualizerModule; import io.github.mzmine.parameters.ParameterSet; import io.github.mzmine.parameters.parametertypes.WindowSettingsParameter; import io.github.mzmine.taskcontrol.TaskPriority; import io.github.mzmine.util.javafx.WindowsMenu; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.ToolBar; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * Neutral loss visualizer using JFreeChart library */ public class NeutralLossVisualizerWindow extends Stage implements ActionListener { private static final long serialVersionUID = 1L; private ToolBar toolBar; private NeutralLossPlot neutralLossPlot; private BorderPane borderPane; private Scene scene; private NeutralLossDataSet dataset; private RawDataFile dataFile; public NeutralLossVisualizerWindow(RawDataFile dataFile, ParameterSet parameters) { // super(dataFile.getName()); // setDefaultCloseOperation(DISPOSE_ON_CLOSE); // setBackground(Color.white); this.dataFile = dataFile; // Retrieve parameter's values Range<Double> rtRange = parameters.getParameter(NeutralLossParameters.retentionTimeRange).getValue(); Range<Double> mzRange = parameters.getParameter(NeutralLossParameters.mzRange).getValue(); int numOfFragments = parameters.getParameter(NeutralLossParameters.numOfFragments).getValue(); Object xAxisType = parameters.getParameter(NeutralLossParameters.xAxisType).getValue(); // Set window components dataset = new NeutralLossDataSet(dataFile, xAxisType, rtRange, mzRange, numOfFragments, this); borderPane = new BorderPane(); scene = new Scene(borderPane); // Use main CSS scene.getStylesheets().addAll(MZmineCore.getDesktop().getMainWindow().getScene().getStylesheets()); setScene(scene); setMinWidth(400.0); setMinHeight(300.0); // neutralLossPlot = new NeutralLossPlot(this, dataset, xAxisType); // add(neutralLossPlot, BorderLayout.CENTER); // toolBar = new NeutralLossToolBar(this); // add(toolBar, BorderLayout.EAST); toolBar = new ToolBar(); toolBar.setOrientation(Orientation.VERTICAL); WindowsMenu.addWindowsMenu(scene); MZmineCore.getTaskController().addTask(dataset, TaskPriority.HIGH); updateTitle(); // get the window settings parameter ParameterSet paramSet = MZmineCore.getConfiguration().getModuleParameters(NeutralLossVisualizerModule.class); WindowSettingsParameter settings = paramSet.getParameter(NeutralLossParameters.windowSettings); // update the window and listen for changes settings.applySettingsToWindow(this); } void updateTitle() { StringBuffer title = new StringBuffer(); title.append("["); title.append(dataFile.getName()); title.append("]: neutral loss"); setTitle(title.toString()); NeutralLossDataPoint pos = getCursorPosition(); if (pos != null) { title.append(", "); title.append(pos.getName()); } neutralLossPlot.setTitle(title.toString()); } /** * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("HIGHLIGHT")) { JDialog dialog = new NeutralLossSetHighlightDialog(neutralLossPlot, command); dialog.setVisible(true); } if (command.equals("SHOW_SPECTRUM")) { NeutralLossDataPoint pos = getCursorPosition(); if (pos != null) { SpectraVisualizerModule.showNewSpectrumWindow(dataFile, pos.getScanNumber()); } } } public NeutralLossDataPoint getCursorPosition() { double xValue = neutralLossPlot.getXYPlot().getDomainCrosshairValue(); double yValue = neutralLossPlot.getXYPlot().getRangeCrosshairValue(); NeutralLossDataPoint point = dataset.getDataPoint(xValue, yValue); return point; } NeutralLossPlot getPlot() { return neutralLossPlot; } }
package net.finmath.marketdata.model.volatilities; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import net.finmath.exception.CalculationException; import net.finmath.marketdata.calibration.ParameterObjectInterface; import net.finmath.marketdata.calibration.ParameterTransformation; import net.finmath.marketdata.calibration.Solver; import net.finmath.marketdata.model.AnalyticModelInterface; import net.finmath.marketdata.products.AnalyticProductInterface; import net.finmath.optimizer.OptimizerFactoryInterface; import net.finmath.optimizer.SolverException; /** * Base class for parametric volatility surfaces, implementing a generic calibration algorithm. * * @author Christian Fries */ public abstract class AbstractVolatilitySurfaceParametric extends AbstractVolatilitySurface implements ParameterObjectInterface { private static final Logger logger = Logger.getLogger("net.finmath"); public AbstractVolatilitySurfaceParametric(String name, Calendar referenceDate) { super(name, referenceDate); } /** * Returns a clone of this volatility surface with modified parameters. * * @param value Parameter array. * @return Clone with new parameters. * @throws CloneNotSupportedException Thrown if this object cannot be cloned. */ public abstract AbstractVolatilitySurfaceParametric getCloneForParameter(double[] value) throws CloneNotSupportedException; public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModelInterface calibrationModel, final Vector<AnalyticProductInterface> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters) throws CalculationException, SolverException { return getCloneCalibrated(calibrationModel, calibrationProducts, calibrationTargetValues, calibrationParameters, null); } public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModelInterface calibrationModel, final Vector<AnalyticProductInterface> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation) throws CalculationException, SolverException { return getCloneCalibrated(calibrationModel, calibrationProducts, calibrationTargetValues, calibrationParameters, parameterTransformation, null); } /** * Create a clone of this volatility surface using a generic calibration * of its parameters to given market data. * * @param calibrationModel The model used during calibration (contains additional objects required during valuation, e.g. curves). * @param calibrationProducts The calibration products. * @param calibrationTargetValues The target values of the calibration products. * @param calibrationParameters A map containing additional settings like "evaluationTime" (Double). * @param parameterTransformation An optional parameter transformation. * @param optimizerFactory The factory providing the optimizer to be used during calibration. * @return An object having the same type as this one, using (hopefully) calibrated parameters. * @throws CalculationException Exception thrown when evaluation fails. * @throws SolverException Exception thrown when solver fails. */ public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModelInterface calibrationModel, final Vector<AnalyticProductInterface> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactoryInterface optimizerFactory) throws CalculationException, SolverException { if(calibrationParameters == null) calibrationParameters = new HashMap<String,Object>(); Integer maxIterationsParameter = (Integer)calibrationParameters.get("maxIterations"); Double accuracyParameter = (Double)calibrationParameters.get("accuracy"); Double evaluationTimeParameter = (Double)calibrationParameters.get("evaluationTime"); // @TODO currently ignored, we use the setting form the OptimizerFactoryInterface int maxIterations = maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600; double accuracy = accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8; double evaluationTime = evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0; AnalyticModelInterface model = calibrationModel.addVolatilitySurfaces(this); Solver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory); Set<ParameterObjectInterface> objectsToCalibrate = new HashSet<ParameterObjectInterface>(); objectsToCalibrate.add(this); AnalyticModelInterface modelCalibrated = solver.getCalibratedModel(objectsToCalibrate); // Diagnostic output if (logger.isLoggable(Level.FINE)) { double lastAccuracy = solver.getAccuracy(); int lastIterations = solver.getIterations(); logger.fine("The solver achived an accuracy of " + lastAccuracy + " in " + lastIterations + "."); } return (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName()); } }
package org.helioviewer.jhv.plugins.swhvhekplugin.cache; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.NavigableMap; import org.helioviewer.base.logging.Log; import org.helioviewer.jhv.data.container.JHVEventContainer; import org.helioviewer.jhv.data.container.JHVEventHandler; import org.helioviewer.jhv.data.container.cache.JHVEventCache; import org.helioviewer.jhv.data.container.cache.JHVEventCacheResult; import org.helioviewer.jhv.data.datatype.event.JHVEvent; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.layers.LayersListener; import org.helioviewer.jhv.layers.LayersModel; import org.helioviewer.viewmodel.view.View; import org.helioviewer.viewmodel.view.jp2view.JHVJPXView; import org.helioviewer.viewmodel.view.jp2view.datetime.ImmutableDateTime; /** * This class intercepts changes of the layers and request data from the * JHVEventContainer. * * @author Bram Bourgoignie (Bram.Bourgoignie@oma.be) * */ public class SWHVHEKData implements LayersListener, JHVEventHandler { /** The singleton instance of the outgoing request manager */ private static SWHVHEKData instance; private Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> data; private ArrayList<JHVEvent> events; private Date beginDate = null; private Date endDate = null; /** instance of the swek event handler */ /** * private constructor */ private SWHVHEKData() { LayersModel.getSingletonInstance().addLayersListener(this); } /** * Gets the singleton instance of the outgoing request manager * * @return the singleton instance */ public static SWHVHEKData getSingletonInstance() { if (instance == null) { instance = new SWHVHEKData(); } return instance; } @Override public void layerAdded(int idx) { boolean request = false; Date first = LayersModel.getSingletonInstance().getFirstDate(); Date last = LayersModel.getSingletonInstance().getLastDate(); if (beginDate == null || first.getTime() < beginDate.getTime()) { beginDate = first; request = true; } if (endDate == null || last.getTime() > endDate.getTime()) { endDate = last; request = true; } if (request) { JHVEventContainer.getSingletonInstance().requestForInterval(beginDate, endDate, SWHVHEKData.this); } } @Override public void layerRemoved(int oldIdx) { } @Override public void activeLayerChanged(View view) { } @Override public void newEventsReceived(Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> eventList) { } @Override public void cacheUpdated() { if (beginDate != null && endDate != null) { JHVEventCacheResult result = JHVEventCache.getSingletonInstance().get(beginDate, endDate); data = result.getAvailableEvents(); ArrayList<JHVEvent> events = new ArrayList<JHVEvent>(); for (String eventType : data.keySet()) { for (Date sDate : data.get(eventType).keySet()) { for (Date eDate : data.get(eventType).get(sDate).keySet()) { for (JHVEvent event : data.get(eventType).get(sDate).get(eDate)) { events.add(event); } } } } this.events = events; Displayer.display(); } } public Map<String, NavigableMap<Date, NavigableMap<Date, List<JHVEvent>>>> getData() { return data; } public ArrayList<JHVEvent> getActiveEvents(Date currentDate) { ArrayList<JHVEvent> activeEvents = new ArrayList<JHVEvent>(); if (events != null) { for (JHVEvent event : events) { if (event != null && event.getStartDate() != null && event.getEndDate() != null) { if (event.getStartDate().getTime() < currentDate.getTime() && event.getEndDate().getTime() > currentDate.getTime()) { activeEvents.add(event); } event.addHighlightListener(Displayer.getSingletonInstance()); } else { Log.warn("Possibly something strange is going on with incoming events. Either the date or the event is null"); } } } return activeEvents; } }
package com.gravity.root; import java.util.List; import java.util.Random; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import com.google.common.collect.Lists; public final class GameSounds { private GameSounds() { } private static final List<String> jumpSounds = Lists.newArrayList("jump_ha.ogg", "jump_ho.ogg", "jump_hup.ogg"); private static final List<String> slingshotSounds = Lists.newArrayList("slingshot_1.ogg", "slingshot_2.ogg", "slingshot_3.ogg", "slingshot_4.ogg"); private static final List<String> noSlingshotSounds = Lists.newArrayList("slingshot_fail.ogg"); private static final List<String> wheeSounds = Lists.newArrayList("slingshot_whee.ogg", "jump_woo.ogg"); private static final List<String> spikeSounds = Lists.newArrayList("death_spike.ogg", "death_crush3.ogg", "death_crush4.ogg", "death_crush5.ogg", "death_crush7.ogg"); private static final List<String> crushSounds = Lists.newArrayList("death_crush1.ogg", "death_crush2.ogg", "death_crush6.ogg", "death_crush8.ogg", "death_crush5.ogg"); private static final List<String> fellSounds = Lists.newArrayList("death_ugh.ogg"); private static final List<String> bounceSounds = Lists.newArrayList(/*"bounce.ogg"*/); private static final List<String> bonkSounds = Lists.newArrayList("ceiling_bonk.ogg"); private static final List<String> cageSlams = Lists.newArrayList("cage_shut.ogg"); private static final List<String> endOfGame = Lists.newArrayList("city_endoflevel.ogg"); private static final Music backgroundMusic; private static final Music menuMusic; private static final Random random; private static final String soundPath = "./assets/Sound/"; static { try { backgroundMusic = new Music("./assets/Sound/Caketown 1.ogg", true); menuMusic = new Music("./assets/Sound/levelselect_theme.ogg", true); } catch (SlickException e) { throw new RuntimeException(e); } random = new Random(); } public static enum Event { //@formatter:off JUMP (jumpSounds), SLINGSHOT (slingshotSounds), NO_SLING (noSlingshotSounds), WHEE (wheeSounds), SPIKED (spikeSounds), CRUSHED (crushSounds), WALL_OF_DEATH(spikeSounds), FELL_OFF_MAP (fellSounds), BOUNCE (bounceSounds), BONK (bonkSounds), CAGE_SLAM (cageSlams), END_OF_GAME (endOfGame); //@formatter:on private List<Sound> sounds; private Event(List<String> files) { sounds = Lists.newArrayList(); for (String file : files) { try { sounds.add(new Sound(soundPath + file)); } catch (SlickException e) { throw new RuntimeException("Could not load sound file: " + soundPath + file, e); } } } private void playRandomSound() { sounds.get(random.nextInt(sounds.size())).play(); } } public static void playBGM() { if (!backgroundMusic.playing()) { backgroundMusic.loop(); } } public static void playMenuMusic() { if (!menuMusic.playing()) { menuMusic.loop(); } } public static void playSoundFor(Event event) { event.playRandomSound(); } }
package com.palantir.docker.compose.execution; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.Matchers.anyVararg; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class SynchronousDockerComposeExecutableShould { @Mock private Process executedProcess; @Mock private DockerComposeExecutable dockerComposeExecutable; private SynchronousDockerComposeExecutable dockerCompose; @Before public void setup() throws IOException { when(dockerComposeExecutable.execute(anyVararg())).thenReturn(executedProcess); dockerCompose = new SynchronousDockerComposeExecutable(dockerComposeExecutable); givenTheUnderlyingProcessHasOutput(""); givenTheUnderlyingProcessTerminatesWithAnExitCodeOf(0); } @Test public void respond_with_the_exit_code_of_the_executed_process() throws IOException { int expectedExitCode = 1; givenTheUnderlyingProcessTerminatesWithAnExitCodeOf(expectedExitCode); assertThat(dockerCompose.run("rm", "-f").exitCode(), is(expectedExitCode)); } @Test public void respond_with_the_output_of_the_executed_process() throws IOException { String expectedOutput = "some output"; givenTheUnderlyingProcessHasOutput(expectedOutput); assertThat(dockerCompose.run("rm", "-f").output(), is(expectedOutput)); } private void givenTheUnderlyingProcessHasOutput(String output) { byte[] outputBytes = output.getBytes(StandardCharsets.UTF_8); when(executedProcess.getInputStream()) .thenReturn(new ByteArrayInputStream(outputBytes)); } private void givenTheUnderlyingProcessTerminatesWithAnExitCodeOf(int exitCode) { when(executedProcess.exitValue()).thenReturn(exitCode); } }
package org.jenkinsci.plugins.credentialsbinding.masking; import hudson.tasks.Shell; import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil; import org.jenkinsci.plugins.credentialsbinding.test.Executables; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.jvnet.hudson.test.JenkinsRule; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable; import static org.junit.Assume.assumeThat; @RunWith(Theories.class) public class BashPatternMaskerProviderTest { public static final @DataPoint String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_"; public static final @DataPoint String ANOTHER_SAMPLE_PASSWORD = "a'b\"c\\d(e) public static final @DataPoint String ONE_MORE = "'\"'(foo)'\"'"; @DataPoints public static List<String> generatePasswords() { Random random = new Random(100); List<String> passwords = new ArrayList<>(10); for (int i = 0; i < 10; i++) { int length = random.nextInt(24) + 8; StringBuilder sb = new StringBuilder(length); for (int j = 0; j < length; j++) { char next = (char) (' ' + random.nextInt('\u007f' - ' ')); // 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character sb.append(next); } passwords.add(sb.toString()); } return passwords; } @Rule public JenkinsRule j = new JenkinsRule(); private WorkflowJob project; private String credentialsId; @BeforeClass public static void assumeBash() { assumeThat("bash", is(executable())); // due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149 // on Windows assumeThat("nohup", is(executable())); } @Before public void setUp() throws IOException { j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("bash")); project = j.createProject(WorkflowJob.class); credentialsId = UUID.randomUUID().toString(); project.setDefinition(new CpsFlowDefinition( "node {\n" + " withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" + " sh ': \"$CREDENTIALS\"'\n" + // : will expand its parameters and do nothing with them " sh ': \"< $CREDENTIALS >\"'\n" + " }\n" + "}", true)); } @Theory public void credentialsAreMaskedInLogs(String credentials) throws Exception { assumeThat(credentials, not(startsWith("****"))); CredentialsTestUtil.setStringCredentials(j.jenkins, credentialsId, credentials); WorkflowRun run = runProject(); j.assertLogContains(": ****", run); j.assertLogContains(": '< **** >'", run); j.assertLogNotContains(credentials, run); } private WorkflowRun runProject() throws Exception { return j.assertBuildStatusSuccess(project.scheduleBuild2(0)); } }
package org.apache.mesos.elasticsearch.systemtest; import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.jayway.awaitility.Awaitility; import org.apache.commons.io.IOUtils; import org.apache.mesos.elasticsearch.systemtest.base.SchedulerTestBase; import org.apache.mesos.elasticsearch.systemtest.util.DockerUtil; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * System test for the executor */ public class ExecutorSystemTest extends SchedulerTestBase { private DockerUtil dockerUtil = new DockerUtil(CLUSTER.getConfig().dockerClient); @Before public void before() { Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> dockerUtil.getExecutorContainers().size() > 0); // Make sure executors are alive before performing tests } /** * Make sure that lib mesos exists in /usr/lib/libmesos.so * @throws IOException */ @Test public void ensureLibMesosExists() throws IOException { // Remote execute an ls command to make sure the file exists ExecCreateCmdResponse exec = CLUSTER.getConfig().dockerClient.execCreateCmd(getRandomExecutorId()).withAttachStdout().withAttachStderr().withCmd("ls", "/usr/lib/libmesos.so").exec(); InputStream execCmdStream = CLUSTER.getConfig().dockerClient.execStartCmd(exec.getId()).exec(); String result = IOUtils.toString(execCmdStream, "UTF-8"); assertFalse(result.contains("No such file")); } /** * Tests that the scheduler has force set the MESOS_NATIVE_JAVA_LIBRARY and that it points to a file that exists. * @throws IOException */ @Test public void ensureEnvVarPointsToLibMesos() throws IOException { // Get remote env vars ExecCreateCmdResponse exec = CLUSTER.getConfig().dockerClient.execCreateCmd(getRandomExecutorId()).withTty(true).withAttachStdout().withAttachStderr().withCmd("env").exec(); InputStream execCmdStream = CLUSTER.getConfig().dockerClient.execStartCmd(exec.getId()).exec(); String result = IOUtils.toString(execCmdStream, "UTF-8"); // Get MESOS_NATIVE_JAVA_LIBRARY from env List<String> env = Arrays.asList(result.split("\n")).stream().filter(s -> s.contains("MESOS_NATIVE_JAVA_LIBRARY")).collect(Collectors.toList()); assertEquals("env does not have MESOS_NATIVE_JAVA_LIBRARY: " + result, 1, env.size()); // Remote execute the ENV var to make sure it points to a real file String path = env.get(0).split("=")[1].replace("\r", "").replace("\n", ""); exec = CLUSTER.getConfig().dockerClient.execCreateCmd(getRandomExecutorId()).withTty(true).withAttachStdout().withAttachStderr().withCmd("ls", path).exec(); execCmdStream = CLUSTER.getConfig().dockerClient.execStartCmd(exec.getId()).exec(); result = IOUtils.toString(execCmdStream, "UTF-8"); assertFalse(path + " does not exist: " + result, result.contains("No such file")); } private String getRandomExecutorId() { return dockerUtil.getExecutorContainers().get(0).getId(); } }
package org.mtransit.parser.ca_lanaudiere_crtl_bus; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MSpec; import org.mtransit.parser.mt.data.MTrip; public class LanaudiereCRTLBusAgencyTools extends DefaultAgencyTools { public static final String ROUTE_TYPE_FILTER = "3"; // bus only public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-lanaudiere-crtl-bus-android/res/raw/"; args[2] = ""; // files-prefix } new LanaudiereCRTLBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("Generating CRTL bus data...\n"); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this); super.start(args); System.out.printf("Generating CRTL bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public boolean excludeRoute(GRoute gRoute) { if (ROUTE_TYPE_FILTER != null && !gRoute.route_type.equals(ROUTE_TYPE_FILTER)) { return true; } if (gRoute.route_id.length() < 2) { return true; // exclude CTJM Joliette Bus } return super.excludeRoute(gRoute); } @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.route_long_name; routeLongName = MSpec.SAINT.matcher(routeLongName).replaceAll(MSpec.SAINT_REPLACEMENT); return MSpec.cleanLabel(routeLongName); } private static final String AGENCY_COLOR = "0058AD"; @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public void setTripHeadsign(MRoute route, MTrip mTrip, GTrip gTrip) { String stationName = cleanTripHeadsign(gTrip.trip_headsign); int directionId = Integer.valueOf(gTrip.direction_id); mTrip.setHeadsignString(stationName, directionId); } private static final Pattern DIRECTION = Pattern.compile("(direction )", Pattern.CASE_INSENSITIVE); private static final String DIRECTION_REPLACEMENT = ""; private static final Pattern SECTEUR = Pattern.compile("(secteur[s]? )", Pattern.CASE_INSENSITIVE); private static final String SECTEUR_REPLACEMENT = ""; @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = DIRECTION.matcher(tripHeadsign).replaceAll(DIRECTION_REPLACEMENT); tripHeadsign = SECTEUR.matcher(tripHeadsign).replaceAll(SECTEUR_REPLACEMENT); return MSpec.cleanLabelFR(tripHeadsign); } private static final Pattern START_WITH_FACE_A = Pattern.compile("^(face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern START_WITH_FACE_AU = Pattern.compile("^(face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern START_WITH_FACE = Pattern.compile("^(face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern SPACE_FACE_A = Pattern.compile("( face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern SPACE_WITH_FACE_AU = Pattern.compile("( face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern SPACE_WITH_FACE = Pattern.compile("( face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern[] START_WITH_FACES = new Pattern[] { START_WITH_FACE_A, START_WITH_FACE_AU, START_WITH_FACE }; private static final Pattern[] SPACE_FACES = new Pattern[] { SPACE_FACE_A, SPACE_WITH_FACE_AU, SPACE_WITH_FACE }; private static final Pattern AVENUE = Pattern.compile("( avenue)", Pattern.CASE_INSENSITIVE); private static final String AVENUE_REPLACEMENT = " av."; @Override public String cleanStopName(String gStopName) { gStopName = AVENUE.matcher(gStopName).replaceAll(AVENUE_REPLACEMENT); gStopName = Utils.replaceAll(gStopName, START_WITH_FACES, MSpec.SPACE); gStopName = Utils.replaceAll(gStopName, SPACE_FACES, MSpec.SPACE); return super.cleanStopNameFR(gStopName); } @Override public String getStopCode(GStop gStop) { if ("0".equals(gStop.stop_code)) { return null; } return super.getStopCode(gStop); } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); @Override public int getStopId(GStop gStop) { String stopCode = getStopCode(gStop); if (stopCode != null && stopCode.length() > 0) { return Integer.valueOf(stopCode); // using stop code as stop ID } // generating integer stop ID Matcher matcher = DIGITS.matcher(gStop.stop_id); matcher.find(); int digits = Integer.parseInt(matcher.group()); int stopId; if (gStop.stop_id.startsWith("RDP")) { stopId = 100000; } else if (gStop.stop_id.startsWith("SFV")) { stopId = 200000; } else if (gStop.stop_id.startsWith("SMS")) { stopId = 300000; } else { System.out.println("Stop doesn't have an ID (start with)! " + gStop); System.exit(-1); stopId = -1; } if (gStop.stop_id.endsWith("A")) { stopId += 1000; } else if (gStop.stop_id.endsWith("B")) { stopId += 2000; } else if (gStop.stop_id.endsWith("D")) { stopId += 4000; } else { System.out.println("Stop doesn't have an ID (end with)! " + gStop); System.exit(-1); } return stopId + digits; } }
package org.mtransit.parser.ca_welland_transit_bus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MDirectionType; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; // http://www.niagararegion.ca/government/opendata/data-set.aspx#id=32 // http://www.niagararegion.ca/government/opendata/data-set.aspx#id=32&tab=data_table&f=xml&r=500&p=1 public class WellandTransitBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-welland-transit-bus-android/res/raw/"; args[2] = ""; // files-prefix } new WellandTransitBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating Welland Transit bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); System.out.printf("\nGenerating Welland Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } private static final String WE_ = "WE_"; @Override public boolean excludeRoute(GRoute gRoute) { if (!gRoute.getAgencyId().startsWith(WE_)) { return true; } return super.excludeRoute(gRoute); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public long getRouteId(GRoute gRoute) { if (gRoute.getRouteShortName() != null && gRoute.getRouteShortName().length() > 0 && Utils.isDigitsOnly(gRoute.getRouteShortName())) { return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID } System.out.printf("\nUnexpected route ID for %s!\n", gRoute); System.exit(-1); return -1l; } private static final String NOTL = "NOTL"; private static final String PC1EAST = "PC1"; private static final String PC2WEST = "PC2"; private static final String PCL = "PCL"; private static final String BL = "BL"; @Override public String getRouteShortName(GRoute gRoute) { if ("NOTL Link".equals(gRoute.getRouteLongName())) { return NOTL; } else if ("Port Colborne East Side - Rt. 1".equals(gRoute.getRouteLongName())) { return PC1EAST; } else if ("Port Colborne West Side - Rt 2".equals(gRoute.getRouteLongName())) { return PC2WEST; } else if ("Port Colborne Link".equals(gRoute.getRouteLongName())) { return PCL; } else if ("College-Brock".equals(gRoute.getRouteId())) { return BL; } else { if (gRoute.getRouteShortName() != null && gRoute.getRouteShortName().length() > 0 && Utils.isDigitsOnly(gRoute.getRouteShortName())) { return gRoute.getRouteShortName(); } } System.out.printf("\nUnexpected route short name for %s!\n", gRoute); System.exit(-1); return null; } private static final Pattern POINT = Pattern.compile("((^|\\W){1}([\\w]{1})\\.(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String POINT_REPLACEMENT = "$2$3$4"; private static final Pattern POINTS = Pattern.compile("((^|\\W){1}([\\w]+)\\.(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String POINTS_REPLACEMENT = "$2$3$4"; @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = POINT.matcher(routeLongName).replaceAll(POINT_REPLACEMENT); routeLongName = POINTS.matcher(routeLongName).replaceAll(POINTS_REPLACEMENT); routeLongName = CleanUtils.cleanNumbers(routeLongName); routeLongName = CleanUtils.cleanStreetTypes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_GREEN = "00AAA0"; // GREEN (from PDF) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public String getRouteColor(GRoute gRoute) { if (gRoute.getRouteShortName() != null && gRoute.getRouteShortName().length() > 0 && Utils.isDigitsOnly(gRoute.getRouteShortName())) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 23: return "2B6ABC"; case 25: return "9E50AE"; case 34: return "2B6ABC"; case 501: return "ED1C24"; case 502: return "A05843"; case 503: return "00A990"; case 504: return "2E3192"; case 505: return "7B2178"; case 506: return "19B5F1"; case 508: return "EC008C"; case 509: return "127BCA"; case 599: return null; // TODO case 510: return "ED1C24"; case 511: return "2E3192"; case 701: return "ED1C24"; case 702: return "127BCA"; // @formatter:on } } System.out.printf("\nUnexpected route color for %s!\n", gRoute); System.exit(-1); return null; } private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(23L, new RouteTripSpec(23L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Niagara College", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Brock U") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "BRU", // Brock University "4010", "WlndCamp", // Woodlawn Road #NiagaraCollege })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "WlndCamp", // Woodlawn Road #NiagaraCollege "4004", "BRU", // Brock University })) .compileBothTripSort()); map2.put(25L, new RouteTripSpec(25L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Welland", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Port Colborne") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "PCH", // Port Colborne City Hall "3076", "Welland", // Welland Bus Terminal })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4181", "PCH", // Port Colborne City Hall })) .compileBothTripSort()); map2.put(34L, new RouteTripSpec(34L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Welland", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "NOTL") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "GlndCmps", // 135 Taylor Rd N.O.T.L. "4010", "WlndCamp", // Woodlawn Road #NiagaraCollege })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "WlndCamp", // Woodlawn Road #NiagaraCollege "4004", "GlndCmps", // 135 Taylor Rd N.O.T.L. })) .compileBothTripSort()); map2.put(501L, new RouteTripSpec(501L, MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal", MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "St George / Roach") .addTripSort(MDirectionType.EAST.intValue(), Arrays.asList(new String[] { "SGR", // St. George St & Roach Av "4046", "Welland", // Welland Bus Terminal })) .addTripSort(MDirectionType.WEST.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "LIO", "SGR", // St. George St & Roach Av })) .compileBothTripSort()); map2.put(502L, new RouteTripSpec(502L, MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal", MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Niagara College") .addTripSort(MDirectionType.EAST.intValue(), Arrays.asList(new String[] { "NCC", // Niagara College Welland - Chippa "4078", "Welland", // Welland Bus Terminal })) .addTripSort(MDirectionType.WEST.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4061", "NCC", // Niagara College Welland - Chippa })) .compileBothTripSort()); map2.put(503L, new RouteTripSpec(503L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Niagara College", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "FIN", "WlndCamp", // Woodlawn Road #NiagaraCollege })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "WlndCamp", // Woodlawn Road #NiagaraCollege "4102", "Welland", // Welland Bus Terminal })) .compileBothTripSort()); map2.put(504L, new RouteTripSpec(504L, MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal", MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Woodlawn / S Pelham") .addTripSort(MDirectionType.EAST.intValue(), Arrays.asList(new String[] { "WOS", // Woodlawn Rd & South Pelham Rd "AQE", "Welland", // Welland Bus Terminal })) .addTripSort(MDirectionType.WEST.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4111", "WOS", // Woodlawn Rd & South Pelham Rd })) .compileBothTripSort()); map2.put(505L, new RouteTripSpec(505L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Community Living") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "WPC", // Welland Pelham Community Living "4165", "Welland", // Welland Bus Terminal })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4145", "4146", "WPC", // Welland Pelham Community Living })) .compileBothTripSort()); map2.put(506L, new RouteTripSpec(506L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Southworth / Gordon") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "4191", // Gordon St & Southworth St "4205", "Welland", // Welland Bus Terminal })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "KIO", "4191", // Gordon St & Southworth St })) .compileBothTripSort()); map2.put(508L, new RouteTripSpec(508L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Niagara College", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4224", "WlndCamp", // Woodlawn Road #NiagaraCollege })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "WlndCamp", // Woodlawn Road #NiagaraCollege "4227", "Welland", // Welland Bus Terminal })) .compileBothTripSort()); map2.put(509L, new RouteTripSpec(509L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Seaway Mall", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4238", "SewayMal", // Seaway Mall })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "SewayMal", // Seaway Mall "4249", "Welland", // Welland Bus Terminal })) .compileBothTripSort()); map2.put(510L, new RouteTripSpec(510L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Niagara College", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4224", "WlndCamp", // Woodlawn Road #NiagaraCollege })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "WlndCamp", // Woodlawn Road #NiagaraCollege "4077", "Welland", // Welland Bus Terminal })) .compileBothTripSort()); map2.put(511L, new RouteTripSpec(511L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Hospital") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "4047", // King St & Fourth St #Hospital "4198", "Welland", // Welland Bus Terminal })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "4029", "4047", // King St & Fourth St #Hospital })) .compileBothTripSort()); map2.put(599L, new RouteTripSpec(599L, MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Seaway Mall", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Downtown Terminal") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "Welland", // Welland Bus Terminal "Welland", // Welland Bus Terminal "SewayMal", // Seaway Mall "SewayMal", // Seaway Mall })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "SewayMal", // Seaway Mall "4229", "Welland", // Welland Bus Terminal })) .compileBothTripSort()); map2.put(701L, new RouteTripSpec(701L, // Port Colborne 1 East MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Colborne / McRae", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Hall") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "PCH", // Port Colborne City Hall "3051", "3066", // Flag Stop - Colborne St & MacRae })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "3066", // Flag Stop - Colborne St & MacRae "3071", "PCH", // Port Colborne City Hall })) .compileBothTripSort()); map2.put(702L, new RouteTripSpec(702L, // Port Colborne 2 West MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "PC Mall", MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "City Hall") .addTripSort(MDirectionType.NORTH.intValue(), Arrays.asList(new String[] { "PCH", // Port Colborne City Hall "3031", "3005", // Flag Stop - Port Colborne Mall })) .addTripSort(MDirectionType.SOUTH.intValue(), Arrays.asList(new String[] { "3005", // Flag Stop - Port Colborne Mall "3015", "PCH", // Port Colborne City Hall })) .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } public static final Pattern STARTS_WITH_WE_A00_ = Pattern.compile("((^){1}(we\\_[A-Z]{1}[\\d]{2}(\\_)?(stop)?))", Pattern.CASE_INSENSITIVE); @Override public String cleanStopOriginalId(String gStopId) { gStopId = STARTS_WITH_WE_A00_.matcher(gStopId).replaceAll(StringUtils.EMPTY); return gStopId; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this); } System.out.printf("\n%s: Unexpected compare early route!\n", routeId); System.exit(-1); return -1; } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } System.out.printf("\n%s: Unexpected trip to split %s!\n", mRoute.getId(), gTrip); System.exit(-1); return null; } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this); } System.out.printf("\n%s: Unexpected trip to split %s!\n", mRoute.getId(), gTrip); System.exit(-1); return null; } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } System.out.printf("\n%s: Unexptected trip %s!", mRoute.getId(), gTrip); System.exit(-1); return; } @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = AND.matcher(tripHeadsign).replaceAll(AND_REPLACEMENT); tripHeadsign = POINT.matcher(tripHeadsign).replaceAll(POINT_REPLACEMENT); tripHeadsign = POINTS.matcher(tripHeadsign).replaceAll(POINTS_REPLACEMENT); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern AND_NOT = Pattern.compile("(&)", Pattern.CASE_INSENSITIVE); private static final String AND_NOT_REPLACEMENT = "and"; private static final Pattern AND = Pattern.compile("((^|\\W){1}(and)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String AND_REPLACEMENT = "$2&$4"; private static final Pattern AT = Pattern.compile( "((^|\\W){1}(across fr[\\.]?|after|at|before|between both|between|east of|in front of|north of|opp|south of|west of)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String AT_REPLACEMENT = "$2/$4"; private static final Pattern AND_SLASH = Pattern.compile("((^|\\W){1}(&|@)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String AND_SLASH_REPLACEMENT = "$2/$4"; private static final Pattern ENDS_WITH = Pattern.compile("((&|/|\\-)[\\W]*$)", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_WITH_FLAG_STOP = Pattern.compile("(^(flag stop \\- )+)", Pattern.CASE_INSENSITIVE); private static final Pattern AVE = Pattern.compile("((^|\\W){1}(aven|avenu)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String AVE_REPLACEMENT = "$2Avenue$4"; private static final Pattern DRIV = Pattern.compile("((^|\\W){1}(driv)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String DRIV_REPLACEMENT = "$2Drive$4"; private static final Pattern ST = Pattern.compile("((^|\\W){1}(stree|stre)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String ST_REPLACEMENT = "$2Street$4"; @Override public String cleanStopName(String gStopName) { gStopName = STARTS_WITH_FLAG_STOP.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = AVE.matcher(gStopName).replaceAll(AVE_REPLACEMENT); gStopName = DRIV.matcher(gStopName).replaceAll(DRIV_REPLACEMENT); gStopName = ST.matcher(gStopName).replaceAll(ST_REPLACEMENT); gStopName = AND_NOT.matcher(gStopName).replaceAll(AND_NOT_REPLACEMENT); // fix Alex&ra gStopName = AND.matcher(gStopName).replaceAll(AND_REPLACEMENT); gStopName = AND_SLASH.matcher(gStopName).replaceAll(AND_SLASH_REPLACEMENT); gStopName = AT.matcher(gStopName).replaceAll(AT_REPLACEMENT); gStopName = POINT.matcher(gStopName).replaceAll(POINT_REPLACEMENT); gStopName = POINTS.matcher(gStopName).replaceAll(POINTS_REPLACEMENT); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = ENDS_WITH.matcher(gStopName).replaceAll(StringUtils.EMPTY); return CleanUtils.cleanLabel(gStopName); } private static final String ZERO_0 = "0"; private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final String PC2 = "PC_"; private static final String PC = "PC"; private static final String WE2 = "WE_"; private static final String WE = "WE"; @Override public String getStopCode(GStop gStop) { String stopCode = gStop.getStopCode(); if (stopCode == null || stopCode.length() == 0 || ZERO_0.equals(stopCode)) { stopCode = gStop.getStopId(); } stopCode = STARTS_WITH_WE_A00_.matcher(stopCode).replaceAll(StringUtils.EMPTY); return stopCode; } @Override public int getStopId(GStop gStop) { String stopCode = gStop.getStopCode(); if (stopCode == null || stopCode.length() == 0 || ZERO_0.equals(stopCode)) { stopCode = gStop.getStopId(); } stopCode = STARTS_WITH_WE_A00_.matcher(stopCode).replaceAll(StringUtils.EMPTY); if (Utils.isDigitsOnly(stopCode)) { return Integer.parseInt(stopCode); // using stop code as stop ID } if (stopCode.equals("AQE")) { return 9000000; } else if (stopCode.equals("BRC")) { return 9000001; } else if (stopCode.equals("BRU")) { return 9000002; } else if (stopCode.equals("EMW")) { return 9000003; } else if (stopCode.equals("FIF")) { return 9000004; } else if (stopCode.equals("FIN")) { return 9000005; } else if (stopCode.equals("FIO")) { return 9000006; } else if (stopCode.equals("GlndCmps")) { return 9000007; } else if (stopCode.equals("HAW")) { return 9000008; } else if (stopCode.equals("HOW")) { return 9000009; } else if (stopCode.equals("KIO")) { return 9000010; } else if (stopCode.equals("LIO")) { return 9000011; } else if (stopCode.equals("NCC")) { return 9000012; } else if (stopCode.equals("NIE")) { return 9000013; } else if (stopCode.equals("ONC")) { return 9000014; } else if (stopCode.equals("ONS")) { return 9000015; } else if (stopCode.equals("PCH")) { return 9000016; } else if (stopCode.equals("PRW")) { return 9000017; } else if (stopCode.equals("SewayMal")) { return 9000018; } else if (stopCode.equals("SGR")) { return 9000019; } else if (stopCode.equals("SPM")) { return 9000020; } else if (stopCode.equals("THB")) { return 9000021; } else if (stopCode.equals("THN")) { return 9000022; } else if (stopCode.equals("Welland")) { return 9000023; } else if (stopCode.equals("WlndCamp")) { return 9000024; } else if (stopCode.equals("WOR")) { return 9000025; } else if (stopCode.equals("WOS")) { return 9000026; } else if (stopCode.equals("WPC")) { return 9000027; } else if (stopCode.equals("WWA")) { return 9000028; } else if (stopCode.equals("LIP")) { return 9000029; } else if (stopCode.equals("XXXX")) { return 9000030; } try { Matcher matcher = DIGITS.matcher(stopCode); if (matcher.find()) { int routeId = Integer.parseInt(matcher.group()); if (stopCode.startsWith(NOTL)) { routeId += 14000000; } else if (stopCode.startsWith(PC2)) { routeId += 160000000; } else if (stopCode.startsWith(PC)) { routeId += 161000000; } else if (stopCode.startsWith(WE2)) { routeId += 233000000; } else if (stopCode.startsWith(WE)) { routeId += 234000000; } else { System.out.printf("\nUnexpected stop ID (starts with digits) %s!\n", gStop); System.exit(-1); routeId = -1; } return routeId; } } catch (Exception e) { System.out.printf("\nError while finding stop ID for %s!\n", gStop); e.printStackTrace(); System.exit(-1); return -1; } System.out.printf("\nUnexpected stop ID %s!\n", gStop); System.exit(-1); return -1; } }
package org.objectweb.proactive.core.event; import org.objectweb.proactive.core.runtime.ProActiveRuntime; /** * @author rquilici * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class RuntimeRegistrationEventProducerImpl extends AbstractEventProducer implements RuntimeRegistrationEventProducer { /** * @see org.objectweb.proactive.core.event.RuntimeRegistrationEventProducer#addRuntimeRegistrationEventListener(RuntimeRegistrationEventListener) */ public void addRuntimeRegistrationEventListener(RuntimeRegistrationEventListener listener){ addListener(listener); } /** * @see org.objectweb.proactive.core.event.RuntimeRegistrationEventProducer#removeRuntimeRegistrationEventListener(RuntimeRegistrationEventListener) */ public void removeRuntimeRegistrationEventListener(RuntimeRegistrationEventListener listener){ removeListener(listener); } /** * @see org.objectweb.proactive.core.event.AbstractEventProducer#notifyOneListener(ProActiveListener, ProActiveEvent) */ protected void notifyOneListener(ProActiveListener proActiveListener, ProActiveEvent event){ RuntimeRegistrationEvent runtimeRegistrationEvent = (RuntimeRegistrationEvent) event; RuntimeRegistrationEventListener runtimeRegistrationEventListener = (RuntimeRegistrationEventListener)proActiveListener; //notify the listener that a registration occurs runtimeRegistrationEventListener.runtimeRegistered(runtimeRegistrationEvent); } protected void notifyListeners(ProActiveRuntime proActiveRuntime,int type,String registeredRuntimeName, String creatorID, String protocol){ if (hasListeners()){ notifyAllListeners(new RuntimeRegistrationEvent(proActiveRuntime, type, registeredRuntimeName, creatorID, protocol)); } else System.out.println("no listener"); } }
package edu.afs.commands; import java.util.Timer; import java.util.TimerTask; import edu.afs.subsystems.autoranger.*; /** * This command will move the bot straight forward under auto-ranger and * bearing stabilizer control. The command ends under three conditions: * * 1) The auto-ranger indicates that the bot has reached shot range. * 2) The safety timer expires. * 3) The operator makes manual control inputs via the joystick. * * @author RAmato */ public class AutoDriveToShotRangeCommand extends CommandBase { private static final double DESIRED_RANGE = 120.0; // Range in inches. private static final double STOP = 0.0; // Pick a timeout that allows the bot time to move the maximum // expected distance to reach shot range (during autonomous mode???). // We may have to clone this command so that we can specify a shorter // timeout during tele-op mode. As a consequence, the bot will have // to be positioned closer to shot range before this command is engaged. public static long DRIVE_SAFETY_TIMEOUT = 2500; //Time in milliseconds. private Timer m_safetyTimer; private boolean m_isAutoRangeDone; public AutoDriveToShotRangeCommand() { // Use requires() here to declare subsystem dependencies requires(drive); requires(autoRanger); Timer m_safetyTimer = new Timer(); m_isAutoRangeDone = false; } // Safety timer is intended to stop this command and keep bot from crashing // into a wall if the auto-ranger fails to detect that bot has passed shot // range. Note that the drive's default command is to move under joystick // control. Selecting the timeout is tricky. Assuming the auto-ranger wiggs // out, if the timeout is too long, the bot will continue forward until it // hits the wall. If it is too short, this command will time out before it // can reach shot range (and have to be re-started). class SafetyTimerTask extends TimerTask { public void run() { m_isAutoRangeDone = true; System.out.println("AutoDriveToShotRangeCommand::SafetyTimerTask" + "expired."); m_safetyTimer.cancel(); //Terminate the timer thread } } // Called just before this Command runs the first time protected void initialize() { drive.initBearingStabilizer(); autoRanger.setSetpoint(DESIRED_RANGE); autoRanger.initAutoRanger(); // Saftey timer ends command if timeout occurs. // This keeps bot from crashing into wall if auto-ranger fails. m_safetyTimer.schedule(new SafetyTimerTask(), DRIVE_SAFETY_TIMEOUT); } // Called repeatedly when this Command is scheduled to run protected void execute() { drive.driveStraightGyroStabilized(autoRanger.getAutoRangerOutput()); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { if (autoRanger.onTarget() == true){ m_isAutoRangeDone = true; //Turn on the green indicator. RangeBeacon.getInstance(). setRangeBeaconState(RangeBeaconState.AUTO_RANGE_COMPLETE); // Disable timer. m_safetyTimer.cancel(); } // m_isAutoRangeDone can be set true by Safety Timer timeout. return m_isAutoRangeDone; } // Called once after isFinished returns true protected void end() { autoRanger.disableAutoRanger(); drive.driveStraightGyroStabilized(STOP); drive.disableBearingStabilizer(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { // Manual joystick input will override auto mode. System.out.println("AutoDriveToShotRangeCommand interrupted."); drive.driveStraightGyroStabilized(STOP); m_safetyTimer.cancel(); autoRanger.disableAutoRanger(); drive.disableBearingStabilizer(); } }
package edu.wheaton.simulator.gui.screen; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import com.google.common.collect.ImmutableMap; import edu.wheaton.simulator.gui.BoxLayoutAxis; import edu.wheaton.simulator.gui.Gui; import edu.wheaton.simulator.gui.MaxSize; import edu.wheaton.simulator.gui.MinSize; import edu.wheaton.simulator.gui.PrefSize; import edu.wheaton.simulator.gui.SimulatorFacade; //TODO add elements for step delay public class SetupScreen extends Screen { private JTextField nameField; private JTextField timeField; private JTextField widthField; private JTextField heightField; private JTextField delayField; private String[] agentNames; private JComboBox updateBox; private ArrayList<JComboBox> agentTypes; private ArrayList<JTextField> values; private ArrayList<JButton> deleteButtons; private ArrayList<JPanel> subPanels; private JScrollPane scrollPane; private JPanel conListPanel; private JButton addConditionButton; private static final long serialVersionUID = -8347080877399964861L; public SetupScreen(final SimulatorFacade gm) { super(gm); agentNames = new String[0]; agentTypes = new ArrayList<JComboBox>(); deleteButtons = new ArrayList<JButton>(); subPanels = new ArrayList<JPanel>(); agentTypes = new ArrayList<JComboBox>(); values = new ArrayList<JTextField>(); JPanel upperPanel = makeUpperPanel(); upperPanel.setMinimumSize(new MinSize(300,140)); JPanel lowerPanel = makeLowerPanel(); lowerPanel.setMinimumSize(new MinSize(398,300)); addConditionButton = Gui.makeButton("Add Field", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { addCondition(); } }); JPanel bottomButtons = Gui.makePanel( Gui.makeButton("Revert", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { load(); } }), makeConfirmButton()); JPanel mainPanel = Gui.makePanel(new GridBagLayout(), MaxSize.NULL, null, (Component[])null); GridBagConstraints c = new GridBagConstraints(); c.gridy = 0; mainPanel.add(upperPanel,c); c = new GridBagConstraints(); c.gridy = 1; c.insets = new Insets(15,50,50,15); mainPanel.add(lowerPanel,c); c = new GridBagConstraints(); c.gridy = 2; mainPanel.add(Gui.makePanel(bottomButtons,addConditionButton),c); this.add(mainPanel); validate(); } private JButton makeConfirmButton() { return Gui.makeButton("Confirm", null, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { SimulatorFacade gm = getGuiManager(); int newWidth = Integer.parseInt(widthField.getText()); int newHeight = Integer.parseInt(widthField.getText()); int newTime = Integer.parseInt(timeField.getText()); int newDelay = Integer.parseInt(delayField.getText()); if (newWidth <= 0 || newHeight <= 0 || newTime <= 0 || newDelay <= 0) throw new NumberFormatException(); if (newWidth < gm.getGridWidth() || newHeight < gm.getGridHeight()) { int selection = JOptionPane .showConfirmDialog( null, "The new grid size you provided" + "\nis smaller than its current value." + "\nThis may result in the deletion of objects placed in the grid that" + "\ncannot fit within these new dimensions." + "\nFurthermore, agent data that depended on specific coordinates may" + "\nneed to be checked for bugs after resizing." + "\n\nIf you are sure you want to apply these changes, click 'Ok', otherwise click 'No' or 'Cancel'"); if (selection == JOptionPane.YES_OPTION) gm.resizeGrid(newWidth, newHeight); else return; } if (nameField.getText().equals("")) throw new Exception("All fields must have input"); gm.setName(nameField.getText()); for (int i = 0; i < values.size(); i++) if (values.get(i).getText().equals("")) throw new Exception("All fields must have input."); gm.resizeGrid(newWidth, newHeight); gm.setStepLimit(newTime); gm.setSleepPeriod(newDelay); String str = (String) updateBox.getSelectedItem(); if (str.equals("Linear")) gm.setLinearUpdate(); else if (str.equals("Atomic")) gm.setAtomicUpdate(); else gm.setPriorityUpdate(0, 50); for (int i = 0; i < values.size(); i++) { gm.setPopLimit( (String) (agentTypes.get(i).getSelectedItem()), Integer.parseInt(values.get(i).getText())); } load(); } catch (NumberFormatException excep) { JOptionPane .showMessageDialog(null, "Width, Height, and Time fields must be integers greater than 0"); } catch (Exception excep) { JOptionPane.showMessageDialog(null, excep.getMessage()); } } }); } @Override public void load() { reset(); nameField.setText(getGuiManager().getSimName()); updateBox.setSelectedItem(getGuiManager().getCurrentUpdater()); widthField.setText(gm.getGridWidth().toString()); heightField.setText(gm.getGridHeight().toString()); delayField.setText(gm.getSleepPeriod().toString()); SimulatorFacade gm = getGuiManager(); int stepLimit = gm.getStepLimit(); agentNames = gm.getPrototypeNames().toArray(agentNames); timeField.setText(stepLimit + ""); // to prevent accidental starting simulation with time limit of 0 if (stepLimit <= 0) timeField.setText(10 + ""); ImmutableMap<String, Integer> popLimits = gm.getPopLimits(); if (popLimits.size() == 0) { addConditionButton.setEnabled(true); } else { int i = 0; for (String p : popLimits.keySet()) { addCondition(); agentTypes.get(i).setSelectedItem(p); values.get(i).setText(popLimits.get(p) + ""); i++; } } validate(); } private JPanel makeUpperPanel() { JPanel upperPanel = Gui.makePanel(new GridBagLayout(), MaxSize.NULL, PrefSize.NULL, (Component[]) null); JLabel nameLabel = Gui.makeLabel("Name:", new MinSize(50,30)); nameField = Gui.makeTextField(gm.getSimName(), 25, null, new MinSize(150,30)); JLabel widthLabel = Gui.makeLabel("Width:", new MinSize(50,30)); widthField = Gui.makeTextField("10", 5, MaxSize.NULL, new MinSize(50,30)); JLabel yLabel = Gui.makeLabel("Height:", new MinSize(70,30)); heightField = Gui.makeTextField("10", 5, MaxSize.NULL, new MinSize(50,30)); JLabel updateLabel = Gui.makeLabel("Update type:", MaxSize.NULL, null); updateBox = Gui.makeComboBox(new String[] { "Linear", "Atomic", "Priority" }, MaxSize.NULL); updateBox.setMinimumSize(new MinSize(150,30)); //TODO working on adding step delay components JLabel delayLabel = Gui.makeLabel("Step delay:", MaxSize.NULL, null); delayField = Gui.makeTextField("1.0", 5, MaxSize.NULL, new MinSize(150,30)); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(nameLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 0; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(nameField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(widthLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(widthField, c); c = new GridBagConstraints(); c.gridx = 2; c.gridy = 1; c.insets = new Insets(3, 13, 3, 3); upperPanel.add(yLabel, c); c = new GridBagConstraints(); c.gridx = 3; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(heightField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(delayLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 2; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(delayField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 3; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(updateLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 3; c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); upperPanel.add(updateBox, c); validate(); return upperPanel; } private JPanel makeLowerPanel() { JPanel lowerPanel = Gui.makePanel(new GridBagLayout(), MaxSize.NULL, PrefSize.NULL, (Component[]) null); JLabel conHeader = Gui.makeLabel("Ending Conditions", MaxSize.NULL, null); JLabel timeLabel = Gui.makeLabel("Time Limit", MaxSize.NULL, null); timeField = Gui.makeTextField(null, 15, MaxSize.NULL, MinSize.NULL); JLabel agentTypeLabel = Gui.makeLabel("Agent Type", MaxSize.NULL, null); JLabel valueLabel = Gui.makeLabel("Population Limit", MaxSize.NULL, null); conListPanel = makeConditionListPanel(); scrollPane = new JScrollPane(conListPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setPreferredSize(new PrefSize(200,300)); JPanel scrollPaneWrapper = new JPanel(); scrollPaneWrapper.add(scrollPane); GridBagConstraints c = new GridBagConstraints(); c.gridx = 1; c.gridy = 0; c.gridwidth = 3; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(3, 3, 3, 3); lowerPanel.add(conHeader, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 1; c.insets = new Insets(3, 3, 3, 3); c.anchor = c.CENTER; lowerPanel.add(timeLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 1; c.gridwidth = 2; c.insets = new Insets(3, 3, 3, 3); c.anchor = c.CENTER; lowerPanel.add(timeField, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; c.insets = new Insets(15, 3, 3, 3); c.anchor = c.CENTER; lowerPanel.add(agentTypeLabel, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 2; c.insets = new Insets(15, 35, 3, 3); c.anchor = c.CENTER; lowerPanel.add(valueLabel, c); c = new GridBagConstraints(); c.gridx = 0; c.gridy = 3; c.gridwidth = 4; c.insets = new Insets(8, 3, 3, 3); c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.NONE; lowerPanel.add(scrollPaneWrapper,c); validate(); return lowerPanel; } private JPanel makeConditionListPanel() { JPanel conListPanel = Gui.makePanel(BoxLayoutAxis.PAGE_AXIS, null, null); return conListPanel; } private void addCondition() { JComboBox newBox = Gui.makeComboBox(agentNames, MaxSize.NULL); agentTypes.add(newBox); JTextField newValue = Gui.makeTextField(null, 25, MaxSize.NULL, MinSize.NULL); values.add(newValue); JButton newButton = Gui.makeButton("Delete", null, new DeleteListener()); deleteButtons.add(newButton); newButton.setActionCommand(deleteButtons.indexOf(newButton) + ""); JPanel newPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.fill = c.HORIZONTAL; c.insets = new Insets(3, 0, 3, 0); newPanel.add(newBox, c); c = new GridBagConstraints(); c.gridx = 1; c.gridy = 0; c.fill = c.HORIZONTAL; c.insets = new Insets(3, 0, 3, 0); newPanel.add(newValue, c); c = new GridBagConstraints(); c.gridx = 2; c.gridy = 0; c.fill = c.HORIZONTAL; c.insets = new Insets(3, 0, 3, 0); newPanel.add(newButton, c); subPanels.add(newPanel); conListPanel.add(newPanel); validate(); } private void reset() { nameField.setText(""); conListPanel.removeAll(); agentTypes.clear(); values.clear(); deleteButtons.clear(); subPanels.clear(); } private class DeleteListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int n = Integer.parseInt(e.getActionCommand()); String str = (String) agentTypes.get(n).getSelectedItem(); if (str != null) getGuiManager().removePopLimit(str); conListPanel.remove(subPanels.get(n)); agentTypes.remove(n); values.remove(n); deleteButtons.remove(n); for (int i = n; i < deleteButtons.size(); i++) deleteButtons.get(i).setActionCommand( (Integer.parseInt(deleteButtons.get(i) .getActionCommand()) - 1) + ""); subPanels.remove(n); validate(); repaint(); } } }
package de.terrestris.shogun2.web; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.terrestris.shogun2.dao.ImageFileDao; import de.terrestris.shogun2.model.ImageFile; import de.terrestris.shogun2.service.ImageFileService; import de.terrestris.shogun2.util.data.ResultSet; import de.terrestris.shogun2.util.json.Shogun2JsonObjectMapper; /** * * @author Johannes Weskamm * @author Daniel Koch * */ @Controller @RequestMapping("/image") public class ImageFileController<E extends ImageFile, D extends ImageFileDao<E>, S extends ImageFileService<E, D>> extends FileController<E, D, S> { /** * Default constructor, which calls the type-constructor */ @SuppressWarnings("unchecked") public ImageFileController() { this((Class<E>) ImageFile.class); } /** * Constructor that sets the concrete entity class for the controller. * Subclasses MUST call this constructor. */ protected ImageFileController(Class<E> entityClass) { super(entityClass); } /** * We have to use {@link Qualifier} to define the correct service here. * Otherwise, spring can not decide which service has to be autowired here * as there are multiple candidates. */ @Override @Autowired @Qualifier("imageFileService") public void setService(S service) { this.service = service; } /** * Use the object mapper from the spring context, if available (e.g. * {@link Shogun2JsonObjectMapper}). If not available, the default * implementation will be used. */ @Autowired(required = false) private ObjectMapper objectMapper; /** * Persists an image as bytearray in the database * * @param uploadedImage * @return */ @Override @RequestMapping(value = "/upload.action", method = RequestMethod.POST) public ResponseEntity<String> uploadFile( @RequestParam("file") MultipartFile uploadedImage) { LOG.debug("Requested to upload an image"); // build response map Map<String, Object> responseMap = new HashMap<String, Object>(); try { ImageFile imageFile = service.uploadImageFile(uploadedImage); responseMap = ResultSet.success(imageFile); } catch (Exception e) { responseMap = ResultSet.error(e.getMessage()); } // we have to return the response-Map as String to be browser conform. // as this controller is typically being called by a form.submit() the // browser expects a response with the Content-Type header set to // "text/html". HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_HTML); // rewrite the response map as String String responseMapAsString = null; try { // try to use autowired object mapper from spring context ObjectMapper om = (objectMapper != null) ? objectMapper : new ObjectMapper(); responseMapAsString = om.writeValueAsString(responseMap); } catch (JsonProcessingException e) { String errMsg = "Error while rewriting the response Map to a String: " + e.getMessage(); LOG.error(errMsg); // use errorMsg if serialization as json failed responseMapAsString = errMsg; } return new ResponseEntity<String>(responseMapAsString, responseHeaders, HttpStatus.OK); } /** * Gets an image from the database by the given id * * @return * @throws SQLException */ @RequestMapping(value = "/getThumbnail.action", method=RequestMethod.GET) public ResponseEntity<?> getThumbnail(@RequestParam Integer id) { final HttpHeaders responseHeaders = new HttpHeaders(); Map<String, Object> responseMap = new HashMap<String, Object>(); try { // try to get the image ImageFile image = service.findById(id); if(image == null) { throw new Exception("Could not find the image with id " + id); } byte[] imageBytes = null; imageBytes = image.getThumbnail(); responseHeaders.setContentType( MediaType.parseMediaType(image.getFileType())); LOG.info("Successfully got the image thumbnail " + image.getFileName()); return new ResponseEntity<byte[]>( imageBytes, responseHeaders, HttpStatus.OK); } catch (Exception e) { final String errorMessage = "Could not get the image thumbnail: " + e.getMessage(); LOG.error(errorMessage); responseMap = ResultSet.error(errorMessage); responseHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<Map<String, Object>>( responseMap, responseHeaders, HttpStatus.OK); } } /** * @return the objectMapper */ public ObjectMapper getObjectMapper() { return objectMapper; } /** * @param objectMapper the objectMapper to set */ public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } }
package eventdetection.validator; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import toberumono.json.JSONArray; import toberumono.json.JSONBoolean; import toberumono.json.JSONObject; import toberumono.json.JSONString; import toberumono.json.JSONSystem; import toberumono.structures.tuples.Triple; import static eventdetection.common.ThreadingUtils.pool; import eventdetection.common.Article; import eventdetection.common.ArticleManager; import eventdetection.common.DBConnection; import eventdetection.common.Query; import eventdetection.validator.types.Validator; import eventdetection.validator.types.ValidatorType; /** * A class that manages multiple validation algorithms and allows them to run in parallel. * * @author Joshua Lipstone */ public class ValidatorController { private final Connection connection; private final Map<ValidatorType, Map<String, ValidatorWrapper>> validators; private static final Logger logger = LoggerFactory.getLogger("ValidatorController"); private final ArticleManager articleManager; /** * Constructs a {@link ValidatorController} that uses the given {@link Connection} to connect to the database. * * @param connection * a {@link Connection} to the database to be used * @param config * the {@link JSONObject} holding the configuration data */ public ValidatorController(Connection connection, JSONObject config) { this.connection = connection; this.validators = new EnumMap<>(ValidatorType.class); for (ValidatorType vt : ValidatorType.values()) validators.put(vt, new LinkedHashMap<>()); JSONObject paths = (JSONObject) config.get("paths"); JSONObject articles = (JSONObject) config.get("articles"); this.articleManager = new ArticleManager(connection, ((JSONObject) config.get("tables")).get("articles").value().toString(), paths, articles); ((JSONArray) paths.get("validators")).value().stream().map(a -> ((JSONString) a).value()).forEach(s -> { try { loadValidators(((JSONObject) config.get("tables")).get("validators").value().toString(), Paths.get(s)); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | SQLException | IOException e) { logger.warn("Unabile to initialize a validator described in " + s, e); } }); } private void loadValidators(String table, Path path) throws ClassNotFoundException, NoSuchMethodException, SecurityException, SQLException, IOException { if (Files.isRegularFile(path)) { if (path.getFileName().toString().endsWith(".json")) { JSONObject json = (JSONObject) JSONSystem.loadJSON(path); if (!json.containsKey("enabled") || ((JSONBoolean) json.get("enabled")).value()) { ValidatorWrapper vw = new ValidatorWrapper(connection, table, getClass().getClassLoader(), json); validators.get(vw.getType()).put(vw.getName(), vw); } } } else { ClassLoader classloader = new URLClassLoader(new URL[]{path.toUri().toURL()}); try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, p -> p.getFileName().toString().endsWith(".json"))) { for (Path p : stream) { JSONObject json = (JSONObject) JSONSystem.loadJSON(p); if (!json.containsKey("enabled") || ((JSONBoolean) json.get("enabled")).value()) { ValidatorWrapper vw = new ValidatorWrapper(connection, table, classloader, json); validators.get(vw.getType()).put(vw.getName(), vw); } } } } } /** * Main method of the validation program. * * @param args * the command line arguments * @throws IOException * if an I/O error occurs * @throws SQLException * if an SQL error occurs * @throws ClassNotFoundException * if there is an issue loading an {@link Article} */ public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException { Path configPath = null; //The configuration file must be provided int action = 0; Collection<Integer> articleIDs = new LinkedHashSet<>(); Collection<Integer> queryIDs = new LinkedHashSet<>(); for (String arg : args) { if (arg.equalsIgnoreCase("-c")) action = 0; else if (arg.equalsIgnoreCase("-a")) action = 1; else if (arg.equalsIgnoreCase("-q")) action = 2; else if (action == 0) configPath = Paths.get(arg); else if (action == 1) articleIDs.add(Integer.parseInt(arg)); else if (action == 2) queryIDs.add(Integer.parseInt(arg)); } JSONObject config = (JSONObject) JSONSystem.loadJSON(configPath); DBConnection.configureConnection((JSONObject) config.get("database")); try (Connection connection = DBConnection.getConnection()) { ValidatorController vc = new ValidatorController(connection, config); vc.executeValidators(queryIDs, articleIDs); } } private List<Query> loadQueries(Collection<Integer> ids) throws SQLException { List<Query> queries = new ArrayList<>(); try (ResultSet rs = connection.prepareStatement("select * from queries").executeQuery()) { if (ids.size() > 0) { int id = 0; while (ids.size() > 0 && rs.next()) { id = rs.getInt("id"); if (ids.contains(id)) { ids.remove(id); //Prevents queries from being loaded more than once queries.add(new Query(rs)); } } } else { while (rs.next()) queries.add(new Query(rs)); } } if (ids.size() > 0) logger.warn("Did not find queries with ids matching " + ids.stream().reduce("", (a, b) -> a + ", " + b.toString(), (a, b) -> a + b).substring(2)); return queries; } /** * Executes the {@link Validator Validators} registered with the {@link ValidatorController} on the given * {@link Collection} of {@link Query} IDs and {@link Collection} of {@link Article} IDs after loading them from the * database and writes the results to the database. * * @param queryIDs * the IDs of the {@link Query Queries} to be validated * @param articleIDs * the IDs of the {@link Article Articles} against which the {@link Query Queries} are to be validated * @throws SQLException * if an error occurs while reading from or writing to the database * @throws IOException * if an error occurs while securing access to the serialized {@link Article Articles} */ public void executeValidators(Collection<Integer> queryIDs, Collection<Integer> articleIDs) throws SQLException, IOException { long start = System.currentTimeMillis(); synchronized (connection) { Path active = Paths.get(System.getProperty("user.home"), ".event-detection-active"); if (!Files.exists(active)) { Files.createDirectories(active.getParent()); Files.createFile(active); } List<Article> articles = null; try (FileChannel chan = FileChannel.open(active, StandardOpenOption.CREATE, StandardOpenOption.WRITE); FileLock lock = chan.lock();) { articles = articleManager.loadArticles(articleIDs); } executeValidatorsUsingObjects(loadQueries(queryIDs), articles); } System.out.println(System.currentTimeMillis() - start); } /** * Executes the {@link Validator Validators} registered with the {@link ValidatorController} on the given * {@link Collection} of {@link Query} IDs and {@link Collection} of {@link Article} IDs after loading them from the * database and writes the results to the database. * * @param queries * the IDs of the {@link Query Queries} to be validated * @param articles * the IDs of the {@link Article Articles} against which the {@link Query Queries} are to be validated * @throws SQLException * if an error occurs while reading from or writing to the database */ public void executeValidatorsUsingObjects(Collection<Query> queries, Collection<Article> articles) throws SQLException { Collection<Integer> queryIDs = null, articleIDs = null; synchronized (connection) { List<Triple<Integer, Integer, Future<ValidationResult[]>>> results = new ArrayList<>(); for (ValidatorWrapper vw : validators.get(ValidatorType.ManyToMany).values()) { try { results.add(new Triple<>(null, vw.getID(), pool.submit(vw.construct(queries.toArray(new Query[0]), articles.toArray(new Article[0]))))); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Unable to initialize the validator, " + vw.getName() + ", for queries " + (queryIDs == null ? (queryIDs = queries.stream().collect(ArrayList::new, (a, b) -> a.add(b.getID()), ArrayList::addAll)) : queryIDs).toString() + " and articles " + (articleIDs == null ? (articleIDs = articles.stream().collect(ArrayList::new, (a, b) -> a.add(b.getID()), ArrayList::addAll)) : articleIDs).toString(), e); } } for (ValidatorWrapper vw : validators.get(ValidatorType.OneToMany).values()) { for (Query query : queries) { try { results.add(new Triple<>(query.getID(), vw.getID(), pool.submit(vw.construct(query, articles.toArray(new Article[0]))))); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Unable to initialize the validator, " + vw.getName() + ", for query " + query.getID() + " and articles " + (articleIDs == null ? (articleIDs = articles.stream().collect(ArrayList::new, (a, b) -> a.add(b.getID()), ArrayList::addAll)) : articleIDs).toString(), e); } } } for (ValidatorWrapper vw : validators.get(ValidatorType.ManyToOne).values()) { for (Article article : articles) { try { results.add(new Triple<>(null, vw.getID(), pool.submit(vw.construct(queries.toArray(new Query[0]), article)))); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Unable to initialize the validator, " + vw.getName() + ", for queries " + (articleIDs == null ? (articleIDs = articles.stream().collect(ArrayList::new, (a, b) -> a.add(b.getID()), ArrayList::addAll)) : articleIDs).toString() + " and article " + article.getID(), e); } } } //Unfortunately, we can only perform existence checks for one-to-one validation algorithms try (PreparedStatement stmt = connection.prepareStatement("select * from validation_results as vr where vr.query = ? and vr.algorithm = ? and vr.article = ?")) { for (Query query : queries) { stmt.setInt(1, query.getID()); for (Article article : articles) { stmt.setInt(3, article.getID()); for (ValidatorWrapper vw : validators.get(ValidatorType.OneToOne).values()) { stmt.setInt(2, vw.getID()); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) //If we've already processed the current article with the current validator for the current query continue; } try { results.add(new Triple<>(query.getID(), vw.getID(), pool.submit(vw.construct(query, article)))); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Unable to initialize the validator, " + vw.getName() + ", for query " + query.getID() + " and article " + article.getID(), e); } } } } } String statement = "insert into validation_results as vr (query, algorithm, article, validates, invalidates) values (?, ?, ?, ?, ?) " + "ON CONFLICT (query, algorithm, article) DO UPDATE set (validates, invalidates) = (EXCLUDED.validates, EXCLUDED.invalidates)"; //This is valid as of PostgreSQL 9.5 try (PreparedStatement stmt = connection.prepareStatement(statement)) { for (Triple<Integer, Integer, Future<ValidationResult[]>> result : results) { try { ValidationResult[] ress = result.getZ().get(); for (ValidationResult res : ress) { String stringVer = "(" + result.getX() + ", " + result.getY() + ", " + res.getArticleID() + ") -> (" + res.getValidates() + ", " + (res.getInvalidates() == null ? "null" : res.getInvalidates()) + ")"; if (res.getValidates().isNaN() || (res.getInvalidates() != null && res.getInvalidates().isNaN())) { logger.error("Cannot add " + stringVer + " to the database because it has NaN values."); continue; } stmt.setInt(1, res.getQueryID() == null ? result.getX() : res.getQueryID()); stmt.setInt(2, result.getY()); stmt.setInt(3, res.getArticleID()); stmt.setFloat(4, res.getValidates().floatValue()); if (res.getInvalidates() != null) stmt.setFloat(5, res.getInvalidates().floatValue()); else stmt.setNull(5, Types.REAL); stmt.executeUpdate(); logger.info("Added " + stringVer + " to the database."); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } } } } class ValidatorWrapper { private static final Logger logger = LoggerFactory.getLogger("ValidatorWrapper"); private final int algorithmID; private final String name; private final Class<? extends Validator> clazz; private final ValidatorType type; private final Constructor<? extends Validator> constructor; private final JSONObject instanceParameters; private final boolean useInstanceParameters; @SuppressWarnings("unchecked") public ValidatorWrapper(Connection connection, String table, ClassLoader classloader, JSONObject validator) throws SQLException, ClassNotFoundException, NoSuchMethodException, SecurityException { clazz = (Class<? extends Validator>) classloader.loadClass(validator.get("class").value().toString()); name = validator.get("id").value().toString(); type = ValidatorType.valueOf(validator.get("type").value().toString()); JSONObject parameters = (JSONObject) validator.get("parameters"); instanceParameters = parameters != null ? (JSONObject) parameters.get("instance") : null; Class<?>[][] constructorTypes = type.getConstructorArgTypes(); Constructor<? extends Validator> temp = null; if (instanceParameters != null) try { temp = clazz.getConstructor(constructorTypes[0]); } catch (NoSuchMethodException e) { if (instanceParameters != null) logger.warn("Validator " + name + " has declared instance parameters but no constructor for them."); temp = clazz.getConstructor(constructorTypes[1]); } else temp = clazz.getConstructor(constructorTypes[1]); constructor = temp; constructor.setAccessible(true); useInstanceParameters = constructor.getParameterCount() > 2; try (PreparedStatement stmt = connection.prepareStatement("select id from " + table + " as va where va.algorithm = ?")) { stmt.setString(1, name); try (ResultSet rs = stmt.executeQuery()) { rs.next(); algorithmID = rs.getInt("id"); } } if (parameters.containsKey("static")) loadStaticProperties(((JSONObject) parameters.get("static"))); } private void loadStaticProperties(JSONObject properties) { try { Method staticInit = clazz.getMethod("loadStaticParameters", JSONObject.class); staticInit.setAccessible(true); try { staticInit.invoke(null, properties); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Failed to invoke the found static property initialization method for " + name, e); } } catch (NoSuchMethodException | SecurityException e) { logger.warn("Validator " + name + " has declared static parameters but no static parameter initialization method for them."); } } public int getID() { return algorithmID; } public String getName() { return name; } public ValidatorType getType() { return type; } public Validator construct(Object... args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Object[] params; if (useInstanceParameters) params = new Object[]{instanceParameters, args[0], args[1]}; else params = args; return constructor.newInstance(params); } }
package fr.lip6.jkernelmachines.classifier; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import fr.lip6.jkernelmachines.kernel.Kernel; import fr.lip6.jkernelmachines.kernel.SimpleCacheKernel; import fr.lip6.jkernelmachines.kernel.ThreadedKernel; import fr.lip6.jkernelmachines.kernel.adaptative.ThreadedSumKernel; import fr.lip6.jkernelmachines.threading.ThreadPoolServer; import fr.lip6.jkernelmachines.threading.ThreadedMatrixOperator; import fr.lip6.jkernelmachines.type.TrainingSample; import fr.lip6.jkernelmachines.util.DebugPrinter; /** * <p> * Implementation of the SimpleMKL solver.<br/> * Java conversion of the original matlab code. * </p> * * <p> * <b>SimpleMKL</b><br/> * Alain Rakotomamonjy, Francis Bach, Stephane Canu, Yves Grandvalet<br/> * <i>Journal of Machine Learning Research 9 (2008) 2491-2521</i> * </p> * @author dpicard * * @param <T> Datatype of training samples */ public class SimpleMKL<T> implements Classifier<T> { private ArrayList<Kernel<T>> kernels; private ArrayList<Double> kernelWeights; private int maxIteration = 50; private double C = 1.e5; private double numPrec = 1.e-12, epsKTT = 0.1, epsDG = 0.01, epsGS = 1.e-8, eps = 1.e-8; private boolean checkDualGap = true, checkKTT = false; private KernelSVM<T> svm; private DecimalFormat format = new DecimalFormat("#0.0000"); DebugPrinter debug = new DebugPrinter(); public SimpleMKL() { kernels = new ArrayList<Kernel<T>>(); kernelWeights = new ArrayList<Double>(); } /** * adds a kernel to the MKL problem * @param k */ public void addKernel(Kernel<T> k) { if(!kernels.contains(k)) { kernels.add(k); kernelWeights.add(1.0); } } @Override public void train(TrainingSample<T> t) { List<TrainingSample<T>> l = new ArrayList<TrainingSample<T>>(); l.add(t); train(l); } @Override public void train(List<TrainingSample<T>> l) { //caching matrices ArrayList<SimpleCacheKernel<T>> km = new ArrayList<SimpleCacheKernel<T>>(); ArrayList<Double> dm = new ArrayList<Double>(); double dm0 = 1./kernels.size(); for(int i = 0 ; i < kernels.size(); i++) { Kernel<T> k = kernels.get(i); SimpleCacheKernel<T> csk = new SimpleCacheKernel<T>(new ThreadedKernel<T>(k), l); csk.setName(k.toString()); km.add(csk); dm.add(dm0); } // INIT //creating kernel ThreadedSumKernel<T> tsk = buildKernel(km, dm); retrainSVM(tsk, l); double oldObj = svmObj(km, dm, l); ArrayList<Double> grad = gradSVM(km, dm, l); debug.println(1, "iter \t | \t obj \t\t | \t dualgap \t | \t KKT"); debug.println(1, "init \t | \t "+format.format(oldObj)+" \t | \t "+Double.NaN+" \t\t | \t "+Double.NaN); // START boolean loop = true; int iteration = 1; while(loop && iteration < maxIteration) { // UPDATE WEIGHTS double newObj = mklUpdate(grad, km, dm, l); // numerical cleaning double sum = 0; for(int i = 0 ; i < dm.size(); i++) { double d = dm.get(i); if(d < numPrec) d = 0.; sum += d; dm.set(i, d); } for(int i = 0 ; i < dm.size(); i++) { double d = dm.get(i); dm.set(i, d/sum); } //verbosity debug.println(3, "loop : dm after cleaning = "+dm); // approximate KTT condition grad = gradSVM(km, dm, l); debug.println(3, "loop : grad = "+grad); //searching min and max grad for non nul dm double gMin = Double.POSITIVE_INFINITY, gMax = Double.NEGATIVE_INFINITY; for(int i = 0 ; i < dm.size(); i++) { double d = dm.get(i); if(d > 0) { double g = grad.get(i); if(g <= gMin) gMin = g; if(g >= gMax) gMax = g; } } double kttConstraint = Math.abs((gMin-gMax)/gMin); debug.println(3, "Condition check : KTT gmin = "+gMin+" gmax = "+gMax); //searching grad min over zeros dm double gZeroMin = Double.POSITIVE_INFINITY; for(int i = 0 ; i < km.size(); i++) { if(dm.get(i) < numPrec) { double g = grad.get(i); if(g < gZeroMin) gZeroMin = g; } } boolean kttZero = (gZeroMin > gMax)?true:false; // Duality gap //searching -grad max double max = -Double.MAX_VALUE; for(int i = 0 ; i < dm.size(); i++) { double g = -grad.get(i); if(g > max) max = g; } //computing sum alpha sum = 0.; double alp[] = svm.getAlphas(); for(int i = 0 ; i < alp.length; i++) if(alp[i] > 0) sum += alp[i]; double dualGap = (newObj + max - sum)/newObj; // Verbosity debug.println(1, "iter \t | \t obj \t\t | \t dualgap \t | \t KKT"); debug.println(1, iteration+" \t | \t "+format.format(newObj)+" \t | \t "+format.format(dualGap)+" \t | \t "+format.format(kttConstraint)); // STOP CRITERIA boolean stop = false; //ktt if(kttConstraint < epsKTT && kttZero && checkKTT) { debug.println(1, "KTT conditions met, possible stoping"); stop = true; } //dualgap if(dualGap < epsDG && checkDualGap) { debug.println(1, "DualGap reached, possible stoping"); stop = true; } //stagnant gradient if(Math.abs(oldObj - newObj) < numPrec) { debug.println(1, "No improvement during iteration, stoping (old : "+oldObj+" new : "+newObj+")"); stop = true; } if(stop) loop = false; //storing newObj oldObj = newObj; iteration++; } kernelWeights = dm; //creating kernel tsk = buildKernel(km, dm); retrainSVM(tsk, l); //stop threads ThreadPoolServer.shutdownNow(); } /** * computing the objective function value * @param km * @param dm * @param l * @return */ private double svmObj(List<SimpleCacheKernel<T>> km, List<Double> dm, final List<TrainingSample<T>> l) { debug.print(3, "["); //creating kernel ThreadedSumKernel<T> k = buildKernel(km, dm); SimpleCacheKernel<T> csk = new SimpleCacheKernel<T>(k, l); double kmatrix[][] = csk.getKernelMatrix(l); debug.print(3, "-"); //updating svm retrainSVM(csk, l); final double alp[] = svm.getAlphas(); debug.print(3, "-"); //verbosity debug.println(4, "svmObj : alphas = "+Arrays.toString(alp)); // debug.println(4, "svmObj : b="+svm.getB()); //parallelized final double[] resLine = new double[kmatrix.length]; ThreadedMatrixOperator objFactory = new ThreadedMatrixOperator() { @Override public void doLines(double[][] matrix, int from , int to) { for(int index = from ; index < to ; index++) { if(alp[index] > 0) { double al1 = alp[index] * l.get(index).label; for(int j = 0 ; j < matrix[index].length ; j++) { if(alp[j] > 0) resLine[index] += al1 * alp[j] * l.get(j).label * matrix[index][j]; } } } } }; objFactory.getMatrix(kmatrix); double obj1 = 0; for(double d : resLine) obj1 += d; double obj2 = 0; for(int i = 0; i < l.size(); i++) if(alp[i] > 0) obj2 += alp[i]; double obj = -0.5 * obj1 + obj2; debug.print(3, "]"); if(obj < 0) { debug.println(1, "A fatal error occured, please report to picard@ensea.fr"); debug.println(1, "error obj : "+obj+" obj1:"+obj1+" obj2:"+obj2); debug.println(1, "alp : "+Arrays.toString(alp)); debug.println(1, "resline : "+Arrays.toString(resLine)); System.exit(0); return Double.POSITIVE_INFINITY; } return obj; } /** * computing the gradient of the objective function * @param km * @param dm * @param l * @return */ private ArrayList<Double> gradSVM(List<SimpleCacheKernel<T>> km, List<Double> dm, final List<TrainingSample<T>> l) { //creating kernel ThreadedSumKernel<T> tsk = buildKernel(km, dm); //updating svm retrainSVM(tsk, l); final double alp[] = svm.getAlphas(); //computing grad ArrayList<Double> grad = new ArrayList<Double>(); for(int i = 0 ; i < km.size(); i++) { Kernel<T> k = km.get(i); double kmatrix[][] = k.getKernelMatrix(l); //parallelized final double[] resLine = new double[kmatrix.length]; ThreadedMatrixOperator gradFactory = new ThreadedMatrixOperator() { @Override public void doLines(double[][] matrix , int from , int to) { for(int index = from ; index < to ; index++) { if(alp[index] > 0) { double al1 = -0.5 * alp[index] * l.get(index).label; for(int j = 0 ; j < matrix[index].length ; j++) { resLine[index] += al1 * alp[j] * l.get(j).label * matrix[index][j]; } } } } }; gradFactory.getMatrix(kmatrix); double g = 0; for(double d : resLine) g += d; grad.add(i, g); } return grad; } /** * performs an update of the weights in the mkl * @param km * @param dm * @param l * @return value of objective fonction */ private double mklUpdate(List<Double> gradOld, List<SimpleCacheKernel<T>> km, List<Double> dmOld, List<TrainingSample<T>> l) { //save ArrayList<Double> dm = new ArrayList<Double>(); dm.addAll(dmOld); ArrayList<Double> grad = new ArrayList<Double>(); grad.addAll(gradOld); //init obj double costMin = svmObj(km, dm, l); double costOld = costMin; //norme du gradient double normGrad = 0; for(int i = 0 ; i < grad.size(); i++) normGrad += grad.get(i)*grad.get(i); normGrad = Math.sqrt(normGrad); for(int i = 0 ; i < grad.size(); i++) { double g = grad.get(i)/normGrad; grad.set(i, g); } //finding max dm double max = -Double.MAX_VALUE; int indMax = 0; for(int i = 0 ; i < dm.size(); i++) { double d = dm.get(i); if(d > max) { max = d; indMax = i; } } double gradMax = grad.get(indMax); //reduced gradient ArrayList<Double> desc = new ArrayList<Double>(); double sum = 0; for(int i = 0; i < dm.size(); i++) { grad.set(i, grad.get(i)- gradMax); double d = - grad.get(i); if(!(dm.get(i) > 0 || grad.get(i) < 0)) d = 0; sum += -d; desc.add(i, d); } desc.set(indMax, sum); // NB : grad.get(indMax) == 0 //verbosity debug.println(3, "mklupdate : grad = "+grad); debug.println(3, "mklupdate : desc = "+desc); //optimal stepsize double stepMax = Double.POSITIVE_INFINITY; for(int i = 0 ; i < desc.size(); i++) { double d = desc.get(i); if(d < 0) { double min = - dm .get(i)/d; if(min < stepMax) stepMax = min; } } if(Double.isInfinite(stepMax) || stepMax == 0) return costMin; if(stepMax > 0.1) stepMax = 0.1; //small loop double costMax = 0; while(costMax < costMin) { ArrayList<Double> dmNew = new ArrayList<Double>(); for(int i = 0 ; i < dm.size(); i++) { dmNew.add(i, dm.get(i) + desc.get(i)*stepMax); } //verbosity debug.println(3, "* descent : dm = "+dmNew); costMax = svmObj(km, dmNew, l); if(costMax < costMin) { costMin = costMax; dm = dmNew; //numerical cleaning //empty //keep direction in admisible cone for(int i = 0; i < desc.size(); i++) { double d = 0; if((dm.get(i) > numPrec || desc.get(i) > 0)) d = desc.get(i); desc.set(i, d); } sum = 0; for(int i = 0 ; i < indMax; i++) sum += desc.get(i); for(int i = indMax+1; i < desc.size(); i++) sum += desc.get(i); desc.set(indMax, -sum); //nex stepMap stepMax = Double.POSITIVE_INFINITY; for(int i = 0 ; i < desc.size(); i++) { double d = desc.get(i); if(d < 0) { double Dm = dm.get(i); if(Dm < numPrec) Dm = 0.; double min = - Dm/d; if(min < stepMax) stepMax = min; } } if(Double.isInfinite(stepMax)) stepMax = 0.; else costMax = 0; } //verbosity debug.print(2, "*"); debug.println(3, " descent : costMin : "+costMin+" costOld : "+costOld+" stepMax : "+stepMax); } //verbosity debug.println(3, "mklupdate : dm after descent = "+dm); // Golden Search double stepMin = 0; int indMin = 0; double gold = (1. + Math.sqrt(5))/2.; ArrayList<Double> cost = new ArrayList<Double>(4); cost.add(0, costMin); cost.add(1, 0.); cost.add(2, 0.); cost.add(3, costMax); ArrayList<Double> step = new ArrayList<Double>(4); step.add(0, 0.); step.add(1, 0.); step.add(2, 0.); step.add(3, stepMax); double deltaMax = stepMax; while(stepMax-stepMin > epsGS*deltaMax && stepMax > eps) { double stepMedR = stepMin +(stepMax-stepMin)/gold; double stepMedL = stepMin +(stepMedR-stepMin)/gold; //setting cost array cost.set(0, costMin); cost.set(3, costMax); //setting step array step.set(0, stepMin); step.set(3, stepMax); //cost medr ArrayList<Double> dMedR = new ArrayList<Double>(); for(int i = 0 ; i < dm.size(); i++) { double d = dm.get(i); dMedR.add(i, d + desc.get(i)*stepMedR); } double costMedR = svmObj(km, dMedR, l); //cost medl ArrayList<Double> dMedL = new ArrayList<Double>(); for(int i = 0 ; i < dm.size(); i++) { double d= dm.get(i); dMedL.add(i, d + desc.get(i)*stepMedL); } double costMedL = svmObj(km, dMedL, l); cost.set(1, costMedL); step.set(1, stepMedL); cost.set(2, costMedR); step.set(2, stepMedR); //search min cost double min = Double.POSITIVE_INFINITY; indMin = -1; for(int i = 0 ; i < 4; i++) { if(cost.get(i) < min) { indMin = i; min = cost.get(i); } } debug.println(3, "golden search : cost = ["+costMin+" "+costMedL+" "+costMedR+" "+costMax+"]"); debug.println(3, "golden search : step = ["+stepMin+" "+stepMedL+" "+stepMedR+" "+stepMax+"]"); debug.println(3, "golden search : costOpt="+cost.get(indMin)+" costOld="+costOld); //update search switch(indMin) { case 0: stepMax = stepMedL; costMax = costMedL; break; case 1: stepMax = stepMedR; costMax = costMedR; break; case 2: stepMin = stepMedL; costMin = costMedL; break; case 3: stepMin = stepMedR; costMin = costMedR; break; default: debug.println(1, "Error in golden search."); return costMin; } //verbosity debug.print(2, "."); } //verbosity debug.println(2, ""); //final update double costNew = cost.get(indMin); double stepNew = step.get(indMin); dmOld.clear(); dmOld.addAll(dm); if(costNew < costOld) { for(int i = 0 ; i < dmOld.size(); i++) { double d = dm.get(i); dmOld.set(i, d + desc.get(i)*stepNew); } } //creating kernel ThreadedSumKernel<T> tsk = buildKernel(km, dm); //updating svm retrainSVM(tsk, l); //verbosity debug.print(3, "mklupdate : dm = "+dmOld); return costNew; } private ThreadedSumKernel<T> buildKernel(List<SimpleCacheKernel<T>> km, List<Double> dm) { long startTime = System.currentTimeMillis(); ThreadedSumKernel<T> tsk = new ThreadedSumKernel<T>(); for(int i = 0 ; i < km.size(); i++) if(dm.get(i) > numPrec) tsk.addKernel(km.get(i), dm.get(i)); long stopTime = System.currentTimeMillis() - startTime; debug.println(3, "building kernel : time="+stopTime); return tsk; } /** * update svm classifier (update alphas) * * @param k * @param l */ private void retrainSVM(Kernel<T> k, List<TrainingSample<T>> l) { //default svm algorithm is lasvm if(svm == null) { LaSVM<T> lasvm = new LaSVM<T>(k); lasvm.setE(2); svm = lasvm; } //new settings svm.setKernel(k); svm.setC(C); svm.train(l); } @Override public double valueOf(T e) { return svm.valueOf(e); } /** * Tells the weights of the samples * @return an array of double representing the weights */ public double[] getTrainingWeights() { return svm.getAlphas(); } /** * Tells the weights of the kernels * @return an array of double representing the weights */ public double[] getKernelWeights() { double dm[] = new double[kernelWeights.size()]; for(int i = 0 ; i < dm.length; i++) dm[i] = kernelWeights.get(i); return dm; } /** * associative table of kernels and their corresponding weights * @return a Map indexing pairs of <Kernel, Weight> */ public Map<Kernel<T>, Double> getWeights() { Map<Kernel<T>, Double> hash = new HashMap<Kernel<T>, Double>(); for(int i = 0 ; i < kernels.size(); i++) { hash.put(kernels.get(i), kernelWeights.get(i)); } return hash; } /** * Tells the values of hyperparameter C * @return C */ public double getC() { return C; } /** * Sets the value of the hyperparameter C * @param c the hyperparameter C */ public void setC(double c) { C = c; } /** * Tells the value of stopping criteria * @return the dual gap */ public double getDualGap() { return epsDG; } /** * Sets the value of the stopping criteria * @param epsDG the dual gap */ public void setDualGap(double epsDG) { this.epsDG = epsDG; } /** * Sets the default training algorithm for the underlying svm calls (default LASVM). * @param cls the algorithm used to solve the svm problem */ public void setClassifier(KernelSVM<T> cls) { svm = cls; } /** * Creates and returns a copy of this object. * @see java.lang.Object#clone() */ @SuppressWarnings("unchecked") @Override public SimpleMKL<T> copy() throws CloneNotSupportedException { return (SimpleMKL<T>) super.clone(); } /** * Returns the list of kernels * @return kernels */ public List<Kernel<T>> getKernels() { return kernels; } /** * Returns the classifier used by this MKL algorithm * @return svm */ public KernelSVM<T> getClassifier() { return svm; } }
package org.devgateway.ocvn.web.rest.controller; import static org.springframework.data.mongodb.core.aggregation.Aggregation.group; import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit; import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation; import static org.springframework.data.mongodb.core.aggregation.Aggregation.skip; import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort; import static org.springframework.data.mongodb.core.aggregation.Aggregation.unwind; import static org.springframework.data.mongodb.core.query.Criteria.where; import java.util.List; import javax.validation.Valid; import org.devgateway.ocvn.web.rest.controller.request.DefaultFilterPagingRequest; import org.devgateway.ocvn.web.rest.controller.request.GroupingFilterPagingRequest; import org.devgateway.toolkit.persistence.mongo.aggregate.CustomProjectionOperation; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; /** * * @author mpostelnicu * */ @RestController public class CostEffectivenessVisualsController extends GenericOcvnController { @RequestMapping("/api/costEffectivenessAwardAmount") public List<DBObject> costEffectivenessAwardAmount(@Valid DefaultFilterPagingRequest filter) { DBObject project = new BasicDBObject(); project.put("year", new BasicDBObject("$year", "$tender.tenderPeriod.endDate")); project.put("awards.value.amount", 1); Aggregation agg = newAggregation( match(where("awards").elemMatch(where("status").is("active")).and("tender.value").exists(true)), getMatchDefaultFilterOperation(filter) ,unwind("$awards"), match(where("awards.status").is("active").and("awards.value").exists(true)), new CustomProjectionOperation(project), group("$year").sum("$awards.value.amount").as("totalAwardAmount"), sort(Direction.DESC,"totalAwardAmount"), skip(filter.getSkip()), limit(filter.getPageSize()) ); AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class); List<DBObject> tagCount = results.getMappedResults(); return tagCount; } @RequestMapping("/api/costEffectivenessTenderAmount") public List<DBObject> costEffectivenessTenderAmount(@Valid GroupingFilterPagingRequest filter) { DBObject project = new BasicDBObject(); project.put("year", new BasicDBObject("$year", "$tender.tenderPeriod.endDate")); project.put("tender.value.amount", 1); project.putAll(filterProjectMap); Aggregation agg = newAggregation( match(where("awards").elemMatch(where("status").is("active")).and("tender.value").exists(true)), getMatchDefaultFilterOperation(filter), new CustomProjectionOperation(project), getTopXFilterOperation(filter,"$year").sum("$tender.value.amount").as("totalTenderAmount"), sort(Direction.DESC,"totalTenderAmount"), skip(filter.getSkip()), limit(filter.getPageSize()) ); AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class); List<DBObject> tagCount = results.getMappedResults(); return tagCount; } }
package org.devgateway.ocvn.web.rest.controller.request; import java.util.List; import cz.jirutka.validator.collection.constraints.EachPattern; /** * @author mihai * Filtering bean applied to all endpoints */ public class DefaultFilterPagingRequest extends GenericPagingRequest { @EachPattern(regexp = "^[a-zA-Z0-9]*$") List<String> bidTypeId; @EachPattern(regexp = "^[a-zA-Z0-9]*$") List<String> procuringEntityId; List<String> bidSelectionMethod; /** * This parameter will invert (negate) all existing filtering parameters. So * A IN B turns into A NOT IN B. A IN B AND AN IN C turns into A NOT IN B * AND A NOT IN C. So this is NOT exactly a logical *not*, the correct way * would be !(A && B) = !A || !B. Which is not what we do here, but we * actually dont use multiple parameters anywhere, so it should not matter * now */ Boolean invert=false; public DefaultFilterPagingRequest() { super(); } public List<String> getBidTypeId() { return bidTypeId; } public void setBidTypeId(List<String> bidTypeId) { this.bidTypeId = bidTypeId; } public List<String> getProcuringEntityId() { return procuringEntityId; } public void setProcuringEntityId(List<String> procuringEntityId) { this.procuringEntityId = procuringEntityId; } public List<String> getBidSelectionMethod() { return bidSelectionMethod; } public void setBidSelectionMethod(List<String> bidSelectionMethod) { this.bidSelectionMethod = bidSelectionMethod; } public Boolean getInvert() { return invert; } public void setInvert(Boolean invert) { this.invert = invert; } }
package org.knowm.xchange.quadrigacx.service; import static org.knowm.xchange.dto.Order.OrderType.BID; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.trade.*; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException; import org.knowm.xchange.quadrigacx.QuadrigaCxAdapters; import org.knowm.xchange.quadrigacx.dto.QuadrigaCxException; import org.knowm.xchange.quadrigacx.dto.trade.QuadrigaCxOrder; import org.knowm.xchange.quadrigacx.dto.trade.QuadrigaCxUserTransaction; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderByIdParams; import org.knowm.xchange.service.trade.params.CancelOrderParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamOffset; import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamsSorted; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamMultiCurrencyPair; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; public class QuadrigaCxTradeService extends QuadrigaCxTradeServiceRaw implements TradeService { /** * Constructor * * @param exchange */ public QuadrigaCxTradeService(Exchange exchange) { super(exchange); } @Override public OpenOrders getOpenOrders() throws IOException, QuadrigaCxException { return getOpenOrders(createOpenOrdersParams()); } @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { Collection<CurrencyPair> currencyPairs; if (params instanceof OpenOrdersParamMultiCurrencyPair) { currencyPairs = ((OpenOrdersParamMultiCurrencyPair) params).getCurrencyPairs(); } else if (params instanceof OpenOrdersParamCurrencyPair) { currencyPairs = Collections.singletonList(((OpenOrdersParamCurrencyPair) params).getCurrencyPair()); } else { currencyPairs = exchange.getExchangeSymbols(); } List<LimitOrder> limitOrders = new ArrayList<>(); for (CurrencyPair pair : currencyPairs) { QuadrigaCxOrder[] openOrders = getQuadrigaCxOpenOrders(pair); for (QuadrigaCxOrder quadrigaCxOrder : openOrders) { OrderType orderType = quadrigaCxOrder.getType() == 0 ? OrderType.BID : OrderType.ASK; String id = quadrigaCxOrder.getId(); BigDecimal price = quadrigaCxOrder.getPrice(); limitOrders.add(new LimitOrder(orderType, quadrigaCxOrder.getAmount(), pair, id, quadrigaCxOrder.getTime(), price)); } } return new OpenOrders(limitOrders); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException, QuadrigaCxException { QuadrigaCxOrder quadrigacxOrder; if (marketOrder.getType() == BID) { quadrigacxOrder = buyQuadrigaCxOrder(marketOrder.getCurrencyPair(), marketOrder.getOriginalAmount()); } else { quadrigacxOrder = sellQuadrigaCxOrder(marketOrder.getCurrencyPair(), marketOrder.getOriginalAmount()); } if (quadrigacxOrder.getErrorMessage() != null) { throw new ExchangeException(quadrigacxOrder.getErrorMessage()); } return quadrigacxOrder.getId(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException, QuadrigaCxException { QuadrigaCxOrder quadrigacxOrder; if (limitOrder.getType() == BID) { quadrigacxOrder = buyQuadrigaCxOrder(limitOrder.getCurrencyPair(), limitOrder.getOriginalAmount(), limitOrder.getLimitPrice()); } else { quadrigacxOrder = sellQuadrigaCxOrder(limitOrder.getCurrencyPair(), limitOrder.getOriginalAmount(), limitOrder.getLimitPrice()); } if (quadrigacxOrder.getErrorMessage() != null) { throw new ExchangeException(quadrigacxOrder.getErrorMessage()); } return quadrigacxOrder.getId(); } @Override public String placeStopOrder(StopOrder stopOrder) throws IOException { throw new NotYetImplementedForExchangeException(); } @Override public boolean cancelOrder(String orderId) throws IOException, QuadrigaCxException { return cancelQuadrigaCxOrder(orderId); } @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByIdParams) { return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); } else { return false; } } /** * Required parameter types: {@link TradeHistoryParamPaging#getPageLength()} * <p/> * Warning: using a limit here can be misleading. The underlying call retrieves trades, withdrawals, and deposits. So the example here will limit * the result to 17 of those types and from those 17 only trades are returned. It is recommended to use the raw service demonstrated below if you * want to use this feature. */ @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { Long limit = null; CurrencyPair currencyPair = null; Long offset = null; String sort = null; if (params instanceof TradeHistoryParamPaging) { limit = Long.valueOf(((TradeHistoryParamPaging) params).getPageLength()); } if (params instanceof TradeHistoryParamOffset) { offset = ((TradeHistoryParamOffset) params).getOffset(); } if (params instanceof TradeHistoryParamsSorted) { TradeHistoryParamsSorted.Order order = ((TradeHistoryParamsSorted) params).getOrder(); if (order != null) { if (order.equals(TradeHistoryParamsSorted.Order.asc)) sort = "asc"; else sort = "desc"; } } if (params instanceof TradeHistoryParamCurrencyPair) { currencyPair = ((TradeHistoryParamCurrencyPair) params).getCurrencyPair(); } QuadrigaCxUserTransaction[] txs = getQuadrigaCxUserTransactions(currencyPair, limit, offset, sort); return QuadrigaCxAdapters.adaptTradeHistory(txs, currencyPair); } @Override public TradeHistoryParams createTradeHistoryParams() { return new QuadrigaCxTradeHistoryParams(CurrencyPair.BTC_CAD, 1000); } @Override public OpenOrdersParams createOpenOrdersParams() { return null; } @Override public Collection<Order> getOrder( String... orderIds) throws IOException { throw new NotYetImplementedForExchangeException(); } }
package org.xwiki.rendering.listener; import java.util.LinkedList; import java.util.Map; import org.xwiki.rendering.listener.chaining.EventType; import org.xwiki.rendering.syntax.Syntax; /** * Manage a {@link java.util.Queue} of events. * * @version $Id$ * @since 2.1M1 */ public class QueueListener extends LinkedList<QueueListener.Event> implements Listener { /** * Class ID for serialization. */ private static final long serialVersionUID = 2869508092440006345L; /** * An event. * * @version $Id$ */ public class Event { /** * The type of the event. */ public EventType eventType; /** * The parameters of the event. */ public Object[] eventParameters; /** * @param eventType the type of the event * @param eventParameters the parameters of the event */ public Event(EventType eventType, Object[] eventParameters) { this.eventType = eventType; this.eventParameters = eventParameters; } } /** * Returns the event at the specified position in this queue. * * @param depth index of event to return. * @return the evnet at the specified position in this queue. */ public Event getEvent(int depth) { Event event = null; if (depth > 0 && size() > depth - 1) { event = get(depth - 1); } return event; } /** * Send all stored events to provided {@link Listener}. * * @param listener the {@link Listener} on which to send events */ public void consumeEvents(Listener listener) { while (!isEmpty()) { Event event = remove(); event.eventType.fireEvent(listener, event.eventParameters); } } /** * Store provided event. * * @param eventType the type of the event * @param objects the parameters of the event */ private void saveEvent(EventType eventType, Object... objects) { offer(new Event(eventType, objects)); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginDefinitionDescription() */ public void beginDefinitionDescription() { saveEvent(EventType.BEGIN_DEFINITION_DESCRIPTION); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginDefinitionList(java.util.Map) * @since 2.0RC1 */ public void beginDefinitionList(Map<String, String> parameters) { saveEvent(EventType.BEGIN_DEFINITION_LIST, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginDefinitionTerm() */ public void beginDefinitionTerm() { saveEvent(EventType.BEGIN_DEFINITION_TERM); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginDocument(java.util.Map) */ public void beginDocument(Map<String, String> parameters) { saveEvent(EventType.BEGIN_DOCUMENT, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginGroup(Map) */ public void beginGroup(Map<String, String> parameters) { saveEvent(EventType.BEGIN_GROUP, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginFormat(org.xwiki.rendering.listener.Format, java.util.Map) */ public void beginFormat(Format format, Map<String, String> parameters) { saveEvent(EventType.BEGIN_FORMAT, format, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginHeader(org.xwiki.rendering.listener.HeaderLevel, * java.lang.String, java.util.Map) */ public void beginHeader(HeaderLevel level, String id, Map<String, String> parameters) { saveEvent(EventType.BEGIN_HEADER, level, id, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginLink(org.xwiki.rendering.listener.Link, boolean, java.util.Map) */ public void beginLink(Link link, boolean isFreeStandingURI, Map<String, String> parameters) { saveEvent(EventType.BEGIN_LINK, link, isFreeStandingURI, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginList(org.xwiki.rendering.listener.ListType, java.util.Map) */ public void beginList(ListType listType, Map<String, String> parameters) { saveEvent(EventType.BEGIN_LIST, listType, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginListItem() */ public void beginListItem() { saveEvent(EventType.BEGIN_LIST_ITEM); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginMacroMarker(java.lang.String, java.util.Map, java.lang.String, * boolean) */ public void beginMacroMarker(String name, Map<String, String> parameters, String content, boolean isInline) { saveEvent(EventType.BEGIN_MACRO_MARKER, name, parameters, content, isInline); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginParagraph(java.util.Map) */ public void beginParagraph(Map<String, String> parameters) { saveEvent(EventType.BEGIN_PARAGRAPH, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginQuotation(java.util.Map) */ public void beginQuotation(Map<String, String> parameters) { saveEvent(EventType.BEGIN_QUOTATION, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginQuotationLine() */ public void beginQuotationLine() { saveEvent(EventType.BEGIN_QUOTATION_LINE); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginSection(java.util.Map) */ public void beginSection(Map<String, String> parameters) { saveEvent(EventType.BEGIN_SECTION, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginTable(java.util.Map) */ public void beginTable(Map<String, String> parameters) { saveEvent(EventType.BEGIN_TABLE, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginTableCell(java.util.Map) */ public void beginTableCell(Map<String, String> parameters) { saveEvent(EventType.BEGIN_TABLE_CELL, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginTableHeadCell(java.util.Map) */ public void beginTableHeadCell(Map<String, String> parameters) { saveEvent(EventType.BEGIN_TABLE_HEAD_CELL, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#beginTableRow(java.util.Map) */ public void beginTableRow(Map<String, String> parameters) { saveEvent(EventType.BEGIN_TABLE_ROW, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endDefinitionDescription() */ public void endDefinitionDescription() { saveEvent(EventType.END_DEFINITION_DESCRIPTION); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endDefinitionList(java.util.Map) * @since 2.0RC1 */ public void endDefinitionList(Map<String, String> parameters) { saveEvent(EventType.END_DEFINITION_LIST, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endDefinitionTerm() */ public void endDefinitionTerm() { saveEvent(EventType.END_DEFINITION_TERM); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endDocument(java.util.Map) */ public void endDocument(Map<String, String> parameters) { saveEvent(EventType.END_DOCUMENT, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endGroup(Map) */ public void endGroup(Map<String, String> parameters) { saveEvent(EventType.END_GROUP, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endFormat(org.xwiki.rendering.listener.Format, java.util.Map) */ public void endFormat(Format format, Map<String, String> parameters) { saveEvent(EventType.END_FORMAT, format, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endHeader(org.xwiki.rendering.listener.HeaderLevel, java.lang.String, * java.util.Map) */ public void endHeader(HeaderLevel level, String id, Map<String, String> parameters) { saveEvent(EventType.END_HEADER, level, id, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endLink(org.xwiki.rendering.listener.Link, boolean, java.util.Map) */ public void endLink(Link link, boolean isFreeStandingURI, Map<String, String> parameters) { saveEvent(EventType.END_LINK, link, isFreeStandingURI, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endList(org.xwiki.rendering.listener.ListType, java.util.Map) */ public void endList(ListType listType, Map<String, String> parameters) { saveEvent(EventType.END_LIST, listType, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endListItem() */ public void endListItem() { saveEvent(EventType.END_LIST_ITEM); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endMacroMarker(java.lang.String, java.util.Map, java.lang.String, * boolean) */ public void endMacroMarker(String name, Map<String, String> parameters, String content, boolean isInline) { saveEvent(EventType.END_MACRO_MARKER, name, parameters, content, isInline); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endParagraph(java.util.Map) */ public void endParagraph(Map<String, String> parameters) { saveEvent(EventType.END_PARAGRAPH, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endQuotation(java.util.Map) */ public void endQuotation(Map<String, String> parameters) { saveEvent(EventType.END_QUOTATION, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endQuotationLine() */ public void endQuotationLine() { saveEvent(EventType.END_QUOTATION_LINE); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endSection(java.util.Map) */ public void endSection(Map<String, String> parameters) { saveEvent(EventType.END_SECTION, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endTable(java.util.Map) */ public void endTable(Map<String, String> parameters) { saveEvent(EventType.END_TABLE, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endTableCell(java.util.Map) */ public void endTableCell(Map<String, String> parameters) { saveEvent(EventType.END_TABLE_CELL, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endTableHeadCell(java.util.Map) */ public void endTableHeadCell(Map<String, String> parameters) { saveEvent(EventType.END_TABLE_HEAD_CELL, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#endTableRow(java.util.Map) */ public void endTableRow(Map<String, String> parameters) { saveEvent(EventType.END_TABLE_ROW, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onRawText(String, Syntax) */ public void onRawText(String text, Syntax syntax) { saveEvent(EventType.ON_RAW_TEXT, text, syntax); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onEmptyLines(int) */ public void onEmptyLines(int count) { saveEvent(EventType.ON_EMPTY_LINES, count); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onHorizontalLine(java.util.Map) */ public void onHorizontalLine(Map<String, String> parameters) { saveEvent(EventType.ON_HORIZONTAL_LINE, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onId(java.lang.String) */ public void onId(String name) { saveEvent(EventType.ON_ID, name); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onImage(org.xwiki.rendering.listener.Image, boolean, java.util.Map) */ public void onImage(Image image, boolean isFreeStandingURI, Map<String, String> parameters) { saveEvent(EventType.ON_IMAGE, image, isFreeStandingURI, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onMacro(java.lang.String, java.util.Map, java.lang.String, boolean) */ public void onMacro(String id, Map<String, String> parameters, String content, boolean isInline) { saveEvent(EventType.ON_MACRO, id, parameters, content, isInline); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onNewLine() */ public void onNewLine() { saveEvent(EventType.ON_NEW_LINE); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onSpace() */ public void onSpace() { saveEvent(EventType.ON_SPACE); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onSpecialSymbol(char) */ public void onSpecialSymbol(char symbol) { saveEvent(EventType.ON_SPECIAL_SYMBOL, symbol); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onVerbatim(String, boolean, Map) */ public void onVerbatim(String protectedString, boolean isInline, Map<String, String> parameters) { saveEvent(EventType.ON_VERBATIM, protectedString, isInline, parameters); } /** * {@inheritDoc} * * @see org.xwiki.rendering.listener.Listener#onWord(java.lang.String) */ public void onWord(String word) { saveEvent(EventType.ON_WORD, word); } }
package com.parrot.arsdk.arsal; import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import android.annotation.TargetApi; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothGattDescriptor; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.bluetooth.BluetoothAdapter; import android.content.IntentFilter; import android.content.pm.PackageManager; import com.parrot.arsdk.arsal.ARSALPrint; @TargetApi(18) public class ARSALBLEManager { private static String TAG = "ARSALBLEManager"; private static final UUID ARSALBLEMANAGER_CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); private static final int ARSALBLEMANAGER_CONNECTION_TIMEOUT_SEC = 5; private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics; private Context context; private BluetoothDevice deviceBLEService; private BluetoothGatt activeGatt; private ARSALBLEManagerListener listener; private HashMap<String, ARSALManagerNotification> registeredNotificationCharacteristics = new HashMap<String, ARSALManagerNotification>(); private Semaphore connectionSem; private Semaphore disconnectionSem; private Semaphore discoverServicesSem; private Semaphore discoverCharacteristicsSem; private Semaphore configurationSem; private ARSAL_ERROR_ENUM discoverServicesError; private ARSAL_ERROR_ENUM discoverCharacteristicsError; private ARSAL_ERROR_ENUM configurationCharacteristicError; private ARSAL_ERROR_ENUM writeCharacteristicError; private boolean askDisconnection; private boolean isDiscoveringServices; private boolean isDiscoveringCharacteristics; private boolean isConfiguringCharacteristics; public class ARSALManagerNotificationData { public BluetoothGattCharacteristic characteristic = null; public byte[] value = null; public ARSALManagerNotificationData(BluetoothGattCharacteristic _characteristic, byte[] _value) { this.characteristic = _characteristic; this.value = _value; } } public class ARSALManagerNotification { private Semaphore readCharacteristicSem = new Semaphore(0); private Lock readCharacteristicMutex = new ReentrantLock(); List<BluetoothGattCharacteristic> characteristics = null; ArrayList<ARSALManagerNotificationData> notificationsArray = new ArrayList<ARSALManagerNotificationData>(); public ARSALManagerNotification(List<BluetoothGattCharacteristic> characteristicsArray) { this.characteristics = characteristicsArray; } void addNotification(ARSALManagerNotificationData notificationData) { readCharacteristicMutex.lock(); notificationsArray.add(notificationData); readCharacteristicMutex.unlock(); synchronized (readCharacteristicSem) { readCharacteristicSem.notify(); } } int getAllNotification(List<ARSALManagerNotificationData> getNoticationsArray, int maxCount) { ArrayList<ARSALManagerNotificationData> removeNotifications = new ArrayList<ARSALManagerNotificationData>(); readCharacteristicMutex.lock(); for (int i=0; (i < maxCount) && (i < notificationsArray.size()); i++) { ARSALManagerNotificationData notificationData = notificationsArray.get(i); getNoticationsArray.add(notificationData); removeNotifications.add(notificationData); } for (int i=0; (i < removeNotifications.size()); i++) { notificationsArray.remove(removeNotifications.get(i)); } readCharacteristicMutex.unlock(); return getNoticationsArray.size(); } boolean waitNotification() { boolean ret = true; try { readCharacteristicSem.acquire(); } catch (InterruptedException e) { ret = false; } return ret; } void signalNotification() { readCharacteristicSem.release(); } } private static class ARSALBLEManagerHolder { private final static ARSALBLEManager instance = new ARSALBLEManager(); } public static ARSALBLEManager getInstance(Context context) { ARSALBLEManager manager = ARSALBLEManagerHolder.instance; manager.setContext(context); return manager; } private synchronized void setContext(Context context) { if (this.context == null) { if (context == null) { throw new IllegalArgumentException("Context must not be null"); } this.context = context; } } /** * Constructor */ private ARSALBLEManager () { this.context = null; this.deviceBLEService = null; this.activeGatt = null; listener = null; connectionSem = new Semaphore (0); disconnectionSem = new Semaphore (0); discoverServicesSem = new Semaphore (0); discoverCharacteristicsSem = new Semaphore (0); configurationSem = new Semaphore (0); askDisconnection = false; isDiscoveringServices = false; isDiscoveringCharacteristics = false; isConfiguringCharacteristics = false; discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_OK; discoverCharacteristicsError = ARSAL_ERROR_ENUM.ARSAL_OK; configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_OK; } /** * Destructor */ public void finalize () throws Throwable { try { disconnect (); } finally { super.finalize (); } } public boolean isDeviceConnected() { boolean ret = false; synchronized (this) { if (activeGatt != null) { ret = true; } } return ret; } @TargetApi(18) public ARSAL_ERROR_ENUM connect (BluetoothDevice deviceBLEService) { ARSAL_ERROR_ENUM result = ARSAL_ERROR_ENUM.ARSAL_OK; synchronized (this) { /* if there is an active activeGatt, disconnecting it */ if (activeGatt != null) { disconnect(); } /* connection to the new activeGatt */ this.deviceBLEService = deviceBLEService; BluetoothGatt gatt = deviceBLEService.connectGatt (context, false, gattCallback); /* wait the connect semaphore*/ try { connectionSem.tryAcquire (ARSALBLEMANAGER_CONNECTION_TIMEOUT_SEC, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (activeGatt != null) { // TODO see } else { /* Connection failed */ gatt.close(); /* Connection failed */ result = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_CONNECTION; } } return result; } public void disconnect () { //synchronized (this) if (activeGatt != null) { askDisconnection = true; activeGatt.disconnect(); ARSALPrint.d(TAG, "wait the disconnect Semaphore"); /* wait the disconnect Semaphore*/ try { //disconnectionSem.acquire (); boolean acquire = disconnectionSem.tryAcquire (ARSALBLEMANAGER_CONNECTION_TIMEOUT_SEC, TimeUnit.SECONDS); if(!acquire) { onDisconectGatt(); } } catch (InterruptedException e) { e.printStackTrace(); } askDisconnection = false; } } public ARSAL_ERROR_ENUM discoverBLENetworkServices () { ARSAL_ERROR_ENUM result = ARSAL_ERROR_ENUM.ARSAL_OK; synchronized (this) { /* If there is an active Gatt, disconnect it */ if (activeGatt != null) { isDiscoveringServices = true; discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_OK; /* run the discovery of the activeGatt services */ boolean discoveryRes = activeGatt.discoverServices(); if (discoveryRes) { /* wait the discoverServices semaphore*/ try { discoverServicesSem.acquire (); result = discoverServicesError; } catch (InterruptedException e) { e.printStackTrace(); result = ARSAL_ERROR_ENUM.ARSAL_ERROR; } } else { result = ARSAL_ERROR_ENUM.ARSAL_ERROR; } isDiscoveringServices = false; } else { result = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; } } return result; } public BluetoothGatt getGatt () { return activeGatt; } public void setListener(ARSALBLEManagerListener listener) { this.listener = listener; } private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { String intentAction; if (newState == BluetoothProfile.STATE_CONNECTED) { ARSALPrint.d(TAG, "Connected to GATT server."); activeGatt = gatt; /* post a connect Semaphore */ connectionSem.release(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { if ((activeGatt != null) && (activeGatt == activeGatt)) { onDisconectGatt(); } } } @Override // New services discovered public void onServicesDiscovered (BluetoothGatt gatt, int status) { if (status != BluetoothGatt.GATT_SUCCESS) { /* the discovery is not successes */ discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_SERVICES_DISCOVERING; } discoverServicesSem.release(); } @Override /* Result of a characteristic read operation */ public void onCharacteristicRead (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //Do Nothing } @Override public void onDescriptorRead (BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { //Do Nothing } @Override public void onDescriptorWrite (BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { /* check the status */ if (status != BluetoothGatt.GATT_SUCCESS) { configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_CHARACTERISTIC_CONFIGURING; } /* post a configuration Semaphore */ configurationSem.release(); } @Override /* Characteristic notification */ /*public void onCharacteristicChanged (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { readCharacteristicMutex.lock(); characteristicNotifications.add(characteristic); readCharacteristicMutex.unlock(); // post a readCharacteristic Semaphore readCharacteristicSem.release(); }*/ public void onCharacteristicChanged (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { ARSALManagerNotification foundNotification = null; Set<String> keys = registeredNotificationCharacteristics.keySet(); for (String key : keys) { ARSALManagerNotification notification = registeredNotificationCharacteristics.get(key); for (BluetoothGattCharacteristic characteristicItem : notification.characteristics) { if (characteristicItem.getUuid().toString().contentEquals(characteristic.getUuid().toString())) { foundNotification = notification; break; } } if (foundNotification != null) { break; } } if (foundNotification != null) { byte[] value = characteristic.getValue(); byte[] newValue = null; if (value != null) { newValue = new byte[value.length]; System.arraycopy(value, 0, newValue, 0, value.length); } else { newValue = new byte[0]; } ARSALManagerNotificationData notificationData = new ARSALManagerNotificationData(characteristic, newValue); foundNotification.addNotification(notificationData); foundNotification.signalNotification(); } } //Characteristic.WRITE_TYPE_NO_RESPONSE dosen't have reply /*@Override public void onCharacteristicWrite (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //ARSALPrint.d(TAG, "onCharacteristicWrite " + status); }*/ }; public ARSAL_ERROR_ENUM setCharacteristicNotification (BluetoothGattService service, BluetoothGattCharacteristic characteristic) { ARSAL_ERROR_ENUM result = ARSAL_ERROR_ENUM.ARSAL_OK; synchronized (this) { BluetoothGatt localActiveGatt = activeGatt; /* If there is an active Gatt, disconnect it */ if(localActiveGatt != null) { isConfiguringCharacteristics = true; configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_OK; boolean notifSet = localActiveGatt.setCharacteristicNotification (characteristic, true); BluetoothGattDescriptor descriptor = characteristic.getDescriptor(ARSALBLEMANAGER_CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID); boolean valueSet = descriptor.setValue (BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); boolean descriptorWriten = localActiveGatt.writeDescriptor (descriptor); /* wait the configuration semaphore*/ try { configurationSem.acquire (); result = configurationCharacteristicError; } catch (InterruptedException e) { e.printStackTrace(); result = ARSAL_ERROR_ENUM.ARSAL_ERROR; } isConfiguringCharacteristics = false; } else { result = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; } } return result; } public boolean writeData (byte data[], BluetoothGattCharacteristic characteristic) { boolean result = false; BluetoothGatt localActiveGatt = activeGatt; if ((localActiveGatt != null) && (characteristic != null) && (data != null)) { characteristic.setValue(data); characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); result = localActiveGatt.writeCharacteristic(characteristic); } return result; } //public void registerNotificationCharacteristics(ArrayList<BluetoothGattCharacteristic> characteristicsArray, String readCharacteristicKey) public void registerNotificationCharacteristics(List<BluetoothGattCharacteristic> characteristicsArray, String readCharacteristicKey) { this.registeredNotificationCharacteristics.put(readCharacteristicKey, new ARSALManagerNotification(characteristicsArray)); } public boolean unregisterNotificationCharacteristics(String readCharacteristicKey) { boolean result = false; ARSALManagerNotification notification = this.registeredNotificationCharacteristics.get(readCharacteristicKey); if (notification != null) { result = true; registeredNotificationCharacteristics.remove(notification); } return result; } public boolean cancelReadNotification(String readCharacteristicKey) { boolean result = false; ARSALManagerNotification notification = this.registeredNotificationCharacteristics.get(readCharacteristicKey); if (notification != null) { result = true; notification.signalNotification(); } return result; } public boolean readData(BluetoothGattCharacteristic characteristic) { return activeGatt.readCharacteristic(characteristic); } public boolean readDataNotificationData (List<ARSALManagerNotificationData> notificationsArray, int maxCount, String readCharacteristicKey) { boolean result = false; ARSALManagerNotification notification = this.registeredNotificationCharacteristics.get(readCharacteristicKey); if (notification != null) { notification.waitNotification(); if (notification.notificationsArray.size() > 0) { notification.getAllNotification(notificationsArray, maxCount); result = true; } } return result; } /*public boolean readData (List<BluetoothGattCharacteristic> characteristicArray) { boolean result = false; // wait the readCharacteristic semaphore try { readCharacteristicSem.acquire (); if (characteristicNotifications.size() > 0) { readCharacteristicMutex.lock(); characteristicArray.addAll(characteristicNotifications); characteristicNotifications.clear(); readCharacteristicMutex.unlock(); result = true; } } catch (InterruptedException e) { e.printStackTrace(); } return result; }*/ public void unlock () { /* post all Semaphore to unlock the all the functions */ connectionSem.release(); configurationSem.release(); discoverServicesSem.release(); discoverCharacteristicsSem.release(); //readCharacteristicSem.release(); for (String key : registeredNotificationCharacteristics.keySet()) { ARSALManagerNotification notification = registeredNotificationCharacteristics.get(key); notification.signalNotification(); } /* disconnectionSem is not post because: * if the connection is fail, disconnect is not call. * if the connection is successful, the BLE callback is always called. * the disconnect function is called after the join of the network threads. */ //TODO } public void reset () { synchronized (this) { /* reset all Semaphores */ while (connectionSem.tryAcquire() == true) { /* Do nothing*/ } while (disconnectionSem.tryAcquire() == true) { /* Do nothing*/ } while (discoverServicesSem.tryAcquire() == true) { /* Do nothing*/ } while (discoverCharacteristicsSem.tryAcquire() == true) { /* Do nothing*/ } /*while (readCharacteristicSem.tryAcquire() == true) {*/ /* Do nothing*/ while (configurationSem.tryAcquire() == true) { /* Do nothing*/ } for (String key : registeredNotificationCharacteristics.keySet()) { ARSALManagerNotification notification = registeredNotificationCharacteristics.get(key); notification.signalNotification(); } registeredNotificationCharacteristics.clear(); //TODO if (activeGatt != null) { activeGatt.close(); activeGatt = null; } } } private void onDisconectGatt() { ARSALPrint.d(TAG, "activeGatt disconnected" ); if (activeGatt != null) { activeGatt.close(); activeGatt = null; } /* Post disconnectionSem only if the disconnect is asked */ if (askDisconnection) { disconnectionSem.release(); } /* if activePeripheral is discovering services */ if (isDiscoveringServices) { discoverServicesError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; discoverServicesSem.release(); } /* if activePeripheral is discovering Characteristics */ if (isDiscoveringCharacteristics) { discoverCharacteristicsError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; discoverCharacteristicsSem.release(); } /* if activePeripheral is configuring Characteristics */ if (isConfiguringCharacteristics) { configurationCharacteristicError = ARSAL_ERROR_ENUM.ARSAL_ERROR_BLE_NOT_CONNECTED; configurationSem.release(); } /* Notify listener */ if (!askDisconnection) { if (listener != null) { listener.onBLEDisconnect(); } } } }
package com.java110.api.listener.inspectionRoute; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.api.bmo.inspection.IInspectionBMO; import com.java110.api.listener.AbstractServiceApiListener; import com.java110.core.annotation.Java110Listener; import com.java110.core.context.DataFlowContext; import com.java110.core.smo.inspectionRoute.IInspectionRoutePointRelInnerServiceSMO; import com.java110.dto.inspectionRoute.InspectionRoutePointRelDto; import com.java110.entity.center.AppService; import com.java110.event.service.api.ServiceDataFlowEvent; import com.java110.utils.constant.BusinessTypeConstant; import com.java110.utils.constant.CommonConstant; import com.java110.utils.constant.ServiceCodeInspectionRouteConstant; import com.java110.utils.util.Assert; import com.java110.utils.util.BeanConvertUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import java.util.List; /** * * add by wuxw 2019-06-30 */ @Java110Listener("deleteInspectionRoutePointListener") public class DeleteInspectionRoutePointListener extends AbstractServiceApiListener { @Autowired private IInspectionBMO inspectionBMOImpl; @Autowired private IInspectionRoutePointRelInnerServiceSMO inspectionRoutePointRelInnerServiceSMOImpl; @Override protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) { //Assert.hasKeyAndValue(reqJson, "xxx", "xxx"); Assert.hasKeyAndValue(reqJson, "inspectionRouteId", ""); Assert.hasKeyAndValue(reqJson, "inspectionId", ""); Assert.hasKeyAndValue(reqJson, "communityId", "ID"); } @Override protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) { HttpHeaders header = new HttpHeaders(); context.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, "D"); JSONArray businesses = new JSONArray(); AppService service = event.getAppService(); businesses.add(deleteInspectionRoute(reqJson, context)); ResponseEntity<String> responseEntity = inspectionBMOImpl.callService(context, service.getServiceCode(), businesses); context.setResponseEntity(responseEntity); } @Override public String getServiceCode() { return ServiceCodeInspectionRouteConstant.DELETE_INSPECTIONROUTE_POINT; } @Override public HttpMethod getHttpMethod() { return HttpMethod.POST; } @Override public int getOrder() { return DEFAULT_ORDER; } /** * * * @param paramInJson * @param dataFlowContext * @return */ private JSONObject deleteInspectionRoute(JSONObject paramInJson, DataFlowContext dataFlowContext) { InspectionRoutePointRelDto inspectionRoutePointRelDto = new InspectionRoutePointRelDto(); inspectionRoutePointRelDto.setCommunityId(paramInJson.getString("communityId")); inspectionRoutePointRelDto.setInspectionId(paramInJson.getString("inspectionId")); inspectionRoutePointRelDto.setInspectionRouteId(paramInJson.getString("inspectionRouteId")); List<InspectionRoutePointRelDto> inspectionRoutePointRelDtos = inspectionRoutePointRelInnerServiceSMOImpl.queryInspectionRoutePointRels(inspectionRoutePointRelDto); Assert.listOnlyOne(inspectionRoutePointRelDtos, " "); JSONObject business = JSONObject.parseObject("{\"datas\":{}}"); business.put(CommonConstant.HTTP_BUSINESS_TYPE_CD, BusinessTypeConstant.BUSINESS_TYPE_DELETE_INSPECTION_ROUTE_POINT_REL); business.put(CommonConstant.HTTP_SEQ, DEFAULT_SEQ); business.put(CommonConstant.HTTP_INVOKE_MODEL, CommonConstant.HTTP_INVOKE_MODEL_S); JSONObject businessInspectionRoute = new JSONObject(); businessInspectionRoute.putAll(BeanConvertUtil.beanCovertMap(inspectionRoutePointRelDtos.get(0))); business.getJSONObject(CommonConstant.HTTP_BUSINESS_DATAS).put("businessInspectionRoutePointRel", businessInspectionRoute); return business; } }
package com.projectattitude.projectattitude.Activities; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.PopupMenu; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ToggleButton; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.projectattitude.projectattitude.Adapters.MoodMainAdapter; import com.projectattitude.projectattitude.Controllers.ElasticSearchUserController; import com.projectattitude.projectattitude.Controllers.MainController; import com.projectattitude.projectattitude.Controllers.UserController; import com.projectattitude.projectattitude.Objects.FilterDecorator; import com.projectattitude.projectattitude.Objects.FilterDecoratorHandler; import com.projectattitude.projectattitude.Objects.FilterEmotionDecorator; import com.projectattitude.projectattitude.Objects.FilterTimeDecorator; import com.projectattitude.projectattitude.Objects.FilterTriggerDecorator; import com.projectattitude.projectattitude.Objects.Mood; import com.projectattitude.projectattitude.Objects.NetWorkChangeReceiver; import com.projectattitude.projectattitude.Objects.User; import com.projectattitude.projectattitude.R; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterCore; import com.twitter.sdk.android.tweetcomposer.TweetComposer; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import io.fabric.sdk.android.Fabric; public class MainActivity extends AppCompatActivity { protected ArrayList<Mood> moodList = new ArrayList<Mood>(); //Holds user's own moods, may be filtered protected ArrayList<Mood> followingOriginalMoodList = new ArrayList<Mood>(); //Holds original followed moods without filter protected ArrayList<Mood> followingMoodList = new ArrayList<Mood>(); //Holds followed moods, may be filtered private ArrayList<String> usersFollowed; private MoodMainAdapter moodAdapter; private MoodMainAdapter followingMoodAdapater; private ListView moodListView; private MainController controller; private Integer itemPosition; private String sortingDate; private ToggleButton toggle; private UserController userController = UserController.getInstance(); private FilterDecorator filterDecorator = null; //Private variables for sorting/filtering private static final String LOG_TAG = "CheckNetworkStatus"; private NetWorkChangeReceiver receiver; private boolean isConnected = false; private ArrayList<User> users = new ArrayList<User>(); private int listItem; //This is the index of the item pressed in the list // Network listener to sync when connecting to network NetWorkChangeReceiver netWorkChangeReceiver = new NetWorkChangeReceiver() { @Override public void onReceive(Context context, Intent intent){ if(isNetworkAvailable()){ //if(ElasticSearchUserController.getInstance().deleteUser(userController.getActiveUser())){ // ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); // addUserTask.execute(UserController.getInstance().getActiveUser()); ElasticSearchUserController.UpdateUserTask updateUserTask = new ElasticSearchUserController.UpdateUserTask(); updateUserTask.execute(UserController.getInstance().getActiveUser()); } } }; @Override protected void onCreate(Bundle savedInstanceState) { controller = new MainController(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //get passed user from LoginActivity final User user = (User) getIntent().getSerializableExtra("PassUserToMain"); userController.setActiveUser(user); moodListView = (ListView) findViewById(R.id.moodListView); toggle = (ToggleButton) findViewById(R.id.moodToggle); //This function allows for the infinite scrollings and loading of "pages" for the moodView //moodListView.setOnScrollListener(new EndlessScrollListener()); // renable when ElasticSearch is modifed to allow pagination //adapter is fed from moodList inside user moodAdapter = new MoodMainAdapter(this, moodList); followingMoodAdapater = new MoodMainAdapter(this, followingMoodList); //moodAdapter = new MoodMainAdapter(this, userController.getActiveUser().getMoodList()); if(toggle.isChecked()){ moodListView.setAdapter(moodAdapter); } else{ moodListView.setAdapter(followingMoodAdapater); } //Load user and mood, and update current displayed list userController.loadFromFile(getApplicationContext()); sortingDate = "Sort"; refreshMoodList(); //This function populates the list of moods from people being followed usersFollowed = userController.getActiveUser().getFollowList(); if(usersFollowed != null){ for(int i = 0; i < usersFollowed.size(); i++){ String stringFollowedUser = usersFollowed.get(i); ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); try { User followedUser = getUserTask.execute(stringFollowedUser).get(); if(followedUser != null){ if(followedUser.getFirstMood() != null){ followingOriginalMoodList.add(followedUser.getFirstMood()); //Populate both an unfiltered mood list and filtered moodlist followingMoodList.add(followedUser.getFirstMood()); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } registerForContextMenu(moodListView); /** * This handles clicking on a mood taking the user to a mood view */ moodListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intentView = new Intent(MainActivity.this, ViewMoodActivity.class); if(toggle.isChecked()){ intentView.putExtra("mood", moodList.get(position)); } else{ intentView.putExtra("mood", followingMoodList.get(position)); } startActivityForResult(intentView, 1); } }); ElasticSearchUserController.UpdateUserTask updateUserTask = new ElasticSearchUserController.UpdateUserTask(); updateUserTask.execute(UserController.getInstance().getActiveUser()); userController.saveInFile(getApplicationContext()); registerReceiver(netWorkChangeReceiver, new IntentFilter("networkConnectBroadcast")); //TODO is crashing the app sometimes when returning from the profile page // twitter init // https://docs.fabric.io/android/twitter/installation.html#twitter-kit-login TwitterAuthConfig authConfig = new TwitterAuthConfig("consumerKey", "consumerSecret"); Fabric.with(this, new TwitterCore(authConfig), new TweetComposer()); try{ ArrayList<Mood> tempList = userController.getActiveUser().getMoodList(); Log.d("moodlist1", tempList.toString()); refreshMoodList(); Log.d("moodList2", moodList.toString()); } catch(Exception e){ Log.d("Error", "Failed to get the moods from the async object"); } // Floating action menu final FloatingActionMenu fabMenu = (FloatingActionMenu) findViewById(R.id.main_fab_menu); FloatingActionButton fabAddMood = (FloatingActionButton) findViewById(R.id.fabAddMood); FloatingActionButton fabMap = (FloatingActionButton) findViewById(R.id.fabMap); FloatingActionButton fabProfile = (FloatingActionButton) findViewById(R.id.fabProfile); FloatingActionButton fabLogout = (FloatingActionButton) findViewById(R.id.fabLogout); FloatingActionButton fabNotifications = (FloatingActionButton) findViewById(R.id.fabNotification); FloatingActionButton fabMapRadius = (FloatingActionButton) findViewById(R.id.fabMapRadius); // on click listener for adding moods fabAddMood.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { fabMenu.close(true); createMood(); } }); /** * Handles clicking on the map button, taking either the users moods or their followed list */ fabMap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fabMenu.close(true); if(toggle.isChecked()){ //user moods Intent viewMapIntent = new Intent(MainActivity.this, MapActivity.class); viewMapIntent.putExtra("user", moodList); startActivityForResult(viewMapIntent, 0); } else{ //following Intent viewMapIntent = new Intent(MainActivity.this, MapActivity.class); viewMapIntent.putExtra("user", followingMoodList); startActivityForResult(viewMapIntent, 0); } // Intent viewMapIntent = new Intent(MainActivity.this, MapActivity.class); // viewMapIntent.putExtra("user", moodList); // startActivityForResult(viewMapIntent, 0); } }); /** * Handles the 5km radius button */ fabMapRadius.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ ElasticSearchUserController.GetAllUsersTask getAllUsersTask = new ElasticSearchUserController.GetAllUsersTask(); try { users = getAllUsersTask.execute("").get(); } catch(Exception e){ } Intent viewMapIntent = new Intent(MainActivity.this, MapActivity.class); viewMapIntent.putExtra("users", users); // viewMapIntent.putExtra("flag", 1); startActivity(viewMapIntent); } }); /** * Takes the user to the profile */ fabProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fabMenu.close(true); Intent intent = new Intent(MainActivity.this, ViewProfileActivity.class); if (moodList.size() > 0) { intent.putExtra("mood", userController.getActiveUser().getMoodList().get(0)); } User user1 = new User(); ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); try{ user1 = getUserTask.execute(user.getUserName()).get(); userController.setActiveUser(user1); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } intent.putExtra("user", user1); //intent.putExtra("user", user); startActivityForResult(intent, 3); } }); /** * Logs the user out and returns them to login screen */ fabLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fabMenu.close(true); userController.clearCache(getApplicationContext()); Intent intent = new Intent(MainActivity.this, LoginActivity.class); finish(); startActivity(intent); } }); /** * Takes the user to their notifications */ fabNotifications.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fabMenu.close(true); Intent intent = new Intent(MainActivity.this, ViewNotificationsActivity.class); User user1 = new User(); ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); try{ user1 = getUserTask.execute(user.getUserName()).get(); userController.setActiveUser(user1); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } userController.saveInFile(getApplicationContext()); intent.putExtra("user", user1); startActivityForResult(intent, 3); } }); /** * This handles the toggle button to alternate between your mood list and the mood list of * people you are following. */ toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // The toggle is enabled, or its set to my moods registerForContextMenu(moodListView); moodListView.setAdapter(moodAdapter); } else { // The toggle is disabled, or it is set to followed moods unregisterForContextMenu(moodListView); moodListView.setAdapter(followingMoodAdapater); if (isNetworkAvailable()) { populateFollowing(); refreshMoodList(); } userController.saveInFile(getApplicationContext()); } //Have to re-filter mood when changing mood lists filterMood(); } }); //Sorting and filtering menu final Context activityContext = this; final ImageButton SFButton = (ImageButton) findViewById(R.id.filterButton); ImageButton SearchButton = (ImageButton) findViewById(R.id.searchButton); ImageButton ClearButton = (ImageButton) findViewById(R.id.clearButton); /** * This menu button handles interactions with sorting and filtering. */ SFButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(activityContext, SFButton); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { //Listener for Sort/Filter Menu @Override public boolean onMenuItemClick(MenuItem item) { PopupMenu popup = new PopupMenu(activityContext, SFButton); MenuInflater inflater = popup.getMenuInflater(); FilterDecorator foundDecorator; switch(item.getItemId()){ case R.id.dateOption: item.setChecked(true); sortMood("Sort"); break; case R.id.reverseDateOption: item.setChecked(true); sortMood("Reverse Sort"); break; case R.id.timeOption: inflater.inflate(R.menu.time_menu, popup.getMenu()); foundDecorator = FilterDecoratorHandler.find(filterDecorator, "Time"); if(foundDecorator != null){ findItemInMenu(popup.getMenu(), foundDecorator.getFilterParameter()).setChecked(true); } //On-click handler for time menu popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item){ if(!item.isChecked()){ //If turning on filter, add/replace filter in decorator filterDecorator = FilterDecoratorHandler.findAndReplace(filterDecorator, new FilterTimeDecorator(item.getTitle().toString())); }else{ //If turning off filter, delete filter in decorator filterDecorator = FilterDecoratorHandler.findAndDelete(filterDecorator, "Time"); } filterMood(); item.setChecked(item.isChecked()); return false; } }); popup.show(); break; case R.id.emotionOption: inflater.inflate(R.menu.mood_menu, popup.getMenu()); foundDecorator = FilterDecoratorHandler.find(filterDecorator, "Emotion"); if(foundDecorator != null){ findItemInMenu(popup.getMenu(), foundDecorator.getFilterParameter()).setChecked(true); } //On-click handler for emotion menu popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item){ if(!item.isChecked()){ //If turning on filter, add/replace filter in decorator filterDecorator = FilterDecoratorHandler.findAndReplace(filterDecorator, new FilterEmotionDecorator(item.getTitle().toString())); }else{ //If turning off filter, delete filter in decorator filterDecorator = FilterDecoratorHandler.findAndDelete(filterDecorator, "Emotion"); } filterMood(); item.setChecked(item.isChecked()); return false; } }); popup.show(); break; case R.id.allOption: //Delete all filters and refresh data filterDecorator = null; findViewById(R.id.clearButton).setVisibility(View.INVISIBLE); userController.loadFromFile(getApplicationContext()); refreshMoodList(); moodAdapter.notifyDataSetChanged(); break; } return false; } });//Code End of Listener for Sort/Filter Menu MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.sort_filter_menu, popup.getMenu()); //Set up checkables Menu popupMenu = popup.getMenu(); if(sortingDate.equals("Sort")){ popupMenu.findItem(R.id.dateOption).setChecked(true); }else if (sortingDate.equals("Reverse Sort")){ popupMenu.findItem(R.id.reverseDateOption).setChecked(true); } if(FilterDecoratorHandler.find(filterDecorator, "Time") != null){ //If currently filtering for time, check the time menu box popupMenu.findItem(R.id.timeOption).setChecked(true); } if(FilterDecoratorHandler.find(filterDecorator, "Emotion") != null){ //If currently filtering for emotion, check the emotion menu box popupMenu.findItem(R.id.emotionOption).setChecked(true); } popup.show(); } }); /** * Search for triggers using the text box */ SearchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Enter new trigger filter into decorator head filterDecorator = FilterDecoratorHandler.findAndReplace(filterDecorator, new FilterTriggerDecorator(((EditText)findViewById(R.id.searchBar)).getText().toString())); filterMood(); findViewById(R.id.clearButton).setVisibility(View.VISIBLE); //Make clear button visible } }); /** * Clears the search bar */ ClearButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { filterDecorator = FilterDecoratorHandler.findAndDelete(filterDecorator, "Trigger"); filterMood(); findViewById(R.id.clearButton).setVisibility(View.INVISIBLE); //Make clear button visible } }); } /** * Clean up when the activity finishes. */ @Override protected void onDestroy(){ super.onDestroy(); unregisterReceiver(netWorkChangeReceiver); //Make sure to unregister receiver to avoid android complaining } /** * This method will take the user to the Create Mood view */ private void createMood(){ Intent createMoodIntent = new Intent(MainActivity.this, CreateMoodActivity.class); createMoodIntent.putExtra("username", userController.getActiveUser().getUserName()); startActivityForResult(createMoodIntent, 0); } /** * This method takes a mood the user made and brings them to the edit mood view */ private void editMood(Mood returnedMood){ Mood moodCheck = userController.getActiveUser().getMoodList().get(itemPosition); Log.d("moodCheckEdit", moodCheck.getEmotionState() + " " + moodCheck.getMoodDate() + " " + moodCheck.getTrigger() + " " + moodCheck.getSocialSituation()); userController.getActiveUser().getMoodList().set(itemPosition, returnedMood); MainController.sortList(userController.getActiveUser().getMoodList(),"Sort"); //Sort inside moods incase anything changed userController.saveInFile(getApplicationContext()); filterMood(); //Calls refreshMoodList moodAdapter.notifyDataSetChanged(); Log.d("editing", userController.getActiveUser().getMoodList().get(itemPosition).toString()); //updating db ElasticSearchUserController.UpdateUserTask updateUserTask = new ElasticSearchUserController.UpdateUserTask(); updateUserTask.execute(UserController.getInstance().getActiveUser()); } /** * This deletes a selected mood. * @param i, the integer of the moodList to be removed */ private void deleteMood(Integer i){ //Log.d("deleting", moodList.get(i).toString()); //Mood delMood = moodList.get(i); Log.d("deleting", userController.getActiveUser().getMoodList().get(i).toString()); //Mood moodCheck = userController.getActiveUser().getMoodList().get(itemPosition); //Log.d("moodCheckDelete", moodCheck.getEmotionState() + " " + moodCheck.getMoodDate() + " " + moodCheck.getTrigger() + " " + moodCheck.getSocialSituation()); ArrayList<Mood> tmpList = userController.getActiveUser().getMoodList(); for (int j = 0; j < tmpList.size(); j++) { if (tmpList.get(j).equals(moodList.get(i))) { Mood delMood = userController.getActiveUser().getMoodList().get(j); Mood moodCheck = userController.getActiveUser().getMoodList().get(j); Log.d("moodCheckDelete", moodCheck.getEmotionState() + " " + moodCheck.getMoodDate() + " " + moodCheck.getTrigger() + " " + moodCheck.getSocialSituation()); //moodList = controller.getMyMoodList().getMoodList(); //moodList.remove(delMood); userController.getActiveUser().getMoodList().remove(delMood); //controller.setMyMoodList(new MoodList(moodList)); //Log.d("deleting", moodList.get(i).toString()); userController.saveInFile(getApplicationContext()); Log.d("userController deleted", userController.getActiveUser().getMoodList().toString()); filterMood(); //Calls refreshMoodList moodAdapter.notifyDataSetChanged(); break; } } //updating db ElasticSearchUserController.UpdateUserTask updateUserTask = new ElasticSearchUserController.UpdateUserTask(); updateUserTask.execute(UserController.getInstance().getActiveUser()); } /** * Handles sorting the list, called when an item in the sortMenu is pressed * @param dateSort - specifies the type of sort to sort. * Three options: "null", "Sort", "Reverse Sort" */ public void sortMood(String dateSort){ if(dateSort != null){ sortingDate = dateSort; } if(toggle.isChecked()){ //sort my moods controller.sortList(moodList, sortingDate); moodAdapter.notifyDataSetChanged(); }else{ //sort following moods controller.sortList(followingMoodList, sortingDate); followingMoodAdapater.notifyDataSetChanged(); } } /** * Handles filtering the list (multi-filtering included) */ public void filterMood(){ refreshMoodList(); if(filterDecorator != null){ if(toggle.isChecked()){//filter my moods Log.d("Error", "Filtering MyMoodList"); filterDecorator.filter(moodList); //Go through filter decorator moodAdapter.notifyDataSetChanged(); } else{ //filter following moods Log.d("Error", "Filtering FollowingMoodList"); filterDecorator.filter(followingMoodList); //Go through filter decorator followingMoodAdapater.notifyDataSetChanged(); } } } /** * findItemInMenu * Given a menu and a menuitem, attempts to find the menuitem in menu * If no menu item found, returns null */ public MenuItem findItemInMenu(Menu menu, String stringToCheck){ MenuItem checkedItem = null; int menuSize = menu.size(); //Loop through filter by time menu looking for checked option for(int i = 0; i < menuSize; i++){ checkedItem = menu.getItem(i); if(stringToCheck.equals(checkedItem.getTitle().toString())){ //Break loop when checked item is found break; } } return checkedItem; } /** * refreshMood - Used to refresh the mood list with the most current moods. * Currently works by using the global variable moodList */ public void refreshMoodList(){ if(toggle.isChecked()){ //viewing my moods moodList.clear(); moodList.addAll(userController.getActiveUser().getMoodList()); moodAdapter.notifyDataSetChanged(); }else{ //viewing following moods followingMoodList.clear(); followingMoodList.addAll(followingOriginalMoodList); followingMoodAdapater.notifyDataSetChanged(); } sortMood(null); } /** * accept returned information from activities * requestCode 0 = Add mood * requestCode 1 = View mood -- resultCode 2 = delete, 3 = Edit Mood * requestCode 2 = Edit Mood * requestCode 3 = User's followList may have changed * @param requestCode the activity to go to * @param resultCode the code returned by that activity * @param data the intent that contains any information with it */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Mood returnedMood; Log.d("Error", "Returning to MainActivity"); if (requestCode == 0) { if (resultCode == RESULT_OK) { returnedMood = (Mood) data.getSerializableExtra("addMoodIntent"); userController.getActiveUser().getMoodList().add(returnedMood); MainController.sortList(userController.getActiveUser().getMoodList(),"Sort"); //Sort inside moods incase anything changed Log.d("moodCheckAdd", returnedMood.getMaker() + " " + returnedMood.getEmotionState() + " " + returnedMood.getMoodDate() + " " + returnedMood.getTrigger() + " " + returnedMood.getSocialSituation()); userController.saveInFile(getApplicationContext()); filterMood(); //Calls refreshMoodList moodAdapter.notifyDataSetChanged(); //This to-do applies to the viewMoodActivity and EditMoodActivity result too Log.d("userController Added", userController.getActiveUser().getMoodList().toString()); //update the user // if(ElasticSearchUserController.getInstance().deleteUser(userController.getActiveUser())){ // ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); // addUserTask.execute(UserController.getInstance().getActiveUser()); ElasticSearchUserController.UpdateUserTask updateUserTask = new ElasticSearchUserController.UpdateUserTask(); updateUserTask.execute(UserController.getInstance().getActiveUser()); } } //ViewMoodActivity results if (requestCode == 1){ //ViewMoodActivity says delete the mood if (resultCode == 2){ deleteMood(itemPosition); } //ViewMoodActivity says edit if (resultCode == 3){ returnedMood = (Mood) data.getSerializableExtra("newMood"); editMood(returnedMood); } } //EditMoodActivity results if (requestCode == 2){ if (resultCode == RESULT_OK) { returnedMood = (Mood) data.getSerializableExtra("mood"); editMood(returnedMood); } } //ViewProfileActivity and ViewNotificationsActivity results if (requestCode == 3){ //Update user following list //This function populates the list of moods from people being followed if (resultCode == RESULT_OK) { populateFollowing(); filterMood(); //calls refreshMoodList } } } /** * Populates the list of moods from users we follow */ public void populateFollowing() { followingOriginalMoodList.clear(); usersFollowed = userController.getActiveUser().getFollowList(); Log.d("Error", "Current follow list:"+userController.getActiveUser().getFollowList().toString()); if (usersFollowed != null) { for (int i = 0; i < usersFollowed.size(); i++) { String stringFollowedUser = usersFollowed.get(i); ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); try { User followedUser = getUserTask.execute(stringFollowedUser).get(); if (followedUser != null) { if (followedUser.getFirstMood() != null) { followingOriginalMoodList.add(followedUser.getFirstMood()); //Populate both an unfiltered mood list and filtered moodlist } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v.getId()==R.id.moodListView) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_list, menu); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); itemPosition = info.position; Log.d("Adapter click position", itemPosition+""); boolean edit = true; //For some reason view as also bringing up the edit window //This bool fixes that switch(item.getItemId()) { case R.id.edit: //When edit is pressed Intent intentEdit = new Intent(MainActivity.this, EditMoodActivity.class); // intentEdit.putExtra("mood", moodList.get(itemPosition)); if(toggle.isChecked()){ intentEdit.putExtra("mood", moodList.get(itemPosition)); intentEdit.putExtra("username", userController.getActiveUser().getUserName()); } else{ intentEdit.putExtra("mood", followingMoodList.get(itemPosition)); } startActivityForResult(intentEdit, 2); //Handled in the results section //calculate itemPosition in user list ArrayList<Mood> tmpList = userController.getActiveUser().getMoodList(); for (int i = 0; i < tmpList.size(); i++) { if (tmpList.get(i).equals(moodList.get(itemPosition))) { itemPosition = i; break; } } listItem = itemPosition; return true; case R.id.delete: //When delete is pressed the item is removed, and everything is updated deleteMood(itemPosition); return true; // When tweet is pressed TODO build a proper string case R.id.tweet: Mood tmp = moodList.get(itemPosition); TweetComposer.Builder builder = new TweetComposer.Builder(this) .text("Today I'm feeling " + tmp.toString() + (tmp.getSocialSituation().equals("") ? "" : ("\nSocial Situation: " + tmp.getSocialSituation())) + (tmp.getTrigger().equals("") ? "" : ("\nTrigger: " + tmp.getTrigger()))); builder.show(); default: return super.onContextItemSelected(item); } } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
package com.projectattitude.projectattitude.Activities; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.PopupMenu; import android.util.Log; import android.view.ContextMenu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.projectattitude.projectattitude.Adapters.MoodMainAdapter; import com.projectattitude.projectattitude.Controllers.ElasticSearchUserController; import com.projectattitude.projectattitude.Controllers.MainController; import com.projectattitude.projectattitude.Controllers.UserController; import com.projectattitude.projectattitude.Objects.Mood; import com.projectattitude.projectattitude.Objects.MoodList; import com.projectattitude.projectattitude.Objects.NetWorkChangeReceiver; import com.projectattitude.projectattitude.Objects.User; import com.projectattitude.projectattitude.R; import java.util.ArrayList; import java.util.Date; public class MainActivity extends AppCompatActivity { protected ArrayList<Mood> moodList = new ArrayList<Mood>(); private MoodMainAdapter moodAdapter; private ListView moodListView; private MainController controller; private boolean viewingMyList; private Integer itemPosition; private UserController userController = UserController.getInstance(); private static final String LOG_TAG = "CheckNetworkStatus"; private NetWorkChangeReceiver receiver; private boolean isConnected = false; private int listItem; //This is the index of the item pressed in the list // Network listener to sync when connecting to network NetWorkChangeReceiver netWorkChangeReceiver = new NetWorkChangeReceiver() { @Override public void onReceive(Context context, Intent intent){ if(isNetworkAvailable()){ if(ElasticSearchUserController.getInstance().deleteUser(userController.getActiveUser())){ ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); addUserTask.execute(UserController.getInstance().getActiveUser()); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { controller = new MainController(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //get passed user from LoginActivity User user = (User) getIntent().getSerializableExtra("PassUserToMain"); userController.setActiveUser(user); moodListView = (ListView) findViewById(R.id.moodListView); FloatingActionButton addMoodButton = (FloatingActionButton) findViewById(R.id.addMoodButton); //adapter is fed from moodList inside user moodAdapter = new MoodMainAdapter(this, moodList); moodListView.setAdapter(moodAdapter); viewingMyList = false; Button viewMapButton = (Button) findViewById(R.id.viewMapButton); //Load user and mood, and update current displayed list userController.loadFromFile(); Log.d("userController load", userController.getActiveUser().getMoodList().toString()); refreshMoodList(); registerForContextMenu(moodListView); //on click listener for adding moods addMoodButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { createMood(); } }); //on click listener for viewing map viewMapButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { goToMap(); } }); registerReceiver(netWorkChangeReceiver, new IntentFilter("networkConnectBroadcast")); try{ ArrayList<Mood> tempList = userController.getActiveUser().getMoodList(); Log.d("moodlist1", tempList.toString()); refreshMoodList(); Log.d("moodList2", moodList.toString()); } catch(Exception e){ Log.d("Error", "Failed to get the moods from the async object"); } } /** * OpenSFMenu - Open Sort/Filter Menu * Is used when the sort/filter button is pressed to display a menu * @param view - the sort/filter button * @see #openSortMenu(MenuItem) * @see #openFilterMenu(MenuItem) */ public void openSFMenu(View view){ //TODO: Test all this popupmenu crap PopupMenu popup = new PopupMenu(this, view); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.sort_filter_menu, popup.getMenu()); popup.show(); } /** * openSortMenu * Is used when the sort option in sort/filter menu is pressed to display a menu * @param item - the sort option in sort_filter_menu * @see #sortMood(MenuItem) */ public void openSortMenu(MenuItem item){ PopupMenu popup = new PopupMenu(this, findViewById(R.id.filterButton)); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.sort_menu, popup.getMenu()); popup.show(); } /** * openFilterMenu * Is used when the filter option in sort/filter menu is pressed to display a menu * @param item - the filter option in sort_filter_menu * @see #filterMood(MenuItem) */ public void openFilterMenu(MenuItem item){ PopupMenu popup = new PopupMenu(this, findViewById(R.id.filterButton)); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.filter_menu, popup.getMenu()); popup.show(); } /** * OpenMainMenu * Is used when the main menu button is pressed to display a menu * @param view - the main menu button */ public void openMainMenu(View view){ PopupMenu popup = new PopupMenu(this, findViewById(R.id.menuButton)); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.main_menu, popup.getMenu()); popup.show(); } /** * This method will take the user to the Create Mood view */ private void createMood(){ Intent createMoodIntent = new Intent(MainActivity.this, CreateMoodActivity.class); startActivityForResult(createMoodIntent, 0); } /** * This method takes a mood the user made and brings them to the edit mood view */ private void editMood(Mood returnedMood){ ArrayList<Mood> tmpList = userController.getActiveUser().getMoodList(); for (int i = 0; i < tmpList.size(); i++) { if (tmpList.get(i).equals(returnedMood)){ userController.getActiveUser().getMoodList().set(i, returnedMood); userController.saveInFile(); refreshMoodList(); moodAdapter.notifyDataSetChanged(); break; } } //updating db if(ElasticSearchUserController.getInstance().deleteUser(userController.getActiveUser())){ ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); addUserTask.execute(UserController.getInstance().getActiveUser()); } } /** * This deletes a selected mood. * @param i, the integer of the moodList to be removed */ private void deleteMood(Integer i){ //Log.d("deleting", moodList.get(i).toString()); //Mood delMood = moodList.get(i); Log.d("deleting", userController.getActiveUser().getMoodList().get(i).toString()); ArrayList<Mood> tmpList = userController.getActiveUser().getMoodList(); for (int j = 0; j < tmpList.size(); j++) { if (tmpList.get(j).equals(moodList.get(i))) { Mood delMood = userController.getActiveUser().getMoodList().get(j); //moodList = controller.getMyMoodList().getMoodList(); //moodList.remove(delMood); userController.getActiveUser().getMoodList().remove(delMood); //controller.setMyMoodList(new MoodList(moodList)); //Log.d("deleting", moodList.get(i).toString()); userController.saveInFile(); Log.d("userController deleted", userController.getActiveUser().getMoodList().toString()); refreshMoodList(); moodAdapter.notifyDataSetChanged(); break; } } //updating db if(ElasticSearchUserController.getInstance().deleteUser(userController.getActiveUser())){ ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); addUserTask.execute(UserController.getInstance().getActiveUser()); } } /** * Handles sorting the list, called when an item in the sortMenu is pressed * @param item - one of the sort options from the sort menu */ public void sortMood(MenuItem item){ if(item == null){ controller.sortList(moodList, "Sort"); //True = sorting by date return; } switch (item.getItemId()) { case R.id.dateOption: controller.sortList(moodList, "Sort"); //True = sorting by date break; case R.id.reverseDateOption: controller.sortList(moodList, "Reverse Sort"); //False = sorting by reverse date break; } moodAdapter.notifyDataSetChanged(); } /** * Handles filtering the list * @param item - one of the options from the filter menu * @see #filterMoodsByEmotion(MenuItem) * @see #filterMoodsByTime(MenuItem) */ public void filterMood(MenuItem item){ PopupMenu popup = new PopupMenu(this, findViewById(R.id.filterButton)); MenuInflater inflater = popup.getMenuInflater(); switch (item.getItemId()) { case R.id.timeOption: inflater.inflate(R.menu.time_menu, popup.getMenu()); popup.show(); break; case R.id.followingOption: //TODO: Following viewingMyList = !viewingMyList; break; case R.id.emotionOption: inflater.inflate(R.menu.mood_menu, popup.getMenu()); popup.show(); break; case R.id.allOption: //TODO: Add following to allOption userController.loadFromFile(); refreshMoodList(); moodAdapter.notifyDataSetChanged(); break; } } /** * This is the method that handles finding moods with a given keyword * Called by pressing the searchButton on main_layout */ public void filterMoodByTrigger(View view){ //Get text from search bar and then call controller function controller.filterListByTrigger(moodList, ((EditText)findViewById(R.id.searchBar)).getText().toString()); moodAdapter.notifyDataSetChanged(); } /** * Handles filtering the list, but specifically for the time menu * @param item */ public void filterMoodsByTime(MenuItem item){ //TODO: Make sure moods are up to date? switch (item.getItemId()) { case R.id.dayOption: controller.filterListByTime(moodList, (long)8.64e+7); //1 day's worth of milliseconds break; case R.id.monthOption: controller.filterListByTime(moodList, (long)2.628e+9); //1 month's worth of milliseconds approximately break; case R.id.yearOption: controller.filterListByTime(moodList, (long)3.154e+10); //1 year's worth of milliseconds approximately break; } moodAdapter.notifyDataSetChanged(); } /** * Handles filtering the list, but specifically for the mood menu * @param item - option from the filter emotion menu */ public void filterMoodsByEmotion(MenuItem item){ Long milliseconds = new Date().getTime(); switch (item.getItemId()) { case R.id.angerOption: controller.filterListByEmotion(moodList, "Anger"); //1 day's worth of milliseconds break; case R.id.confusionOption: controller.filterListByEmotion(moodList, "Confusion"); //1 day's worth of milliseconds break; case R.id.disgustOption: controller.filterListByEmotion(moodList, "Disgust"); //1 day's worth of milliseconds break; case R.id.fearOption: controller.filterListByEmotion(moodList, "Fear"); //1 day's worth of milliseconds break; case R.id.happinessOption: controller.filterListByEmotion(moodList, "Happiness"); //1 day's worth of milliseconds break; case R.id.sadnessOption: controller.filterListByEmotion(moodList, "Sadness"); //1 day's worth of milliseconds break; case R.id.shameOption: controller.filterListByEmotion(moodList, "Shame"); //1 day's worth of milliseconds break; case R.id.surpriseOption: controller.filterListByEmotion(moodList, "Surprise"); //1 day's worth of milliseconds break; } moodAdapter.notifyDataSetChanged(); } /** * When the user clicks the map button this takes them to the map view */ private void goToMap(){ Intent viewMapIntent = new Intent(MainActivity.this, MapActivity.class); startActivityForResult(viewMapIntent, 0); } /** * When the user clicks the profile button it will take them to the profile view * Later may take a profile as an argument to go to someone elses profile. */ public void viewProfile(MenuItem item){ Intent intent = new Intent(MainActivity.this, ViewProfileActivity.class); intent.putExtra("moodCount", moodList.size()); startActivity(intent); } /** * Logs the current profile out of the application and returns the user to the log in view. * No data will be saved if user logs out while offline * and you will not be able to log back in when offline */ public void logOut(MenuItem item){ Intent intent = new Intent(MainActivity.this, LoginActivity.class); finish(); startActivity(intent); } /** * refreshMood - Used to refresh the mood list with the most current moods. * Currently works by using the global variable moodList */ public void refreshMoodList(){ //TODO: Add following and perhaps make algorithm more elegant ArrayList<Mood> newList = userController.getActiveUser().getMoodList(); moodList.clear(); moodList.addAll(newList); sortMood(null); } //accept returned information from activities @Override // requestCode 0 = Add mood // requestCode 1 = View mood -- resultCode 2 = delete, 3 = Edit Mood // requestCode 2 = Edit Mood protected void onActivityResult(int requestCode, int resultCode, Intent data) { Mood returnedMood; if (requestCode == 0) { if (resultCode == RESULT_OK) { returnedMood = (Mood) data.getSerializableExtra("addMoodIntent"); userController.getActiveUser().getMoodList().add(returnedMood); userController.saveInFile(); refreshMoodList(); moodAdapter.notifyDataSetChanged(); //TODO: Only update moodList if displaying myMoodList, not following list, otherwise moodList = followingList //This to-do applies to the viewMoodActivity and EditMoodActivity result too Log.d("userController Added", userController.getActiveUser().getMoodList().toString()); //update the user if(ElasticSearchUserController.getInstance().deleteUser(userController.getActiveUser())){ ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); addUserTask.execute(UserController.getInstance().getActiveUser()); } } } //ViewMoodActivity results if (requestCode == 1){ //ViewMoodActivity says delete the mood if (resultCode == 2){ deleteMood(itemPosition); } //ViewMoodActivity says edit if (resultCode == 3){ returnedMood = (Mood) data.getSerializableExtra("newMood"); editMood(returnedMood); } } //EditMoodActivity results if (requestCode == 2){ if (resultCode == RESULT_OK) { returnedMood = (Mood) data.getSerializableExtra("mood"); editMood(returnedMood); } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v.getId()==R.id.moodListView) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_list, menu); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); itemPosition = info.position; boolean edit = true; //For some reason view as also bringing up the edit window //This bool fixes that switch(item.getItemId()) { case R.id.view: //TODO Make this MVC. Use a controller that calls this code? //On second though this is all UI so it doenst need a controller? edit = false;//Makes it so the edit window will not pop up Intent intentView = new Intent(MainActivity.this, ViewMoodActivity.class); //intentView.putExtra("mood", moodList.get(itemPosition)); intentView.putExtra("mood", moodList.get(itemPosition)); startActivityForResult(intentView, 1); case R.id.edit: //When edit is pressed if (edit) { Intent intentEdit = new Intent(MainActivity.this, EditMoodActivity.class); // intentEdit.putExtra("mood", moodList.get(itemPosition)); intentEdit.putExtra("mood", moodList.get(itemPosition)); startActivityForResult(intentEdit, 2); //Handled in the results section listItem = itemPosition; } return true; case R.id.delete: //When delete is pressed the item is removed, and everything is updated deleteMood(itemPosition); return true; default: return super.onContextItemSelected(item); } } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
package com.hubspot.singularity.mesos; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import javax.inject.Singleton; import org.apache.mesos.v1.Protos.AgentID; import org.apache.mesos.v1.Protos.Offer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Multiset; import com.google.inject.Inject; import com.google.inject.name.Named; import com.hubspot.mesos.json.MesosMasterSlaveObject; import com.hubspot.mesos.json.MesosMasterStateObject; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.RequestUtilization; import com.hubspot.singularity.SingularityMachineAbstraction; import com.hubspot.singularity.SingularityPendingRequest.PendingType; import com.hubspot.singularity.SingularityPendingTask; import com.hubspot.singularity.SingularityPendingTaskId; import com.hubspot.singularity.SingularityRack; import com.hubspot.singularity.SingularityRequest; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.SlaveMatchState; import com.hubspot.singularity.SlavePlacement; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.AbstractMachineManager; import com.hubspot.singularity.data.InactiveSlaveManager; import com.hubspot.singularity.data.RackManager; import com.hubspot.singularity.data.SlaveManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.mesos.SingularitySlaveAndRackHelper.CpuMemoryPreference; import com.hubspot.singularity.scheduler.SingularityLeaderCache; import com.hubspot.singularity.sentry.SingularityExceptionNotifier; @Singleton public class SingularitySlaveAndRackManager { private static final Logger LOG = LoggerFactory.getLogger(SingularitySlaveAndRackManager.class); private final SingularityConfiguration configuration; private final SingularityExceptionNotifier exceptionNotifier; private final RackManager rackManager; private final SlaveManager slaveManager; private final TaskManager taskManager; private final InactiveSlaveManager inactiveSlaveManager; private final SingularitySlaveAndRackHelper slaveAndRackHelper; private final AtomicInteger activeSlavesLost; private final SingularityLeaderCache leaderCache; @Inject SingularitySlaveAndRackManager(SingularitySlaveAndRackHelper slaveAndRackHelper, SingularityConfiguration configuration, SingularityExceptionNotifier exceptionNotifier, RackManager rackManager, SlaveManager slaveManager, TaskManager taskManager, InactiveSlaveManager inactiveSlaveManager, @Named(SingularityMesosModule.ACTIVE_SLAVES_LOST_COUNTER) AtomicInteger activeSlavesLost, SingularityLeaderCache leaderCache) { this.configuration = configuration; this.exceptionNotifier = exceptionNotifier; this.slaveAndRackHelper = slaveAndRackHelper; this.rackManager = rackManager; this.slaveManager = slaveManager; this.taskManager = taskManager; this.inactiveSlaveManager = inactiveSlaveManager; this.activeSlavesLost = activeSlavesLost; this.leaderCache = leaderCache; } SlaveMatchState doesOfferMatch(SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest, List<SingularityTaskId> activeTaskIdsForRequest, boolean isPreemptibleTask, RequestUtilization requestUtilization) { final String host = offerHolder.getHostname(); final String rackId = offerHolder.getRackId(); final String slaveId = offerHolder.getSlaveId(); Optional<SingularitySlave> maybeSlave = slaveManager.getObject(slaveId); if (!maybeSlave.isPresent()) { return SlaveMatchState.RESOURCES_DO_NOT_MATCH; } final MachineState currentSlaveState = maybeSlave.get().getCurrentState().getState(); if (currentSlaveState == MachineState.FROZEN) { return SlaveMatchState.SLAVE_FROZEN; } if (currentSlaveState.isDecommissioning()) { return SlaveMatchState.SLAVE_DECOMMISSIONING; } final MachineState currentRackState = rackManager.getObject(rackId).get().getCurrentState().getState(); if (currentRackState == MachineState.FROZEN) { return SlaveMatchState.RACK_FROZEN; } if (currentRackState.isDecommissioning()) { return SlaveMatchState.RACK_DECOMMISSIONING; } if (!taskRequest.getRequest().getRackAffinity().orElse(Collections.emptyList()).isEmpty()) { if (!taskRequest.getRequest().getRackAffinity().get().contains(rackId)) { LOG.trace("Task {} requires a rack in {} (current rack {})", taskRequest.getPendingTask().getPendingTaskId(), taskRequest.getRequest().getRackAffinity().get(), rackId); return SlaveMatchState.RACK_AFFINITY_NOT_MATCHING; } } if (!isSlaveAttributesMatch(offerHolder, taskRequest, isPreemptibleTask)) { return SlaveMatchState.SLAVE_ATTRIBUTES_DO_NOT_MATCH; } else if (!areSlaveAttributeMinimumsFeasible(offerHolder, taskRequest, activeTaskIdsForRequest)) { return SlaveMatchState.SLAVE_ATTRIBUTES_DO_NOT_MATCH; } final SlavePlacement slavePlacement = taskRequest.getRequest().getSlavePlacement().orElse(configuration.getDefaultSlavePlacement()); if (!taskRequest.getRequest().isRackSensitive() && slavePlacement == SlavePlacement.GREEDY) { // todo: account for this or let this behavior continue? return SlaveMatchState.NOT_RACK_OR_SLAVE_PARTICULAR; } final int numDesiredInstances = taskRequest.getRequest().getInstancesSafe(); boolean allowBounceToSameHost = isAllowBounceToSameHost(taskRequest.getRequest()); Multiset<String> countPerRack = HashMultiset.create(slaveManager.getNumActive()); double numOnSlave = 0; double numCleaningOnSlave = 0; double numFromSameBounceOnSlave = 0; double numOtherDeploysOnSlave = 0; boolean taskLaunchedFromBounceWithActionId = taskRequest.getPendingTask().getPendingTaskId().getPendingType() == PendingType.BOUNCE && taskRequest.getPendingTask().getActionId().isPresent(); final String sanitizedHost = offerHolder.getSanitizedHost(); final String sanitizedRackId = offerHolder.getSanitizedRackId(); Collection<SingularityTaskId> cleaningTasks = leaderCache.getCleanupTaskIds(); for (SingularityTaskId taskId : activeTaskIdsForRequest) { // TODO consider using executorIds if (!cleaningTasks.contains(taskId) && taskRequest.getDeploy().getId().equals(taskId.getDeployId())) { countPerRack.add(taskId.getSanitizedRackId()); } if (!taskId.getSanitizedHost().equals(sanitizedHost)) { continue; } if (taskRequest.getDeploy().getId().equals(taskId.getDeployId())) { if (cleaningTasks.contains(taskId)) { numCleaningOnSlave++; } else { numOnSlave++; } if (taskLaunchedFromBounceWithActionId) { Optional<SingularityTask> maybeTask = taskManager.getTask(taskId); boolean errorInTaskData = false; if (maybeTask.isPresent()) { SingularityPendingTask pendingTask = maybeTask.get().getTaskRequest().getPendingTask(); if (pendingTask.getPendingTaskId().getPendingType() == PendingType.BOUNCE) { if (pendingTask.getActionId().isPresent()) { if (pendingTask.getActionId().get().equals(taskRequest.getPendingTask().getActionId().get())) { numFromSameBounceOnSlave++; } } else { // No actionId present on bounce, fall back to more restrictive placement strategy errorInTaskData = true; } } } else { // Could not find appropriate task data, fall back to more restrictive placement strategy errorInTaskData = true; } if (errorInTaskData) { allowBounceToSameHost = false; } } } else { numOtherDeploysOnSlave++; } } if (taskRequest.getRequest().isRackSensitive()) { final boolean isRackOk = isRackOk(countPerRack, sanitizedRackId, numDesiredInstances, taskRequest.getRequest().getId(), slaveId, host, numCleaningOnSlave); if (!isRackOk) { return SlaveMatchState.RACK_SATURATED; } } switch (slavePlacement) { case SEPARATE: case SEPARATE_BY_DEPLOY: case SPREAD_ALL_SLAVES: if (allowBounceToSameHost && taskLaunchedFromBounceWithActionId) { if (numFromSameBounceOnSlave > 0) { LOG.trace("Rejecting SEPARATE task {} from slave {} ({}) due to numFromSameBounceOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numFromSameBounceOnSlave); return SlaveMatchState.SLAVE_SATURATED; } } else { if (numOnSlave > 0 || numCleaningOnSlave > 0) { LOG.trace("Rejecting {} task {} from slave {} ({}) due to numOnSlave {} numCleaningOnSlave {}", slavePlacement.name(), taskRequest.getRequest().getId(), slaveId, host, numOnSlave, numCleaningOnSlave); return SlaveMatchState.SLAVE_SATURATED; } } break; case SEPARATE_BY_REQUEST: if (numOnSlave > 0 || numCleaningOnSlave > 0 || numOtherDeploysOnSlave > 0) { LOG.trace("Rejecting SEPARATE_BY_REQUEST task {} from slave {} ({}) due to numOnSlave {} numCleaningOnSlave {} numOtherDeploysOnSlave {}", taskRequest.getRequest().getId(), slaveId, host, numOnSlave, numCleaningOnSlave, numOtherDeploysOnSlave); return SlaveMatchState.SLAVE_SATURATED; } break; case OPTIMISTIC: // If no tasks are active for this request yet, we can fall back to greedy. if (activeTaskIdsForRequest.size() > 0) { Collection<SingularityPendingTaskId> pendingTasksForRequestClusterwide = leaderCache.getPendingTaskIdsForRequest(taskRequest.getRequest().getId()); Set<String> currentHostsForRequest = activeTaskIdsForRequest.stream() .map(SingularityTaskId::getSanitizedHost) .collect(Collectors.toSet()); final double numPerSlave = activeTaskIdsForRequest.size() / (double) currentHostsForRequest.size(); final double leniencyCoefficient = configuration.getPlacementLeniency(); final double threshold = numPerSlave * (1 + (pendingTasksForRequestClusterwide.size() * leniencyCoefficient)); final boolean isSlaveOk = numOnSlave <= threshold; if (!isSlaveOk) { LOG.trace( "Rejecting OPTIMISTIC task {} from slave {} ({}) because numOnSlave {} violates threshold {} (based on active tasks for request {}, current hosts for request {}, pending tasks for request {})", taskRequest.getRequest().getId(), slaveId, host, numOnSlave, threshold, activeTaskIdsForRequest.size(), currentHostsForRequest.size(), pendingTasksForRequestClusterwide.size() ); return SlaveMatchState.SLAVE_SATURATED; } } break; case GREEDY: } if (isSlavePreferred(offerHolder, taskRequest, requestUtilization)) { LOG.info("Slave {} is preferred", offerHolder.getHostname()); return SlaveMatchState.PREFERRED_SLAVE; } return SlaveMatchState.OK; } private boolean isSlavePreferred(SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest, RequestUtilization requestUtilization) { return isSlavePreferredByAllowedAttributes(offerHolder, taskRequest) || isSlavePreferredByCpuMemory(offerHolder, requestUtilization); } private boolean isSlavePreferredByAllowedAttributes(SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest) { Map<String, String> allowedAttributes = getAllowedAttributes(taskRequest); Map<String, String> hostAttributes = offerHolder.getTextAttributes(); boolean containsAtLeastOneMatchingAttribute = slaveAndRackHelper.containsAtLeastOneMatchingAttribute(hostAttributes, allowedAttributes); LOG.trace("is slave {} by allowed attributes? {}", offerHolder.getHostname(), containsAtLeastOneMatchingAttribute); return containsAtLeastOneMatchingAttribute; } public boolean isSlavePreferredByCpuMemory(SingularityOfferHolder offerHolder, RequestUtilization requestUtilization) { if (requestUtilization != null) { CpuMemoryPreference cpuMemoryPreferenceForSlave = slaveAndRackHelper.getCpuMemoryPreferenceForSlave(offerHolder); CpuMemoryPreference cpuMemoryPreferenceForRequest = slaveAndRackHelper.getCpuMemoryPreferenceForRequest(requestUtilization); LOG.trace("CpuMemoryPreference for slave {} is {}, CpuMemoryPreference for request {} is {}", offerHolder.getHostname(), cpuMemoryPreferenceForSlave.toString(), requestUtilization.getRequestId(), cpuMemoryPreferenceForRequest.toString()); return cpuMemoryPreferenceForSlave == cpuMemoryPreferenceForRequest; } return false; } private boolean isSlaveAttributesMatch(SingularityOfferHolder offer, SingularityTaskRequest taskRequest, boolean isPreemptibleTask) { final Map<String, String> requiredAttributes = getRequiredAttributes(taskRequest); final Map<String, String> allowedAttributes = getAllowedAttributes(taskRequest); if (offer.hasReservedSlaveAttributes()) { Map<String, String> reservedSlaveAttributes = offer.getReservedSlaveAttributes(); Map<String, String> mergedAttributes = new HashMap<>(); mergedAttributes.putAll(requiredAttributes); mergedAttributes.putAll(allowedAttributes); if (!mergedAttributes.isEmpty()) { if (!slaveAndRackHelper.containsAllAttributes(mergedAttributes, reservedSlaveAttributes)) { LOG.trace("Slaves with attributes {} are reserved for matching tasks. Task with attributes {} does not match", reservedSlaveAttributes, mergedAttributes); return false; } } else { LOG.trace("Slaves with attributes {} are reserved for matching tasks. No attributes specified for task {}", reservedSlaveAttributes, taskRequest.getPendingTask().getPendingTaskId().getId()); return false; } } if (!configuration.getPreemptibleTasksOnlyMachineAttributes().isEmpty()) { if (slaveAndRackHelper.containsAllAttributes(offer.getTextAttributes(), configuration.getPreemptibleTasksOnlyMachineAttributes()) && !isPreemptibleTask) { LOG.debug("Host {} is reserved for preemptible tasks", offer.getHostname()); return false; } } if (!requiredAttributes.isEmpty()) { if (!slaveAndRackHelper.containsAllAttributes(offer.getTextAttributes(), requiredAttributes)) { LOG.trace("Task requires slave with attributes {}, (slave attributes are {})", requiredAttributes, offer.getTextAttributes()); return false; } } return true; } private Map<String, String> getRequiredAttributes(SingularityTaskRequest taskRequest) { if (!taskRequest.getPendingTask().getRequiredSlaveAttributeOverrides().isEmpty()) { return taskRequest.getPendingTask().getRequiredSlaveAttributeOverrides(); } else if ((taskRequest.getRequest().getRequiredSlaveAttributes().isPresent() && !taskRequest.getRequest().getRequiredSlaveAttributes().get().isEmpty())) { return taskRequest.getRequest().getRequiredSlaveAttributes().get(); } return new HashMap<>(); } private Map<String, String> getAllowedAttributes(SingularityTaskRequest taskRequest) { if (!taskRequest.getPendingTask().getAllowedSlaveAttributeOverrides().isEmpty()) { return taskRequest.getPendingTask().getAllowedSlaveAttributeOverrides(); } else if ((taskRequest.getRequest().getAllowedSlaveAttributes().isPresent() && !taskRequest.getRequest().getAllowedSlaveAttributes().get().isEmpty())){ return taskRequest.getRequest().getAllowedSlaveAttributes().get(); } return new HashMap<>(); } private boolean areSlaveAttributeMinimumsFeasible(SingularityOfferHolder offerHolder, SingularityTaskRequest taskRequest, List<SingularityTaskId> activeTaskIdsForRequest) { if (!taskRequest.getRequest().getSlaveAttributeMinimums().isPresent()) { return true; } Map<String, String> offerAttributes = slaveManager.getObject(offerHolder.getSlaveId()).get().getAttributes(); Integer numDesiredInstances = taskRequest.getRequest().getInstancesSafe(); Integer numActiveInstances = activeTaskIdsForRequest.size(); for (Entry<String, Map<String, Integer>> keyEntry : taskRequest.getRequest().getSlaveAttributeMinimums().get().entrySet()) { String attrKey = keyEntry.getKey(); for (Entry<String, Integer> valueEntry : keyEntry.getValue().entrySet()) { Integer percentInstancesWithAttr = valueEntry.getValue(); Integer minInstancesWithAttr = Math.max(1, (int) ((percentInstancesWithAttr / 100.0) * numDesiredInstances)); if (offerAttributes.containsKey(attrKey) && offerAttributes.get(attrKey).equals(valueEntry.getKey())) { // Accepting this offer would add an instance of the needed attribute, so it's okay. continue; } // Would accepting this offer prevent meeting the necessary attribute in the future? long numInstancesWithAttr = getNumInstancesWithAttribute(activeTaskIdsForRequest, attrKey, valueEntry.getKey()); long numInstancesWithoutAttr = numActiveInstances - numInstancesWithAttr + 1; long maxPotentialInstancesWithAttr = numDesiredInstances - numInstancesWithoutAttr; if (maxPotentialInstancesWithAttr < minInstancesWithAttr) { return false; } } } return true; } private long getNumInstancesWithAttribute(List<SingularityTaskId> taskIds, String attrKey, String attrValue) { return taskIds.stream() .map(id -> leaderCache.getSlave(taskManager.getTask(id).get().getMesosTask().getSlaveId().getValue()).get().getAttributes().get(attrKey)) .filter(Objects::nonNull) .filter(x -> x.equals(attrValue)) .count(); } private boolean isAllowBounceToSameHost(SingularityRequest request) { if (request.getAllowBounceToSameHost().isPresent()) { return request.getAllowBounceToSameHost().get(); } else { return configuration.isAllowBounceToSameHost(); } } private boolean isRackOk(Multiset<String> countPerRack, String sanitizedRackId, int numDesiredInstances, String requestId, String slaveId, String host, double numCleaningOnSlave) { int racksAccountedFor = countPerRack.elementSet().size(); double numPerRack = numDesiredInstances / (double) rackManager.getNumActive(); if (racksAccountedFor < rackManager.getNumActive()) { if (countPerRack.count(sanitizedRackId) < Math.max(numPerRack, 1)) { return true; } } else { Integer rackMin = null; for (String rackId : countPerRack.elementSet()) { if (rackMin == null || countPerRack.count(rackId) < rackMin) { rackMin = countPerRack.count(rackId); } } if (rackMin == null || rackMin < (int) numPerRack) { if (countPerRack.count(sanitizedRackId) < (int) numPerRack) { return true; } } else if (countPerRack.count(sanitizedRackId) < numPerRack) { return true; } } LOG.trace("Rejecting RackSensitive task {} from slave {} ({}) due to numOnRack {} and cleaningOnSlave {}", requestId, slaveId, host, countPerRack.count(sanitizedRackId), numCleaningOnSlave); return false; } void slaveLost(AgentID slaveIdObj) { final String slaveId = slaveIdObj.getValue(); Optional<SingularitySlave> slave = slaveManager.getObject(slaveId); if (slave.isPresent()) { MachineState previousState = slave.get().getCurrentState().getState(); slaveManager.changeState(slave.get(), MachineState.DEAD, Optional.empty(), Optional.empty()); if (configuration.getDisasterDetection().isEnabled()) { updateDisasterCounter(previousState); } checkRackAfterSlaveLoss(slave.get()); } else { LOG.warn("Lost a slave {}, but didn't know about it", slaveId); } } private void updateDisasterCounter(MachineState previousState) { if (previousState == MachineState.ACTIVE) { activeSlavesLost.getAndIncrement(); } } private void checkRackAfterSlaveLoss(SingularitySlave lostSlave) { List<SingularitySlave> slaves = slaveManager.getObjectsFiltered(MachineState.ACTIVE); int numInRack = 0; for (SingularitySlave slave : slaves) { if (slave.getRackId().equals(lostSlave.getRackId())) { numInRack++; } } LOG.info("Found {} slaves left in rack {}", numInRack, lostSlave.getRackId()); if (numInRack == 0) { rackManager.changeState(lostSlave.getRackId(), MachineState.DEAD, Optional.empty(), Optional.empty()); } } public void loadSlavesAndRacksFromMaster(MesosMasterStateObject state, boolean isStartup) { Map<String, SingularitySlave> activeSlavesById = slaveManager.getObjectsByIdForState(MachineState.ACTIVE); Map<String, SingularityRack> activeRacksById = rackManager.getObjectsByIdForState(MachineState.ACTIVE); Map<String, SingularityRack> remainingActiveRacks = Maps.newHashMap(activeRacksById); int slaves = 0; int racks = 0; for (MesosMasterSlaveObject slaveJsonObject : state.getSlaves()) { String slaveId = slaveJsonObject.getId(); String rackId = slaveAndRackHelper.getRackId(slaveJsonObject.getAttributes()); Map<String, String> textAttributes = slaveAndRackHelper.getTextAttributes(slaveJsonObject.getAttributes()); String host = slaveAndRackHelper.getMaybeTruncatedHost(slaveJsonObject.getHostname()); if (activeSlavesById.containsKey(slaveId)) { SingularitySlave slave = activeSlavesById.get(slaveId); if (slave != null && (!slave.getResources().isPresent() || !slave.getResources().get().equals(slaveJsonObject.getResources()))) { LOG.trace("Found updated resources ({}) for slave {}", slaveJsonObject.getResources(), slave); slaveManager.saveObject(slave.withResources(slaveJsonObject.getResources())); } activeSlavesById.remove(slaveId); } else { SingularitySlave newSlave = new SingularitySlave(slaveId, host, rackId, textAttributes, Optional.of(slaveJsonObject.getResources())); if (check(newSlave, slaveManager) == CheckResult.NEW) { slaves++; } } if (activeRacksById.containsKey(rackId)) { remainingActiveRacks.remove(rackId); } else { SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { racks++; } } } for (SingularitySlave leftOverSlave : activeSlavesById.values()) { slaveManager.changeState(leftOverSlave, isStartup ? MachineState.MISSING_ON_STARTUP : MachineState.DEAD, Optional.empty(), Optional.empty()); } for (SingularityRack leftOverRack : remainingActiveRacks.values()) { rackManager.changeState(leftOverRack, isStartup ? MachineState.MISSING_ON_STARTUP : MachineState.DEAD, Optional.empty(), Optional.empty()); } LOG.info("Found {} new racks ({} missing) and {} new slaves ({} missing)", racks, remainingActiveRacks.size(), slaves, activeSlavesById.size()); } public enum CheckResult { NEW, NOT_ACCEPTING_TASKS, ALREADY_ACTIVE; } private <T extends SingularityMachineAbstraction<T>> CheckResult check(T object, AbstractMachineManager<T> manager) { Optional<T> existingObject = manager.getObject(object.getId()); if (!existingObject.isPresent()) { manager.saveObject(object); return CheckResult.NEW; } MachineState currentState = existingObject.get().getCurrentState().getState(); switch (currentState) { case ACTIVE: return CheckResult.ALREADY_ACTIVE; case DEAD: case MISSING_ON_STARTUP: manager.changeState(object.getId(), MachineState.ACTIVE, Optional.empty(), Optional.empty()); return CheckResult.NEW; case FROZEN: case DECOMMISSIONED: case DECOMMISSIONING: case STARTING_DECOMMISSION: return CheckResult.NOT_ACCEPTING_TASKS; } throw new IllegalStateException(String.format("Invalid state %s for %s", currentState, object.getId())); } public CheckResult checkOffer(Offer offer) { final String slaveId = offer.getAgentId().getValue(); final String rackId = slaveAndRackHelper.getRackIdOrDefault(offer); final String host = slaveAndRackHelper.getMaybeTruncatedHost(offer); final Map<String, String> textAttributes = slaveAndRackHelper.getTextAttributes(offer); final SingularitySlave slave = new SingularitySlave(slaveId, host, rackId, textAttributes, Optional.empty()); CheckResult result = check(slave, slaveManager); if (result == CheckResult.NEW) { if (inactiveSlaveManager.isInactive(slave.getHost())) { LOG.info("Slave {} on inactive host {} attempted to rejoin. Marking as decommissioned.", slave, host); slaveManager.changeState(slave, MachineState.STARTING_DECOMMISSION, Optional.of(String.format("Slave %s on inactive host %s attempted to rejoin cluster.", slaveId, host)), Optional.empty()); } else { LOG.info("Offer revealed a new slave {}", slave); } } final SingularityRack rack = new SingularityRack(rackId); if (check(rack, rackManager) == CheckResult.NEW) { LOG.info("Offer revealed a new rack {}", rack); } return result; } void checkStateAfterFinishedTask(SingularityTaskId taskId, String slaveId, SingularityLeaderCache leaderCache) { Optional<SingularitySlave> slave = slaveManager.getObject(slaveId); if (!slave.isPresent()) { final String message = String.format("Couldn't find slave with id %s for task %s", slaveId, taskId); LOG.warn(message); exceptionNotifier.notify(message, ImmutableMap.of("slaveId", slaveId, "taskId", taskId.toString())); return; } if (slave.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnSlave(taskId, slaveId, leaderCache)) { slaveManager.changeState(slave.get(), MachineState.DECOMMISSIONED, slave.get().getCurrentState().getMessage(), slave.get().getCurrentState().getUser()); } } Optional<SingularityRack> rack = rackManager.getObject(slave.get().getRackId()); if (!rack.isPresent()) { final String message = String.format("Couldn't find rack with id %s for task %s", slave.get().getRackId(), taskId); LOG.warn(message); exceptionNotifier.notify(message, ImmutableMap.of("rackId", slave.get().getRackId(), "taskId", taskId.toString())); return; } if (rack.get().getCurrentState().getState() == MachineState.DECOMMISSIONING) { if (!hasTaskLeftOnRack(taskId, leaderCache)) { rackManager.changeState(rack.get(), MachineState.DECOMMISSIONED, rack.get().getCurrentState().getMessage(), rack.get().getCurrentState().getUser()); } } } private boolean hasTaskLeftOnRack(SingularityTaskId taskId, SingularityLeaderCache leaderCache) { for (SingularityTaskId activeTaskId : leaderCache.getActiveTaskIds()) { if (!activeTaskId.equals(taskId) && activeTaskId.getSanitizedRackId().equals(taskId.getSanitizedRackId())) { return true; } } return false; } private boolean hasTaskLeftOnSlave(SingularityTaskId taskId, String slaveId, SingularityLeaderCache stateCache) { for (SingularityTaskId activeTaskId : stateCache.getActiveTaskIds()) { if (!activeTaskId.equals(taskId) && activeTaskId.getSanitizedHost().equals(taskId.getSanitizedHost())) { Optional<SingularityTask> maybeTask = taskManager.getTask(activeTaskId); if (maybeTask.isPresent() && slaveId.equals(maybeTask.get().getAgentId().getValue())) { return true; } } } return false; } }
package com.hubspot.singularity.scheduler; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.inject.Singleton; import org.apache.mesos.v1.Protos.Offer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.hubspot.singularity.SingularityAction; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.DisasterManager; import com.hubspot.singularity.mesos.OfferCache; import com.hubspot.singularity.mesos.SingularityMesosOfferScheduler; import com.hubspot.singularity.mesos.SingularityMesosSchedulerClient; import com.hubspot.singularity.mesos.SingularityOfferCache.CachedOffer; import com.hubspot.singularity.mesos.SingularityOfferHolder; import com.hubspot.singularity.mesos.SingularitySchedulerLock; @Singleton public class SingularitySchedulerPoller extends SingularityLeaderOnlyPoller { private static final Logger LOG = LoggerFactory.getLogger(SingularitySchedulerPoller.class); private final OfferCache offerCache; private final SingularityMesosSchedulerClient schedulerClient; private final SingularityMesosOfferScheduler offerScheduler; private final DisasterManager disasterManager; private final SingularitySchedulerLock lock; @Inject SingularitySchedulerPoller(SingularityMesosOfferScheduler offerScheduler, OfferCache offerCache, SingularityMesosSchedulerClient schedulerClient, SingularityConfiguration configuration, SingularitySchedulerLock lock, DisasterManager disasterManager) { super(configuration.getCheckSchedulerEverySeconds(), TimeUnit.SECONDS, true); this.offerCache = offerCache; this.offerScheduler = offerScheduler; this.schedulerClient = schedulerClient; this.disasterManager = disasterManager; this.lock = lock; } @Override public void runActionOnPoll() { if (disasterManager.isDisabled(SingularityAction.RUN_SCHEDULER_POLLER)) { LOG.warn("Scheduler poller is disabled"); return; } lock.runWithOffersLock(() -> { List<CachedOffer> cachedOffers = offerCache.checkoutOffers(); Map<String, CachedOffer> offerIdToCachedOffer = new HashMap<>(cachedOffers.size()); List<Offer> offers = new ArrayList<>(cachedOffers.size()); for (CachedOffer cachedOffer : cachedOffers) { offerIdToCachedOffer.put(cachedOffer.getOfferId(), cachedOffer); offers.add(cachedOffer.getOffer()); } Collection<SingularityOfferHolder> offerHolders = offerScheduler.checkOffers(offers); if (offerHolders.isEmpty()) { return; } int acceptedOffers = 0; int launchedTasks = 0; for (SingularityOfferHolder offerHolder : offerHolders) { List<CachedOffer> cachedOffersFromHolder = offerHolder.getOffers().stream().map((o) -> offerIdToCachedOffer.get(o.getId().getValue())).collect(Collectors.toList()); if (!offerHolder.getAcceptedTasks().isEmpty()) { List<Offer> unusedOffers = offerHolder.launchTasksAndGetUnusedOffers(schedulerClient); launchedTasks += offerHolder.getAcceptedTasks().size(); acceptedOffers += cachedOffersFromHolder.size() - unusedOffers.size(); // Return to the cache those offers which we checked out of the cache, but didn't end up using. List<CachedOffer> unusedCachedOffers = unusedOffers.stream().map((o) -> offerIdToCachedOffer.get(o.getId().getValue())).collect(Collectors.toList()); unusedCachedOffers.forEach((cachedOffer) -> { offerIdToCachedOffer.remove(cachedOffer.getOfferId()); offerCache.returnOffer(cachedOffer); }); // Notify the cache of the cached offers that we did use. cachedOffersFromHolder.removeAll(unusedCachedOffers); cachedOffersFromHolder.forEach((cachedOffer) -> { offerIdToCachedOffer.remove(cachedOffer.getOfferId()); offerCache.useOffer(cachedOffer); }); } else { cachedOffersFromHolder.forEach((cachedOffer) -> { offerIdToCachedOffer.remove(cachedOffer.getOfferId()); offerCache.returnOffer(cachedOffer); }); } } LOG.info("{} remaining offers not accounted for in offer check", offerIdToCachedOffer.size()); offerIdToCachedOffer.values().forEach(offerCache::returnOffer); LOG.info("Launched {} tasks on {} cached offers (returned {})", launchedTasks, acceptedOffers, offerHolders.size() - acceptedOffers); }, getClass().getSimpleName()); } }
package com.mycompany.testproject.iterativeTests; import fi.lolcatz.profiler.ClassBlacklist; import fi.lolcatz.profiler.Util; import org.apache.log4j.Logger; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class ComplexityExponentialsTest { public ComplexityExponentialsTest() { } IntegerImpl impl; @BeforeClass public static void setUpClass() { ClassBlacklist.add(ComplexityExponentialsTest.class); Util.loadAgent(); Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF); } @Before public void testSetup() { impl = new IntegerImpl(); impl.setClassName("com.mycompany.testproject.iteratives.IterativeComplexityExample"); } @Test public void squaredTest() throws Exception { impl.setMethodName("squaredFunction"); long[] totalCost = new long[5]; int syote = 10; totalCost[0] = impl.runStatic(impl.getInput(syote)); for (int i = 1; i < totalCost.length; i++) { syote = 2*syote; totalCost[i] = impl.runStatic(impl.getInput(syote)); } printResults(" assertTrue(totalCost[0] * 4 >= totalCost[1]); assertTrue(totalCost[1] * 4 >= totalCost[2]); assertTrue(totalCost[2] * 4 >= totalCost[3]); assertTrue(totalCost[3] * 4 >= totalCost[4]); System.out.println("- - - - -"); } @Test public void testApproximatedSquared() throws Exception { impl.setMethodName("approximatedSquaredFunction"); long[] totalCost = new long[5]; int syote = 10; totalCost[0] = impl.runStatic(impl.getInput(syote)); for (int i = 1; i < totalCost.length; i++) { syote = 2*syote; totalCost[i] = impl.runStatic(impl.getInput(syote)); } printResults(" assertTrue(totalCost[0] * 4 >= totalCost[1]); assertTrue(totalCost[1] * 4 >= totalCost[2]); assertTrue(totalCost[2] * 4 >= totalCost[3]); assertTrue(totalCost[3] * 4 >= totalCost[4]); } @Test public void testCoinFlipExponential() throws Exception { impl.setMethodName("squaredCoinFlipFunction"); long[] totalCost = new long[5]; int syote = 10; totalCost[0] = impl.runStatic(impl.getInput(syote)); for (int i = 1; i < totalCost.length; i++) { syote = 2*syote; totalCost[i] = impl.runStatic(impl.getInput(syote)); } printResults(" assertTrue(totalCost[0] * 4 >= totalCost[1]); assertTrue(totalCost[1] * 4 >= totalCost[2]); assertTrue(totalCost[2] * 4 >= totalCost[3]); assertTrue(totalCost[3] * 4 >= totalCost[4]); System.out.println("- - - - -"); } public void printResults(String testname, long[] results) { System.out.println(" int i = 0; for (long l : results) { i++; System.out.println(i + ": " + l); } } }
package com.searchmetrics.simpleEmailService.dto; import com.amazonaws.services.simpleemail.model.SendRawEmailRequest; import com.searchmetrics.simpleEmailService.Config; import com.searchmetrics.simpleEmailService.converters.SendEmailRequestConverter; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import javax.mail.MessagingException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SendEmailRequestTest { private final Config CONFIG; private final static List<String> EMAIL_LIST = new ArrayList<String>(){ { addAll( Arrays.asList( "a.robinson@searchmetrics.com", "linus.jahn@searchmetrics.com", "p.pohlitz@searchmetrics.com")); } }; public SendEmailRequestTest() { Config config = new Config(); Config.SimpleEmailServiceConfig emailServiceConfig = new Config.SimpleEmailServiceConfig(); emailServiceConfig.setFromEmailAddress("linus.jahn@searchmetrics.com"); emailServiceConfig.setReplyToEmailAddress("linus.jahn@searchmetrics.com"); emailServiceConfig.setPrintOutgoingEmails(false); config.setSimpleEmailServiceConfig(emailServiceConfig); CONFIG = config; } @Test public void testConstructorAndGettersWithoutAttachments() { SendEmailRequest emailRequest = new SendEmailRequest(EMAIL_LIST, "[Service Test] This is a subject", "This is the message body. Hello!", null); Assert.assertEquals(EMAIL_LIST, emailRequest.getToEmailList()); Assert.assertEquals("[Service Test] This is a subject", emailRequest.getSubject()); Assert.assertEquals("This is the message body. Hello!", emailRequest.getMessageBody()); } @Test public void testMultipleAttachments() { List<SendEmailRequest.Attachment> attachmentList = new ArrayList<>(); attachmentList.add(new SendEmailRequest.Attachment("myFileName.txt", "text/plain", "SSB3YXMgYmFzZTY0LCBidXQgbm93IEknbSBwbGFpbiB0ZXh0IQ==")); attachmentList.add(new SendEmailRequest.Attachment("another_file.png", "image/png", "iVBORw0KGgoAAAANSUhEUgAAACQAAAAQCAIAAADxiUp0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAD6ElEQVQ4jb2UX0xbVRzHf+feS3vvbVcLreLGWOkf/m5r6ZhhWZw4eNiMSwCf1cQXfcGZLLqYLZk8OaNhmuHUQXALZr7oEl1xD2ZCxkjIYNjbTaFcVv4U2lF6b8taKO3tPff4UMVogg8k8/dyzvl+Hz4553vyRYQQ+L+G2cogWNHmB/HSCGV20NWvAMNi8Udt5T5V6qVdL6EiwzZgaKub5QNXiDSJuBKipIEQVMSTfAbpzSSbQGxx0eH3twGjtjJIcgYH+shGAt+/qoWHtZiA/Zchv46FXi3m3wbpv2AIFV4YAQAwemC4zRPQ+u3BECGEqFkcvk0eL9AVzcjshPw6XryjRccBK5S1jihp2t4CNIfnfkZcCWRXqYpmylS+DRhD8hl14hJZj4GaU1fnKdtRbWEQsAIEA8Mhc8WkbDj3xqlcNtd14dP+vqvJ1aQs/bCrrEyW5EtffHn27Jm52dm2tvZ9+/d3X/xMkqSPP+m6du2bUCh08uQ7wWDwtwcPRHG6p7fPbrdTgBX8+7d4ZgAYPfZ/pcUELPTiqe9Ab8L+y5ocBIDW1naWZYeHbweDwYMHn5ubm29sPCQI/lTqcX19/QtNTdevf+/1epuaXkQIyZLk/9Xf0fH2+fMfhkKhp8xmi8U6MXEP/soMgaaCmi1kBQCAc4DzBevWL7dGRu6wHItVDADV1dU8z9XU1Oj1bDi8eOXrPlavx1h9FI12d198973TiqLwBn7nzl3pVErN550Oh/VpK8YYACjQGYuOfkRXtSKzk/a+iWgd3dBBuU6gYhdz+AztPB6Px2Ox5ZVYbGFhfjPpwrK2lk6lUkJAkCTJN+CzWK0XurpySm4lttL5wbljx46zHPvvD1LY4chdLN4g6SWk24GKHUWNpwq6oiji9LTd4QCARCKRz+czmUylyxWJRm02WygUslosNMMYjQaKogEgODX1TGnp0tKi2+2Jx+M6nS6bzfI8bzKZ/m4QLTKKhR7m0Gl14nMA2ISNjo6yLBt6+DAuSeHwAsdxi+Ew9fIJSZbGx8c8nnrfgG/v3n2iKBqNhtrauqGhQbfHE41ENE0LBAINBxrGxu62tbfDP+sKAcFESYOSBp1pU52ZEQOCoBHNaDC6XK7J2dlXX3vd57thtVgzG5nenh63x33z5k9Hnj8yOTW5/GhZluV74+PNLS39/f1Op3NwaDCvKIlE0mKx0p2dnX+i2GLQVLRjN2gqc+At6llvQec4PrmaZFnO7XavJpNOpysQEGpr6yiaikSW7BX27MZGWdnuPTZbVVW14PdbLBae50VRdLpc62trlZVVsiyVlJSUl+/ZshufxGxZV09i/gDl8uDxBTmWkwAAAABJRU5ErkJggg==")); SendEmailRequest emailRequest = new SendEmailRequest(EMAIL_LIST, "This is a subject", "This is the message body. Hello!", attachmentList); Assert.assertEquals(attachmentList, emailRequest.getAttachmentList()); } }
package com.marshalchen.ultimaterecyclerview.demo; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.ActionMode; 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.FrameLayout; import android.widget.LinearLayout; import android.widget.Spinner; import com.marshalchen.ultimaterecyclerview.DragDropTouchListener; import com.marshalchen.ultimaterecyclerview.ItemTouchListenerAdapter; import com.marshalchen.ultimaterecyclerview.Logs; import com.marshalchen.ultimaterecyclerview.ScrollState; import com.marshalchen.ultimaterecyclerview.ScrollViewCallbacks; import com.marshalchen.ultimaterecyclerview.SwipeToDismissTouchListener; import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView; import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter; import com.marshalchen.ultimaterecyclerview.animators.BaseItemAnimator; import com.marshalchen.ultimaterecyclerview.animators.*; import com.nineoldandroids.animation.ValueAnimator; import com.nineoldandroids.view.ViewHelper; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity implements ActionMode.Callback { UltimateRecyclerView ultimateRecyclerView; SimpleAdapter simpleRecyclerViewAdapter = null; LinearLayoutManager linearLayoutManager; int moreNum = 100; private ActionMode actionMode; DragDropTouchListener dragDropTouchListener; ItemTouchListenerAdapter itemTouchListenerAdapter; Toolbar toolbar; boolean isDrag = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.tool_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view); ultimateRecyclerView.setHasFixedSize(false); List<String> stringList = new ArrayList<>(); simpleRecyclerViewAdapter = new SimpleAdapter(stringList); simpleRecyclerViewAdapter.setCustomLoadMoreView(LayoutInflater.from(this) .inflate(R.layout.custom_bottom_progressbar, null)); stringList.add("111"); stringList.add("aaa"); stringList.add("222"); stringList.add("33"); stringList.add("44"); stringList.add("55"); stringList.add("66"); stringList.add("11771"); linearLayoutManager = new LinearLayoutManager(this); ultimateRecyclerView.setLayoutManager(linearLayoutManager); ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter); ultimateRecyclerView.enableLoadmore(); ultimateRecyclerView.setParallaxHeader(getLayoutInflater().inflate(R.layout.parallax_recyclerview_header, ultimateRecyclerView.mRecyclerView, false)); ultimateRecyclerView.setOnParallaxScroll(new UltimateRecyclerView.OnParallaxScroll() { @Override public void onParallaxScroll(float percentage, float offset, View parallax) { Drawable c = toolbar.getBackground(); c.setAlpha(Math.round(127 + percentage * 128)); toolbar.setBackgroundDrawable(c); } }); ultimateRecyclerView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { simpleRecyclerViewAdapter.insert("Refresh things", 0); ultimateRecyclerView.setRefreshing(false); // ultimateRecyclerView.scrollBy(0, -50); linearLayoutManager.scrollToPosition(0); } }, 1000); } }); ultimateRecyclerView.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() { @Override public void loadMore(int itemsCount, final int maxLastVisiblePosition) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount()); simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount()); simpleRecyclerViewAdapter.insert("More " + moreNum++, simpleRecyclerViewAdapter.getAdapterItemCount()); // linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition,-1); // linearLayoutManager.scrollToPosition(maxLastVisiblePosition); } }, 1000); } }); ultimateRecyclerView.setScrollViewCallbacks(new ScrollViewCallbacks() { @Override public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) { } @Override public void onDownMotionEvent() { } @Override public void onUpOrCancelMotionEvent(ScrollState scrollState) { if (scrollState == ScrollState.DOWN) { Logs.d("scroll down"); showToolbar(toolbar); } else if (scrollState == ScrollState.UP) { Logs.d("scroll UP"); hideToolbar(toolbar); } else if (scrollState == ScrollState.STOP) { Logs.d("scroll STOP"); } else { Logs.d("other } } }); itemTouchListenerAdapter = new ItemTouchListenerAdapter(ultimateRecyclerView.mRecyclerView, new ItemTouchListenerAdapter.RecyclerViewOnItemClickListener() { @Override public void onItemClick(RecyclerView parent, View clickedView, int position) { Logs.d("onItemClick()"); if (actionMode != null && isDrag) { toggleSelection(position); } } @Override public void onItemLongClick(RecyclerView parent, View clickedView, int position) { Logs.d("onItemLongClick()" + isDrag); if (isDrag) { Logs.d("onItemLongClick()" + isDrag); toolbar.startActionMode(MainActivity.this); toggleSelection(position); dragDropTouchListener.startDrag(); ultimateRecyclerView.enableSwipeRefresh(false); } } }); ultimateRecyclerView.mRecyclerView.addOnItemTouchListener(itemTouchListenerAdapter); ultimateRecyclerView.setSwipeToDismissCallback(new SwipeToDismissTouchListener.DismissCallbacks() { @Override public SwipeToDismissTouchListener.SwipeDirection dismissDirection(int position) { return SwipeToDismissTouchListener.SwipeDirection.BOTH; } @Override public void onDismiss(RecyclerView view, List<SwipeToDismissTouchListener.PendingDismissData> dismissData) { for (SwipeToDismissTouchListener.PendingDismissData data : dismissData) { simpleRecyclerViewAdapter.remove(data.position); } } @Override public void onResetMotion() { isDrag = true; } @Override public void onTouchDown() { isDrag = false; } }); dragDropTouchListener = new DragDropTouchListener(ultimateRecyclerView.mRecyclerView, this) { @Override protected void onItemSwitch(RecyclerView recyclerView, int from, int to) { simpleRecyclerViewAdapter.swapPositions(from, to); simpleRecyclerViewAdapter.clearSelection(from); simpleRecyclerViewAdapter.notifyItemChanged(to); if (actionMode != null) actionMode.finish(); Logs.d("switch } @Override protected void onItemDrop(RecyclerView recyclerView, int position) { Logs.d("drop ultimateRecyclerView.enableSwipeRefresh(true); } }; dragDropTouchListener.setCustomDragHighlight(getResources().getDrawable(R.drawable.custom_drag_frame)); ultimateRecyclerView.mRecyclerView.addOnItemTouchListener(dragDropTouchListener); Spinner spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1); for (Type type : Type.values()) { spinnerAdapter.add(type.getTitle()); } spinner.setAdapter(spinnerAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Logs.d("selected---" + Type.values()[position].getTitle()); ultimateRecyclerView.setItemAnimator(Type.values()[position].getAnimator()); ultimateRecyclerView.getItemAnimator().setAddDuration(300); ultimateRecyclerView.getItemAnimator().setRemoveDuration(300); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); findViewById(R.id.add).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { simpleRecyclerViewAdapter.insert("newly added item", 1); } }); findViewById(R.id.del).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { simpleRecyclerViewAdapter.remove(1); } }); // ultimateRecyclerView.addItemDecoration( // new HorizontalDividerItemDecoration.Builder(this).build()); } private void toggleSelection(int position) { simpleRecyclerViewAdapter.toggleSelection(position); actionMode.setTitle("Selected " + "1"); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { Logs.d("actionmode---" + (mode == null)); mode.getMenuInflater().inflate(R.menu.menu_main, menu); return true; // return false; } /** * Called to refresh an action mode's action menu whenever it is invalidated. * * @param mode ActionMode being prepared * @param menu Menu used to populate action buttons * @return true if the menu or action mode was updated, false otherwise. */ @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // swipeToDismissTouchListener.setEnabled(false); this.actionMode = mode; return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } @Override public void onDestroyActionMode(ActionMode mode) { this.actionMode = null; } @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_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, SwipeBottomActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } enum Type { FadeIn("FadeIn", new FadeInAnimator()), FadeInDown("FadeInDown", new FadeInDownAnimator()), FadeInUp("FadeInUp", new FadeInUpAnimator()), FadeInLeft("FadeInLeft", new FadeInLeftAnimator()), FadeInRight("FadeInRight", new FadeInRightAnimator()), Landing("Landing", new LandingAnimator()), ScaleIn("ScaleIn", new ScaleInAnimator()), ScaleInTop("ScaleInTop", new ScaleInTopAnimator()), ScaleInBottom("ScaleInBottom", new ScaleInBottomAnimator()), ScaleInLeft("ScaleInLeft", new ScaleInLeftAnimator()), ScaleInRight("ScaleInRight", new ScaleInRightAnimator()), FlipInTopX("FlipInTopX", new FlipInTopXAnimator()), FlipInBottomX("FlipInBottomX", new FlipInBottomXAnimator()), FlipInLeftY("FlipInLeftY", new FlipInLeftYAnimator()), FlipInRightY("FlipInRightY", new FlipInRightYAnimator()), SlideInLeft("SlideInLeft", new SlideInLeftAnimator()), SlideInRight("SlideInRight", new SlideInRightAnimator()), SlideInDown("SlideInDown", new SlideInDownAnimator()), SlideInUp("SlideInUp", new SlideInUpAnimator()), OvershootInRight("OvershootInRight", new OvershootInRightAnimator()), OvershootInLeft("OvershootInLeft", new OvershootInLeftAnimator()); private String mTitle; private BaseItemAnimator mAnimator; Type(String title, BaseItemAnimator animator) { mTitle = title; mAnimator = animator; } public BaseItemAnimator getAnimator() { return mAnimator; } public String getTitle() { return mTitle; } } private void showToolbar(Toolbar mToolbar) { moveToolbar(mToolbar, 0); } private void hideToolbar(Toolbar mToolbar) { moveToolbar(mToolbar, -mToolbar.getHeight()); } private void moveToolbar(final Toolbar mToolbar, float toTranslationY) { if (ViewHelper.getTranslationY(mToolbar) == toTranslationY) { return; } ValueAnimator animator = ValueAnimator.ofFloat(ViewHelper.getTranslationY(mToolbar), toTranslationY).setDuration(200); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float translationY = (float) animation.getAnimatedValue(); ViewHelper.setTranslationY(mToolbar, translationY); ViewHelper.setTranslationY((View) ultimateRecyclerView, translationY); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ((View) ultimateRecyclerView).getLayoutParams(); lp.height = (int) -translationY + getScreenHeight() - lp.topMargin; ((View) ultimateRecyclerView).requestLayout(); } }); animator.start(); } protected int getScreenHeight() { return findViewById(android.R.id.content).getHeight(); } }
package de.frosner.datagenerator.generator; import static org.fest.assertions.Assertions.assertThat; import java.util.Iterator; import org.junit.Before; import org.junit.Test; import de.frosner.datagenerator.distributions.DummyDistribution; import de.frosner.datagenerator.distributions.Parameter; import de.frosner.datagenerator.exceptions.CircularDependencyException; import de.frosner.datagenerator.features.FeatureDefinition; public class FeatureDefinitionGraphTest { private FeatureDefinitionGraph _graph; @Before public void createGraph() { _graph = new FeatureDefinitionGraph(); } @Test public void testAddFeatureDefinition() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); assertThat(_graph.addFeatureDefinition(feature1)).isTrue(); assertThat(_graph._adjacentNodes.keySet()).containsOnly(feature1); assertThat(_graph._insertionOrder).containsExactly(feature1); FeatureDefinition feature2 = new FeatureDefinition("feature2", new DummyDistribution()); assertThat(_graph.addFeatureDefinition(feature2)).isTrue(); assertThat(_graph._adjacentNodes.keySet()).containsOnly(feature1, feature2); assertThat(_graph._insertionOrder).containsExactly(feature1, feature2); } @Test public void testAddFeatureDefinition_sameFeatureTwice() { FeatureDefinition feature = new FeatureDefinition("feature", new DummyDistribution()); _graph.addFeatureDefinition(feature); assertThat(_graph.addFeatureDefinition(feature)).isFalse(); assertThat(_graph._adjacentNodes.keySet()).containsOnly(feature); assertThat(_graph._insertionOrder).containsExactly(feature); } @Test public void testAddDependency() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); FeatureDefinition feature1_1 = new FeatureDefinition("feature1_1", new DummyDistribution()); Parameter parameter1_1 = new DummyParameter(0); _graph.addFeatureDefinition(feature1); assertThat(_graph.addDependency(feature1, feature1_1, parameter1_1)).isTrue(); assertThat(_graph._adjacentNodes.get(feature1)).containsOnly( new FeatureDefinitionParameterPair(feature1_1, parameter1_1)); assertThat(_graph._insertionOrder).containsExactly(feature1, feature1_1); } @Test public void testAddDependency_toDependentFeature() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); FeatureDefinition feature1_1 = new FeatureDefinition("feature1_1", new DummyDistribution()); Parameter parameter1_1 = new DummyParameter(0); FeatureDefinition feature1_1_1 = new FeatureDefinition("feature1_1_1", new DummyDistribution()); Parameter parameter1_1_1 = new DummyParameter(0); _graph.addFeatureDefinition(feature1); _graph.addDependency(feature1, feature1_1, parameter1_1); _graph.addDependency(feature1_1, feature1_1_1, parameter1_1_1); assertThat(_graph._adjacentNodes.get(feature1)).containsOnly( new FeatureDefinitionParameterPair(feature1_1, parameter1_1)); assertThat(_graph._adjacentNodes.get(feature1_1)).containsOnly( new FeatureDefinitionParameterPair(feature1_1_1, parameter1_1_1)); assertThat(_graph._insertionOrder).containsExactly(feature1, feature1_1, feature1_1_1); } @Test public void testAddDependency_sameDependencyTwice() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); FeatureDefinition feature1_1 = new FeatureDefinition("feature1_1", new DummyDistribution()); Parameter parameter1_1 = new DummyParameter(0); _graph.addFeatureDefinition(feature1); _graph.addDependency(feature1, feature1_1, parameter1_1); assertThat(_graph.addDependency(feature1, feature1_1, parameter1_1)).isFalse(); assertThat(_graph._adjacentNodes.get(feature1)).containsOnly( new FeatureDefinitionParameterPair(feature1_1, parameter1_1)); assertThat(_graph._insertionOrder).containsExactly(feature1, feature1_1); } @Test(expected = CircularDependencyException.class) public void testAddDependency_circularDependencyByEdge() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); Parameter parameter1 = new DummyParameter(0); FeatureDefinition feature2 = new FeatureDefinition("feature2", new DummyDistribution()); Parameter parameter2 = new DummyParameter(0); _graph.addFeatureDefinition(feature1); _graph.addDependency(feature1, feature2, parameter2); _graph.addDependency(feature2, feature1, parameter1); } @Test(expected = CircularDependencyException.class) public void testAddDependency_circularDependencyByLongerPath() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); Parameter parameter1 = new DummyParameter(0); FeatureDefinition feature2 = new FeatureDefinition("feature2", new DummyDistribution()); Parameter parameter2 = new DummyParameter(0); FeatureDefinition feature3 = new FeatureDefinition("feature3", new DummyDistribution()); Parameter parameter3 = new DummyParameter(0); _graph.addFeatureDefinition(feature1); _graph.addDependency(feature1, feature2, parameter2); _graph.addDependency(feature2, feature3, parameter3); _graph.addDependency(feature3, feature1, parameter1); } @Test public void testIsLeaf() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); FeatureDefinition feature1_1 = new FeatureDefinition("feature1_1", new DummyDistribution()); Parameter parameter1_1 = new DummyParameter(0); _graph.addFeatureDefinition(feature1); assertThat(_graph.isLeaf(feature1)).isTrue(); _graph.addDependency(feature1, feature1_1, parameter1_1); assertThat(_graph.isLeaf(feature1)).isFalse(); assertThat(_graph.isLeaf(feature1_1)).isTrue(); } @Test public void testIsLeaf_featureNotInGraph() { assertThat(_graph.isLeaf(new FeatureDefinition("feature", new DummyDistribution()))).isFalse(); } @Test public void testGetDependentParameters() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); FeatureDefinition feature1_1 = new FeatureDefinition("feature1_1", new DummyDistribution()); Parameter parameter1_1 = new DummyParameter(0); FeatureDefinition feature1_2 = new FeatureDefinition("feature1_2", new DummyDistribution()); Parameter parameter1_2 = new DummyParameter(0); _graph.addFeatureDefinition(feature1); _graph.addDependency(feature1, feature1_1, parameter1_1); _graph.addDependency(feature1, feature1_2, parameter1_2); assertThat(_graph.getDependentParameters(feature1)).containsExactly(parameter1_1, parameter1_2); assertThat(_graph.getDependentParameters(feature1_1)).isEmpty(); assertThat(_graph.getDependentParameters(feature1_2)).isEmpty(); } @Test public void testIterator() { FeatureDefinition feature1 = new FeatureDefinition("feature1", new DummyDistribution()); FeatureDefinition feature1_1 = new FeatureDefinition("feature1_1", new DummyDistribution()); Parameter parameter1_1 = new DummyParameter(0); FeatureDefinition feature2 = new FeatureDefinition("feature2", new DummyDistribution()); FeatureDefinition feature2_1 = new FeatureDefinition("feature2_1", new DummyDistribution()); Parameter parameter2_1 = new DummyParameter(0); FeatureDefinition feature3 = new FeatureDefinition("feature3", new DummyDistribution()); _graph.addFeatureDefinition(feature1); _graph.addFeatureDefinition(feature2); _graph.addFeatureDefinition(feature3); _graph.addDependency(feature1, feature1_1, parameter1_1); _graph.addDependency(feature2, feature2_1, parameter2_1); Iterator<FeatureDefinition> iterator = _graph.iterator(); assertThat(iterator.next()).isEqualTo(feature1); assertThat(iterator.next()).isEqualTo(feature2); assertThat(iterator.next()).isEqualTo(feature3); assertThat(iterator.next()).isEqualTo(feature1_1); assertThat(iterator.next()).isEqualTo(feature2_1); } }
package net.nemerosa.ontrack.jenkins.steps; import com.google.common.collect.ImmutableMap; import net.nemerosa.ontrack.dsl.Build; import net.nemerosa.ontrack.dsl.Ontrack; import net.nemerosa.ontrack.dsl.ValidationRun; import net.nemerosa.ontrack.jenkins.dsl.OntrackDSLConnector; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import static org.mockito.Mockito.*; public class OntrackValidateStepRunTest { @Rule public JenkinsRule jenkinsRule = new JenkinsRule(); @Test public void test_validate_default() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS')", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validate("VS", "PASSED")).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validate("VS", "PASSED"); verify(mockRun, times(1)).setRunInfo(anyMapOf(String.class, Object.class)); } @Test public void test_validate_custom() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', validationStatus: 'FAILED')", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validate("VS", "FAILED")).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validate("VS", "FAILED"); verify(mockRun, times(1)).setRunInfo(anyMapOf(String.class, Object.class)); } @Test public void test_validate_with_fraction_data() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', dataType: 'fraction', data: [numerator: 99, denominator: 100])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithFraction(anyString(), anyInt(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithFraction("VS", 99, 100, null); } @Test public void test_validate_with_fraction_data_and_status() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', validationStatus: 'FAILED', dataType: 'fraction', data: [numerator: 99, denominator: 100])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithFraction(anyString(), anyInt(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithFraction("VS", 99, 100, "FAILED"); } @Test public void test_validate_with_chml_data() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', dataType: 'chml', data: [critical: 12, high: 100])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithCHML(anyString(), anyInt(), anyInt(), anyInt(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithCHML("VS", 12, 100, 0, 0, null); } @Test public void test_validate_with_chml_data_and_status() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', validationStatus: 'FAILED', dataType: 'chml', data: [critical: 12, high: 100])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithCHML(anyString(), anyInt(), anyInt(), anyInt(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithCHML("VS", 12, 100, 0, 0, "FAILED"); } @Test public void test_validate_with_text_data_and_status() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', validationStatus: 'FAILED', dataType: 'text', data: [value: 'My text'])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithText(anyString(), anyString(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithText("VS", "FAILED", "My text"); } @Test public void test_validate_with_number_data() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', dataType: 'number', data: [value: 12])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithNumber(anyString(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithNumber("VS", 12, null); } @Test public void test_validate_with_number_data_and_status() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', validationStatus: 'FAILED', dataType: 'number', data: [value: 12])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithNumber(anyString(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithNumber("VS", 12, "FAILED"); } @Test public void test_validate_with_percentage_data() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', dataType: 'percentage', data: [value: 33])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithPercentage(anyString(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithPercentage("VS", 33, null); } @Test public void test_validate_with_percentage_data_and_status() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', validationStatus: 'FAILED', dataType: 'percentage', data: [value: 33])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithPercentage(anyString(), anyInt(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithPercentage("VS", 33, "FAILED"); } @Test public void test_validate_with_generic_data() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', dataType: 'net.nemerosa.ontrack.extension.general.validation.CHMLValidationDataType', data: [value: 33])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithData(anyString(), any(), anyString(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithData("VS", ImmutableMap.of("value", 33), "net.nemerosa.ontrack.extension.general.validation.CHMLValidationDataType", null); } @Test public void test_validate_with_generic_data_and_status() throws Exception { WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow"); // leave out the subject job.setDefinition(new CpsFlowDefinition("ontrackValidate(project: 'prj', branch: 'master', build: '1', validationStamp: 'VS', validationStatus: 'FAILED', dataType: 'net.nemerosa.ontrack.extension.general.validation.CHMLValidationDataType', data: [value: 33])", true)); Ontrack ontrack = mock(Ontrack.class); Build mockBuild = mock(Build.class); ValidationRun mockRun = mock(ValidationRun.class); when(ontrack.build("prj", "master", "1")).thenReturn(mockBuild); when(mockBuild.validateWithData(anyString(), any(), anyString(), anyString())).thenReturn(mockRun); OntrackDSLConnector.setOntrack(ontrack); jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0)); verify(mockBuild, times(1)).validateWithData("VS", ImmutableMap.of("value", 33), "net.nemerosa.ontrack.extension.general.validation.CHMLValidationDataType", "FAILED"); } }
package nom.bdezonia.zorbage.type.data.float64.real; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import nom.bdezonia.zorbage.groups.G; import nom.bdezonia.zorbage.type.ctor.MemoryConstruction; import nom.bdezonia.zorbage.type.ctor.StorageConstruction; import nom.bdezonia.zorbage.type.data.float64.real.Float64MatrixMember; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; /** * * @author Barry DeZonia * */ public class TestFloat64Matrix { // toggle true/false if want to run this big slow test private static final boolean RUN = false; @Test public void testHugeMatrix() { if (RUN) { System.out.println("Making a huge virtual matrix > 2 gig entries"); Float64MatrixMember m = G.DBL_MAT.construct(MemoryConstruction.DENSE, StorageConstruction.FILE, 50000, 50000); G.DBL_MAT.unity(m); Float64Member value = G.DBL.construct(); Float64Member zero = G.DBL.construct(); Float64Member one = G.DBL.construct(); G.DBL.unity(one); for (long r = 0; r < m.rows(); r++) { for (long c = 0; c < m.cols(); c++) { m.v(r, c, value); if (r == c) { assertTrue(G.DBL.isEqual(value, one)); } else { assertTrue(G.DBL.isEqual(value, zero)); } } } } } @Test public void testMatrixInverse() { double tol = 0.00000000000001; Float64MatrixMember mat = new Float64MatrixMember(3, 3, new double[] {1,7,4,1,2,4,8,3,3}); Float64MatrixMember invMat = new Float64MatrixMember(3, 3, new double[9]); Float64MatrixMember ident = new Float64MatrixMember(3, 3, new double[9]); G.DBL_MAT.invert(mat, invMat); Float64Member value = new Float64Member(); invMat.v(0, 0, value); assertEquals(-6.0/145, value.v(), tol); invMat.v(0, 1, value); assertEquals(-9.0/145, value.v(), tol); invMat.v(0, 2, value); assertEquals(20.0/145, value.v(), tol); invMat.v(1, 0, value); assertEquals(29.0/145, value.v(), tol); invMat.v(1, 1, value); assertEquals(-29.0/145, value.v(), tol); invMat.v(1, 2, value); assertEquals(0.0/145, value.v(), tol); invMat.v(2, 0, value); assertEquals(-13.0/145, value.v(), tol); invMat.v(2, 1, value); assertEquals(53.0/145, value.v(), tol); invMat.v(2, 2, value); assertEquals(-5.0/145, value.v(), tol); G.DBL_MAT.multiply(mat, invMat, ident); ident.v(0, 0, value); assertEquals(1, value.v(), tol); ident.v(0, 1, value); assertEquals(0, value.v(), tol); ident.v(0, 2, value); assertEquals(0, value.v(), tol); ident.v(1, 0, value); assertEquals(0, value.v(), tol); ident.v(1, 1, value); assertEquals(1, value.v(), tol); ident.v(1, 2, value); assertEquals(0, value.v(), tol); ident.v(2, 0, value); assertEquals(0, value.v(), tol); ident.v(2, 1, value); assertEquals(0, value.v(), tol); ident.v(2, 2, value); assertEquals(1, value.v(), tol); } }
package net.malisis.core.renderer; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.malisis.core.MalisisCore; import net.malisis.core.renderer.element.Face; import net.malisis.core.renderer.element.Shape; import net.malisis.core.renderer.element.Vertex; import net.malisis.core.renderer.icon.MalisisIcon; import net.malisis.core.renderer.preset.ShapePreset; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.DestroyBlockProgress; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.relauncher.ReflectionHelper; public class BaseRenderer extends TileEntitySpecialRenderer implements ISimpleBlockRenderingHandler, IItemRenderer { /** * Set rendering for world */ public static final int TYPE_ISBRH_WORLD = 1; /** * Set rendering for inventory with ISBRH */ public static final int TYPE_ISBRH_INVENTORY = 2; /** * Set rendering for inventory with IItemRenderer */ public static final int TYPE_ITEM_INVENTORY = 3; /** * Set rendering for TESR */ public static final int TYPE_TESR_WORLD = 4; //Reference to Minecraft.renderGlobal.damagedBlocks (lazy loaded) private static Map damagedBlocks; protected static IIcon[] damagedIcons; /** * Id for the renderer */ protected int renderId = -1; /** * Tessellator */ protected Tessellator t = Tessellator.instance; /** * Current world reference (ISBRH/TESR) */ protected IBlockAccess world; /** * RenderBlocks reference (ISBRH) */ protected RenderBlocks renderBlocks; /** * Block to render (ISBRH/TESR) */ protected Block block; /** * Metadata of the block to render (ISBRH/TESR) */ protected int blockMetadata; /** * Position of the block (ISBRH/TESR) */ protected int x, y, z; /** * ItemStack to render (ITEM) */ protected ItemStack itemStack; /** * Type of item rendering (ITEM) * * @see {@link ItemRenderType} */ protected ItemRenderType itemRenderType; /** * Type of rendering : <code>TYPE_ISBRH_WORLD</code>, <code>TYPE_ISBRH_INVENTORY</code>, <code>TYPE_ITEM_INVENTORY</code> or * <code>TYPE_TESR_WORLD</code> */ protected int renderType; /** * Mode of rendering (GL constants) */ protected int drawMode; /** * Are render coordinates already shifted (ISBRH) */ protected boolean isShifted = false; /** * Current shape being rendered */ protected Shape shape; /** * Current face being rendered */ protected Face face; /** * Current parameters for the shape being rendered */ protected RenderParameters rp; /** * Current parameters for the face being rendered */ protected RenderParameters params; /** * Base brightness of the block */ protected int baseBrightness; /** * An override texture set by the renderer */ protected IIcon overrideTexture; /** * TileEntity currently drawing (for TESR) */ protected TileEntity tileEntity; /** * Partial tick time (for TESR) */ protected float partialTick = 0; /** * Get the damage for the block (for TESR) */ protected boolean getBlockDamage = false; /** * Current block destroy progression (for TESR) */ protected DestroyBlockProgress destroyBlockProgress = null; /** * Is at least one vertex been drawn */ protected boolean vertexDrawn = false; public BaseRenderer() { this.renderId = RenderingRegistry.getNextAvailableRenderId(); this.t = Tessellator.instance; initShapes(); initParameters(); } /** * Gets the partialTick for this frame. Used for TESR and ITEMS * * @return */ public float getPartialTick() { return partialTick; } // #region set() /** * Resets data so this <code>BaseRenderer</code> can be reused. */ public void reset() { this.renderType = 0; this.drawMode = 0; this.world = null; this.block = null; this.blockMetadata = 0; this.x = 0; this.y = 0; this.z = 0; this.overrideTexture = null; this.destroyBlockProgress = null; } /** * Sets informations for this <code>BaseRenderer</code>. * * @param world * @param block * @param x * @param y * @param z * @param metadata */ public void set(IBlockAccess world, Block block, int x, int y, int z, int metadata) { this.world = world; this.block = block; this.blockMetadata = metadata; this.x = x; this.y = y; this.z = z; } /** * Sets informations for this <code>BaseRenderer</code>. * * @param block */ public void set(Block block) { set(world, block, x, y, z, blockMetadata); } /** * Sets informations for this <code>BaseRenderer</code>. * * @param blockMetadata */ public void set(int blockMetadata) { set(world, block, x, y, z, blockMetadata); } /** * Sets informations for this <code>BaseRenderer</code>. * * @param block * @param blockMetadata */ public void set(Block block, int blockMetadata) { set(world, block, x, y, z, blockMetadata); } /** * Sets informations for this <code>BaseRenderer</code>. * * @param x * @param y * @param z */ public void set(int x, int y, int z) { set(world, block, x, y, z, blockMetadata); } /** * Sets informations for this <code>BaseRenderer</code>. * * @param te * @param partialTick */ public void set(TileEntity te, float partialTick) { set(te.getWorldObj(), te.getBlockType(), te.xCoord, te.yCoord, te.zCoord, te.getBlockMetadata()); this.partialTick = partialTick; this.tileEntity = te; } /** * Sets informations for this <code>BaseRenderer</code>. * * @param type * @param itemStack */ public void set(ItemRenderType type, ItemStack itemStack) { if (itemStack.getItem() instanceof ItemBlock) set(Block.getBlockFromItem(itemStack.getItem())); this.itemStack = itemStack; this.itemRenderType = type; } // #end // #region ISBRH @Override public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) { set(block, metadata); renderBlocks = renderer; prepare(TYPE_ISBRH_INVENTORY); render(); clean(); } @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { set(world, block, x, y, z, world.getBlockMetadata(x, y, z)); renderBlocks = renderer; vertexDrawn = false; prepare(TYPE_ISBRH_WORLD); if (renderer.hasOverrideBlockTexture()) overrideTexture = renderer.overrideBlockTexture; render(); clean(); return vertexDrawn; } @Override public boolean shouldRender3DInInventory(int modelId) { return true; } // #end ISBRH // #region IItemRenderer @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { return true; } @Override public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return true; } @Override public void renderItem(ItemRenderType type, ItemStack item, Object... data) { set(type, item); prepare(TYPE_ITEM_INVENTORY); render(); clean(); } // #end IItemRenderer // #region TESR @Override public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTick) { set(te, partialTick); prepare(TYPE_TESR_WORLD, x, y, z); render(); if (getBlockDamage) { destroyBlockProgress = getBlockDestroyProgress(); if (destroyBlockProgress != null) { next(); GL11.glEnable(GL11.GL_BLEND); OpenGlHelper.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO); GL11.glAlphaFunc(GL11.GL_GREATER, 0); GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); t.disableColor(); renderDestroyProgress(); next(); GL11.glDisable(GL11.GL_BLEND); } } clean(); } // #end TESR // #region prepare() /** * Prepares the tessellator and the GL states for the <b>renderType</b>. <b>data</b> is only for TESR. * * @param renderType * @param data */ public void prepare(int renderType, double... data) { this.renderType = renderType; if (renderType == TYPE_ISBRH_WORLD) { tessellatorShift(); } else if (renderType == TYPE_ISBRH_INVENTORY) { GL11.glTranslatef(-0.5F, -0.5F, -0.5F); startDrawing(); } else if (renderType == TYPE_ITEM_INVENTORY) { GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); startDrawing(); } else if (renderType == TYPE_TESR_WORLD) { GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); RenderHelper.disableStandardItemLighting(); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glShadeModel(GL11.GL_SMOOTH); GL11.glPushMatrix(); GL11.glTranslated(data[0], data[1], data[2]); bindTexture(TextureMap.locationBlocksTexture); startDrawing(); } } /** * Tells the tessellator to start drawing GL_QUADS. */ public void startDrawing() { startDrawing(GL11.GL_QUADS); } /** * Tells the tessellator to start drawing <b>drawMode</b>. * * @param drawMode */ public void startDrawing(int drawMode) { t.startDrawing(drawMode); this.drawMode = drawMode; } /** * Triggers a draw and restart drawing with current <i>drawMode</i>. */ public void next() { next(drawMode); } /** * Triggers a draw and restart drawing with <b>drawMode</b>. * * @param drawMode */ public void next(int drawMode) { draw(); startDrawing(drawMode); } /** * Triggers a draw. */ public void draw() { t.draw(); } /** * Cleans the current renderer state. */ public void clean() { if (renderType == TYPE_ISBRH_WORLD) { tessellatorUnshift(); } else if (renderType == TYPE_ISBRH_INVENTORY) { draw(); GL11.glTranslatef(0.5F, 0.5F, 0.5F); } else if (renderType == TYPE_ITEM_INVENTORY) { draw(); GL11.glPopAttrib(); } else if (renderType == TYPE_TESR_WORLD) { draw(); GL11.glPopMatrix(); GL11.glPopAttrib(); } reset(); } /** * Shifts the tessellator for ISBRH rendering. */ public void tessellatorShift() { if (isShifted) return; isShifted = true; t.addTranslation(x, y, z); } /** * Unshifts the tessellator for ISBRH rendering. */ public void tessellatorUnshift() { if (!isShifted) return; isShifted = false; t.addTranslation(-x, -y, -z); } /** * Enables the blending for the rendering. Ineffective for ISBRH. */ public void enableBlending() { if (renderType == TYPE_ISBRH_WORLD) return; GL11.glEnable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glShadeModel(GL11.GL_SMOOTH); OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); GL11.glAlphaFunc(GL11.GL_GREATER, 0.0F); } // #end prepare() /** * Called when the renderer is instantiated */ protected void initShapes() { shape = ShapePreset.Cube(); } /** * Called when the renderer is instantiated */ protected void initParameters() { rp = new RenderParameters(); } /** * Renders the block using the default Minecraft rendering system * * @param renderer */ public void renderStandard() { renderStandard(renderBlocks); } /** * Renders the blocks using the defaul Minecraft rendering system with the specified <b>renderer</b> * * @param renderer */ public void renderStandard(RenderBlocks renderer) { if (renderer == null) return; boolean b = isShifted; if (b) tessellatorUnshift(); renderer.setRenderBoundsFromBlock(block); renderer.renderStandardBlock(block, x, y, z); if (b) tessellatorShift(); } /** * Main rendering method. */ public void render() {} /** * Renders the destroy progress manually for TESR. Called if BaseRenderer.destroyBlockProgress is not null */ public void renderDestroyProgress() {} /** * Draws a shape with its own parameters * * @param shape */ public void drawShape(Shape shape) { drawShape(shape, null); } /** * Draws a shape with specified parameters * * @param shape * @param params */ public void drawShape(Shape s, RenderParameters params) { if (s == null) return; shape = s; rp = params != null ? params : new RenderParameters(); s.applyMatrix(); // vertex position if (rp.vertexPositionRelativeToRenderBounds.get()) calcVertexesPosition(getRenderBounds()); if (rp.applyTexture.get()) applyTexture(s, rp); for (Face face : s.getFaces()) drawFace(face, face.getParameters()); } /** * Draws a face with its own parameters * * @param face */ public void drawFace(Face face) { drawFace(face, face.getParameters()); } /** * Draws a face with specified parameters. * * @param f * @param faceParams */ protected void drawFace(Face f, RenderParameters faceParams) { if (f == null) return; int vertexCount = f.getVertexes().length; if (vertexCount != 4 && renderType == TYPE_ISBRH_WORLD) { MalisisCore.log.error("[BaseRenderer] Attempting to render a face containing {} vertexes in ISBRH. Ignored", vertexCount); return; } face = f; params = RenderParameters.merge(rp, faceParams); if (!shouldRenderFace(face)) return; if (renderType == TYPE_ITEM_INVENTORY || renderType == TYPE_ISBRH_INVENTORY || params.useNormals.get()) t.setNormal(params.direction.get().offsetX, params.direction.get().offsetY, params.direction.get().offsetZ); baseBrightness = getBaseBrightness(); drawVertexes(face.getVertexes()); if (drawMode == GL11.GL_POLYGON) next(); } /*** * Draws an array of vertexes (usually <i>Face.getVertexes()</i>) * * @param vertexes */ protected void drawVertexes(Vertex[] vertexes) { for (int i = 0; i < vertexes.length; i++) { drawVertex(vertexes[i], i); if (drawMode == GL11.GL_LINE_STRIP) drawVertex(vertexes[i == vertexes.length - 1 ? 0 : i + 1], i); } } /** * Draws a single vertex * * @param vertex */ protected void drawVertex(Vertex vertex, int count) { // brightness int brightness = calcVertexBrightness(vertex, (int[][]) params.aoMatrix.get(count)); vertex.setBrightness(brightness); // color int color = calcVertexColor(vertex, (int[][]) params.aoMatrix.get(count)); vertex.setColor(color); // alpha if (!params.usePerVertexAlpha.get()) vertex.setAlpha(params.alpha.get()); t.setColorRGBA_I(vertex.getColor(), vertex.getAlpha()); t.setBrightness(vertex.getBrightness()); if (drawMode != GL11.GL_LINE && params.useTexture.get()) t.addVertexWithUV(vertex.getX(), vertex.getY(), vertex.getZ(), vertex.getU(), vertex.getV()); else t.addVertex(vertex.getX(), vertex.getY(), vertex.getZ()); vertexDrawn = true; } /** * Gets the IIcon corresponding to <b>params</b>. * * @param params * @return */ protected IIcon getIcon(RenderParameters params) { IIcon icon = params.icon.get(); if (params.useCustomTexture.get()) icon = new MalisisIcon(); //use a generic icon where UVs go from 0 to 1 else if (overrideTexture != null) icon = overrideTexture; else if (block != null && icon == null) { int side = 0; if (params.textureSide.get() != null) side = params.textureSide.get().ordinal(); if (world != null && params.useWorldSensitiveIcon.get()) icon = block.getIcon(world, x, y, z, side); else icon = block.getIcon(side, blockMetadata); } return icon; } /** * Checks if <b>side</b> should be rendered * * @param side */ protected boolean shouldRenderFace(Face face) { if (renderType != TYPE_ISBRH_WORLD || world == null || block == null) return true; if (rp != null && rp.renderAllFaces.get()) return true; if (renderBlocks != null && renderBlocks.renderAllFaces == true) return true; RenderParameters p = face.getParameters(); if (p.direction.get() == null) return true; boolean b = block.shouldSideBeRendered(world, x + p.direction.get().offsetX, y + p.direction.get().offsetY, z + p.direction.get().offsetZ, p.direction.get().ordinal()); return b; } /** * Applies the texture to the <b>shape</b>. Usually necessary before some shape transformations in conjunction with * RenderParameters.applyTexture set to false to prevent reapplying texture when rendering. * * @param shape */ public void applyTexture(Shape shape) { applyTexture(shape, null); } /** * Applies the texture to the <b>shape</b> with specified <b>parameters. Usually necessary before some shape transformations in * conjunction with RenderParameters.applyTexture set to false to prevent reapplying texture when rendering. * * @param shape * @param parameters */ public void applyTexture(Shape shape, RenderParameters parameters) { //shape.applyMatrix(); for (Face f : shape.getFaces()) { RenderParameters params = RenderParameters.merge(f.getParameters(), parameters); IIcon icon = getIcon(params); if (icon != null) f.setTexture(icon, params.flipU.get(), params.flipV.get(), params.interpolateUV.get()); } } /** * Calculates the ambient occlusion for a vertex and also apply the side dependent shade.<br /> * <b>aoMatrix</b> is the list of block coordinates necessary to compute AO. If it's empty, only the global face shade is applied.<br /> * Also, <i>params.colorMultiplier</i> is applied as well. * * @param vertex * @param aoMatrix */ protected int calcVertexColor(Vertex vertex, int[][] aoMatrix) { int color = 0xFFFFFF; if (params.usePerVertexColor.get()) color = vertex.getColor(); if (params.colorMultiplier.get() != null) color = params.colorMultiplier.get(); else if (block != null) color = world != null ? block.colorMultiplier(world, x, y, z) : block.getRenderColor(blockMetadata); if (drawMode == GL11.GL_LINE) return color; if (renderType != TYPE_ISBRH_WORLD && renderType != TYPE_TESR_WORLD) return color; float factor = 1; if (params.calculateAOColor.get() && aoMatrix != null && Minecraft.isAmbientOcclusionEnabled() && block.getLightValue(world, x, y, z) == 0) { factor = getBlockAmbientOcclusion(world, x + params.direction.get().offsetX, y + params.direction.get().offsetY, z + params.direction.get().offsetZ); for (int i = 0; i < aoMatrix.length; i++) factor += getBlockAmbientOcclusion(world, x + aoMatrix[i][0], y + aoMatrix[i][1], z + aoMatrix[i][2]); factor /= (aoMatrix.length + 1); } factor *= params.colorFactor.get(); int r = (int) ((color >> 16 & 255) * factor); int g = (int) ((color >> 8 & 255) * factor); int b = (int) ((color & 255) * factor); color = r << 16 | g << 8 | b; return color; } /** * Gets the base brightness for the current face.<br /> * If <i>params.useBlockBrightness</i> = false, <i>params.brightness</i>. Else, the brightness is determined base on * <i>params.offset</i> and <i>getBlockBounds()</i> */ protected int getBaseBrightness() { if ((renderType != TYPE_ISBRH_WORLD && renderType != TYPE_TESR_WORLD) || world == null || !params.useBlockBrightness.get()) return params.brightness.get(); if (params.direction.get() == null) return block.getMixedBrightnessForBlock(world, x, y, z); AxisAlignedBB bounds = getRenderBounds(); ForgeDirection dir = params.direction.get(); int ox = x + dir.offsetX; int oy = y + dir.offsetY; int oz = z + dir.offsetZ; if (bounds != null) { if (dir == ForgeDirection.WEST && bounds.minX > 0) ox += 1; else if (dir == ForgeDirection.EAST && bounds.maxX < 1) ox -= 1; else if (dir == ForgeDirection.NORTH && bounds.minZ > 0) oz += 1; else if (dir == ForgeDirection.SOUTH && bounds.maxZ < 1) oz -= 1; else if (dir == ForgeDirection.DOWN && bounds.minY > 0) oy += 1; else if (dir == ForgeDirection.UP && bounds.maxY < 1) oy -= 1; } return getMixedBrightnessForBlock(world, ox, oy, oz); } /** * Calculates the ambient occlusion brightness for a vertex. <b>aoMatrix</b> is the list of block coordinates necessary to compute AO. * Only first 3 blocks are used.<br /> * * @param vertex * @param baseBrightness * @param aoMatrix */ protected int calcVertexBrightness(Vertex vertex, int[][] aoMatrix) { if (drawMode == GL11.GL_LINE) return baseBrightness; if (renderType != TYPE_ISBRH_WORLD && renderType != TYPE_TESR_WORLD) return baseBrightness; if (!params.calculateBrightness.get() || aoMatrix == null) return baseBrightness; if (!Minecraft.isAmbientOcclusionEnabled() || block.getLightValue(world, x, y, z) != 0) return baseBrightness; int[] b = new int[Math.max(3, aoMatrix.length)]; for (int i = 0; i < aoMatrix.length; i++) b[i] += getMixedBrightnessForBlock(world, x + aoMatrix[i][0], y + aoMatrix[i][1], z + aoMatrix[i][2]); int brightness = getAoBrightness(b[0], b[1], b[2], baseBrightness); return brightness; } /** * Does the actual brightness calculation (copied from net.minecraft.client.renderer.BlocksRenderer.java) */ protected int getAoBrightness(int b1, int b2, int b3, int base) { if (b1 == 0) b1 = base; if (b2 == 0) b2 = base; if (b3 == 0) b3 = base; return b1 + b2 + b3 + base >> 2 & 16711935; } /** * Gets the block ambient occlusion value. Contrary to base Minecraft code, it's the actual block at the <b>x</b>, <b>y</b> and <b>z</b> * coordinates which is used to get the value, and not value of the block drawn. This allows to have different logic behaviors for AO * values for a block. * * @param world * @param x * @param y * @param z */ protected float getBlockAmbientOcclusion(IBlockAccess world, int x, int y, int z) { Block block = world.getBlock(x, y, z); if (block == null) return 1.0F; return block.getAmbientOcclusionLightValue(); } /** * Gets the mix brightness for a block (sky + block source) * * @param world * @param x * @param y * @param z */ protected int getMixedBrightnessForBlock(IBlockAccess world, int x, int y, int z) { // return world.getLightBrightnessForSkyBlocks(x, y, z, 0); return world.getBlock(x, y, z).getMixedBrightnessForBlock(world, x, y, z); } /** * Gets the rendering bounds. If <i>params.useBlockBounds</i> = false, <i>params.renderBounds</i> is used instead of the actual block * bounds. * * @return */ protected AxisAlignedBB getRenderBounds() { if (block == null || !rp.useBlockBounds.get()) return rp.renderBounds.get(); if (world != null) block.setBlockBoundsBasedOnState(world, x, y, z); return AxisAlignedBB.getBoundingBox(block.getBlockBoundsMinX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(), block.getBlockBoundsMaxX(), block.getBlockBoundsMaxY(), block.getBlockBoundsMaxZ()); } /** * Modifies the vertexes coordinates relative to the bounds specified.<br /> * Eg : if x = 0.5, minX = 1, maxX = 3, x becomes 2 * * @param bounds */ protected void calcVertexesPosition(AxisAlignedBB bounds) { for (Face f : shape.getFaces()) for (Vertex v : f.getVertexes()) v.interpolateCoord(bounds); } /** * Gets and hold reference to damagedBlocks from Minecraft.renderGlobal via reflection. * * @return */ protected Map getDamagedBlocks() { if (damagedBlocks != null) return damagedBlocks; try { Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); Field f = ReflectionHelper.findField(RenderGlobal.class, MalisisCore.isObfEnv ? "field_94141_F" : "destroyBlockIcons"); modifiers.setInt(f, f.getModifiers() & ~Modifier.FINAL); damagedIcons = (IIcon[]) f.get(Minecraft.getMinecraft().renderGlobal); f = ReflectionHelper.findField(RenderGlobal.class, MalisisCore.isObfEnv ? "field_72738_E" : "damagedBlocks"); modifiers.setInt(f, f.getModifiers()); damagedBlocks = (HashMap) f.get(Minecraft.getMinecraft().renderGlobal); return damagedBlocks; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Gets the destroy block progress for this rendering. Only used for TESR. * * @return */ protected DestroyBlockProgress getBlockDestroyProgress() { if (renderType != TYPE_TESR_WORLD) return null; Map damagedBlocks = getDamagedBlocks(); if (damagedBlocks == null || damagedBlocks.isEmpty()) return null; Iterator iterator = damagedBlocks.values().iterator(); while (iterator.hasNext()) { DestroyBlockProgress dbp = (DestroyBlockProgress) iterator.next(); if (isCurrentBlockDestroyProgress(dbp)) return dbp; } return null; } /** * Checks whether the DestroyBlockProgress specified should apply for this TESR. * * @param dbp * @return */ protected boolean isCurrentBlockDestroyProgress(DestroyBlockProgress dbp) { return dbp.getPartialBlockX() == x && dbp.getPartialBlockY() == y && dbp.getPartialBlockZ() == z; } @Override public int getRenderId() { return renderId; } public void registerFor(Class... listClass) { for (Class clazz : listClass) { if (Block.class.isAssignableFrom(clazz)) { try { clazz.getField("renderId").set(null, renderId); RenderingRegistry.registerBlockHandler(this); } catch (ReflectiveOperationException e) { MalisisCore.log.error("Tried to register ISBRH for block class {} that does not have renderId field", clazz.getSimpleName()); e.printStackTrace(); } } else if (TileEntity.class.isAssignableFrom(clazz)) { ClientRegistry.bindTileEntitySpecialRenderer(clazz, this); } } } public void registerFor(Item item) { MinecraftForgeClient.registerItemRenderer(item, this); } }
package fr.inra.maiage.bibliome.alvisir.core.query; import org.apache.lucene.index.Term; import org.apache.lucene.search.WildcardQuery; final class RelationArgumentVisitor implements AlvisIRQueryNodeVisitor<Void,StringBuilder,RuntimeException> { @Override public Void visit(AlvisIRTermQueryNode termQueryNode, StringBuilder param) { param.append(termQueryNode.getText()); return null; } @Override public Void visit(AlvisIRPhraseQueryNode phraseQueryNode, StringBuilder param) { param.append("___PHRASE_AS_RELATION_ARGUMENT___"); return null; // throw new RuntimeException(); } @Override public Void visit(AlvisIRPrefixQueryNode prefixQueryNode, StringBuilder param) { param.append(prefixQueryNode.getPrefix()); param.append('*'); return null; } @Override public Void visit(AlvisIRAndQueryNode andQueryNode, StringBuilder param) { param.append("___CONJUNCTION_AS_RELATION_ARGUMENT___"); return null; // throw new RuntimeException(); } @Override public Void visit(AlvisIROrQueryNode orQueryNode, StringBuilder param) { orQueryNode.getClauses().get(0).accept(this, param); return null; // XXX throw new RuntimeException(); } @Override public Void visit(AlvisIRNearQueryNode nearQueryNode, StringBuilder param) { param.append("___NEAR_AS_RELATION_ARGUMENT___"); return null; // throw new RuntimeException(); } @Override public Void visit(AlvisIRRelationQueryNode relationQueryNode, StringBuilder param) { param.append("___RELATION_AS_RELATION_ARGUMENT___"); return null; // throw new RuntimeException(); } @Override public Void visit(AlvisIRNoExpansionQueryNode noExpansionQueryNode, StringBuilder param) { noExpansionQueryNode.getQueryNode().accept(this, param); return null; } @Override public Void visit(AlvisIRAnyQueryNode anyQueryNode, StringBuilder param) { param.append('*'); return null; } @Override public Void visit(AlvisIRTermListQueryNode termListQueryNode, StringBuilder param) throws RuntimeException { param.append("___TERM_LIST_AS_RELATION_ARGUMENT___"); return null; } static WildcardQuery getWildcardQuery(AlvisIRRelationQueryNode relationQueryNode, String fieldName) { StringBuilder sb = new StringBuilder(); sb.append('{'); sb.append(relationQueryNode.getRelation()); sb.append('}'); RelationArgumentVisitor visitor = new RelationArgumentVisitor(); AlvisIRQueryNodeReducer.reduce(relationQueryNode.getLeft()).accept(visitor, sb); sb.append('~'); AlvisIRQueryNodeReducer.reduce(relationQueryNode.getRight()).accept(visitor, sb); // System.err.println("sb = " + sb); Term term = new Term(fieldName, sb.toString()); return new WildcardQuery(term); } }
package org.jasig.portal; import org.w3c.dom.*; import java.util.*; /** * Combines all of the information required to describe * an XSLT stylesheet. * @author Peter Kharchenko * @version $Revision$ */ public class StylesheetDescription { public String s_href; public String s_type; public String s_title; public String s_media; public String s_charset; public boolean b_alternate; public StylesheetDescription () { } public StylesheetDescription (String uri, String type) { s_href = fixURI (uri); s_type=type; s_media = new String (""); s_charset = null; b_alternate = false; s_title = new String (""); } public StylesheetDescription (String uri, String type, String title, String media, String charset, boolean alternate) { s_href = fixURI (uri); s_type = type; s_media = media; s_charset = charset; b_alternate = alternate; s_title = title; } public StylesheetDescription (ProcessingInstruction pi) { // determine parameters from the ProcessingInstruction if (pi.getNodeName ().equals ("xml-stylesheet")) { PIAttributes pia = new PIAttributes (pi); s_href = fixURI (pia.getAttribute ("href")); s_type = pia.getAttribute ("type"); s_title = pia.getAttribute ("title"); s_media = pia.getAttribute ("media"); s_charset = pia.getAttribute ("charset"); if ("yes".equals (pia.getAttribute ("alternate"))) b_alternate=true; else b_alternate=false; if (s_media==null) s_media=new String (""); if (s_title==null) s_title=new String (""); } } public StylesheetDescription (String data) { PIAttributes pia = new PIAttributes (data); s_href = fixURI (pia.getAttribute ("href")); s_type = pia.getAttribute ("type"); s_title = pia.getAttribute ("title"); s_media = pia.getAttribute ("media"); s_charset = pia.getAttribute ("charset"); if ("yes".equals (pia.getAttribute ("alternate"))) b_alternate=true; else b_alternate=false; if (s_media==null) s_media=new String (""); if (s_title==null) s_title=new String (""); } public String getTitle () { return s_title; } public String getURI () { return s_href; } public String getType () { return s_type; } public String getMedia () { return s_media; } public boolean getAlternate () { return b_alternate; } public String getCharset () { return s_charset; } public void setTitle (String title) { s_title=title; } public void setType (String type) { s_type=type; } public void setMedia (String media) { s_media=media; } public void setURI (String uri) { s_href=uri; } public void setCharset (String charset) { s_charset=charset; } public void setAlternate (boolean alternate) { b_alternate=alternate; } private static String fixURI (String str) { // Windows fix char ch0 = str.charAt (0); char ch1 = str.charAt (1); if (str.indexOf ("://") == -1 && ch1 != ':') { // Relative path was specified, so prepend portal base dir str = "file:/" + GenericPortalBean.getPortalBaseDir () + str; } else if (str.startsWith ("file: { // Replace "file://" with "file:/" str = "file:/" + str.substring (7); } else if (ch1 == ':') { // If Windows full path, prepend with "file:/" str = "file:/" + str; } // Handle platform-dependent strings str = str.replace (java.io.File.separatorChar, '/'); return str; } } /** * Parses a processing instruction's (PI) attributes for easy retrieval. */ class PIAttributes { private Hashtable piAttributes = null; PIAttributes (String data) { piAttributes = new Hashtable (); StringTokenizer tokenizer = new StringTokenizer (data, "=\""); while (tokenizer.hasMoreTokens ()) { piAttributes.put (tokenizer.nextToken ().trim (), tokenizer.nextToken ().trim ()); } } /** * Constructor. * @param pi The processing instruction whose attributes are to be parsed */ PIAttributes (ProcessingInstruction pi) { this (pi.getNodeValue ()); } /** * Returns value of specified attribute. * @param name Attribute name * @return Attribute value, or null if the attribute name does not exist */ String getAttribute (String name) { return (String) piAttributes.get (name); } }
package org.apache.jcs.auxiliary.lateral.socket.tcp; import junit.framework.TestCase; import org.apache.jcs.JCS; import org.apache.jcs.auxiliary.lateral.LateralCacheAttributes; import org.apache.jcs.auxiliary.lateral.LateralElementDescriptor; import org.apache.jcs.engine.CacheElement; import org.apache.jcs.engine.behavior.ICacheElement; import org.apache.jcs.engine.behavior.ICompositeCacheManager; import org.apache.jcs.engine.control.CompositeCacheManager; import org.apache.jcs.engine.control.CompositeCacheManagerMockImpl; import org.apache.jcs.utils.timing.SleepUtil; /** * Basic unit tests for the sending and receiving portions of the lateral cache. * * @author Aaron Smuts * */ public class TestTCPLateralUnitTest extends TestCase { /** * Test setup */ public void setUp() { JCS.setConfigFilename( "/TestTCPLateralCache.ccf" ); } /** * Make sure we can send a bunch to the listener. This would be better if we * could plugin a Mock CacheManger. The listener will instantiate on on its * own. We have to configure one before that. * <p> * @throws Exception */ public void testSimpleSend() throws Exception { // force initialization JCS.getInstance( "test" ); TCPLateralCacheAttributes lac = new TCPLateralCacheAttributes(); lac.setTransmissionType( LateralCacheAttributes.TCP ); lac.setTcpServer( "localhost" + ":" + 8111 ); lac.setTcpListenerPort( 8111 ); ICompositeCacheManager cacheMgr = CompositeCacheManager.getInstance(); // start the listener LateralTCPListener listener = (LateralTCPListener) LateralTCPListener.getInstance( lac, cacheMgr ); // send to the listener LateralTCPSender lur = new LateralTCPSender( lac ); int numMes = 10; for ( int i = 0; i < numMes; i++ ) { String message = "adsfasasfasfasdasf"; CacheElement ce = new CacheElement( "test", "test", message ); LateralElementDescriptor led = new LateralElementDescriptor( ce ); led.command = LateralElementDescriptor.UPDATE; led.requesterId = 1; lur.send( led ); } SleepUtil.sleepAtLeast( numMes ); System.out.println( "PutCount = " + listener.getPutCnt() ); assertEquals( "Should have received " + numMes + " by now.", numMes, listener.getPutCnt() ); } /** * * @throws Exception */ public void testReceive() throws Exception { TCPLateralCacheAttributes lattr = new TCPLateralCacheAttributes(); lattr.setTcpListenerPort( 1101 ); lattr.setTransmissionTypeName( "TCP" ); CompositeCacheManagerMockImpl cacheMgr = new CompositeCacheManagerMockImpl(); System.out.println( "mock cache = " + cacheMgr.getCache( "test" ) ); // force initialization //LateralTCPCacheFactory fact = new LateralTCPCacheFactory(); //.getInstance( lattr, cacheMgr ); //LateralCacheNoWait nwait1 = (LateralCacheNoWait)lcMgr1.getCache( // "test" ); //AuxiliaryCache nowait1 = fact.createCache( lattr, cacheMgr ); //nowait1.update( ); // start the listener //LateralTCPListener listener = (LateralTCPListener) LateralTCPListener.getInstance( lattr, cacheMgr ); TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes(); lattr2.setTcpListenerPort( 1102 ); lattr2.setTransmissionTypeName( "TCP" ); lattr2.setTcpServer( "localhost:1101" ); LateralTCPService service = new LateralTCPService( lattr2 ); service.setListenerId( 123456 ); int cnt = 100; for ( int i = 0; i < cnt; i++ ) { ICacheElement element = new CacheElement( "test", "key" + i, "value1" ); service.update( element ); } Thread.sleep( 1000 ); System.out.println( "cache. getPutCount = " + cacheMgr.getCache().getUpdateCount() ); assertEquals( "Didn't get the correct number", cnt, cacheMgr.getCache().getUpdateCount() ); } /** * Send objects with the same key but different values. * @throws Exception */ public void testSameKeyDifferentObject() throws Exception { // setup a listener TCPLateralCacheAttributes lattr = new TCPLateralCacheAttributes(); lattr.setTcpListenerPort( 1103 ); CompositeCacheManagerMockImpl cacheMgr = new CompositeCacheManagerMockImpl(); System.out.println( "mock cache = " + cacheMgr.getCache( "test" ) ); // get the listener started // give it our mock cache manager //LateralTCPListener listener = (LateralTCPListener) LateralTCPListener.getInstance( lattr, cacheMgr ); // setup a service to talk to the listener started above. TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes(); lattr2.setTcpListenerPort( 1104 ); lattr2.setTcpServer( "localhost:1103" ); LateralTCPService service = new LateralTCPService( lattr2 ); service.setListenerId( 123456 ); ICacheElement element = new CacheElement( "test", "key", "value1" ); service.update( element ); Thread.sleep( 300 ); ICacheElement element2 = new CacheElement( "test", "key", "value2" ); service.update( element2 ); Thread.sleep( 1000 ); ICacheElement cacheElement = cacheMgr.getCache().get( "key" ); System.out.println( "cacheElement = " + cacheElement ); assertEquals( "Didn't get the correct object", element2.getVal(), cacheElement.getVal() ); } /** * Send objects with the same key but different values. * @throws Exception */ public void testSameKeyObjectDifferentValueObject() throws Exception { TCPLateralCacheAttributes lattr = new TCPLateralCacheAttributes(); lattr.setTcpListenerPort( 1105 ); lattr.setTransmissionTypeName( "TCP" ); CompositeCacheManagerMockImpl cacheMgr = new CompositeCacheManagerMockImpl(); System.out.println( "mock cache = " + cacheMgr.getCache( "test" ) ); // get the listener started // give it our mock cache manager //LateralTCPListener listener = (LateralTCPListener) LateralTCPListener.getInstance( lattr, cacheMgr ); TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes(); lattr2.setTcpListenerPort( 1106); lattr2.setTransmissionTypeName( "TCP" ); lattr2.setTcpServer( "localhost:1105" ); LateralTCPService service = new LateralTCPService( lattr2 ); service.setListenerId( 123456 ); String key = "key"; ICacheElement element = new CacheElement( "test", key, "value1" ); service.update( element ); Thread.sleep( 300 ); ICacheElement element2 = new CacheElement( "test", key, "value2" ); service.update( element2 ); Thread.sleep( 1000 ); ICacheElement cacheElement = cacheMgr.getCache().get( "key" ); System.out.println( "cacheElement = " + cacheElement ); assertEquals( "Didn't get the correct object", element2.getVal(), cacheElement.getVal() ); } /** * Create a listener. Add an element to the listeners cache. Setup a service. Try to get from the service. * <p> * @throws Exception */ public void testSendAndReceived() throws Exception { // setup a listener TCPLateralCacheAttributes lattr = new TCPLateralCacheAttributes(); lattr.setTcpListenerPort( 1107 ); CompositeCacheManagerMockImpl cacheMgr = new CompositeCacheManagerMockImpl(); System.out.println( "mock cache = " + cacheMgr.getCache( "test" ) ); // get the listener started // give it our mock cache manager //LateralTCPListener listener = (LateralTCPListener) LateralTCPListener.getInstance( lattr, cacheMgr ); // add the item to the listeners cache ICacheElement element = new CacheElement( "test", "key", "value1" ); cacheMgr.getCache().update( element ); // setup a service to talk to the listener started above. TCPLateralCacheAttributes lattr2 = new TCPLateralCacheAttributes(); lattr2.setTcpListenerPort( 1108 ); lattr2.setTcpServer( "localhost:1107" ); LateralTCPService service = new LateralTCPService( lattr2 ); service.setListenerId( 123456 ); Thread.sleep( 300 ); // DO WORK ICacheElement result = service.get( "test", "key" ); System.out.println( "testSendAndReceived, result = " + result ); assertNotNull( "Result should not be null.", result ); assertEquals( "Didn't get the correct object", element.getVal(), result.getVal() ); } }
package uk.ac.ebi.quickgo.annotation.service.search; import uk.ac.ebi.quickgo.annotation.common.AnnotationFields; import uk.ac.ebi.quickgo.annotation.common.AnnotationRepoConfig; import uk.ac.ebi.quickgo.annotation.model.Annotation; import uk.ac.ebi.quickgo.annotation.service.comm.rest.geneproduct.transformer.GeneProductNameInjector; import uk.ac.ebi.quickgo.annotation.service.comm.rest.geneproduct.transformer.GeneProductSynonymsInjector; import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjector; import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.SlimResultsTransformer; import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.TaxonomyNameInjector; import uk.ac.ebi.quickgo.annotation.service.converter.AnnotationDocConverterImpl; import uk.ac.ebi.quickgo.common.SearchableField; import uk.ac.ebi.quickgo.common.loader.DbXRefLoader; import uk.ac.ebi.quickgo.common.validator.DbXRefEntityValidation; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelper; import uk.ac.ebi.quickgo.rest.controller.ControllerValidationHelperImpl; import uk.ac.ebi.quickgo.rest.search.RequestRetrieval; import uk.ac.ebi.quickgo.rest.search.SearchService; import uk.ac.ebi.quickgo.rest.search.query.QueryRequestConverter; import uk.ac.ebi.quickgo.rest.search.query.SortCriterion; import uk.ac.ebi.quickgo.rest.search.request.converter.RESTFilterConverterFactory; import uk.ac.ebi.quickgo.rest.search.results.QueryResult; import uk.ac.ebi.quickgo.rest.search.results.config.FieldNameTransformer; import uk.ac.ebi.quickgo.rest.search.results.transformer.ExternalServiceResultsTransformer; import uk.ac.ebi.quickgo.rest.search.results.transformer.ResponseValueInjector; import uk.ac.ebi.quickgo.rest.search.results.transformer.ResultTransformerChain; import uk.ac.ebi.quickgo.rest.search.solr.SolrQueryConverter; import uk.ac.ebi.quickgo.rest.search.solr.SolrRequestRetrieval; import uk.ac.ebi.quickgo.rest.search.solr.SolrRetrievalConfig; import uk.ac.ebi.quickgo.rest.search.solr.UnsortedSolrQuerySerializer; import uk.ac.ebi.quickgo.rest.service.ServiceRetrievalConfig; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.beans.DocumentObjectBinder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.data.solr.core.SolrTemplate; import static java.util.Arrays.asList; @Configuration @Import({AnnotationRepoConfig.class}) @ComponentScan({"uk.ac.ebi.quickgo.annotation.service.search"}) @PropertySource("classpath:search.properties") public class SearchServiceConfig { public static final int MAX_PAGE_RESULTS = 100; private static final boolean DEFAULT_XREF_VALIDATION_IS_CASE_SENSITIVE = true; private static final String COMMA = ","; private static final String DEFAULT_UNSORTED_QUERY_FIELDS = "assignedBy_unsorted,dbSubset_unsorted,evidenceCode_unsorted,goEvidence_unsorted," + "goId_unsorted,geneProductId_unsorted,geneProductType_unsorted," + "qualifier_unsorted,targetSet_unsorted,taxonId_unsorted"; private static final String DEFAULT_ANNOTATION_SEARCH_RETURN_FIELDS = "id,geneProductId,qualifier,goId,goEvidence," + "evidenceCode,reference,withFrom,taxonId,assignedBy,extensions,symbol"; private static final String SOLR_ANNOTATION_QUERY_REQUEST_HANDLER = "/query"; private static final String DEFAULT_DOWNLOAD_SORT_FIELDS = "rowNumber,id"; private static final int DEFAULT_DOWNLOAD_PAGE_SIZE = 500; @Value("${geneproduct.db.xref.valid.regexes}") String xrefValidationRegexFile; @Value("${geneproduct.db.xref.valid.casesensitive:" + DEFAULT_XREF_VALIDATION_IS_CASE_SENSITIVE + "}") boolean xrefValidationCaseSensitive; @Value("${annotation.terms.query.compatible.fields:" + DEFAULT_UNSORTED_QUERY_FIELDS + "}") private String fieldsThatCanBeUnsorted; @Value("${annotation.download.sort.fields:" + DEFAULT_DOWNLOAD_SORT_FIELDS + "}") private String defaultDownloadSortFields; @Value("${annotation.download.pageSize:" + DEFAULT_DOWNLOAD_PAGE_SIZE + "}") private int downloadPageSize; @Bean public SearchService<Annotation> annotationSearchService( RequestRetrieval<Annotation> annotationSolrRequestRetrieval) { return new SearchServiceImpl(annotationSolrRequestRetrieval); } @Bean public RequestRetrieval<Annotation> annotationSolrRequestRetrieval( SolrTemplate annotationTemplate, QueryRequestConverter<SolrQuery> queryRequestConverter, AnnotationCompositeRetrievalConfig annotationRetrievalConfig) { SolrQueryResultConverter resultConverter = new SolrQueryResultConverter( new DocumentObjectBinder(), new AnnotationDocConverterImpl(), annotationRetrievalConfig); return new SolrRequestRetrieval<>( annotationTemplate.getSolrClient(), queryRequestConverter, resultConverter, annotationRetrievalConfig); } @Bean public ControllerValidationHelper validationHelper() { return new ControllerValidationHelperImpl(MAX_PAGE_RESULTS); } @Bean public QueryRequestConverter<SolrQuery> annotationSolrQueryRequestConverter() { Set<String> unsortedFields = Stream.of(fieldsThatCanBeUnsorted.split(COMMA)).collect(Collectors.toSet()); return new SolrQueryConverter( SOLR_ANNOTATION_QUERY_REQUEST_HANDLER, new UnsortedSolrQuerySerializer(unsortedFields)); } /** * Annotation retrieval config. Annotations searches don't use highlighting. * * @param annotationSearchSolrReturnedFields A list of fields that can be used for filtering. * @return An instance of AnnotationCompositeRetrievalConfig which meets the requirements of the Configuration * interfaces it extends. */ @Bean public AnnotationCompositeRetrievalConfig annotationRetrievalConfig( @Value("${search.return.fields:" + DEFAULT_ANNOTATION_SEARCH_RETURN_FIELDS + "}") String annotationSearchSolrReturnedFields, FieldNameTransformer fieldNameTransformer) { return new AnnotationCompositeRetrievalConfig() { @Override public List<SortCriterion> getDownloadSortCriteria() { return Stream.of(defaultDownloadSortFields.split(COMMA)) .map(downloadSortField -> new SortCriterion(downloadSortField, SortCriterion.SortOrder.ASC)) .collect(Collectors.toList()); } @Override public int getDownloadPageSize() { return downloadPageSize; } @Override public Map<String, String> repo2DomainFieldMap() { return fieldNameTransformer.getTransformations(); } @Override public List<String> getSearchReturnedFields() { return asList(annotationSearchSolrReturnedFields.split(COMMA)); } //Not called @Override public String getHighlightStartDelim() { return ""; } //Not called @Override public String getHighlightEndDelim() { return ""; } }; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Bean public ResultTransformerChain<QueryResult<Annotation>> resultTransformerChain( ExternalServiceResultsTransformer<Annotation> ontologyResultsTransformer, ExternalServiceResultsTransformer<Annotation> geneProductResultsTransformer) { ResultTransformerChain<QueryResult<Annotation>> transformerChain = new ResultTransformerChain<>(); transformerChain.addTransformer(new SlimResultsTransformer()); transformerChain.addTransformer(ontologyResultsTransformer); transformerChain.addTransformer(geneProductResultsTransformer); return transformerChain; } @Bean public ExternalServiceResultsTransformer<Annotation> ontologyResultsTransformer(RESTFilterConverterFactory restFilterConverterFactory) { List<ResponseValueInjector<Annotation>> responseValueInjectors = asList( new OntologyNameInjector(), new TaxonomyNameInjector()); return new ExternalServiceResultsTransformer<>(restFilterConverterFactory, responseValueInjectors); } @Bean public ExternalServiceResultsTransformer<Annotation> geneProductResultsTransformer(RESTFilterConverterFactory restFilterConverterFactory) { List<ResponseValueInjector<Annotation>> responseValueInjectors = asList( new GeneProductNameInjector(), new GeneProductSynonymsInjector()); return new ExternalServiceResultsTransformer<>(restFilterConverterFactory, responseValueInjectors); } @Bean public DbXRefEntityValidation geneProductValidator() { return DbXRefEntityValidation.createWithData(geneProductLoader().load()); } @Bean public SearchableField annotationSearchableField() { return new SearchableField() { @Override public boolean isSearchable(String field) { return AnnotationFields.Searchable.isSearchable(field); } @Override public Stream<String> searchableFields() { return AnnotationFields.Searchable.searchableFields().stream(); } }; } private DbXRefLoader geneProductLoader() { return new DbXRefLoader(this.xrefValidationRegexFile, xrefValidationCaseSensitive); } public interface AnnotationCompositeRetrievalConfig extends SolrRetrievalConfig, ServiceRetrievalConfig { List<SortCriterion> getDownloadSortCriteria(); int getDownloadPageSize(); } }
package ee.elinyo.teamcity.plugins.ansible.agent; import java.util.ArrayList; import java.util.List; import jetbrains.buildServer.RunBuildException; import jetbrains.buildServer.agent.artifacts.ArtifactsWatcher; import jetbrains.buildServer.agent.runner.BuildServiceAdapter; import jetbrains.buildServer.agent.runner.ProcessListener; import jetbrains.buildServer.agent.runner.ProgramCommandLine; import jetbrains.buildServer.agent.runner.SimpleProgramCommandLine; import jetbrains.buildServer.runner.CommandLineArgumentsUtil; import org.jetbrains.annotations.NotNull; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import ee.elinyo.teamcity.plugins.ansible.common.AnsibleCommand; import ee.elinyo.teamcity.plugins.ansible.common.AnsibleRunConfig; public class AnsibleRunService extends BuildServiceAdapter { protected static final Logger LOG = Logger.getInstance(AnsibleRunService.class.getName()); private ArtifactsWatcher artifactsWatcher; public AnsibleRunService(ArtifactsWatcher artifactsWatcher) { this.artifactsWatcher = artifactsWatcher; } @Override public ProgramCommandLine makeProgramCommandLine() throws RunBuildException { AnsibleRunConfig config = new AnsibleRunConfig(getRunnerParameters()); if (LOG.isDebugEnabled()) { LOG.debug("Going to run ansible with parameters: " + config.toString()); } if (AnsibleCommand.CUSTOM_SCRIPT.equals(config.getCommandType())) { return makeCustomScriptCommand(config); } return makeExecutableCommand(config); } private ProgramCommandLine makeExecutableCommand(AnsibleRunConfig config) throws RunBuildException { String workingDir = getWorkingDirectory().getPath(); StringBuilder args = new StringBuilder(""); if (!StringUtil.isEmptyOrSpaces(config.getInventory())) { args.append("-i ").append(config.getInventory()); } if (StringUtil.isEmptyOrSpaces(config.getPlaybook())) { throw new RunBuildException("Ansible playbook should be specified"); } args.append(" ").append(config.getPlaybook()); if (!StringUtil.isEmptyOrSpaces(config.getOptions())) { args.append(" ").append(config.getOptions()); } return new SimpleProgramCommandLine(getEnvironmentVariables(), workingDir, config.getExecutable(), CommandLineArgumentsUtil.extractArguments(args.toString())); } private ProgramCommandLine makeCustomScriptCommand(AnsibleRunConfig config) throws RunBuildException { // String workingDir = getWorkingDirectory().getPath(); LOG.warn("Not Implemented"); throw new RunBuildException("Ansible customs script is not imlemented"); } @NotNull @Override public List<ProcessListener> getListeners() { List<ProcessListener> listeners = new ArrayList<ProcessListener>(super.getListeners()); listeners.add(new AnsibleOutputListener(getBuild(), getRunnerContext(), artifactsWatcher)); return listeners; } }
package org.spine3.examples.todolist.projection; import com.google.protobuf.Timestamp; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.spine3.examples.todolist.LabelAssignedToTask; import org.spine3.examples.todolist.LabelColor; import org.spine3.examples.todolist.LabelDetailsUpdated; import org.spine3.examples.todolist.LabelRemovedFromTask; import org.spine3.examples.todolist.TaskDeleted; import org.spine3.examples.todolist.TaskDescriptionUpdated; import org.spine3.examples.todolist.TaskDraftCreated; import org.spine3.examples.todolist.TaskDraftFinalized; import org.spine3.examples.todolist.TaskDueDateUpdated; import org.spine3.examples.todolist.TaskId; import org.spine3.examples.todolist.TaskLabelId; import org.spine3.examples.todolist.TaskListId; import org.spine3.examples.todolist.TaskPriority; import org.spine3.examples.todolist.TaskPriorityUpdated; import org.spine3.examples.todolist.view.TaskListView; import org.spine3.examples.todolist.view.TaskView; import org.spine3.protobuf.Timestamps; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.spine3.base.Identifiers.newUuid; import static org.spine3.examples.todolist.testdata.TestEventFactory.LABEL_ID; import static org.spine3.examples.todolist.testdata.TestEventFactory.UPDATED_DESCRIPTION; import static org.spine3.examples.todolist.testdata.TestEventFactory.labelAssignedToTaskInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.labelDetailsUpdatedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.labelRemovedFromTaskInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskCompletedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskDeletedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskDescriptionUpdatedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskDraftCreatedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskDraftFinalizedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskDueDateUpdatedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskPriorityUpdatedInstance; import static org.spine3.examples.todolist.testdata.TestEventFactory.taskReopenedInstance; import static org.spine3.examples.todolist.testdata.TestTaskLabelCommandFactory.UPDATED_LABEL_TITLE; /** * @author Illia Shepilov */ public class DraftTasksViewProjectionShould { private DraftTasksViewProjection projection; private TaskDraftFinalized taskDraftFinalizedEvent; private TaskDraftCreated taskDraftCreatedEvent; private TaskDeleted taskDeletedEvent; private TaskDueDateUpdated taskDueDateUpdatedEvent; private TaskDescriptionUpdated taskDescriptionUpdatedEvent; private TaskPriorityUpdated taskPriorityUpdatedEvent; private LabelAssignedToTask labelAssignedToTaskEvent; private LabelRemovedFromTask labelRemovedFromTaskEvent; private LabelDetailsUpdated labelDetailsUpdatedEvent; private final TaskListId ID = TaskListId.newBuilder() .setValue(newUuid()) .build(); @BeforeEach public void setUp() { projection = new DraftTasksViewProjection(ID); taskDraftFinalizedEvent = taskDraftFinalizedInstance(); taskDeletedEvent = taskDeletedInstance(); taskDraftCreatedEvent = taskDraftCreatedInstance(); taskDescriptionUpdatedEvent = taskDescriptionUpdatedInstance(); taskDueDateUpdatedEvent = taskDueDateUpdatedInstance(); taskPriorityUpdatedEvent = taskPriorityUpdatedInstance(); labelAssignedToTaskEvent = labelAssignedToTaskInstance(); labelRemovedFromTaskEvent = labelRemovedFromTaskInstance(); labelDetailsUpdatedEvent = labelDetailsUpdatedInstance(); } @Test public void remove_task_view_from_state_when_it_is_finalized() { final int expectedListSize = 0; projection.on(taskDraftCreatedEvent); projection.on(taskDraftFinalizedEvent); final List<TaskView> views = projection.getState() .getDraftTasks() .getItemsList(); assertEquals(expectedListSize, views.size()); } @Test public void remove_task_view_from_state_when_it_is_deleted() { final int expectedListSize = 0; projection.on(taskDraftCreatedEvent); projection.on(taskDeletedEvent); final List<TaskView> views = projection.getState() .getDraftTasks() .getItemsList(); assertEquals(expectedListSize, views.size()); } @Test public void add_task_view_to_state_when_it_is_created() { final int expectedListSize = 1; projection.on(taskDraftCreatedEvent); final List<TaskView> views = projection.getState() .getDraftTasks() .getItemsList(); assertEquals(expectedListSize, views.size()); } @Test public void update_task_description_when_handled_task_description_updated_event() { projection.on(taskDraftCreatedEvent); final String updatedDescription = UPDATED_DESCRIPTION; final TaskId expectedTaskId = taskDraftCreatedEvent.getId(); taskDescriptionUpdatedEvent = taskDescriptionUpdatedInstance(expectedTaskId, updatedDescription); projection.on(taskDescriptionUpdatedEvent); final int expectedViewSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewSize, taskListView.getItemsCount()); final TaskView view = taskListView.getItemsList() .get(0); assertEquals(expectedTaskId, view.getId()); assertEquals(updatedDescription, view.getDescription()); } @Test public void not_update_task_description_when_handled_task_description_updated_event_with_wrong_task_id() { projection.on(taskDraftCreatedEvent); final String updatedDescription = UPDATED_DESCRIPTION; taskDescriptionUpdatedEvent = taskDescriptionUpdatedInstance(TaskId.getDefaultInstance(), updatedDescription); projection.on(taskDescriptionUpdatedEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView view = taskListView.getItemsList() .get(0); assertNotEquals(updatedDescription, view.getDescription()); } @Test public void update_task_due_date_when_handled_task_due_date_updated_event() { projection.on(taskDraftCreatedEvent); final Timestamp updatedDueDate = Timestamps.getCurrentTime(); final TaskId expectedTaskId = taskDraftCreatedEvent.getId(); taskDueDateUpdatedEvent = taskDueDateUpdatedInstance(expectedTaskId, updatedDueDate); projection.on(taskDueDateUpdatedEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView taskView = taskListView.getItemsList() .get(0); assertEquals(expectedTaskId, taskView.getId()); assertEquals(updatedDueDate, taskView.getDueDate()); } @Test public void not_update_task_due_date_when_handled_task_due_date_updated_event_with_wrong_task_id() { projection.on(taskDraftCreatedEvent); final Timestamp updatedDueDate = Timestamps.getCurrentTime(); taskDueDateUpdatedEvent = taskDueDateUpdatedInstance(TaskId.getDefaultInstance(), updatedDueDate); projection.on(taskDueDateUpdatedEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView taskView = taskListView.getItemsList() .get(0); assertNotEquals(updatedDueDate, taskView.getDueDate()); } @Test public void update_task_priority_when_handled_task_priority_updated_event() { projection.on(taskDraftCreatedEvent); final TaskPriority updatedTaskPriority = TaskPriority.LOW; final TaskId expectedTaskId = taskDraftCreatedEvent.getId(); taskPriorityUpdatedEvent = taskPriorityUpdatedInstance(expectedTaskId, updatedTaskPriority); projection.on(taskPriorityUpdatedEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView taskView = taskListView.getItemsList() .get(0); assertEquals(expectedTaskId, taskView.getId()); assertEquals(updatedTaskPriority, taskView.getPriority()); } @Test public void not_update_task_priority_when_handled_task_priority_updated_event_with_wrong_task_id() { projection.on(taskDraftCreatedEvent); final TaskPriority updatedTaskPriority = TaskPriority.LOW; taskPriorityUpdatedEvent = taskPriorityUpdatedInstance(TaskId.getDefaultInstance(), updatedTaskPriority); projection.on(taskPriorityUpdatedEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView taskView = taskListView.getItemsList() .get(0); assertNotEquals(updatedTaskPriority, taskView.getPriority()); } @Test public void update_label_details_when_handled_label_details_updated_event() { projection.on(taskDraftCreatedEvent); final TaskId expectedTaskId = taskDraftCreatedEvent.getId(); labelAssignedToTaskEvent = labelAssignedToTaskInstance(expectedTaskId, LABEL_ID); projection.on(labelAssignedToTaskEvent); final LabelColor updatedColor = LabelColor.BLUE; labelDetailsUpdatedEvent = labelDetailsUpdatedInstance(updatedColor, UPDATED_LABEL_TITLE); projection.on(labelDetailsUpdatedEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView taskView = taskListView.getItemsList() .get(0); assertEquals(LABEL_ID, taskView.getLabelId()); assertEquals(updatedColor, taskView.getLabelColor()); } @Test public void not_update_label_details_when_handled_label_details_updated_event_with_wrong_label_id() { projection.on(taskDraftCreatedEvent); final TaskId expectedTaskId = taskDraftCreatedEvent.getId(); labelAssignedToTaskEvent = labelAssignedToTaskInstance(expectedTaskId, TaskLabelId.getDefaultInstance()); projection.on(labelAssignedToTaskEvent); final LabelColor updatedColor = LabelColor.BLUE; labelDetailsUpdatedEvent = labelDetailsUpdatedInstance(updatedColor, UPDATED_LABEL_TITLE); projection.on(labelDetailsUpdatedEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView taskView = taskListView.getItemsList() .get(0); assertNotEquals(updatedColor, taskView.getLabelColor()); } @Test public void remove_label_from_task_view_when_handled_label_removed_from_task_event(){ projection.on(taskDraftCreatedEvent); projection.on(labelAssignedToTaskEvent); projection.on(labelRemovedFromTaskEvent); final int expectedViewListSize = 1; final TaskListView taskListView = projection.getState() .getDraftTasks(); assertEquals(expectedViewListSize, taskListView.getItemsCount()); final TaskView taskView = taskListView.getItemsList() .get(0); assertNotEquals(LABEL_ID, taskView.getLabelId()); } }
// WriteRGBMovie.java import loci.common.services.ServiceFactory; import loci.formats.*; import loci.formats.meta.IMetadata; import loci.formats.services.OMEXMLService; import ome.xml.model.enums.DimensionOrder; import ome.xml.model.enums.EnumerationException; import ome.xml.model.enums.PixelType; import ome.xml.model.primitives.PositiveInteger; public class WriteRGBMovie { public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Please specify an output file name."); System.exit(1); } String id = args[0]; // create 20 blank 512x512 image planes System.out.println("Creating random image planes..."); int w = 511, h = 507, numFrames = 20, numChannels = 3; int pixelType = FormatTools.UINT8; int bpp = FormatTools.getBytesPerPixel(pixelType); int planeSize = h * w * numChannels * bpp; byte[][] img = new byte[numFrames][planeSize]; // fill with random data for (int t=0; t<numFrames; t++) { for (int i=0; i<img[t].length; i+=numChannels) { for (int c=0; c<numChannels; c++) { img[t][i + c] = (byte) (256 * Math.random()); } } } // create metadata object with required metadata fields System.out.println("Populating metadata..."); ServiceFactory factory = new ServiceFactory(); OMEXMLService service = factory.getInstance(OMEXMLService.class); IMetadata meta = service.createOMEXMLMetadata(); MetadataTools.populateMetadata(meta, 0, null, false, "XYZCT", FormatTools.getPixelTypeString(pixelType), w, h, 1, numChannels, numFrames, numChannels); // write image planes to disk System.out.print("Writing planes to '" + id + "'"); IFormatWriter writer = new ImageWriter(); writer.setMetadataRetrieve(meta); writer.setId(id); for (int t=0; t<numFrames; t++) { System.out.print("."); writer.saveBytes(t, img[t]); } writer.close(); System.out.println("Done."); } }
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.storage.domain.StorageDomainCommandBase; import org.ovirt.engine.core.bll.utils.PermissionSubject; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.storage.MultipleStorageDomainsValidator; import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters; import org.ovirt.engine.core.common.action.MoveOrCopyParameters; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.asynctasks.EntityInfo; import org.ovirt.engine.core.common.businessentities.IVdcQueryable; import org.ovirt.engine.core.common.businessentities.OvfEntityData; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.network.VmNic; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.ImageOperation; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.utils.MacAddressValidationPatterns; import org.ovirt.engine.core.common.vdscommands.GetImagesListVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; @Deprecated public class MoveOrCopyTemplateCommand<T extends MoveOrCopyParameters> extends StorageDomainCommandBase<T> { private static final Pattern VALIDATE_MAC_ADDRESS = Pattern.compile(MacAddressValidationPatterns.UNICAST_MAC_ADDRESS_FORMAT); /** * Map which contains the disk id (new generated id if the disk is cloned) and the disk parameters from the export * domain. */ protected final Map<Guid, DiskImage> newDiskIdForDisk = new HashMap<>(); protected Map<Guid, Guid> imageToDestinationDomainMap; protected Map<Guid, DiskImage> imageFromSourceDomainMap; private List<PermissionSubject> permissionCheckSubject; private List<DiskImage> _templateDisks; private StorageDomain sourceDomain; private Guid sourceDomainId = Guid.Empty; /** * Constructor for command creation when compensation is applied on startup * * @param commandId */ protected MoveOrCopyTemplateCommand(Guid commandId) { super(commandId); } public MoveOrCopyTemplateCommand(T parameters) { this(parameters, null); } public MoveOrCopyTemplateCommand(T parameters, CommandContext commandContext) { super(parameters, commandContext); } @Override protected void init(T parameters) { super.init(parameters); setVmTemplateId(parameters.getContainerId()); parameters.setEntityInfo(new EntityInfo(VdcObjectType.VmTemplate, getVmTemplateId())); imageToDestinationDomainMap = getParameters().getImageToDestinationDomainMap(); imageFromSourceDomainMap = new HashMap<>(); } protected StorageDomain getSourceDomain() { if (sourceDomain == null && !Guid.Empty.equals(sourceDomainId)) { sourceDomain = getStorageDomainDao().getForStoragePool(sourceDomainId, getStoragePool().getId()); } return sourceDomain; } protected void setSourceDomainId(Guid storageId) { sourceDomainId = storageId; } protected ImageOperation getMoveOrCopyImageOperation() { return ImageOperation.Copy; } protected List<DiskImage> getTemplateDisks() { if (_templateDisks == null && getVmTemplate() != null) { VmTemplateHandler.updateDisksFromDb(getVmTemplate()); _templateDisks = getVmTemplate().getDiskList(); } return _templateDisks; } @Override protected boolean canDoAction() { boolean retValue = true; if (getVmTemplate() == null) { retValue = false; addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); } else if (getTemplateDisks() != null && !getTemplateDisks().isEmpty()) { ensureDomainMap(getTemplateDisks(), getParameters().getStorageDomainId()); // check that images are ok ImagesHandler.fillImagesMapBasedOnTemplate(getVmTemplate(), imageFromSourceDomainMap, null); if (getVmTemplate().getDiskTemplateMap().values().size() != imageFromSourceDomainMap.size()) { log.error("Can not found any default active domain for one of the disks of template with id '{}'", getVmTemplate().getId()); addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); retValue = false; } retValue = retValue && VmTemplateCommand.isVmTemplateImagesReady(getVmTemplate(), null, getReturnValue().getCanDoActionMessages(), true, true, true, false, getTemplateDisks()); if (retValue) { setStoragePoolId(getVmTemplate().getStoragePoolId()); StorageDomainValidator sdValidator = createStorageDomainValidator(getStorageDomain()); retValue = validate(sdValidator.isDomainExistAndActive()) && validate(sdValidator.isDomainWithinThresholds()) && (getParameters().getForceOverride() || (!isImagesAlreadyOnTarget() && checkIfDisksExist(getTemplateDisks()))) && validateFreeSpaceOnDestinationDomain(sdValidator, getTemplateDisks()); } if (retValue && DbFacade.getInstance() .getStoragePoolIsoMapDao() .get(new StoragePoolIsoMapId(getStorageDomain().getId(), getVmTemplate().getStoragePoolId())) == null) { retValue = false; addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_MATCH); } } return retValue; } private StorageDomainValidator createStorageDomainValidator(StorageDomain storageDomain) { return new StorageDomainValidator(storageDomain); } protected boolean validateUnregisteredEntity(IVdcQueryable entityFromConfiguration, OvfEntityData ovfEntityData) { if (ovfEntityData == null && !getParameters().isImportAsNewEntity()) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_UNSUPPORTED_OVF); } if (entityFromConfiguration == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_OVF_CONFIGURATION_NOT_SUPPORTED); } for (DiskImage image : getImages()) { StorageDomain sd = getStorageDomainDao().getForStoragePool( image.getStorageIds().get(0), getStoragePool().getId()); if (!validate(new StorageDomainValidator(sd).isDomainExistAndActive())) { return false; } } if (!getStorageDomain().getStorageDomainType().isDataDomain()) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_UNSUPPORTED, String.format("$domainId %1$s", getParameters().getStorageDomainId()), String.format("$domainType %1$s", getStorageDomain().getStorageDomainType())); } return true; } protected List<DiskImage> getImages() { return null; } protected boolean isImagesAlreadyOnTarget() { return getParameters().isImagesExistOnTargetStorageDomain(); } @Override protected void setActionMessageParameters() { if (getMoveOrCopyImageOperation() == ImageOperation.Move) { addCanDoActionMessage(EngineMessage.VAR__ACTION__MOVE); } else { addCanDoActionMessage(EngineMessage.VAR__ACTION__COPY); } addCanDoActionMessage(EngineMessage.VAR__TYPE__VM_TEMPLATE); } private boolean validateFreeSpaceOnDestinationDomain(StorageDomainValidator storageDomainValidator, List<DiskImage> disksList) { return validate(storageDomainValidator.hasSpaceForClonedDisks(disksList)); } @Override protected void executeCommand() { } protected void moveOrCopyAllImageGroups() { moveOrCopyAllImageGroups(getVmTemplateId(), getTemplateDisks()); } protected void moveOrCopyAllImageGroups(final Guid containerID, final Iterable<DiskImage> disks) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { for (DiskImage disk : disks) { VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( getImagesActionType(), buildModeOrCopyImageGroupParameters(containerID, disk)); getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } return null; } private MoveOrCopyImageGroupParameters buildModeOrCopyImageGroupParameters( final Guid containerID, DiskImage disk) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters( containerID, disk.getId(), disk.getImageId(), getParameters().getStorageDomainId(), getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setEntityInfo(getParameters().getEntityInfo()); params.setAddImageDomainMapping(getMoveOrCopyImageOperation() == ImageOperation.Copy); params.setSourceDomainId(imageFromSourceDomainMap.get(disk.getId()).getStorageIds().get(0)); params.setParentParameters(getParameters()); return params; } }); } @Override public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: return getSucceeded() ? (getMoveOrCopyImageOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_TEMPLATE : AuditLogType.USER_COPIED_TEMPLATE : (getMoveOrCopyImageOperation() == ImageOperation.Move) ? AuditLogType.USER_FAILED_MOVE_TEMPLATE : AuditLogType.USER_FAILED_COPY_TEMPLATE; case END_SUCCESS: return getSucceeded() ? (getMoveOrCopyImageOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_TEMPLATE_FINISHED_SUCCESS : AuditLogType.USER_COPIED_TEMPLATE_FINISHED_SUCCESS : (getMoveOrCopyImageOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_TEMPLATE_FINISHED_FAILURE : AuditLogType.USER_COPIED_TEMPLATE_FINISHED_FAILURE; default: return (getMoveOrCopyImageOperation() == ImageOperation.Move) ? AuditLogType.USER_MOVED_TEMPLATE_FINISHED_FAILURE : AuditLogType.USER_COPIED_TEMPLATE_FINISHED_FAILURE; } } protected boolean checkIfDisksExist(Iterable<DiskImage> disksList) { Map<Guid, List<Guid>> alreadyRetrieved = new HashMap<>(); for (DiskImage disk : disksList) { Guid targetStorageDomainId = imageToDestinationDomainMap.get(disk.getId()); List<Guid> imagesOnStorageDomain = alreadyRetrieved.get(targetStorageDomainId); if (imagesOnStorageDomain == null) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GetImagesList, new GetImagesListVDSCommandParameters(targetStorageDomainId, getStoragePoolId()) ); if (returnValue.getSucceeded()) { imagesOnStorageDomain = (List<Guid>) returnValue.getReturnValue(); alreadyRetrieved.put(targetStorageDomainId, imagesOnStorageDomain); } else { return failCanDoAction(EngineMessage.ERROR_GET_IMAGE_LIST, String.format("$sdName %1$s", getStorageDomain(targetStorageDomainId).getName())); } } if (imagesOnStorageDomain.contains(disk.getId())) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_ALREADY_CONTAINS_DISK); } } return true; } protected void endMoveOrCopyCommand() { endActionOnAllImageGroups(); endVmTemplateRelatedOps(); setSucceeded(true); } protected final void endVmTemplateRelatedOps() { if (getVmTemplate() != null) { VmDeviceUtils.setVmDevices(getVmTemplate()); VmHandler.updateVmInitFromDB(getVmTemplate(), true); incrementDbGeneration(); VmTemplateHandler.unlockVmTemplate(getVmTemplateId()); } else { setCommandShouldBeLogged(false); log.warn("MoveOrCopyTemplateCommand::EndMoveOrCopyCommand: VmTemplate is null, not performing full endAction"); } } protected void incrementDbGeneration() { getVmStaticDao().incrementDbGeneration(getVmTemplate().getId()); } @Override protected void endSuccessfully() { endMoveOrCopyCommand(); } @Override protected void endWithFailure() { endMoveOrCopyCommand(); } protected void endActionOnAllImageGroups() { for (VdcActionParametersBase p : getParameters().getImagesParameters()) { getBackend().endAction(getImagesActionType(), p, getContext().clone().withoutCompensationContext().withoutExecutionContext().withoutLock()); } } protected VdcActionType getImagesActionType() { return VdcActionType.CopyImageGroup; } protected StorageDomain getStorageDomain(Guid domainId) { return getStorageDomainDao().getForStoragePool(domainId, getStoragePool().getId()); } /** * Space Validations are done using data extracted from the disks. The disks in question in this command * don't have all the needed data, and in order not to contaminate the command's data structures, an alter * one is created specifically fo this validation - hence dummy. * @param disksList * @return */ protected List<DiskImage> createDiskDummiesForSpaceValidations(List<DiskImage> disksList) { List<DiskImage> dummies = new ArrayList<>(disksList.size()); for (DiskImage image : disksList) { Guid targetSdId = imageToDestinationDomainMap.get(image.getId()); DiskImage dummy = ImagesHandler.createDiskImageWithExcessData(image, targetSdId); dummies.add(dummy); } return dummies; } protected boolean validateSpaceRequirements(Collection<DiskImage> diskImages) { MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(diskImages); if (!validate(sdValidator.allDomainsExistAndActive()) || !validate(sdValidator.allDomainsWithinThresholds())) { return false; } if (getParameters().getCopyCollapse()) { return validate(sdValidator.allDomainsHaveSpaceForClonedDisks(diskImages)); } return validate(sdValidator.allDomainsHaveSpaceForDisksWithSnapshots(diskImages)); } protected MultipleStorageDomainsValidator createMultipleStorageDomainsValidator(Collection<DiskImage> diskImages) { return new MultipleStorageDomainsValidator(getStoragePoolId(), ImagesHandler.getAllStorageIdsForImageIds(diskImages)); } protected void ensureDomainMap(Collection<DiskImage> images, Guid defaultDomainId) { if (imageToDestinationDomainMap == null) { imageToDestinationDomainMap = new HashMap<>(); } if (imageToDestinationDomainMap.isEmpty() && images != null && defaultDomainId != null) { for (DiskImage image : images) { if (isImagesAlreadyOnTarget()) { imageToDestinationDomainMap.put(image.getId(), image.getStorageIds().get(0)); } else if (!Guid.Empty.equals(defaultDomainId)) { imageToDestinationDomainMap.put(image.getId(), defaultDomainId); } } } } @Override public List<PermissionSubject> getPermissionCheckSubjects() { if (permissionCheckSubject == null) { if (imageToDestinationDomainMap == null || imageToDestinationDomainMap.isEmpty()) { permissionCheckSubject = super.getPermissionCheckSubjects(); } else { permissionCheckSubject = new ArrayList<>(); Set<PermissionSubject> permissionSet = new HashSet<>(); for (Guid storageId : imageToDestinationDomainMap.values()) { permissionSet.add(new PermissionSubject(storageId, VdcObjectType.Storage, getActionType().getActionGroup())); } permissionCheckSubject.addAll(permissionSet); } } return permissionCheckSubject; } protected boolean validateMacAddress(List<VmNic> ifaces) { int freeMacs = 0; for (VmNic iface : ifaces) { if (!StringUtils.isEmpty(iface.getMacAddress())) { if(!VALIDATE_MAC_ADDRESS.matcher(iface.getMacAddress()).matches()) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NETWORK_INTERFACE_MAC_INVALID, String.format("$IfaceName %1$s", iface.getName()), String.format("$MacAddress %1$s", iface.getMacAddress())); } } else { freeMacs++; } } if (freeMacs > 0 && !(getMacPool().getAvailableMacsCount() >= freeMacs)) { return failCanDoAction(EngineMessage.MAC_POOL_NOT_ENOUGH_MAC_ADDRESSES); } return true; } /** * Updating managed device map of VM, with the new disk {@link Guid}s.<br/> * The update of managedDeviceMap is based on the newDiskIdForDisk map, * so this method should be called only after newDiskIdForDisk is initialized. * * @param disk * - The disk which is about to be cloned * @param managedDeviceMap * - The managed device map contained in the VM. */ protected void updateManagedDeviceMap(DiskImage disk, Map<Guid, VmDevice> managedDeviceMap) { Guid oldDiskId = newDiskIdForDisk.get(disk.getId()).getId(); managedDeviceMap.put(disk.getId(), managedDeviceMap.get(oldDiskId)); managedDeviceMap.remove(oldDiskId); } /** * Cloning a new disk with a new generated id, with the same parameters as <code>disk</code>. Also * adding the disk to <code>newDiskGuidForDisk</code> map, so we will be able to link between the new cloned disk * and the old disk id. * * @param disk * - The disk which is about to be cloned */ protected Guid generateNewDiskId(DiskImage disk) { Guid newGuidForDisk = Guid.newGuid(); // Copy the disk so it will preserve the old disk id and image id. newDiskIdForDisk.put(newGuidForDisk, DiskImage.copyOf(disk)); disk.setId(newGuidForDisk); disk.setImageId(Guid.newGuid()); return newGuidForDisk; } protected void setImagesWithStoragePoolId(Guid storagePoolId, List<DiskImage> diskImages) { for (DiskImage diskImage : diskImages) { diskImage.setStoragePoolId(storagePoolId); } } }
package org.ovirt.engine.core.common.businessentities; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.core.compat.Version; public class VM extends IVdcQueryable implements Serializable, BusinessEntity<Guid>, HasStoragePool<Guid>, Nameable { private static final long serialVersionUID = -4078140531074414263L; @Valid private VmStatic vmStatic; private VmDynamic vmDynamic; private VmStatistics vmStatistics; @EditableField private VmPayload vmPayload; @EditableField private boolean balloonEnabled = true; @Valid private List<Snapshot> snapshots = new ArrayList<Snapshot>(); private boolean runOnce = false; public String getUserDefinedProperties() { return vmStatic.getUserDefinedProperties(); } public void setUserDefinedProperties(String userDefinedProperties) { vmStatic.setUserDefinedProperties(userDefinedProperties); } public String getPredefinedProperties() { return vmStatic.getPredefinedProperties(); } public String getCustomProperties() { return vmStatic.getCustomProperties(); } public void setCustomProperties(String customProperties) { vmStatic.setCustomProperties(customProperties); } public void setPredefinedProperties(String predefinedProperties) { vmStatic.setPredefinedProperties(predefinedProperties); } public VM() { this(new VmStatic(), new VmDynamic(), new VmStatistics()); } public VM(VmStatic vmStatic, VmDynamic vmDynamic, VmStatistics vmStatistics) { this.setStaticData(vmStatic); this.setDynamicData(vmDynamic); this.setStatisticsData(vmStatistics); this.setImages(new ArrayList<DiskImage>()); this.setInterfaces(new ArrayList<VmNetworkInterface>()); this.setDiskMap(new HashMap<Guid, Disk>()); this.setCdPath(""); this.setFloppyPath(""); this.setDiskSize(0); } public VmPauseStatus getVmPauseStatus() { return this.vmDynamic.getPauseStatus(); } public void setVmPauseStatus(VmPauseStatus aPauseStatus) { this.vmDynamic.setPauseStatus(aPauseStatus); } @Override public Guid getId() { return this.vmStatic.getId(); } @Override public void setId(Guid value) { this.vmStatic.setId(value); this.vmDynamic.setId(value); this.vmStatistics.setId(value); } public void setName(String value) { this.vmStatic.setName(value); } public int getMemSizeMb() { return this.getVmMemSizeMb(); } public int getVmMemSizeMb() { return this.vmStatic.getMemSizeMb(); } public void setVmMemSizeMb(int value) { this.vmStatic.setMemSizeMb(value); } public String getVmDomain() { return this.vmStatic.getDomain(); } public void setVmDomain(String value) { this.vmStatic.setDomain(value); } public VmOsType getOs() { return this.getVmOs(); } public VmOsType getVmOs() { return this.vmStatic.getOs(); } public void setVmOs(VmOsType value) { this.vmStatic.setOs(value); } public Date getVmCreationDate() { return this.vmStatic.getCreationDate(); } public void setVmCreationDate(Date value) { this.vmStatic.setCreationDate(value); } public Guid getQuotaId() { return this.vmStatic.getQuotaId(); } public void setQuotaId(Guid value) { this.vmStatic.setQuotaId(value); } public String getQuotaName() { return this.vmStatic.getQuotaName(); } public void setQuotaName(String value) { this.vmStatic.setQuotaName(value); } public boolean isQuotaDefault() { return this.vmStatic.isQuotaDefault(); } public void setIsQuotaDefault(boolean isQuotaDefault) { this.vmStatic.setQuotaDefault(isQuotaDefault); } public QuotaEnforcementTypeEnum getQuotaEnforcementType() { return this.vmStatic.getQuotaEnforcementType(); } public void setQuotaEnforcementType(QuotaEnforcementTypeEnum quotaEnforcementType) { this.vmStatic.setQuotaEnforcementType(quotaEnforcementType); } public String getDescription() { return this.getVmDescription(); } public String getVmDescription() { return this.vmStatic.getDescription(); } public void setVmDescription(String value) { this.vmStatic.setDescription(value); } public int getNumOfMonitors() { return this.vmStatic.getNumOfMonitors(); } public void setNumOfMonitors(int value) { this.vmStatic.setNumOfMonitors(value); } public boolean getAllowConsoleReconnect() { return this.vmStatic.isAllowConsoleReconnect(); } public void setAllowConsoleReconnect(boolean value) { this.vmStatic.setAllowConsoleReconnect(value); } public boolean isInitialized() { return this.vmStatic.isInitialized(); } public void setInitialized(boolean value) { this.vmStatic.setInitialized(value); } public boolean isAutoSuspend() { return this.vmStatic.isAutoSuspend(); } public void setAutoSuspend(boolean value) { this.vmStatic.setAutoSuspend(value); } public int getNumOfCpus() { return this.vmStatic.getNumOfCpus(); } /** * This method is created for SOAP serialization of primitives that are readonly but sent by the client. The setter * implementation is empty and the field is not being changed. * * @param value */ @Deprecated public void setNumOfCpus(int value) { // Purposely empty } public int getNumOfSockets() { return this.vmStatic.getNumOfSockets(); } public void setNumOfSockets(int value) { this.vmStatic.setNumOfSockets(value); } public int getCpuPerSocket() { return this.vmStatic.getCpuPerSocket(); } public void setCpuPerSocket(int value) { this.vmStatic.setCpuPerSocket(value); } public UsbPolicy getUsbPolicy() { return vmStatic.getUsbPolicy(); } public void setUsbPolicy(UsbPolicy value) { vmStatic.setUsbPolicy(value); } public boolean isAutoStartup() { return vmStatic.isAutoStartup(); } public void setAutoStartup(boolean value) { vmStatic.setAutoStartup(value); } public NGuid getDedicatedVmForVds() { return vmStatic.getDedicatedVmForVds(); } public void setDedicatedVmForVds(NGuid value) { vmStatic.setDedicatedVmForVds(value); } public Guid getVdsGroupId() { return this.vmStatic.getVdsGroupId(); } public void setVdsGroupId(Guid value) { this.vmStatic.setVdsGroupId(value); } public String getTimeZone() { return vmStatic.getTimeZone(); } public void setTimeZone(String value) { vmStatic.setTimeZone(value); } public boolean isStateless() { return vmStatic.isStateless(); } public boolean isSmartcardEnabled() { return vmStatic.isSmartcardEnabled(); } public void setSmartcardEnabled(boolean isSmartcardEnabled) { vmStatic.setSmartcardEnabled(isSmartcardEnabled); } public void setStateless(boolean value) { vmStatic.setStateless(value); } public void setDeleteProtected(boolean deleteProtected) { vmStatic.setDeleteProtected(deleteProtected); } public boolean isDeleteProtected() { return vmStatic.isDeleteProtected(); } public String getVncKeyboardLayout() { return vmStatic.getVncKeyboardLayout(); } public void setVncKeyboardLayout(String vncKeyboardLayout) { vmStatic.setVncKeyboardLayout(vncKeyboardLayout); } public DisplayType getDefaultDisplayType() { return vmStatic.getDefaultDisplayType(); } public void setDefaultDisplayType(DisplayType value) { vmStatic.setDefaultDisplayType(value); } public int getPriority() { return vmStatic.getPriority(); } public void setPriority(int value) { vmStatic.setPriority(value); } public String getIsoPath() { return vmStatic.getIsoPath(); } public void setIsoPath(String value) { vmStatic.setIsoPath(value); } public OriginType getOrigin() { return vmStatic.getOrigin(); } public void setOrigin(OriginType value) { vmStatic.setOrigin(value); } public String getInitrdUrl() { return vmStatic.getInitrdUrl(); } public void setInitrdUrl(String value) { vmStatic.setInitrdUrl(value); } public String getKernelUrl() { return vmStatic.getKernelUrl(); } public void setKernelUrl(String value) { vmStatic.setKernelUrl(value); } public String getKernelParams() { return vmStatic.getKernelParams(); } public void setKernelParams(String value) { vmStatic.setKernelParams(value); } private NGuid vmPoolId; private String vmPoolName; public VMStatus getStatus() { return this.vmDynamic.getStatus(); } public void setStatus(VMStatus value) { this.vmDynamic.setStatus(value); } public String getVmIp() { return this.vmDynamic.getVmIp(); } public void setVmIp(String value) { this.vmDynamic.setVmIp(value); } public String getVmHost() { String vmHost = this.vmDynamic.getVmHost(); if (!StringHelper.isNullOrEmpty(this.getVmIp())) { this.vmDynamic.setVmHost(getVmIp()); } else { String vmDomain = getVmDomain(); // If VM's host name isn't available - set as VM's name // If no IP address is available - assure that 'vm_host' is FQN by concatenating // vmHost and vmDomain. if (StringHelper.isNullOrEmpty(vmHost)) { vmHost = StringHelper.isNullOrEmpty(vmDomain) ? getName() : getName() + "." + vmDomain; this.vmDynamic.setVmHost(vmHost); } else if (!StringHelper.isNullOrEmpty(vmDomain) && !vmHost.endsWith(vmDomain)) { this.vmDynamic.setVmHost(vmHost + "." + vmDomain); } } return this.vmDynamic.getVmHost(); } public void setVmHost(String value) { this.vmDynamic.setVmHost(value); } public Integer getVmPid() { return this.vmDynamic.getVmPid(); } public void setVmPid(Integer value) { this.vmDynamic.setVmPid(value); } public Date getLastStartTime() { return this.vmDynamic.getLastStartTime(); } public void setLastStartTime(Date value) { this.vmDynamic.setLastStartTime(value); } public String getConsoleCurentUserName() { return this.vmDynamic.getConsoleCurrentUserName(); } public void setConsoleCurrentUserName(String value) { this.vmDynamic.setConsoleCurrentUserName(value); } public String getGuestCurentUserName() { return this.vmDynamic.getGuestCurrentUserName(); } public void setGuestCurrentUserName(String value) { this.vmDynamic.setGuestCurrentUserName(value); } public Date getGuestLastLoginTime() { return this.vmDynamic.getGuestLastLoginTime(); } public void setGuestLastLoginTime(Date value) { this.vmDynamic.setGuestLastLoginTime(value); } public NGuid getConsoleUserId() { return this.vmDynamic.getConsoleUserId(); } public void setConsoleUserId(NGuid value) { this.vmDynamic.setConsoleUserId(value); } public Date getGuestLastLogoutTime() { return this.vmDynamic.getGuestLastLogoutTime(); } public void setGuestLastLogoutTime(Date value) { this.vmDynamic.setGuestLastLogoutTime(value); } public String getGuestOs() { return this.vmDynamic.getGuestOs(); } public void setGuestOs(String value) { this.vmDynamic.setGuestOs(value); } public NGuid getRunOnVds() { return this.vmDynamic.getRunOnVds(); } public void setRunOnVds(NGuid value) { this.vmDynamic.setRunOnVds(value); } public NGuid getMigratingToVds() { return this.vmDynamic.getMigratingToVds(); } public void setMigratingToVds(NGuid value) { this.vmDynamic.setMigratingToVds(value); } public String getAppList() { return this.vmDynamic.getAppList(); } public void setAppList(String value) { this.vmDynamic.setAppList(value); } public Integer getDisplay() { return this.vmDynamic.getDisplay(); } public void setDisplay(Integer value) { this.vmDynamic.setDisplay(value); } public Boolean getAcpiEnable() { return this.vmDynamic.getAcpiEnable(); } public void setAcpiEnable(Boolean value) { this.vmDynamic.setAcpiEnable(value); } public String getDisplayIp() { return this.vmDynamic.getDisplayIp(); } public void setDisplayIp(String value) { this.vmDynamic.setDisplayIp(value); } public DisplayType getDisplayType() { return this.vmDynamic.getDisplayType(); } public void setDisplayType(DisplayType value) { this.vmDynamic.setDisplayType(value); } public Boolean getKvmEnable() { return this.vmDynamic.getKvmEnable(); } public void setKvmEnable(Boolean value) { this.vmDynamic.setKvmEnable(value); } public SessionState getSession() { return this.vmDynamic.getSession(); } public void setSession(SessionState value) { this.vmDynamic.setSession(value); } public BootSequence getBootSequence() { return this.vmDynamic.getBootSequence(); } public void setBootSequence(BootSequence value) { this.vmDynamic.setBootSequence(value); } public Integer getDisplaySecurePort() { return this.vmDynamic.getDisplaySecurePort(); } public void setDisplaySecurePort(Integer value) { this.vmDynamic.setDisplaySecurePort(value); } public VmExitStatus getExitStatus() { return this.vmDynamic.getExitStatus(); } public void setExitStatus(VmExitStatus value) { this.vmDynamic.setExitStatus(value); } public String getExitMessage() { return this.vmDynamic.getExitMessage(); } public void setExitMessage(String value) { this.vmDynamic.setExitMessage(value); } public Integer getUtcDiff() { return this.vmDynamic.getUtcDiff(); } public void setUtcDiff(Integer value) { this.vmDynamic.setUtcDiff(value); } public NGuid getLastVdsRunOn() { return this.vmDynamic.getLastVdsRunOn(); } public void setLastVdsRunOn(NGuid value) { this.vmDynamic.setLastVdsRunOn(value); } public String getClientIp() { return this.vmDynamic.getClientIp(); } public void setClientIp(String value) { this.vmDynamic.setClientIp(value); } public Integer getGuestRequestedMemory() { return this.vmDynamic.getGuestRequestedMemory(); } public void setGuestRequestedMemory(Integer value) { this.vmDynamic.setGuestRequestedMemory(value); } public String getHash() { return vmDynamic.getHash(); } public void setHash(String hash) { vmDynamic.setHash(hash); } public int getGuestAgentNicsHash() { return vmDynamic.getGuestAgentNicsHash(); } public void setGuestAgentNicsHash(int guestAgentNicsHash) { vmDynamic.setGuestAgentNicsHash(guestAgentNicsHash); } public Double getCpuUser() { return this.vmStatistics.getcpu_user(); } public void setCpuUser(Double value) { this.vmStatistics.setcpu_user(value); } public Double getCpuSys() { return this.vmStatistics.getcpu_sys(); } public void setCpuSys(Double value) { this.vmStatistics.setcpu_sys(value); } public Double getElapsedTime() { return this.vmStatistics.getelapsed_time(); } public void setElapsedTime(Double value) { this.vmStatistics.setelapsed_time(value); } public Double getRoundedElapsedTime() { return this.vmStatistics.getRoundedElapsedTime(); } public void setRoundedElapsedTime(Double value) { this.vmStatistics.setRoundedElapsedTime(value); } public Integer getUsageNetworkPercent() { return this.vmStatistics.getusage_network_percent(); } public void setUsageNetworkPercent(Integer value) { this.vmStatistics.setusage_network_percent(value); } public Integer getUsageMemPercent() { return this.vmStatistics.getusage_mem_percent(); } public void setUsageMemPercent(Integer value) { this.vmStatistics.setusage_mem_percent(value); } public Integer getUsageCpuPercent() { return this.vmStatistics.getusage_cpu_percent(); } public void setUsageCpuPercent(Integer value) { this.vmStatistics.setusage_cpu_percent(value); } public Guid getVmtGuid() { return this.vmStatic.getVmtGuid(); } public void setVmtGuid(Guid value) { this.vmStatic.setVmtGuid(value); } private String vmtName; public String getVmtName() { return this.vmtName; } public void setVmtName(String value) { this.vmtName = value; } private int vmtMemSizeMb; public int getVmtMemSizeMb() { return this.vmtMemSizeMb; } public void setVmtMemSizeMb(int value) { this.vmtMemSizeMb = value; } private VmOsType vmtOs = VmOsType.forValue(0); public VmOsType getVmtOs() { return this.vmtOs; } public void setVmtOs(VmOsType value) { this.vmtOs = value; } private Date vmtCreationDate = new Date(0); public Date getVmtCreationDate() { return this.vmtCreationDate; } public void setVmtCreationDate(Date value) { this.vmtCreationDate = value; } private int vmtchildCount; public int getVmtChildCount() { return this.vmtchildCount; } public void setVmtChildCount(int value) { this.vmtchildCount = value; } private int vmtNumOfCpus; public int getVmtNumOfCpus() { return this.vmtNumOfCpus; } public void setVmtNumOfCpus(int value) { this.vmtNumOfCpus = value; } private int vmtNumOfSockets; public int getVmtNumOfSockets() { return this.vmtNumOfSockets; } public void setVmtNumOfSockets(int value) { this.vmtNumOfSockets = value; } private int vmtCpuPerSocket; public int getVmtCpuPerSocket() { return this.vmtCpuPerSocket; } public void setVmtCpuPerSocket(int value) { this.vmtCpuPerSocket = value; } private String vmtDescription; public String getVmtDescription() { return this.vmtDescription; } public void setVmtDescription(String value) { this.vmtDescription = value; } private String vmtTimeZone; public String getVmtTimeZone() { return vmtTimeZone; } public void setVmtTimeZone(String value) { vmtTimeZone = value; } private Version vdsGroupCompatibilityVersion; public Version getVdsGroupCompatibilityVersion() { return this.vdsGroupCompatibilityVersion; } public void setVdsGroupCompatibilityVersion(Version value) { if (Version.OpInequality(getVdsGroupCompatibilityVersion(), value)) { this.vdsGroupCompatibilityVersion = value; } } private String vdsGroupName; public String getVdsGroupName() { return this.vdsGroupName; } public void setVdsGroupName(String value) { this.vdsGroupName = value; } private String vdsGroupDescription; public String getVdsGroupDescription() { return this.vdsGroupDescription; } public void setVdsGroupDescription(String value) { this.vdsGroupDescription = value; } private String vdsGroupCpuName; public String getVdsGroupCpuName() { return this.vdsGroupCpuName; } public void setVdsGroupCpuName(String value) { this.vdsGroupCpuName = value; } public boolean isFailBack() { return this.vmStatic.isFailBack(); } public void setFailBack(boolean value) { this.vmStatic.setFailBack(value); } public BootSequence getDefaultBootSequence() { return this.vmStatic.getDefaultBootSequence(); } public void setDefaultBootSequence(BootSequence value) { this.vmStatic.setDefaultBootSequence(value); } public int getNiceLevel() { return this.vmStatic.getNiceLevel(); } public void setNiceLevel(int value) { this.vmStatic.setNiceLevel(value); } public void setDbGeneration(long value) { this.vmStatic.setDbGeneration(value); } public long getDbGeneration() { return vmStatic.getDbGeneration(); } public MigrationSupport getMigrationSupport() { return this.vmStatic.getMigrationSupport(); } public void setMigrationSupport(MigrationSupport migrationSupport) { this.vmStatic.setMigrationSupport(migrationSupport); } public VmType getVmType() { return this.vmStatic.getVmType(); } public void setVmType(VmType value) { this.vmStatic.setVmType(value); } public String getHibernationVolHandle() { return this.vmDynamic.getHibernationVolHandle(); } public void setHibernationVolHandle(String value) { this.vmDynamic.setHibernationVolHandle(value); } public void setExportDate(Date value) { this.vmStatic.setExportDate(value); } public Date getExportDate() { return this.vmStatic.getExportDate(); } private Guid storagePoolId = new Guid(); @Override public Guid getStoragePoolId() { return storagePoolId; } @Override public void setStoragePoolId(Guid value) { storagePoolId = value; } private String storagePoolName; public String getStoragePoolName() { return storagePoolName; } public void setStoragePoolName(String value) { storagePoolName = value; } private VdsSelectionAlgorithm selectionAlgorithm = VdsSelectionAlgorithm.forValue(0); public VdsSelectionAlgorithm getSelectionAlgorithm() { return selectionAlgorithm; } public void setSelectionAlgorithm(VdsSelectionAlgorithm value) { selectionAlgorithm = value; } public List<VmNetworkInterface> getInterfaces() { return vmStatic.getInterfaces(); } public void setInterfaces(List<VmNetworkInterface> value) { vmStatic.setInterfaces(value); } public ArrayList<DiskImage> getImages() { return vmStatic.getImages(); } public void setImages(ArrayList<DiskImage> value) { vmStatic.setImages(value); } private Map<Guid, Disk> diskMap = new HashMap<Guid, Disk>(); // even this field has no setter, it can not have the final modifier because the GWT serialization mechanism // ignores the final fields private String cdPath = ""; private String floppyPath = ""; /** * Vitaly change. guest last logout time treatment. If vm stoped without logging out - set last logout time now */ public void guestLogoutTimeTreatmentAfterDestroy() { if (getGuestLastLoginTime() != null && (getGuestLastLogoutTime() == null || getGuestLastLoginTime().compareTo( getGuestLastLogoutTime()) > 0)) { setGuestLastLogoutTime(new Date()); } } private boolean useSysPrep; public boolean useSysPrep() { return useSysPrep; } public void setUseSysPrep(boolean value) { useSysPrep = value; } public boolean isFirstRun() { return vmStatic.isFirstRun(); } private double _actualDiskWithSnapthotsSize = 0; public double getActualDiskWithSnapshotsSize() { if (_actualDiskWithSnapthotsSize == 0 && getDiskMap() != null) { for (Disk disk : getDiskMap().values()) { if (DiskStorageType.IMAGE == disk.getDiskStorageType()) { _actualDiskWithSnapthotsSize += ((DiskImage) disk).getActualDiskWithSnapshotsSize(); } } } return _actualDiskWithSnapthotsSize; } /** * This method is created for SOAP serialization of primitives that are readonly but sent by the client. The setter * implementation is empty and the field is not being changed. * * @param value */ @Deprecated public void setActualDiskWithSnapshotsSize(double value) { // Purposely empty } private double diskSize; public double getDiskSize() { if (diskSize == 0) { for (Disk disk : getDiskMap().values()) { if (DiskStorageType.IMAGE == disk.getDiskStorageType()) { diskSize += ((DiskImage) disk).getSize() / Double.valueOf(1024 * 1024 * 1024); } } } return diskSize; } public void setDiskSize(double value) { diskSize = value; } public VmDynamic getDynamicData() { return vmDynamic; } public void setDynamicData(VmDynamic value) { vmDynamic = value; } public VmStatic getStaticData() { return vmStatic; } public void setStaticData(final VmStatic value) { vmStatic = value == null ? new VmStatic() : value; } public VmStatistics getStatisticsData() { return vmStatistics; } public void setStatisticsData(VmStatistics value) { vmStatistics = value; } private int migreatingToPort; public int getMigreatingToPort() { return migreatingToPort; } public void setMigreatingToPort(int value) { migreatingToPort = value; } private int migreatingFromPort; public int getMigreatingFromPort() { return migreatingFromPort; } public void setMigreatingFromPort(int value) { migreatingFromPort = value; } private String runOnVdsName; public String getRunOnVdsName() { return runOnVdsName; } public void setRunOnVdsName(String value) { runOnVdsName = value; } public Map<Guid, Disk> getDiskMap() { return diskMap; } public void setDiskMap(Map<Guid, Disk> diskMap) { this.diskMap = diskMap; } public int getDiskMapCount() { return diskMap.size(); } public int getMinAllocatedMem() { return vmStatic.getMinAllocatedMem(); } public void setMinAllocatedMem(int value) { vmStatic.setMinAllocatedMem(value); } public String getCdPath() { return cdPath; } public void setCdPath(String value) { cdPath = value; } public String getFloppyPath() { return floppyPath; } public void setFloppyPath(String value) { floppyPath = value; } public Boolean isRunAndPause() { return vmStatic.isRunAndPause(); } public void setRunAndPause(Boolean value) { vmStatic.setRunAndPause(value); } public boolean isWin2kHackEnable() { return getDynamicData().getWin2kHackEnable(); } public void setWin2kHackEnable(boolean value) { getDynamicData().setWin2kHackEnable(value); } /** * update vm dynamic data * * @param vm * @param vdsId * @param vdsName */ public void updateRunTimeDynamicData(VmDynamic vm, Guid vdsId, String vdsName) { setStatus(vm.getStatus()); setRunOnVds(vdsId); setRunOnVdsName(vdsName); setDisplay(vm.getDisplay()); setDisplaySecurePort(vm.getDisplaySecurePort()); setVmHost(vm.getVmHost()); setVmIp(vm.getVmIp()); // if (!string.IsNullOrEmpty(vm.app_list)) setAppList(vm.getAppList()); setGuestOs(vm.getGuestOs()); setDisplayType(vm.getDisplayType()); setDisplayIp(vm.getDisplayIp()); setKvmEnable(vm.getKvmEnable()); setAcpiEnable(vm.getAcpiEnable()); setGuestCurrentUserName(vm.getGuestCurrentUserName()); setWin2kHackEnable(vm.getWin2kHackEnable()); setUtcDiff(vm.getUtcDiff()); setExitStatus(vm.getExitStatus()); setExitMessage(vm.getExitMessage()); setClientIp(vm.getClientIp()); setVmPauseStatus(vm.getPauseStatus()); setLastWatchdogEvent(vm.getLastWatchdogEvent()); // TODO: check what to do with update disk data // updateDisksData(vm); // updateSession(vm); } /** * update vm statistics data * * @param vm */ public void updateRunTimeStatisticsData(VmStatistics vmStatistics, VM vm) { setElapsedTime(vmStatistics.getelapsed_time()); setUsageNetworkPercent(vmStatistics.getusage_network_percent()); vm.getStatisticsData().setDisksUsage(vmStatistics.getDisksUsage()); setCpuSys(vmStatistics.getcpu_sys()); setCpuUser(vmStatistics.getcpu_user()); if ((getCpuSys() != null) && (getCpuUser() != null)) { Double percent = (getCpuSys() + getCpuUser()) / vm.getNumOfCpus(); setUsageCpuPercent(percent.intValue()); if (getUsageCpuPercent() != null && getUsageCpuPercent() > 100) { setUsageCpuPercent(100); } } setUsageMemPercent(vmStatistics.getusage_mem_percent()); } /** * Check if two Vms are Equal. Current equality rule is: Two Vms are equal when them points to same object or have * same vm_guid property * * @param obj * @return */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (super.equals(obj)) { return true; } VM eq = (VM) ((obj instanceof VM) ? obj : null); if (eq != null) { if (eq.getId().equals(this.getId())) { return true; } } return false; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(_actualDiskWithSnapthotsSize); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + (balloonEnabled ? 1231 : 1237); result = prime * result + ((cdPath == null) ? 0 : cdPath.hashCode()); result = prime * result + ((configured == null) ? 0 : configured.hashCode()); result = prime * result + ((diskMap == null) ? 0 : diskMap.hashCode()); temp = Double.doubleToLongBits(diskSize); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((floppyPath == null) ? 0 : floppyPath.hashCode()); result = prime * result + migreatingFromPort; result = prime * result + migreatingToPort; result = prime * result + ((privateGuestAgentVersion == null) ? 0 : privateGuestAgentVersion.hashCode()); result = prime * result + ((runOnVdsName == null) ? 0 : runOnVdsName.hashCode()); result = prime * result + (runOnce ? 1231 : 1237); result = prime * result + ((selectionAlgorithm == null) ? 0 : selectionAlgorithm.hashCode()); result = prime * result + ((snapshots == null) ? 0 : snapshots.hashCode()); result = prime * result + ((spiceDriverVersion == null) ? 0 : spiceDriverVersion.hashCode()); result = prime * result + ((storagePoolId == null) ? 0 : storagePoolId.hashCode()); result = prime * result + ((storagePoolName == null) ? 0 : storagePoolName.hashCode()); result = prime * result + (transparentHugePages ? 1231 : 1237); result = prime * result + (useSysPrep ? 1231 : 1237); result = prime * result + ((vdsGroupCompatibilityVersion == null) ? 0 : vdsGroupCompatibilityVersion.hashCode()); result = prime * result + ((vdsGroupCpuFlagsData == null) ? 0 : vdsGroupCpuFlagsData.hashCode()); result = prime * result + ((vdsGroupCpuName == null) ? 0 : vdsGroupCpuName.hashCode()); result = prime * result + ((vdsGroupDescription == null) ? 0 : vdsGroupDescription.hashCode()); result = prime * result + ((vdsGroupName == null) ? 0 : vdsGroupName.hashCode()); result = prime * result + ((vmDynamic == null) ? 0 : vmDynamic.hashCode()); result = prime * result + ((vmPayload == null) ? 0 : vmPayload.hashCode()); result = prime * result + ((vmPoolId == null) ? 0 : vmPoolId.hashCode()); result = prime * result + ((vmPoolName == null) ? 0 : vmPoolName.hashCode()); result = prime * result + ((vmStatic == null) ? 0 : vmStatic.hashCode()); result = prime * result + ((vmStatistics == null) ? 0 : vmStatistics.hashCode()); result = prime * result + vmtCpuPerSocket; result = prime * result + ((vmtCreationDate == null) ? 0 : vmtCreationDate.hashCode()); result = prime * result + ((vmtDescription == null) ? 0 : vmtDescription.hashCode()); result = prime * result + vmtMemSizeMb; result = prime * result + ((vmtName == null) ? 0 : vmtName.hashCode()); result = prime * result + vmtNumOfCpus; result = prime * result + vmtNumOfSockets; result = prime * result + ((vmtOs == null) ? 0 : vmtOs.hashCode()); result = prime * result + ((vmtTimeZone == null) ? 0 : vmtTimeZone.hashCode()); result = prime * result + vmtchildCount; return result; } public String getVmPoolName() { return vmPoolName; } public void setVmPoolName(String value) { vmPoolName = value; } public NGuid getVmPoolId() { return vmPoolId; } public void setVmPoolId(NGuid value) { vmPoolId = value; } private Version privateGuestAgentVersion; /** * assumption: Qumranet Agent version stored in app_list by "Qumranet Agent" name. Qumranet Agent version, * received from vds in format : a.b.d there is no major revision received from vds - always 0 * @see {@link Version} */ public Version getGuestAgentVersion() { return privateGuestAgentVersion; } public void setGuestAgentVersion(Version value) { privateGuestAgentVersion = value; } public Version getPartialVersion() { Version initial = getGuestAgentVersion(); return initial == null ? null : new Version(initial.getMajor(), initial.getMinor()); } public boolean getHasAgent() { return getGuestAgentVersion() != null; } private Version spiceDriverVersion; public Version getSpiceDriverVersion() { return spiceDriverVersion; } public void setSpiceDriverVersion(Version value) { spiceDriverVersion = value; } public boolean getHasSpiceDriver() { return getSpiceDriverVersion() != null; } private String vdsGroupCpuFlagsData; public String getVdsGroupCpuFlagsData() { return vdsGroupCpuFlagsData; } public void setVdsGroupCpuFlagsData(String value) { vdsGroupCpuFlagsData = value; } private boolean transparentHugePages; public boolean isTransparentHugePages() { return this.transparentHugePages; } public void setTransparentHugePages(boolean value) { this.transparentHugePages = value; } @Override public Object getQueryableId() { return getId(); } private Boolean configured; /** * @return true if vm has at least one Disk and one Interface */ public boolean isConfigured() { if (configured == null) { configured = (getInterfaces() != null && getDiskMap() != null && getInterfaces().size() > 0 && getDiskMap() .size() > 0); } return configured; } public void setConfigured(boolean value) { configured = value; } public ArrayList<DiskImage> getDiskList() { return vmStatic.getDiskList(); } public Map<Guid, VmDevice> getManagedVmDeviceMap() { return vmStatic.getManagedDeviceMap(); } public void setManagedDeviceMap(Map<Guid, VmDevice> map) { vmStatic.setManagedDeviceMap(map); } public List<VmDevice> getVmUnamagedDeviceList() { return vmStatic.getUnmanagedDeviceList(); } public void setUnmanagedDeviceList(List<VmDevice> list) { vmStatic.setUnmanagedDeviceList(list); } public List<Snapshot> getSnapshots() { return snapshots; } public void setSnapshots(List<Snapshot> snapshots) { this.snapshots = snapshots; } public void setRunOnce(boolean value) { runOnce = value; } public boolean isRunOnce() { return runOnce; } public void setVmPayload(VmPayload vmPayload) { this.vmPayload = vmPayload; } public VmPayload getVmPayload() { return vmPayload; } public boolean isUseHostCpuFlags() { return vmStatic.isUseHostCpuFlags(); } public void setUseHostCpuFlags(boolean useHostCpuFlags) { vmStatic.setUseHostCpuFlags(useHostCpuFlags); } public String getCpuPinning() { return vmStatic.getCpuPinning(); } public void setCpuPinning(String cpuPinning) { vmStatic.setCpuPinning(cpuPinning); } public boolean isBalloonEnabled() { return balloonEnabled; } public void setBalloonEnabled(boolean isBallonEnabled) { balloonEnabled = isBallonEnabled; } public String getOvfVersion() { return vmStatic.getOvfVersion(); } public void setOvfVersion(String ovfVersion) { vmStatic.setOvfVersion(ovfVersion); } @Override public String getName() { return this.vmStatic.getName(); } @Override public String toString() { return "VM [" + getName() + "]"; } /// Utility methods that check the VM state /// public boolean isDown() { return getStatus() == VMStatus.Down; } public boolean isRunning() { return getStatus().isRunning(); } public boolean isRunningOrPaused() { return getStatus().isRunningOrPaused(); } public boolean isQualifyToMigrate() { return getStatus().isQualifyToMigrate(); } public boolean isRunningAndQualifyForDisksMigration() { return getStatus().isUpOrPaused() && getRunOnVds() != null && !getRunOnVds().equals(Guid.Empty); } public boolean isNotRunning() { return getStatus().isNotRunning(); } public boolean isStartingOrUp() { return getStatus().isStartingOrUp(); } public Boolean getTunnelMigration() { return vmStatic.getTunnelMigration(); } public void setTunnelMigration(Boolean value) { vmStatic.setTunnelMigration(value); } public Long getLastWatchdogEvent() { return vmDynamic.getLastWatchdogEvent(); } public void setLastWatchdogEvent(Long lastWatchdogEvent) { vmDynamic.setLastWatchdogEvent(lastWatchdogEvent); } }
package org.ovirt.engine.core.vdsbroker; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.IVdsEventListener; import org.ovirt.engine.core.common.businessentities.OriginType; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.VmDeviceId; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmGuestAgentInterface; import org.ovirt.engine.core.common.businessentities.VmJob; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmStatistics; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.network.VmNetworkStatistics; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.DiskImageDynamic; import org.ovirt.engine.core.common.businessentities.storage.LUNs; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.VmDeviceCommonUtils; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.common.vdscommands.FullListVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder; import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsProperties; import org.ovirt.engine.core.vdsbroker.vdsbroker.entities.VmInternalData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * invoke all Vm analyzers in hand and iterate over their report * and take actions - fire VDSM commands (destroy,run/rerun,migrate), report complete actions, * hand-over migration and save-to-db */ public class VmsMonitoring { private final boolean timeToUpdateVmStatistics; private final long fetchTime; private VdsManager vdsManager; /** * The Vms we want to monitor and analyze for changes. * VM object represent the persisted object(namely the one in db) and the VmInternalData * is the running one as reported from VDSM */ private List<Pair<VM, VmInternalData>> monitoredVms; /** * A collection of VMs that has changes in devices. */ private List<Pair<VM, VmInternalData>> vmsWithChangedDevices; private final AuditLogDirector auditLogDirector; /** * The managers of the monitored VMs in this cycle. */ private Map<Guid, VmManager> vmManagers = new HashMap<>(); /** * The analyzers which hold all the data per a VM */ private List<VmAnalyzer> vmAnalyzers = new ArrayList<>(); //*** data collectors ***// private final Map<Guid, VmDynamic> vmDynamicToSave = new HashMap(); private final List<VmStatistics> vmStatisticsToSave = new ArrayList<>(); private final List<List<VmNetworkInterface>> vmInterfaceStatisticsToSave = new ArrayList<>(); private final Collection<Pair<Guid, DiskImageDynamic>> vmDiskImageDynamicToSave = new LinkedList<>(); private final List<VmDevice> vmDeviceToSave = new ArrayList<>(); private final Map<Guid, List<VmGuestAgentInterface>> vmGuestAgentNics = new HashMap<>(); private final List<VmDynamic> poweringUpVms = new ArrayList<>(); private final List<VmDevice> newVmDevices = new ArrayList<>(); private final List<VmDeviceId> removedDeviceIds = new ArrayList<>(); private final List<LUNs> vmLunDisksToSave = new ArrayList<>(); private final List<Guid> autoVmsToRun = new ArrayList<>(); private final List<VmStatic> externalVmsToAdd = new ArrayList<>(); private final Map<Guid, VmJob> vmJobsToUpdate = new HashMap<>(); private final List<Guid> vmJobIdsToRemove = new ArrayList<>(); private final List<Guid> existingVmJobIds = new ArrayList<>(); private List<Pair<VM, VmInternalData>> externalVms = new ArrayList<>(); //*** data collectors ***// private static final String EXTERNAL_VM_NAME_FORMAT = "external-%1$s"; private static final Logger log = LoggerFactory.getLogger(VmsMonitoring.class); /** * @param vdsManager the host manager related to this cycle. * @param monitoredVms the vms we want to monitor/analyze/react on. this structure is * a pair of the persisted (db currently) VM and the running VM which was reported from vdsm. * Analysis and reactions would be taken on those VMs only. * @param vmsWithChangedDevices * @param auditLogDirector */ public VmsMonitoring( VdsManager vdsManager, List<Pair<VM, VmInternalData>> monitoredVms, List<Pair<VM, VmInternalData>> vmsWithChangedDevices, AuditLogDirector auditLogDirector, long fetchTime) { this(vdsManager, monitoredVms, vmsWithChangedDevices, auditLogDirector, fetchTime, false); } public VmsMonitoring( VdsManager vdsManager, List<Pair<VM, VmInternalData>> monitoredVms, List<Pair<VM, VmInternalData>> vmsWithChangedDevices, AuditLogDirector auditLogDirector, long fetchTime, boolean timeToUpdateVmStatistics) { this.vdsManager = vdsManager; this.monitoredVms = monitoredVms; this.vmsWithChangedDevices = vmsWithChangedDevices; this.auditLogDirector = auditLogDirector; this.fetchTime = fetchTime; this.timeToUpdateVmStatistics = timeToUpdateVmStatistics; } /** * analyze and react upon changes on the monitoredVms. relevant changes would * be persisted and state transitions and internal commands would * take place accordingly. */ public void perform() { try { refreshExistingVmJobList(); refreshVmStats(); afterVMsRefreshTreatment(); vdsManager.vmsMonitoringInitFinished(); } catch (RuntimeException ex) { log.error("Failed during vms monitoring on host {} error is: {}", vdsManager.getVdsName(), ex); log.error("Exception:", ex); } finally { unlockVmsManager(); } } protected boolean isTimeToUpdateVmStatistics() { return timeToUpdateVmStatistics; } /** * lock Vms which has db entity i.e they are managed by a VmManager * @param pair * @return true if lock acquired */ private boolean tryLockVmForUpdate(Pair<VM, VmInternalData> pair) { Guid vmId = getVmId(pair); if (vmId != null) { VmManager vmManager = getResourceManager().getVmManager(vmId); if (vmManager.trylock()) { if (!vmManager.isLatestData(pair.getSecond(), vdsManager.getVdsId())) { log.warn("skipping VM '{}' from this monitoring cycle" + " - newer VM data was already processed", vmId); vmManager.unlock(); } else if (vmManager.getVmDataChangedTime() != null && fetchTime - vmManager.getVmDataChangedTime() <= 0) { log.warn("skipping VM '{}' from this monitoring cycle" + " - the VM data has changed since fetching the data", vmId); vmManager.unlock(); } else { // store the locked managers to finally release them at the end of the cycle vmManagers.put(vmId, vmManager); return true; } } else { log.debug("skipping VM '{}' from this monitoring cycle" + " - the VM is locked by its VmManager ", getVmId(pair)); } } return false; } private void unlockVmsManager() { for (VmManager vmManager : vmManagers.values()) { vmManager.updateVmDataChangedTime(); vmManager.unlock(); } } /** * Analyze the VM data pair * Skip analysis on VMs which cannot be locked * note: metrics calculation like memCommited and vmsCoresCount should be calculated *before* * this filtering. */ private void refreshVmStats() { for (Pair<VM, VmInternalData> monitoredVm : monitoredVms) { // TODO filter out migratingTo VMs if no action is taken on them if (tryLockVmForUpdate(monitoredVm)) { VmAnalyzer vmAnalyzer = getVmAnalyzer(monitoredVm); vmAnalyzers.add(vmAnalyzer); vmAnalyzer.analyze(); if (vmAnalyzer.isExternalVm()) { externalVms.add(new Pair<>(vmAnalyzer.getDbVm(), vmAnalyzer.getVdsmVm())); } } } processExternallyManagedVms(); processVmsWithDevicesChange(); saveVmsToDb(); } protected VmAnalyzer getVmAnalyzer(Pair<VM, VmInternalData> pair) { return new VmAnalyzer( pair.getFirst(), pair.getSecond(), this, auditLogDirector); } private void afterVMsRefreshTreatment() { Collection<Guid> movedToDownVms = new ArrayList<>(); List<Guid> succeededToRunVms = new ArrayList<>(); // now loop over the result and act for (VmAnalyzer vmAnalyzer : vmAnalyzers) { // rerun all vms from rerun list if (vmAnalyzer.isRerun()) { log.error("Rerun VM '{}'. Called from VDS '{}'", vmAnalyzer.getDbVm().getId(), vdsManager.getVdsName()); ResourceManager.getInstance().RerunFailedCommand(vmAnalyzer.getDbVm().getId(), vdsManager.getVdsId()); } if (vmAnalyzer.isSuccededToRun()) { vdsManager.succeededToRunVm(vmAnalyzer.getDbVm().getId()); succeededToRunVms.add(vmAnalyzer.getDbVm().getId()); } // Refrain from auto-start HA VM during its re-run attempts. if (vmAnalyzer.isAutoVmToRun() && !vmAnalyzer.isRerun()) { autoVmsToRun.add(vmAnalyzer.getDbVm().getId()); } // process all vms that their ip changed. if (vmAnalyzer.isClientIpChanged()) { final VmDynamic vmDynamic = vmAnalyzer.getVdsmVm().getVmDynamic(); getVdsEventListener().processOnClientIpChange(vmDynamic.getId(), vmDynamic.getClientIp()); } // process all vms that powering up. if (vmAnalyzer.isPoweringUp()) { getVdsEventListener().processOnVmPoweringUp(vmAnalyzer.getVdsmVm().getVmDynamic().getId()); } if (vmAnalyzer.isMovedToDown()) { movedToDownVms.add(vmAnalyzer.getDbVm().getId()); } if (vmAnalyzer.isRemoveFromAsync()) { ResourceManager.getInstance().RemoveAsyncRunningVm(vmAnalyzer.getDbVm().getId()); } if (vmAnalyzer.isHostedEngineUnmanaged()) { // @since 3.6 - we take existing HE VM and reimport it importHostedEngineVM(getVmInfo(Collections.singletonList(vmAnalyzer.getVdsmVm() .getVmDynamic() .getId() .toString()))[0]); } } getVdsEventListener().updateSlaPolicies(succeededToRunVms, vdsManager.getVdsId()); // run all vms that crashed that marked with auto startup getVdsEventListener().runFailedAutoStartVMs(autoVmsToRun); // process all vms that went down getVdsEventListener().processOnVmStop(movedToDownVms, vdsManager.getVdsId()); getVdsEventListener().refreshHostIfAnyVmHasHostDevices(succeededToRunVms, vdsManager.getVdsId()); } private void importHostedEngineVM(Map vmStruct) { VM vm = VdsBrokerObjectsBuilder.buildVmsDataFromExternalProvider(vmStruct); if (vm != null) { vm.setImages(VdsBrokerObjectsBuilder.buildDiskImagesFromDevices(vmStruct)); vm.setInterfaces(VdsBrokerObjectsBuilder.buildVmNetworkInterfacesFromDevices(vmStruct)); for (DiskImage diskImage : vm.getImages()) { vm.getDiskMap().put(Guid.newGuid(), diskImage); } vm.setVdsGroupId(getVdsManager().getVdsGroupId()); getVdsEventListener().importHostedEngineVm(vm); } } private void processVmsWithDevicesChange() { // Handle VM devices were changed (for 3.1 cluster and above) if (!VmDeviceCommonUtils.isOldClusterVersion(vdsManager.getGroupCompatibilityVersion())) { // If there are vms that require updating, // get the new info from VDSM in one call, and then update them all if (!vmsWithChangedDevices.isEmpty()) { ArrayList<String> vmsToUpdate = new ArrayList<>(vmsWithChangedDevices.size()); for (Pair<VM, VmInternalData> pair : vmsWithChangedDevices) { Guid vmId = pair.getFirst().getId(); // update only if the vm marked to change, otherwise it might have skipped because data invalidated // this ensure the vmManager lock is taken if (vmDynamicToSave.containsKey(vmId)) { vmDynamicToSave.get(vmId).setHash(pair.getSecond().getVmDynamic().getHash()); vmsToUpdate.add(vmId.toString()); } else { log.warn("VM '{}' not in changed list, skipping devices update.", vmId); } } updateVmDevices(vmsToUpdate); } } } private void saveVmsToDb() { getDbFacade().getVmDynamicDao().updateAllInBatch(vmDynamicToSave.values()); getDbFacade().getVmStatisticsDao().updateAllInBatch(vmStatisticsToSave); final List<VmNetworkStatistics> allVmInterfaceStatistics = new LinkedList<VmNetworkStatistics>(); for (List<VmNetworkInterface> list : vmInterfaceStatisticsToSave) { for (VmNetworkInterface iface : list) { allVmInterfaceStatistics.add(iface.getStatistics()); } } getDbFacade().getVmNetworkStatisticsDao().updateAllInBatch(allVmInterfaceStatistics); getDbFacade().getDiskImageDynamicDao().updateAllDiskImageDynamicWithDiskIdByVmId(vmDiskImageDynamicToSave); getDbFacade().getLunDao().updateAllInBatch(vmLunDisksToSave); getVdsEventListener().addExternallyManagedVms(externalVmsToAdd); saveVmDevicesToDb(); saveVmGuestAgentNetworkDevices(); saveVmJobsToDb(); } protected void processExternallyManagedVms() { // Fetching for details from the host // and marking the VMs for addition List<String> vmsToQuery = new ArrayList<>(externalVms.size()); for (Pair<VM, VmInternalData> pair : externalVms) { vmsToQuery.add(pair.getSecond().getVmDynamic().getId().toString()); } if (!vmsToQuery.isEmpty()) { // Query VDSM for VMs info, and creating a proper VMStatic to be used when importing them Map[] vmsInfo = getVmInfo(vmsToQuery); for (Map vmInfo : vmsInfo) { Guid vmId = Guid.createGuidFromString((String) vmInfo.get(VdsProperties.vm_guid)); VmStatic vmStatic = new VmStatic(); vmStatic.setId(vmId); vmStatic.setCreationDate(new Date()); vmStatic.setVdsGroupId(vdsManager.getVdsGroupId()); String vmNameOnHost = (String) vmInfo.get(VdsProperties.vm_name); if (StringUtils.equals(Config.<String>getValue(ConfigValues.HostedEngineVmName), vmNameOnHost)) { // its a hosted engine VM -> import it and skip the external VM phase importHostedEngineVM(vmInfo); continue; } else { vmStatic.setName(String.format(EXTERNAL_VM_NAME_FORMAT, vmNameOnHost)); vmStatic.setOrigin(OriginType.EXTERNAL); } vmStatic.setNumOfSockets(VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.num_of_cpus))); vmStatic.setMemSizeMb(VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.mem_size_mb))); vmStatic.setSingleQxlPci(false); externalVmsToAdd.add(vmStatic); log.info("Importing VM '{}' as '{}', as it is running on the on Host, but does not exist in the engine.", vmNameOnHost, vmStatic.getName()); } } } private void saveVmGuestAgentNetworkDevices() { if (!vmGuestAgentNics.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { for (Guid vmId : vmGuestAgentNics.keySet()) { getDbFacade().getVmGuestAgentInterfaceDao().removeAllForVm(vmId); } for (List<VmGuestAgentInterface> nics : vmGuestAgentNics.values()) { if (nics != null) { for (VmGuestAgentInterface nic : nics) { getDbFacade().getVmGuestAgentInterfaceDao().save(nic); } } } return null; } } ); } } private void saveVmDevicesToDb() { getDbFacade().getVmDeviceDao().updateAllInBatch(vmDeviceToSave); if (!removedDeviceIds.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDao().removeAll(removedDeviceIds); return null; } }); } if (!newVmDevices.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmDeviceDao().saveAll(newVmDevices); return null; } }); } } private void saveVmJobsToDb() { getDbFacade().getVmJobDao().updateAllInBatch(vmJobsToUpdate.values()); if (!vmJobIdsToRemove.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { getDbFacade().getVmJobDao().removeAll(vmJobIdsToRemove); return null; } }); } } private void refreshExistingVmJobList() { existingVmJobIds.clear(); existingVmJobIds.addAll(getDbFacade().getVmJobDao().getAllIds()); } /** * Update the given list of VMs properties in DB * * @param vmsToUpdate */ protected void updateVmDevices(List<String> vmsToUpdate) { if (vmsToUpdate.isEmpty()) { return; } Map[] vms = getVmInfo(vmsToUpdate); if (vms != null) { for (Map vm : vms) { processVmDevices(vm); } } } /** * Actually process the VM device update in DB. * * @param vm */ private void processVmDevices(Map vm) { if (vm == null || vm.get(VdsProperties.vm_guid) == null) { log.error("Received NULL VM or VM id when processing VM devices, abort."); return; } Guid vmId = new Guid((String) vm.get(VdsProperties.vm_guid)); Set<Guid> processedDevices = new HashSet<Guid>(); List<VmDevice> devices = getDbFacade().getVmDeviceDao().getVmDeviceByVmId(vmId); Map<VmDeviceId, VmDevice> deviceMap = Entities.businessEntitiesById(devices); for (Object o : (Object[]) vm.get(VdsProperties.Devices)) { Map device = (Map<String, Object>) o; if (device.get(VdsProperties.Address) == null) { logDeviceInformation(vmId, device); continue; } Guid deviceId = getDeviceId(device); VmDevice vmDevice = deviceMap.get(new VmDeviceId(deviceId, vmId)); String logicalName = null; if (deviceId != null && FeatureSupported.reportedDisksLogicalNames(getVdsManager().getGroupCompatibilityVersion()) && VmDeviceType.DISK.getName().equals(device.get(VdsProperties.Device))) { try { logicalName = getDeviceLogicalName((Map<?, ?>) vm.get(VdsProperties.GuestDiskMapping), deviceId); } catch (Exception e) { log.error("error while getting device name when processing, vm '{}', device info '{}' with exception, skipping '{}'", vmId, device, e.getMessage()); log.error("Exception", e); } } if (deviceId == null || vmDevice == null) { deviceId = addNewVmDevice(vmId, device, logicalName); } else { vmDevice.setIsPlugged(Boolean.TRUE); vmDevice.setAddress(((Map<String, String>) device.get(VdsProperties.Address)).toString()); vmDevice.setAlias(StringUtils.defaultString((String) device.get(VdsProperties.Alias))); vmDevice.setLogicalName(logicalName); addVmDeviceToList(vmDevice); } processedDevices.add(deviceId); } handleRemovedDevices(vmId, processedDevices, devices); } private String getDeviceLogicalName(Map<?, ?> diskMapping, Guid deviceId) { if (diskMapping == null) { return null; } Map<?, ?> deviceMapping = null; String modifiedDeviceId = deviceId.toString().substring(0, 20); for (Map.Entry<?, ?> entry : diskMapping.entrySet()) { String serial = (String) entry.getKey(); if (serial != null && serial.contains(modifiedDeviceId)) { deviceMapping = (Map<?, ?>) entry.getValue(); break; } } return deviceMapping == null ? null : (String) deviceMapping.get(VdsProperties.Name); } /** * Removes unmanaged devices from DB if were removed by libvirt. Empties device address with isPlugged = false * * @param vmId * @param processedDevices */ private void handleRemovedDevices(Guid vmId, Set<Guid> processedDevices, List<VmDevice> devices) { for (VmDevice device : devices) { if (processedDevices.contains(device.getDeviceId())) { continue; } if (device.getIsManaged()) { if (device.getIsPlugged()) { device.setIsPlugged(Boolean.FALSE); device.setAddress(""); addVmDeviceToList(device); log.debug("VM '{}' managed pluggable device was unplugged : '{}'", vmId, device); } else if (!devicePluggable(device)) { log.error("VM '{}' managed non pluggable device was removed unexpectedly from libvirt: '{}'", vmId, device); } } else { removedDeviceIds.add(device.getId()); log.debug("VM '{}' unmanaged device was marked for remove : {1}", vmId, device); } } } private boolean devicePluggable(VmDevice device) { return VmDeviceCommonUtils.isDisk(device) || VmDeviceCommonUtils.isBridge(device); } /** * Adds new devices recognized by libvirt * * @param vmId * @param device */ private Guid addNewVmDevice(Guid vmId, Map device, String logicalName) { Guid newDeviceId = Guid.Empty; String typeName = (String) device.get(VdsProperties.Type); String deviceName = (String) device.get(VdsProperties.Device); // do not allow null or empty device or type values if (StringUtils.isEmpty(typeName) || StringUtils.isEmpty(deviceName)) { log.error("Empty or NULL values were passed for a VM '{}' device, Device is skipped", vmId); } else { String address = ((Map<String, String>) device.get(VdsProperties.Address)).toString(); String alias = StringUtils.defaultString((String) device.get(VdsProperties.Alias)); Object o = device.get(VdsProperties.SpecParams); newDeviceId = Guid.newGuid(); VmDeviceId id = new VmDeviceId(newDeviceId, vmId); VmDevice newDevice = new VmDevice(id, VmDeviceGeneralType.forValue(typeName), deviceName, address, 0, o == null ? new HashMap<String, Object>() : (Map<String, Object>) o, false, true, Boolean.getBoolean((String) device.get(VdsProperties.ReadOnly)), alias, null, null, logicalName); newVmDevices.add(newDevice); log.debug("New device was marked for adding to VM '{}' Devices : '{}'", vmId, newDevice); } return newDeviceId; } /** * gets the device id from the structure returned by VDSM device ids are stored in specParams map * * @param device * @return */ private static Guid getDeviceId(Map device) { String deviceId = (String) device.get(VdsProperties.DeviceId); return deviceId == null ? null : new Guid(deviceId); } /** * gets VM full information for the given list of VMs * * @param vmsToUpdate * @return */ protected Map[] getVmInfo(List<String> vmsToUpdate) { // TODO refactor commands to use vdsId only - the whole vds object here is useless VDS vds = new VDS(); vds.setId(vdsManager.getVdsId()); Map[] result = {}; VDSReturnValue vdsReturnValue = getResourceManager().runVdsCommand(VDSCommandType.FullList, new FullListVDSCommandParameters(vds, vmsToUpdate)); if (vdsReturnValue.getSucceeded()) { result = (Map[]) (vdsReturnValue.getReturnValue()); } return result; } private boolean shouldLogDeviceDetails(String deviceType) { return !StringUtils.equalsIgnoreCase(deviceType, VmDeviceType.FLOPPY.getName()); } private void logDeviceInformation(Guid vmId, Map device) { String message = "Received a {} Device without an address when processing VM {} devices, skipping device"; String deviceType = (String) device.get(VdsProperties.Device); if (shouldLogDeviceDetails(deviceType)) { Map<String, Object> deviceInfo = device; log.info(message + ": {}", StringUtils.defaultString(deviceType), vmId, deviceInfo); } else { log.info(message, StringUtils.defaultString(deviceType), vmId); } } private Guid getVmId(Pair<VM, VmInternalData> pair) { return (pair.getFirst() != null) ? pair.getFirst().getId() : ((pair.getSecond() != null) ? pair.getSecond().getVmDynamic().getId() : null); } /** * Add or update vmDynamic to save list * * @param vmDynamic */ protected void addVmDynamicToList(VmDynamic vmDynamic) { vmDynamicToSave.put(vmDynamic.getId(), vmDynamic); } /** * Add or update vmStatistics to save list * * @param vmStatistics */ protected void addVmStatisticsToList(VmStatistics vmStatistics) { vmStatisticsToSave.add(vmStatistics); } protected void addVmInterfaceStatisticsToList(List<VmNetworkInterface> list) { if (list.isEmpty()) { return; } vmInterfaceStatisticsToSave.add(list); } /** * Add or update vmDynamic to save list * * @param vmDevice */ private void addVmDeviceToList(VmDevice vmDevice) { vmDeviceToSave.add(vmDevice); } /** * An access method for test usages * * @return The devices to be added to the database */ protected List<VmDevice> getNewVmDevices() { return Collections.unmodifiableList(newVmDevices); } /** * An access method for test usages * * @return The devices to be removed from the database */ protected List<VmDeviceId> getRemovedVmDevices() { return Collections.unmodifiableList(removedDeviceIds); } /** * An access method for test usages * * @return The LUNs to update in DB */ protected List<LUNs> getVmLunDisksToSave() { return vmLunDisksToSave; } protected List<VmDynamic> getPoweringUpVms() { return poweringUpVms; } protected DbFacade getDbFacade() { return DbFacade.getInstance(); } protected ResourceManager getResourceManager() { return ResourceManager.getInstance(); } protected IVdsEventListener getVdsEventListener() { return ResourceManager.getInstance().getEventListener(); } public void addDiskImageDynamicToSave(Pair<Guid, DiskImageDynamic> imageDynamicByVmId) { vmDiskImageDynamicToSave.add(imageDynamicByVmId); } public List<Guid> getExistingVmJobIds() { return existingVmJobIds; } public Map<Guid, VmJob> getVmJobsToUpdate() { return vmJobsToUpdate; } public List<Guid> getVmJobIdsToRemove() { return vmJobIdsToRemove; } public VdsManager getVdsManager() { return vdsManager; } public void addVmGuestAgentNics(Guid id, List<VmGuestAgentInterface> vmGuestAgentInterfaces) { vmGuestAgentNics.put(id, vmGuestAgentInterfaces); } }
package step.plugins.datatable.formatters.custom; import org.bson.Document; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import step.core.GlobalContext; import step.plugins.datatable.formatters.Formatter; import step.plugins.views.ViewPlugin; import step.plugins.views.functions.ReportNodeStatusDistribution; public class ExecutionSummaryFormatter implements Formatter { ObjectMapper mapper = new ObjectMapper(); ViewPlugin viewPlugin; public ExecutionSummaryFormatter(GlobalContext context) { super(); this.viewPlugin = (ViewPlugin) context.get(ViewPlugin.VIEW_PLUGIN_KEY); } @Override public String format(Object value, Document row) { String eid = row.get("_id").toString(); ReportNodeStatusDistribution distribution = (ReportNodeStatusDistribution) viewPlugin.query("statusDistributionForFunctionCalls", eid); if(distribution!=null) { try { return mapper.writeValueAsString(distribution); } catch (JsonProcessingException e1) { throw new RuntimeException("Error while writing distribution",e1); } } else { return "{}"; } } @Override public Object parse(String formattedValue) { // TODO Auto-generated method stub return null; } }
package uk.ac.ebi.atlas.model.analyticsindex; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.atlas.commons.streams.ObjectInputStream; import uk.ac.ebi.atlas.experimentimport.analytics.differential.DifferentialAnalytics; import uk.ac.ebi.atlas.model.experiment.differential.DifferentialExperiment; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkState; public class DifferentialExperimentDataPointStream implements ObjectInputStream<DifferentialExperimentDataPoint> { private static final Logger LOGGER = LoggerFactory.getLogger(DifferentialExperimentDataPointStream.class); protected final DifferentialExperiment experiment; protected final Map<String, Integer> numReplicatesByContrastId; protected final ObjectInputStream<? extends DifferentialAnalytics> inputStream; protected final Multimap<String, String> conditionSearchTermsByContrastId; protected final Set<String> assaysSeen = Sets.newHashSet(); public DifferentialExperimentDataPointStream(DifferentialExperiment experiment, ObjectInputStream<? extends DifferentialAnalytics> inputStream, Multimap<String, String> conditionSearchTermsByContrastId, Map<String, Integer> numReplicatesByContrastId) { this.experiment = experiment; this.inputStream = inputStream; this.conditionSearchTermsByContrastId = conditionSearchTermsByContrastId; this.numReplicatesByContrastId = numReplicatesByContrastId; } @Override public DifferentialExperimentDataPoint readNext() { DifferentialAnalytics analytics = inputStream.readNext(); if (analytics != null) { return new DifferentialExperimentDataPoint(experiment, analytics, getConditionSearchTerms(analytics .getContrastId(), experiment.getExperimentDesign().getFactorHeaders()), getNumReplicates(analytics .getContrastId())); } else { return null; } } @Override public void close() throws IOException { inputStream.close(); } private int getNumReplicates(String contrastId) { // This is an experiment for which John Collins, the data provider, explicitly requested to leave a contrast // out. However, this check is useful to check for experiment sanity (it has proved it more than once), so we if (experiment.getAccession().equalsIgnoreCase("E-MTAB-5224") && contrastId.equalsIgnoreCase("g2_g1")) { return 0; } int numReplicates = numReplicatesByContrastId.getOrDefault(contrastId, 0); checkState(numReplicates != 0, "No replicates for contrast " + contrastId); return numReplicates; } private String getConditionSearchTerms(String contrastId, Set<String> factors) { Collection<String> searchTerms = conditionSearchTermsByContrastId.get(contrastId); if (searchTerms.isEmpty() && !assaysSeen.contains(contrastId)) { assaysSeen.add(contrastId); LOGGER.warn("No condition search terms found for {}", contrastId); } ImmutableList.Builder<String> conditionSearchTermsBuilder = new ImmutableList.Builder<>(); return Joiner.on(" ").join(conditionSearchTermsBuilder.addAll(searchTerms).addAll(factors).build()); } }
package org.intermine.bio.dataconversion; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildException; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.FormattedTextParser; import org.intermine.xml.full.Item; /** * DataConverter to parse BDGP insitu data file into Items. * * @author Julie Sullivan */ public class BDGPInsituConverter extends BioFileConverter { protected static final Logger LOG = Logger.getLogger(BDGPInsituConverter.class); private static final String URL = "http: private Map<String, Item> genes = new HashMap<String, Item>(); private Map<String, Item> terms = new HashMap<String, Item>(); private Map<String, Item> results = new HashMap<String, Item>(); private Map<String, Item> imgs = new HashMap<String, Item>(); protected Item orgDrosophila; private Item pub; private String[] stages; protected IdResolverFactory resolverFactory; private static final String TAXON_ID = "7227"; private Item ontology = null; static final String[] STAGE_LABELS; static { STAGE_LABELS = new String[7]; STAGE_LABELS[1] = "stage 1-3"; STAGE_LABELS[2] = "stage 4-6"; STAGE_LABELS[3] = "stage 7-8"; STAGE_LABELS[4] = "stage 9-10"; STAGE_LABELS[5] = "stage 11-12"; STAGE_LABELS[6] = "stage 13-16"; } /** * Construct a new instance of BDGPInsituConverter. * * @param model the Model * @param writer the ItemWriter used to handle the resultant items * @throws ObjectStoreException if an error occurs in storing */ public BDGPInsituConverter(ItemWriter writer, Model model) throws ObjectStoreException { super(writer, model, "BDGP", "BDGP in situ data set"); orgDrosophila = createItem("Organism"); orgDrosophila.setAttribute("taxonId", TAXON_ID); store(orgDrosophila); pub = createItem("Publication"); pub.setAttribute("pubMedId", "17645804"); store(pub); setStages(); ontology = createItem("Ontology"); ontology.setAttribute("name", "ImaGO"); store(ontology); resolverFactory = new FlyBaseIdResolverFactory("gene"); } /** * Process the csv file * @param reader the Reader * @see DataConverter#process * @throws Exception if something goes wrong */ @Override public void process(Reader reader) throws Exception { Iterator<String[]> it = FormattedTextParser.parseTabDelimitedReader(reader); while (it.hasNext()) { String[] lineBits = it.next(); String geneCG = lineBits[0]; if (!geneCG.startsWith("CG")) { // ignore clones for now continue; } // Try to create/fetch gene, if null the IdResolver failed so do nothing for this row Item gene = getGene(geneCG); if (gene == null) { continue; } String stage = lineBits[1]; String resultKey = geneCG + stage; Item result = getResult(resultKey, gene.getIdentifier(), pub.getIdentifier(), stage); Integer stageNumber = null; try { stageNumber = new Integer(stage); } catch (NumberFormatException e) { // bad line in file, just keep going continue; } result.setAttribute("stageRange", STAGE_LABELS[stageNumber.intValue()] + " (BDGP in situ)"); if (lineBits.length > 2) { String image = lineBits[2]; if (StringUtils.isNotEmpty(image)) { setImage(result, URL + image); } } if (lineBits.length > 3) { String term = lineBits[3]; Item termItem = getTerm(term); if (termItem != null) { result.addToCollection("mRNAExpressionTerms", termItem); } if ("no staining".equals(term)) { result.setAttribute("expressed", "false"); } } } for (Item result: results.values()) { if (!result.hasCollection("mRNAExpressionTerms") || result.getCollection("mRNAExpressionTerms").getRefIds().isEmpty()) { result.setAttribute("expressed", "false"); } } storeAll(imgs); storeAll(results); } private void storeAll(Map<String, Item> map) throws ObjectStoreException { for (Item item: map.values()) { store(item); } } private Item getResult(String key, String geneId, String pubId, String stage) { if (results.containsKey(key)) { return results.get(key); } Item result = createItem("MRNAExpressionResult"); result.setAttribute("expressed", "true"); result.setReference("gene", geneId); result.setReference("publication", pubId); result.setCollection("stages", getStages(stage)); // result.setCollection("images", new ArrayList<String>()); // result.setCollection("mRNAExpressionTerms", new ArrayList<String>()); results.put(key, result); return result; } private List<String> getStages(String stage) { List<String> stagesColl = new ArrayList<String>(); if ("1".equals(stage)) { stagesColl.add(stages[1]); stagesColl.add(stages[2]); stagesColl.add(stages[3]); } else if ("2".equals(stage)) { stagesColl.add(stages[4]); stagesColl.add(stages[5]); stagesColl.add(stages[6]); } else if ("3".equals(stage)) { stagesColl.add(stages[7]); stagesColl.add(stages[8]); } else if ("4".equals(stage)) { stagesColl.add(stages[9]); stagesColl.add(stages[10]); } else if ("5".equals(stage)) { stagesColl.add(stages[11]); stagesColl.add(stages[12]); } else if ("6".equals(stage)) { stagesColl.add(stages[13]); stagesColl.add(stages[14]); stagesColl.add(stages[15]); stagesColl.add(stages[16]); } else { throw new BuildException("bad stage value " + stage); } return stagesColl; } private Item getTerm(String name) throws ObjectStoreException { if (!isValidTerm(name)) { return null; } else if (terms.containsKey(name)) { return terms.get(name); } Item termItem = createItem("OntologyTerm"); termItem.setAttribute("name", name); termItem.setReference("ontology", ontology); store(termItem); terms.put(name, termItem); return termItem; } private Item getGene(String geneCG) throws ObjectStoreException { IdResolver resolver = resolverFactory.getIdResolver(); int resCount = resolver.countResolutions(TAXON_ID, geneCG); if (resCount != 1) { LOG.info("RESOLVER: failed to resolve gene to one identifier, ignoring gene: " + geneCG + " count: " + resCount + " FBgn: " + resolver.resolveId(TAXON_ID, geneCG)); return null; } String primaryIdentifier = resolver.resolveId(TAXON_ID, geneCG).iterator().next(); if (genes.containsKey(primaryIdentifier)) { return genes.get(primaryIdentifier); } Item gene = createItem("Gene"); gene.setAttribute("primaryIdentifier", primaryIdentifier); gene.setReference("organism", orgDrosophila); genes.put(primaryIdentifier, gene); store(gene); return gene; } private void setImage(Item result, String img) { if (!imgs.containsKey(img)) { Item item = createItem("Image"); item.setAttribute("url", img); imgs.put(img, item); result.addToCollection("images", item.getIdentifier()); } } private void setStages() throws ObjectStoreException { Item item = createItem("Ontology"); item.setAttribute("name", "Fly Development"); store(item); stages = new String[17]; for (int i = 1; i <= 16; i++) { Item stage = createItem("DevelopmentTerm"); stage.setAttribute("name", "embryonic stage " + i); stage.setReference("ontology", item); stages[i] = stage.getIdentifier(); store(stage); } } private boolean isValidTerm(String name) { if (StringUtils.isEmpty(name)) { return false; } if (name.contains("_")) { return false; } return true; } /* These terms may not be in the updated file private Set<String> getBadTerms() { Set<String> forbiddenTerms = new HashSet<String>(); forbiddenTerms.add("does_not_fit_array"); forbiddenTerms.add("epi_combo"); forbiddenTerms.add("flag_as_conflicting"); forbiddenTerms.add("flag_as_incompleto"); forbiddenTerms.add("flag_as_nonspecific"); forbiddenTerms.add("flag_for_volker"); forbiddenTerms.add("go_term"); return forbiddenTerms; } */ }
package org.biojava.bio.structure.align.fatcat.calc; import java.util.List; import org.biojava.bio.structure.Atom; import org.biojava.bio.structure.align.model.AFP; import org.biojava.bio.structure.align.model.AFPChain; /** does post processing after alignment chaingin * * @author Andreas Prlic * */ public class AFPPostProcessor { public static final boolean debug = FatCatAligner.debug; public static void postProcess(FatCatParameters params, AFPChain afpChain,Atom[] ca1, Atom[] ca2){ int blockNum = afpChain.getBlockNum(); afpChain.setBlockNumIni(blockNum); //PostProcess of chaining result afpChain.setBlockNumIni(blockNum); //split blocks (introduce twists) with high RMSD splitBlock(params,afpChain, ca1,ca2); blockNum = afpChain.getBlockNum(); afpChain.setBlockNumSpt( blockNum); if ( debug){ System.err.println("AFPPOstProcessor: postProcess blocknum = blocknumSpt:" + blockNum); } //redo: merge blocks with similar transformations & remove small blocks //if(blockNum >= 2) ClustBlock(); deleteBlock(params,afpChain,ca1,ca2); mergeBlock(params,afpChain,ca1,ca2); afpChain.setBlockNumClu(afpChain.getBlockNum()); } private static int[] getSubrange(int[] orig, int startPos){ int nl1 = orig.length - startPos + 1; int[] subrange = new int[nl1]; int posi = -1; for ( int itmp = startPos ; itmp< orig.length ; itmp++){ posi++; subrange[posi] = orig[itmp]; } return subrange; } /** * in some special cases, there is no maginificent twists in the final chaining result; however, their rmsd (original and after optimizing) are very large. Therefore, a post-process is taken to split the blocks further at the ralative bad connections ( with relative high distance variation) to be tested: split or not according to optimized or initial chaining??? */ private static void splitBlock(FatCatParameters params, AFPChain afpChain, Atom[] ca1, Atom[] ca2) { if ( debug) System.err.println("AFPPostProcessor: splitBlock"); int i, a, bk, cut; double maxs, maxt; int blockNum = afpChain.getBlockNum(); int maxTra = params.getMaxTra(); double badRmsd = params.getBadRmsd(); int blockNum0 = blockNum; double[] blockRmsd = afpChain.getBlockRmsd(); int[] blockSize = afpChain.getBlockSize(); int[] block2Afp = afpChain.getBlock2Afp(); double[] afpChainTwiList = afpChain.getAfpChainTwiList(); bk = 0; while(blockNum < maxTra + 1) { maxs = 0; for(i = 0; i < blockNum; i ++) { if(blockRmsd[i] > maxs && blockSize[i] > 2) { //according to the optimized alignment maxs = blockRmsd[i]; bk = i; } //!(Note: optRmsd, not blockRmsd, according to the optimized alignment } if(maxs < badRmsd) break; maxt = 0; cut = 0; for(i = 1; i < blockSize[bk]; i ++) { a = i + block2Afp[bk]; if(afpChainTwiList[a] > maxt) { maxt = afpChainTwiList[a]; cut = i; } } if(debug) System.out.println(String.format("block %d original size %d rmsd %.3f maxt %.2f cut at %d\n", bk, blockSize[bk], maxs, maxt, cut)); for(i = blockNum - 1; i > bk; i block2Afp[i + 1] = block2Afp[i]; blockSize[i + 1] = blockSize[i]; blockRmsd[i + 1] = blockRmsd[i]; } //update block information block2Afp[bk + 1] = cut + block2Afp[bk]; blockSize[bk + 1] = blockSize[bk] - cut; blockSize[bk] = cut; if(debug) System.out.println(String.format(" split into %d and %d sizes\n", blockSize[bk], blockSize[bk + 1])); int[] afpChainList = afpChain.getAfpChainList(); //int[] subrange1 = getSubrange(afpChainList, block2Afp[bk + 1] ); blockRmsd[bk + 1] = AFPChainer.calAfpRmsd(blockSize[bk + 1], afpChainList, block2Afp[bk + 1] , afpChain, ca1, ca2); //int[] subrange2 = getSubrange(afpChainList, block2Afp[bk] ); blockRmsd[bk] = AFPChainer.calAfpRmsd(blockSize[bk], afpChainList, block2Afp[bk], afpChain, ca1, ca2); //split a block at the biggest position blockNum ++; afpChain.setAfpChainList(afpChainList); } if(blockNum - blockNum0 > 0) { if(debug) System.out.println(String.format("Split %d times:\n", blockNum - blockNum0)); for(i = 0; i < blockNum; i ++) { if(debug) System.out.println(String.format(" block %d size %d from %d rmsd %.3f\n", i, blockSize[i], block2Afp[i], blockRmsd[i])); } } afpChain.setBlockNum(blockNum); afpChain.setBlockSize(blockSize); afpChain.setBlockRmsd(blockRmsd); afpChain.setBlock2Afp(block2Afp); } /** * remove the artifical small rigid-body superimpose in the middle clust the similar superimpositions (caused by the small flexible region, which is detected as a seperate rigid superimposing region by adding two twists before and after it(artifically!) one possible solution: allowing long enough loops in the chaining process, which however increase the calculation complexity */ private static void deleteBlock(FatCatParameters params, AFPChain afpChain,Atom[] ca1, Atom[] ca2) { int blockNum = afpChain.getBlockNum(); List<AFP> afpSet = afpChain.getAfpSet(); int[] afpChainList =afpChain.getAfpChainList(); int[] block2Afp = afpChain.getBlock2Afp(); int[] blockSize = afpChain.getBlockSize(); double[] blockRmsd = afpChain.getBlockRmsd(); int fragLen = params.getFragLen(); //remove those blocks (both in terminals and in the middle) with only a AFP //but still keep those small blocks spaning large regions if(blockNum <= 1) return; int blockNumOld = blockNum; int i, j, b1, b2, e1, e2, len; e1 = e2 = 0; for(i = 0; i < blockNum; i ++) { b1 = e1; b2 = e2; if(i < blockNum - 1) { e1 = afpSet.get(afpChainList[block2Afp[i + 1]]).getP1(); e2 = afpSet.get(afpChainList[block2Afp[i + 1]]).getP2(); } else { e1 = ca1.length; e2 = ca2.length; } if(blockSize[i] > 1) continue; len = (e1 - b1) < (e2 - b2)?(e1 - b1):(e2 - b2); //if(i == blockNum - 1) blockNum --; if(len < 2 * fragLen) { for(j = i; j < blockNum - 1; j ++) { blockRmsd[j] = blockRmsd[j + 1]; blockSize[j] = blockSize[j + 1]; block2Afp[j] = block2Afp[j + 1]; } blockNum i } //delete a block } if(blockNumOld > blockNum) if(debug) System.out.println( String.format("Delete %d small blocks\n", blockNumOld - blockNum) ); if (debug) System.err.println("deleteBlock: end blockNum:"+ blockNum); afpChain.setBlock2Afp(block2Afp); afpChain.setBlockSize(blockSize); afpChain.setAfpChainList(afpChainList); afpChain.setBlockNum(blockNum); afpChain.setBlockRmsd(blockRmsd); } /** //Merge consecutive blocks with similar transformation */ private static void mergeBlock(FatCatParameters params, AFPChain afpChain,Atom[] ca1,Atom[] ca2) { int blockNum = afpChain.getBlockNum(); double badRmsd = params.getBadRmsd(); int[] block2Afp = afpChain.getBlock2Afp(); int[] blockSize = afpChain.getBlockSize(); double[] blockRmsd = afpChain.getBlockRmsd(); int afpChainTwiNum = afpChain.getAfpChainTwiNum(); //clustering the neighbor blocks if their transformations are similar int i, j, b1, b2, minb1, minb2; double minrmsd; int merge = 0; int blockNumOld = blockNum; double[][] rmsdlist = null; if(blockNum > 1) { rmsdlist = new double[blockNumOld][blockNumOld]; for(b1 = 0; b1 < blockNum - 1; b1 ++) { for(b2 = b1 + 1; b2 < blockNum; b2 ++) { rmsdlist[b1][b2] = combineRmsd(b1, b2,afpChain,ca1,ca2); } } } minb1 = 0; while(blockNum > 1) { minrmsd = 1000; for(i = 0; i < blockNum - 1; i ++) { j = i + 1; //only consider neighbor blocks if(minrmsd > rmsdlist[i][j]) { minrmsd = rmsdlist[i][j]; minb1 = i; } } minb2 = minb1 + 1; //merge those most similar blocks //maxrmsd = (blockRmsd[minb1] > blockRmsd[minb2])?blockRmsd[minb1]:blockRmsd[minb2]; if(minrmsd < badRmsd) { if(debug) System.out.println(String.format("merge block %d (rmsd %.3f) and %d (rmsd %.3f), total rmsd %.3f\n", minb1, blockRmsd[minb1], minb2, blockRmsd[minb2], minrmsd)); blockSize[minb1] += blockSize[minb2]; blockRmsd[minb1] = minrmsd; for(i = minb2; i < blockNum - 1; i ++) { block2Afp[i] = block2Afp[i + 1]; blockSize[i] = blockSize[i + 1]; blockRmsd[i] = blockRmsd[i + 1]; } //update block information afpChainTwiNum blockNum for(b1 = 0; b1 < blockNum - 1; b1 ++) { for(b2 = b1 + 1; b2 < blockNum; b2 ++) { if(b1 == minb1 || b2 == minb1) { rmsdlist[b1][b2] = combineRmsd(b1, b2, afpChain,ca1,ca2); } else if(b2 < minb1) continue; else if(b1 < minb1) { rmsdlist[b1][b2] = rmsdlist[b1][b2 + 1]; } else { rmsdlist[b1][b2] = rmsdlist[b1 + 1][b2 + 1]; } } } //update the rmsdlist merge ++; } //merge two blocks else if(minrmsd >= 100) break; else { rmsdlist[minb1][minb2] += 100; } //not merge, modify the rmsdlist so that this combination is not considered in next iteration } if(merge > 0) { if(debug) System.out.println(String.format("Merge %d blocks, remaining %d blocks\n", merge, blockNum)); } if (debug){ System.err.println("AFPPostProcessor: mergeBlock end blocknum:" + blockNum); } afpChain.setBlock2Afp(block2Afp); afpChain.setBlockSize(blockSize); afpChain.setBlockNum(blockNum); afpChain.setBlockRmsd(blockRmsd); afpChain.setAfpChainTwiNum(afpChainTwiNum); } /** return the rmsd of two blocks */ private static double combineRmsd(int b1, int b2, AFPChain afpChain,Atom[] ca1,Atom[] ca2) { int i; int afpn = 0; int[] afpChainList =afpChain.getAfpChainList(); int[] block2Afp = afpChain.getBlock2Afp(); int[] blockSize = afpChain.getBlockSize(); int[] list = new int[blockSize[b1]+blockSize[b2]]; for(i = block2Afp[b1]; i < block2Afp[b1] + blockSize[b1]; i ++) { list[afpn ++] = afpChainList[i]; } for(i = block2Afp[b2]; i < block2Afp[b2] + blockSize[b2]; i ++) { list[afpn ++] = afpChainList[i]; } double rmsd = AFPChainer.calAfpRmsd(afpn, list,0, afpChain,ca1,ca2); afpChain.setBlock2Afp(block2Afp); afpChain.setBlockSize(blockSize); afpChain.setAfpChainList(afpChainList); return rmsd; } }
package weave.utils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.rmi.RemoteException; import java.security.InvalidParameterException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; /** * SQLUtils * * @author Andy Dufilie * @author Andrew Wilkinson * @author Kyle Monico * @author Yen-Fu Luo * @author Philip Kovac */ public class SQLUtils { public static String MYSQL = "MySQL"; public static String POSTGRESQL = "PostgreSQL"; public static String SQLSERVER = "Microsoft SQL Server"; public static String ORACLE = "Oracle"; public static String SQLUTILS_SERIAL_TRIGGER_TYPE = "SQLUTILS_SERIAL_TRIGGER_TYPE"; // used internally in createTable(), not an actual valid type /** * @param dbms The name of a DBMS (MySQL, PostGreSQL, ...) * @return A driver name that can be used in the getConnection() function. */ public static String getDriver(String dbms) throws RemoteException { if (dbms.equalsIgnoreCase(MYSQL)) return "com.mysql.jdbc.Driver"; if (dbms.equalsIgnoreCase(POSTGRESQL)) return "org.postgis.DriverWrapper"; if (dbms.equalsIgnoreCase(SQLSERVER)) return "net.sourceforge.jtds.jdbc.Driver"; if (dbms.equalsIgnoreCase(ORACLE)) return "oracle.jdbc.OracleDriver"; throw new RemoteException("Unknown DBMS"); } public static String getDbmsFromConnection(Connection conn) { try { String dbms = conn.getMetaData().getDatabaseProductName(); for (String match : new String[]{ ORACLE, SQLSERVER, MYSQL, POSTGRESQL }) if (dbms.equalsIgnoreCase(match)) return match; return dbms; } catch (SQLException e) { return ""; } } public static String getDbmsFromConnectString(String connectString) throws RemoteException { if (connectString.startsWith("jdbc:jtds")) return SQLSERVER; if (connectString.startsWith("jdbc:oracle")) return ORACLE; if (connectString.startsWith("jdbc:mysql")) return MYSQL; if (connectString.startsWith("jdbc:postgresql")) return POSTGRESQL; throw new RemoteException("Unknown DBMS"); } /** * @param dbms The name of a DBMS (MySQL, PostGreSQL, Microsoft SQL Server) * @param ip The IP address of the DBMS. * @param port The port the DBMS is on (optional, can be "" to use default). * @param database The name of a database to connect to (can be "" for MySQL) * @param user The username to use when connecting. * @param pass The password associated with the username. * @return A connect string that can be used in the getConnection() function. */ public static String getConnectString(String dbms, String ip, String port, String database, String user, String pass) { String host; if (port == null || port.length() == 0) host = ip; // default port for specific dbms will be used else host = ip + ":" + port; String format = null; if (SQLSERVER.equalsIgnoreCase(dbms)) { dbms = "sqlserver"; // this will be put in the format string format = "jdbc:jtds:%s://%s/;instance=%s;user=%s;password=%s"; } else if (ORACLE.equalsIgnoreCase(dbms)) { format = "jdbc:%s:thin:%s/%s@%s:%s"; //"jdbc:oracle:thin:<user>/<password>@<host>:<port>:<instance>" } else // MySQL or PostGreSQL { format = "jdbc:%s://%s/%s?user=%s&password=%s"; } // MySQL connect string uses % as an escape character, so we must use URLEncoder. // PostGreSQL does not support % as an escape character, and does not work with the & character. if (dbms.equalsIgnoreCase(MYSQL)) { try { String utf = "UTF-8"; database = URLEncoder.encode(database, utf); user = URLEncoder.encode(user, utf); pass = URLEncoder.encode(pass, utf); } catch (UnsupportedEncodingException e) { // this should never happen throw new RuntimeException(e); } } String result = ""; if (dbms.equalsIgnoreCase(ORACLE)) result = String.format(format, dbms.toLowerCase(), user, pass, host, database); else result = String.format(format, dbms.toLowerCase(), host, database, user, pass); return result; } /** * This maps a driver name to a Driver instance. * The purpose of this map is to avoid instantiating extra Driver objects unnecessarily. */ private static DriverMap _driverMap = new DriverMap(); @SuppressWarnings("serial") private static class DriverMap extends HashMap<String,Driver> { protected void finalize() { for (Driver driver : _driverMap.values()) { try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { e.printStackTrace(); } } } } /** * This maps a connection string to a Connection object. Used by getStaticReadOnlyConnection(). */ private static Map<String, Connection> _staticReadOnlyConnections = new HashMap<String, Connection>(); /** * This function will test a connection by running a simple test query. * We cannot rely on Connection.isValid(timeout) because it does not work in some drivers. * Running a test query is a reliable way to find out if the connection is valid. * @param conn A SQL Connection. * @throws SQLException Thrown if the test query fails. */ public static void testConnection(Connection conn) throws SQLException { Statement stmt = null; try { stmt = conn.createStatement(); if (SQLUtils.isOracleServer(conn)) stmt.execute("SELECT 0 FROM DUAL"); else stmt.execute("SELECT 0"); } catch (RuntimeException e) // This is important for catching unexpected errors. { /* Example unexpected error when the connection is invalid: java.lang.NullPointerException at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2484) at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2460) at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1298) at weave.utils.SQLUtils.testConnection(SQLUtils.java:173) [...] */ throw new SQLException("Connection is invalid", e); } finally { cleanup(stmt); } } /** * This function tests if a given Connection is valid, and closes the connection if it is not. * @param conn A Connection object which may or may not be valid. * @return A value of true if the given Connection is still connected. */ public static boolean connectionIsValid(Connection conn) { if (conn == null) return false; try { testConnection(conn); return true; } catch (SQLException e) { SQLUtils.cleanup(conn); } return false; } /** * This function returns a read-only connection that can be reused. The connection should not be closed. * @param connectString The connect string used to create the Connection. * @return A static read-only Connection. */ public static Connection getStaticReadOnlyConnection(String connectString) throws RemoteException { synchronized (_staticReadOnlyConnections) { Connection conn = null; if (_staticReadOnlyConnections.containsKey(connectString)) { conn = _staticReadOnlyConnections.get(connectString); if (connectionIsValid(conn)) return conn; // if connection is not valid, remove this entry from the Map _staticReadOnlyConnections.remove(connectString); } // get a new connection, throwing an exception if this fails conn = getConnection(connectString); // try to set readOnly.. if this fails, continue anyway. try { conn.setReadOnly(true); } catch (SQLException e) { e.printStackTrace(); } // remember this static, read-only connection. if (conn != null) _staticReadOnlyConnections.put(connectString, conn); return conn; } } /** * @param connectString The connect string to use. * @return A new SQL connection using the specified driver & connect string */ public static Connection getConnection(String connectString) throws RemoteException { String dbms = getDbmsFromConnectString(connectString); String driver = getDriver(dbms); Connection conn = null; try { // only call newInstance once per driver if (!_driverMap.containsKey(driver)) _driverMap.put(driver, (Driver)Class.forName(driver).newInstance()); conn = DriverManager.getConnection(connectString); } catch (SQLException ex) { System.err.println(String.format("driver: %s\nconnectString: %s", driver, connectString)); throw new RemoteException("Unable to connect to SQL database", ex); } catch (Exception ex) { throw new RemoteException("Failed to load driver: \"" + driver + "\"", ex); } return conn; } /** * @param colName * @return colName with special characters replaced and truncated to 64 characters. */ public static String fixColumnName(String colName, String suffix) { colName = colName .replace("<=", "LTE") .replace(">=", "GTE") .replace("<", "LT") .replace(">", "GT"); StringBuilder sb = new StringBuilder(); boolean space = false; for (int i = 0; i < colName.length(); i++) { char c = colName.charAt(i); if (Character.isJavaIdentifierPart(c)) { if (space) sb.append(' '); sb.append(c); space = false; } else { space = true; } } // append suffix before truncating sb.append(suffix); colName = sb.toString(); // if the length of the column name is longer than the 30-character limit in oracle (MySQL limit is 64 characters) int max = 30; // if name too long, remove spaces if (colName.length() > max) colName = colName.replace(" ", ""); // if still too long, truncate if (colName.length() > max) { int halfLeft = max / 2; int halfRight = max / 2 - 1 + max % 2; // subtract 1 for the "_" unless max is odd colName = colName.substring(0, halfLeft) + "_" + colName.substring(colName.length() - halfRight); } return colName; } /** * @param dbms The name of a DBMS (MySQL, PostGreSQL, ...) * @param symbol The symbol to quote. * @return The symbol surrounded in quotes, usable in queries for the specified DBMS. */ public static String quoteSymbol(String dbms, String symbol) throws IllegalArgumentException { //the quote symbol is required for names of variables that include spaces or special characters String openQuote, closeQuote; if (dbms.equalsIgnoreCase(MYSQL)) { openQuote = closeQuote = "`"; } else if (dbms.equalsIgnoreCase(POSTGRESQL) || dbms.equalsIgnoreCase(ORACLE)) { openQuote = closeQuote = "\""; } else if (dbms.equalsIgnoreCase(SQLSERVER)) { openQuote = "["; closeQuote = "]"; } else throw new IllegalArgumentException("Unsupported DBMS type: "+dbms); if (symbol.contains(openQuote) || symbol.contains(closeQuote)) throw new IllegalArgumentException(String.format("Unable to surround SQL symbol with quote marks (%s%s) because it already contains one: %s", openQuote, closeQuote, symbol)); return openQuote + symbol + closeQuote; } /** * @param conn An SQL connection. * @param symbol The symbol to quote. * @return The symbol surrounded in quotes, usable in queries for the specified connection. */ public static String quoteSymbol(Connection conn, String symbol) throws SQLException, IllegalArgumentException { String dbms = getDbmsFromConnection(conn); return quoteSymbol(dbms, symbol); } /** * @param dbms The name of a DBMS (MySQL, PostGreSQL, ...) * @param symbol The quoted symbol. * @return The symbol without its dbms-specific quotes. */ public static String unquoteSymbol(String dbms, String symbol) { char openQuote, closeQuote; int length = symbol.length(); if (dbms.equalsIgnoreCase(MYSQL)) { openQuote = closeQuote = '`'; } else if (dbms.equalsIgnoreCase(POSTGRESQL) || dbms.equalsIgnoreCase(ORACLE)) { openQuote = closeQuote = '"'; } else if (dbms.equalsIgnoreCase(SQLSERVER)) { openQuote = '['; closeQuote = ']'; } else throw new IllegalArgumentException("Unsupported DBMS type: "+dbms); String result = symbol; if (length > 2 && symbol.charAt(0) == openQuote && symbol.charAt(length - 1) == closeQuote) result = symbol.substring(1, length - 1); if (result.indexOf(openQuote) >= 0 || result.indexOf(closeQuote) >= 0) throw new IllegalArgumentException("Cannot unquote symbol: "+symbol); return result; } /** * @param conn An SQL connection. * @param symbol The quoted symbol. * @return The symbol without its dbms-specific quotes. */ public static String unquoteSymbol(Connection conn, String symbol) throws SQLException, IllegalArgumentException { char quote = conn.getMetaData().getIdentifierQuoteString().charAt(0); int length = symbol.length(); String result = symbol; if (length > 2 && symbol.charAt(0) == quote && symbol.charAt(length - 1) == quote) result = symbol.substring(1, length - 1); if (result.indexOf(quote) >= 0) throw new IllegalArgumentException("Cannot unquote symbol: "+symbol); return symbol; } /** * This will build a case sensitive compare expression out of two sql query expressions. * @param conn An SQL Connection. * @param expr1 The first SQL expression to be used in the comparison. * @param expr2 The second SQL expression to be used in the comparison. * @return A SQL expression comparing the two expressions using case-sensitive string comparison. */ public static String caseSensitiveCompare(Connection conn, String expr1, String expr2) throws SQLException { String operator; if (getDbmsFromConnection(conn).equals(MYSQL)) operator = "= BINARY"; else operator = "="; return String.format( "%s %s %s", stringCast(conn, expr1), operator, stringCast(conn, expr2) ); } /** * This will wrap a query expression in a string cast. * @param conn An SQL Connection. * @param queryExpression An expression to be used in a SQL Query. * @return The query expression wrapped in a string cast. */ protected static String stringCast(Connection conn, String queryExpression) throws SQLException { String dbms = getDbmsFromConnection(conn); if (dbms.equals(MYSQL)) return String.format("cast(%s as char)", queryExpression); if (dbms.equals(POSTGRESQL)) return String.format("cast(%s as varchar)", queryExpression); // dbms type not supported by this function yet return queryExpression; } /** * This function returns the name of a binary data type that can be used in SQL queries. * @param dbms The name of a DBMS (MySQL, PostGreSQL, ...) * @return The name of the binary SQL type to use for the given DBMS. */ public static String binarySQLType(String dbms) { if (POSTGRESQL.equalsIgnoreCase(dbms)) return "bytea"; else if (SQLSERVER.equalsIgnoreCase(dbms)) return "image"; //if (dbms.equalsIgnoreCase(MYSQL)) return "BLOB"; } /** * Returns quoted schema & table to use in SQL queries for the given DBMS. * @param dbms The name of a DBMS (MySQL, PostGreSQL, ...) * @param schema The schema the table resides in. * @param table The table. * @return The schema & table name surrounded in quotes, usable in queries for the specified DBMS. */ public static String quoteSchemaTable(String dbms, String schema, String table) { if (schema.length() == 0) return quoteSymbol(dbms, table); if (dbms.equalsIgnoreCase(ORACLE)) schema = schema.toUpperCase(); return quoteSymbol(dbms, schema) + "." + quoteSymbol(dbms, table); } /** * Returns quoted schema & table to use in SQL queries for the given Connection. * @param conn An SQL connection. * @param schema The schema the table resides in. * @param table The table. * @return The schema & table name surrounded in quotes, usable in queries for the specified connection. */ public static String quoteSchemaTable(Connection conn, String schema, String table) throws SQLException { if (schema.length() == 0) return quoteSymbol(conn, table); if (SQLUtils.isOracleServer(conn)) return quoteSymbol(conn, schema).toUpperCase() + "." + quoteSymbol(conn, table); else return quoteSymbol(conn, schema) + "." + quoteSymbol(conn, table); } public static boolean sqlTypeIsNumeric(int sqlType) { switch (sqlType) { case Types.TINYINT: case Types.SMALLINT: case Types.BIGINT: case Types.DECIMAL: case Types.INTEGER: case Types.FLOAT: case Types.DOUBLE: case Types.REAL: case Types.NUMERIC: /* case Types.ROWID: // produces compiler error in some environments */ return true; default: return false; } } public static boolean sqlTypeIsGeometry(int sqlType) { // using 1111 as the literal value returned by postgis as a PGGeometry type. return sqlType == 1111; } /** * @param connection An SQL Connection * @param query An SQL Query with '?' place holders for parameters * @param params Parameters for the SQL query for all '?' place holders, or null if there are no parameters. * @return A SQLResult object containing the result of the query * @throws SQLException */ public static <TYPE> SQLResult getResultFromQuery(Connection connection, String query, TYPE[] params, boolean convertToStrings) throws SQLException { Statement stmt = null; ResultSet rs = null; SQLResult result = null; try { if (params == null || params.length == 0) { stmt = connection.createStatement(); rs = stmt.executeQuery(query); } else { stmt = prepareStatement(connection, query, params); rs = ((PreparedStatement)stmt).executeQuery(); } // make a copy of the query result result = new SQLResult(rs, convertToStrings); } catch (SQLException e) { //e.printStackTrace(); throw new SQLExceptionWithQuery(query, e); } finally { // close everything in reverse order SQLUtils.cleanup(rs); SQLUtils.cleanup(stmt); } // return the copy of the query result return result; } /** * @param rs The ResultSet returned from a SQL query. * @param valueType The Class used for casting values in the ResultSet. * @return A list of field-value pairs containing the record data. * @throws SQLException If the query fails. */ @SuppressWarnings("unchecked") public static <VALUE_TYPE> List<Map<String,VALUE_TYPE>> getRecordsFromResultSet(ResultSet rs, Class<VALUE_TYPE> valueType) throws SQLException { // list the column names in the result String[] columnNames = getColumnNamesFromResultSet(rs); // create a Map from each row List<Map<String,VALUE_TYPE>> records = new Vector<Map<String,VALUE_TYPE>>(); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) { Map<String,VALUE_TYPE> record = new HashMap<String,VALUE_TYPE>(columnNames.length); for (int i = 0; i < columnNames.length; i++) { String columnName = columnNames[i]; Object columnValue = (valueType == String.class) ? rs.getString(columnName) : rs.getObject(columnName); record.put(columnName, (VALUE_TYPE)columnValue); } records.add(record); } return records; } public static String[] getColumnNamesFromResultSet(ResultSet rs) throws SQLException { String[] columnNames = new String[rs.getMetaData().getColumnCount()]; for (int i = 0; i < columnNames.length; i++) columnNames[i] = rs.getMetaData().getColumnName(i + 1); return columnNames; } /** * @param conn An existing SQL Connection * @param selectColumns The list of column names, or null for all columns * @param fromSchema The schema containing the table to perform the SELECT statement on. * @param fromTable The table to perform the SELECT statement on. * @param where Used to construct the WHERE clause * @param orderBy The field to order by, or null for no specific order. * @param valueType Either String.class or Object.class to denote the VALUE_TYPE class. * @return The resulting rows returned by the query. * @throws SQLException If the query fails. */ public static <VALUE_TYPE> List<Map<String,VALUE_TYPE>> getRecordsFromQuery( Connection conn, List<String> selectColumns, String fromSchema, String fromTable, WhereClause<VALUE_TYPE> where, String orderBy, Class<VALUE_TYPE> valueType ) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; String query = null; try { // create list of columns to use in SELECT statement String columnQuery = ""; for (int i = 0; selectColumns != null && i < selectColumns.size(); i++) { if (i > 0) columnQuery += ","; columnQuery += quoteSymbol(conn, selectColumns.get(i)); } if (columnQuery.length() == 0) columnQuery = "*"; // select all columns String orderByQuery = ""; if (orderBy != null) orderByQuery = String.format("ORDER BY %s", quoteSymbol(conn, orderBy)); // build complete query query = String.format( "SELECT %s FROM %s %s %s", columnQuery, quoteSchemaTable(conn, fromSchema, fromTable), where.clause, orderByQuery ); pstmt = prepareStatement(conn, query, where.params); rs = pstmt.executeQuery(); return getRecordsFromResultSet(rs, valueType); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { // close everything in reverse order cleanup(rs); cleanup(pstmt); } } /** * @param conn An existing SQL Connection * @param selectColumns The list of columns in the SELECT statement, or null for all columns. * @param fromSchema The schema containing the table to perform the SELECT statement on. * @param fromTable The table to perform the SELECT statement on. * @param whereParams A map of column names to String values used to construct a WHERE clause. * @return The resulting rows returned by the query. * @throws SQLException If the query fails. */ public static <V> SQLResult getResultFromQuery( Connection conn, List<String> selectColumns, String fromSchema, String fromTable, Map<String,V> whereParams, Set<String> caseSensitiveFields ) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; SQLResult result = null; String query = null; try { // create list of columns to use in SELECT statement String columnQuery = ""; for (int i = 0; selectColumns != null && i < selectColumns.size(); i++) { if (i > 0) columnQuery += ","; columnQuery += quoteSymbol(conn, selectColumns.get(i)); } if (columnQuery.length() == 0) columnQuery = "*"; // select all columns // build WHERE clause WhereClause<V> where = new WhereClause<V>(conn, whereParams, caseSensitiveFields, true); // build complete query query = String.format( "SELECT %s FROM %s %s", columnQuery, quoteSchemaTable(conn, fromSchema, fromTable), where.clause ); pstmt = prepareStatement(conn, query, where.params); rs = pstmt.executeQuery(); // make a copy of the query result result = new SQLResult(rs); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { // close everything in reverse order SQLUtils.cleanup(rs); SQLUtils.cleanup(pstmt); } // return the copy of the query result return result; } /** * @param connection An SQL Connection * @param query An SQL query * @return A SQLResult object containing the result of the query * @throws SQLException */ public static int getRowCountFromUpdateQuery(Connection connection, String query) throws SQLException { Statement stmt = null; int result = 0; try { stmt = connection.createStatement(); result = stmt.executeUpdate(query); } catch (SQLException e) { throw e; } finally { // close everything in reverse order SQLUtils.cleanup(stmt); } // return the copy of the query result return result; } public static int getSingleIntFromQuery(Statement stmt, String query, int defaultValue) throws SQLException { ResultSet resultSet = null; try { resultSet = stmt.executeQuery(query); if (resultSet.next()) return resultSet.getInt(1); return defaultValue; } finally { SQLUtils.cleanup(resultSet); } } /** * @param conn An existing SQL Connection * @return A List of schema names * @throws SQLException If the query fails. */ public static List<String> getSchemas(Connection conn) throws SQLException { List<String> schemas = new Vector<String>(); ResultSet rs = null; try { DatabaseMetaData md = conn.getMetaData(); // MySQL "doesn't support schemas," so use catalogs. if (md.getDatabaseProductName().equalsIgnoreCase(MYSQL)) { rs = md.getCatalogs(); // use column index instead of name because sometimes the names are lower case, sometimes upper. while (rs.next()) schemas.add(rs.getString(1)); // table_catalog } else { rs = md.getSchemas(); // use column index instead of name because sometimes the names are lower case, sometimes upper. while (rs.next()) schemas.add(rs.getString(1)); // table_schem } Collections.sort(schemas, String.CASE_INSENSITIVE_ORDER); } finally { SQLUtils.cleanup(rs); } return schemas; } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @return A List of table names in the given schema * @throws SQLException If the query fails. */ public static List<String> getTables(Connection conn, String schemaName) throws SQLException { if (schemaName != null) { if (SQLUtils.isOracleServer(conn)) schemaName = schemaName.toUpperCase(); if (schemaName.length() == 0) schemaName = null; } List<String> tables = new Vector<String>(); ResultSet rs = null; try { DatabaseMetaData md = conn.getMetaData(); String[] types = new String[]{"TABLE", "VIEW"}; // MySQL uses "catalogs" instead of "schemas" if (md.getDatabaseProductName().equalsIgnoreCase(MYSQL)) rs = md.getTables(schemaName, null, null, types); else rs = md.getTables(null, schemaName, null, types); // use column index instead of name because sometimes the names are lower case, sometimes upper. // column indices: 1=table_cat,2=table_schem,3=table_name,4=table_type,5=remarks while (rs.next()) tables.add(rs.getString(3)); // table_name Collections.sort(tables, String.CASE_INSENSITIVE_ORDER); } finally { // close everything in reverse order cleanup(rs); } return tables; } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName A table name existing in the given schema * @return A List of column names in the given table * @throws SQLException If the query fails. */ public static List<String> getColumns(Connection conn, String schemaName, String tableName) throws SQLException { List<String> columns = new Vector<String>(); ResultSet rs = null; try { DatabaseMetaData md = conn.getMetaData(); tableName = escapeSearchString(conn, tableName); // MySQL uses "catalogs" instead of "schemas" if (md.getDatabaseProductName().equalsIgnoreCase(MYSQL)) rs = md.getColumns(schemaName, null, tableName, null); else if (isOracleServer(conn)) rs = md.getColumns(null, schemaName.toUpperCase(), tableName, null); else rs = md.getColumns(null, schemaName, tableName, null); // use column index instead of name because sometimes the names are lower case, sometimes upper. while (rs.next()) columns.add(rs.getString(4)); // column_name } finally { // close everything in reverse order SQLUtils.cleanup(rs); } return columns; } /** * @param conn An existing SQL Connection * @param schema The value to be used as the Schema name * @throws SQLException If the query fails. */ public static void createSchema(Connection conn, String schema) throws SQLException { if (SQLUtils.schemaExists(conn, schema)) return; String query = "CREATE SCHEMA " + schema; Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(stmt); } } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName The value to be used as the table name * @param columnNames The values to be used as the column names * @param columnTypes The SQL types to use when creating the table * @param primaryKeyColumns The list of columns to be used for primary keys * @throws SQLException If the query fails. */ public static void createTable( Connection conn, String schemaName, String tableName, List<String> columnNames, List<String> columnTypes, List<String> primaryKeyColumns ) throws SQLException { if (columnNames.size() != columnTypes.size()) throw new IllegalArgumentException(String.format("columnNames length (%s) does not match columnTypes length (%s)", columnNames.size(), columnTypes.size())); //if table exists return if( tableExists(conn, schemaName, tableName) ) return; StringBuilder columnClause = new StringBuilder(); int primaryKeyColumn = -1; for (int i = 0; i < columnNames.size(); i++) { if( i > 0 ) columnClause.append(','); String type = columnTypes.get(i); if (SQLUTILS_SERIAL_TRIGGER_TYPE.equals(type)) { type = getBigIntTypeString(conn) + " NOT NULL"; primaryKeyColumn = i; } columnClause.append(String.format("%s %s", quoteSymbol(conn, columnNames.get(i)), type)); } if (primaryKeyColumns == null && primaryKeyColumn >= 0) primaryKeyColumns = Arrays.asList(columnNames.get(primaryKeyColumn)); if (primaryKeyColumns != null && primaryKeyColumns.size() > 0) { String pkName = truncate(String.format("pk_%s", tableName), 30); String[] quotedKeyColumns = new String[primaryKeyColumns.size()]; int i = 0; for (String keyCol : primaryKeyColumns) quotedKeyColumns[i++] = quoteSymbol(conn, keyCol); columnClause.append( String.format( ", CONSTRAINT %s PRIMARY KEY (%s)", quoteSymbol(conn, pkName), Strings.join(",", quotedKeyColumns) ) ); } String quotedSchemaTable = quoteSchemaTable(conn, schemaName, tableName); String query = String.format("CREATE TABLE %s (%s)", quotedSchemaTable, columnClause); Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(query); if (primaryKeyColumn >= 0) { String dbms = getDbmsFromConnection(conn); String quotedSequenceName = getQuotedSequenceName(dbms, schemaName, tableName); String unquotedSequenceName = getUnquotedSequenceName(schemaName, tableName); if (dbms.equals(ORACLE)) { if (getSequences(conn, schemaName).indexOf(unquotedSequenceName) >= 0) stmt.executeUpdate(query = String.format("drop sequence %s", quotedSequenceName)); stmt.executeUpdate(query = String.format("create sequence %s start with 1 increment by 1", quotedSequenceName)); String quotedTriggerName = quoteSchemaTable(ORACLE, schemaName, "trigger_" + unquotedSequenceName); String quotedIdColumn = quoteSymbol(ORACLE, columnNames.get(primaryKeyColumn)); query = String.format("create or replace trigger %s\n", quotedTriggerName) + String.format("before insert on %s\n", quotedSchemaTable) + "for each row\n" + "declare\n" + " max_id number;\n" + " cur_seq number;\n" + "begin\n" + String.format(" if :new.%s is null then\n", quotedIdColumn) + String.format(" select %s.nextval into :new.%s from dual;\n", quotedSequenceName, quotedIdColumn) + " else\n" + String.format(" select greatest(nvl(max(%s),0), :new.%s) into max_id from %s;\n", quotedIdColumn, quotedIdColumn, quotedSchemaTable) + String.format(" select %s.nextval into cur_seq from dual;\n", quotedSequenceName) + " while cur_seq < max_id\n" + " loop\n" + String.format(" select %s.nextval into cur_seq from dual;\n", quotedSequenceName) + " end loop;\n" + " end if;\n" + "end;\n"; } else if (dbms.equals(POSTGRESQL)) { throw new InvalidParameterException("PostGreSQL support not implemented for column type " + SQLUTILS_SERIAL_TRIGGER_TYPE); /* String quotedTriggerName = quoteSchemaTable(POSTGRESQL, schemaName, "trigger_" + unquotedSequenceName); String quotedIdColumn = quoteSymbol(POSTGRESQL, columnNames.get(primaryKeyColumn)); String quotedFuncName = generateQuotedSymbolName("function", conn, schemaName, tableName); query = String.format("create or replace function %s() returns trigger language plpgsql as\n", quotedFuncName) + "$$ begin\n" + String.format(" if ( currval('test_id_seq')<NEW.id ) then\n" + " raise exception 'currval(test_id_seq)<id';\n" + " end if;\n" + " return NEW;\n" + "end; $$;\n" + "create trigger test_id_seq_check before insert or update of id on test\n" + " for each row execute procedure test_id_check();"; */ } stmt.executeUpdate(query); } } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(stmt); } } public static void addForeignKey( Connection conn, String schemaName, String tableName, String keyName, String targetTable, String targetKey ) throws SQLException { // TODO: Check for cross-DB portability Statement stmt = null; String query = String.format("ALTER TABLE %s ADD FOREIGN KEY (%s) REFERENCES %s(%s)", quoteSchemaTable(conn, schemaName, tableName), quoteSymbol(conn, keyName), quoteSchemaTable(conn, schemaName, targetTable), quoteSymbol(conn, targetKey)); try { stmt = conn.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(stmt); } } public static <TYPE> PreparedStatement prepareStatement(Connection conn, String query, List<TYPE> params) throws SQLException { PreparedStatement cstmt = conn.prepareStatement(query); constrainQueryParams(conn, params); setPreparedStatementParams(cstmt, params); return cstmt; } public static <TYPE> PreparedStatement prepareStatement(Connection conn, String query, TYPE[] params) throws SQLException { PreparedStatement cstmt = conn.prepareStatement(query); constrainQueryParams(conn, params); setPreparedStatementParams(cstmt, params); return cstmt; } protected static <T> void constrainQueryParams(Connection conn, List<T> params) { if (isOracleServer(conn)) for (int i = 0; i < params.size(); i++) params.set(i, constrainOracleQueryParam(params.get(i))); } protected static <T> void constrainQueryParams(Connection conn, T[] params) { if (isOracleServer(conn)) for (int i = 0; i < params.length; i++) params[i] = constrainOracleQueryParam(params[i]); } @SuppressWarnings("unchecked") protected static <T> T constrainOracleQueryParam(T param) { // constrain oracle double values to float range if (param instanceof Double) param = (T)(Float)((Double) param).floatValue(); return param; } protected static <TYPE> void setPreparedStatementParams(PreparedStatement cstmt, List<TYPE> params) throws SQLException { int i = 1; for (TYPE param : params) cstmt.setObject(i++, param); } protected static <TYPE> void setPreparedStatementParams(PreparedStatement cstmt, TYPE[] params) throws SQLException { int i = 1; for (TYPE param : params) cstmt.setObject(i++, param); } public static int updateRows(Connection conn, String fromSchema, String fromTable, Map<String,Object> whereParams, Map<String,Object> dataUpdate, Set<String> caseSensitiveFields) throws SQLException { PreparedStatement stmt = null; try { // build the update block String updateBlock; List<String> updateBlockList = new LinkedList<String>(); List<Object> queryParams = new LinkedList<Object>(); for (Entry<String,Object> data : dataUpdate.entrySet()) { updateBlockList.add(String.format("%s=?", data.getKey())); queryParams.add(data.getValue()); } updateBlock = Strings.join(",", updateBlockList); // build where clause WhereClause<Object> where = new WhereClause<Object>(conn, whereParams, caseSensitiveFields, true); queryParams.addAll(where.params); // build and execute query String query = String.format("UPDATE %s SET %s %s", fromTable, updateBlock, where.clause); stmt = prepareStatement(conn, query, queryParams); return stmt.executeUpdate(); } finally { cleanup(stmt); } } /** * Takes a list of maps, each of which corresponds to one rowmatch criteria; in the case it is being used for, * this will only be two entries long, but this covers the general case. * @param conn * @param schemaName * @param table * @param column The name of the column to return. * @param queryParams A list of where parameters specified as Map entries. * @return The values from the specified column. * @throws SQLException */ public static List<Integer> crossRowSelect(Connection conn, String schemaName, String table, String column, List<Map<String,String>> queryParams, Set<String> caseSensitiveFields) throws SQLException { String query = null; List<Integer> results = new LinkedList<Integer>(); WhereClause<String> where = new WhereClause<String>(conn, queryParams, caseSensitiveFields, false); // Construct the query with placeholders. String qColumn = quoteSymbol(conn, column); String qTable = quoteSchemaTable(conn, schemaName, table); if (queryParams.size() == 0) { query = String.format("SELECT %s from %s group by %s", qColumn, qTable, qColumn); } else { query = String.format( "SELECT %s FROM (SELECT %s, count(*) c FROM %s %s group by %s) result WHERE c = %s", qColumn, qColumn, qTable, where.clause, qColumn, queryParams.size() ); } PreparedStatement stmt = null; ResultSet rs = null; try { stmt = prepareStatement(conn, query, where.params); rs = stmt.executeQuery(); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) { results.add(rs.getInt(column)); } return results; } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { cleanup(rs); cleanup(stmt); } } public static Integer insertRowReturnID(Connection conn, String schemaName, String tableName, Map<String,Object> data, String idField) throws SQLException { String dbms = getDbmsFromConnection(conn); boolean isOracle = dbms.equals(ORACLE); boolean isSQLServer = dbms.equals(SQLSERVER); boolean isMySQL = dbms.equals(MYSQL); boolean isPostGreSQL = dbms.equals(POSTGRESQL); String query = null; List<String> columns = new LinkedList<String>(); List<Object> values = new LinkedList<Object>(); for (Entry<String,Object> entry : data.entrySet()) { columns.add(quoteSymbol(conn, entry.getKey())); values.add(entry.getValue()); } String column_string = Strings.join(",", columns); String qmark_string = Strings.mult(",", "?", values.size()); String quotedIdField = quoteSymbol(conn, idField); String quotedTable = quoteSchemaTable(conn, schemaName, tableName); if (isPostGreSQL) { column_string = String.format("%s,%s", quotedIdField, column_string); qmark_string = String.format("GREATEST(1, (SELECT MAX(%s)+1 FROM %s)),", quotedIdField, quotedTable) + qmark_string; } query = String.format("INSERT INTO %s (%s)", quotedTable, column_string); if (isSQLServer) query += String.format(" OUTPUT INSERTED.%s", quotedIdField); query += String.format(" VALUES (%s)", qmark_string); if (isPostGreSQL) query += String.format(" RETURNING %s", quotedIdField); PreparedStatement stmt = null; ResultSet rs = null; try { stmt = prepareStatement(conn, query, values); synchronized (conn) { if (isSQLServer || isPostGreSQL) { rs = stmt.executeQuery(); } else { stmt.executeUpdate(); cleanup(stmt); if (isOracle) { String quotedSequenceName = getQuotedSequenceName(dbms, schemaName, tableName); query = String.format("select %s.currval from dual", quotedSequenceName); } else if (isMySQL) { query = "select last_insert_id()"; } else { throw new SQLException("insertRowReturnID: dbms not supported: " + dbms); } stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); } } rs.next(); return rs.getInt(1); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { cleanup(rs); cleanup(stmt); } } /** * This function is for use with an Oracle connection * @param conn An existing Oracle SQL Connection * @param schemaName A schema name accessible through the given connection * @return A List of sequence names in the given schema * @throws SQLException If the query fails. */ protected static List<String> getSequences(Connection conn, String schemaName) throws SQLException { List<String> sequences = new Vector<String>(); ResultSet rs = null; try { DatabaseMetaData md = conn.getMetaData(); String[] types = new String[]{"SEQUENCE"}; rs = md.getTables(null, schemaName.toUpperCase(), null, types); // use column index instead of name because sometimes the names are lower case, sometimes upper. // column indices: 1=sequence_cat,2=sequence_schem,3=sequence_name,4=sequence_type,5=remarks while (rs.next()) sequences.add(rs.getString(3)); // sequence_name Collections.sort(sequences, String.CASE_INSENSITIVE_ORDER); } finally { // close everything in reverse order cleanup(rs); } return sequences; } /** * This function checks if a connection is for an Oracle server. * @param conn A SQL Connection. * @return A value of true if the Connection is for an Oracle server. * @throws SQLException */ public static boolean isOracleServer(Connection conn) { return getDbmsFromConnection(conn).equals(ORACLE); } /** * This function checks if a connection is for a Microsoft SQL Server. * @param conn A SQL Connection. * @return A value of true if the Connection is for a Microsoft SQL Server. */ public static boolean isSQLServer(Connection conn) { return getDbmsFromConnection(conn).equals(SQLSERVER); } private static String truncate(String str, int maxLength) { if (str.length() > maxLength) return str.substring(0, maxLength); return str; } private static String generateSymbolName(String prefix, Object ...items) { int hash = Arrays.deepToString(items).hashCode(); return String.format("%s_%s", prefix, hash); } private static String generateQuotedSymbolName(String prefix, Connection conn, String schema, String table, String ...columns) throws SQLException { String indexName = generateSymbolName(prefix, schema, table, columns); if (isOracleServer(conn)) return quoteSchemaTable(conn, schema, indexName); else return quoteSymbol(conn, indexName); } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName The name of an existing table * @param columnNames The names of the columns to use * @throws SQLException If the query fails. */ public static void createIndex(Connection conn, String schemaName, String tableName, String[] columnNames) throws SQLException { createIndex(conn, schemaName, tableName, columnNames, null); } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName The name of an existing table * @param columnNames The names of the columns to use. * @param columnLengths The lengths to use as indices, may be null. * @throws SQLException If the query fails. */ public static void createIndex(Connection conn, String schemaName, String tableName, String[] columnNames, Integer[] columnLengths) throws SQLException { boolean isMySQL = getDbmsFromConnection(conn).equals(MYSQL); String fields = ""; for (int i = 0; i < columnNames.length; i++) { if (i > 0) fields += ", "; String symbol = quoteSymbol(conn, columnNames[i]); if (isMySQL && columnLengths != null && columnLengths[i] > 0) fields += String.format("%s(%d)", symbol, columnLengths[i]); else fields += symbol; } String query = String.format( "CREATE INDEX %s ON %s (%s)", generateQuotedSymbolName("index", conn, schemaName, tableName, columnNames), SQLUtils.quoteSchemaTable(conn, schemaName, tableName), fields ); Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(stmt); } } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName The name of an existing table * @param columnName The name of the column to create * @param columnType An SQL type to use when creating the column * @throws SQLException If the query fails. */ public static void addColumn( Connection conn, String schemaName, String tableName, String columnName, String columnType) throws SQLException { String format = "ALTER TABLE %s ADD %s %s"; // Note: PostGreSQL does not accept parentheses around the new column definition. String query = String.format(format, quoteSchemaTable(conn, schemaName, tableName), quoteSymbol(conn, columnName), columnType); Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(query); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(stmt); } } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName A table name existing in the given schema * @param columnArg The name of the column to grab * @return A List of string values from the column * @throws SQLException If the query fails. */ public static List<String> getColumn(Connection conn, String schemaName, String tableName, String columnArg) throws SQLException { List<String> values = new Vector<String>(); //Return value Statement stmt = null; ResultSet rs = null; String query = ""; try { query = "SELECT " + quoteSymbol(conn, columnArg) + " FROM " + quoteSchemaTable(conn, schemaName, tableName); stmt = conn.createStatement(); rs = stmt.executeQuery(query); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) values.add(rs.getString(1)); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(rs); SQLUtils.cleanup(stmt); } return values; } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName A table name existing in the given schema * @param columnArg The name of the integer column to grab * @return A List of integer values from the column * @throws SQLException If the query fails. */ public static List<Integer> getIntColumn(Connection conn, String schemaName, String tableName, String columnArg) throws SQLException { List<Integer> values = new Vector<Integer>(); //Return value Statement stmt = null; ResultSet rs = null; String query = ""; try { query = "SELECT " + quoteSymbol(conn, columnArg) + " FROM " + quoteSchemaTable(conn, schemaName, tableName); stmt = conn.createStatement(); rs = stmt.executeQuery(query); rs.setFetchSize(SQLResult.FETCH_SIZE); while (rs.next()) values.add(rs.getInt(1)); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(rs); SQLUtils.cleanup(stmt); } return values; } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName A table name existing in the given schema * @param record The record to be inserted into the table * @return The number of rows inserted. * @throws SQLException If the query fails. */ public static <V> int insertRow( Connection conn, String schemaName, String tableName, Map<String,V> record) throws SQLException { List<Map<String,V>> list = new Vector<Map<String,V>>(1); list.add(record); return insertRows(conn, schemaName, tableName, list); } /** * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName A table name existing in the given schema * @param records The records to be inserted into the table * @return The number of rows inserted. * @throws SQLException If the query fails. */ public static <V> int insertRows( Connection conn, String schemaName, String tableName, List<Map<String,V>> records) throws SQLException { PreparedStatement pstmt = null; String query = "insertRows()"; try { // get a list of all the field names in all the records Set<String> fieldSet = new HashSet<String>(); for (Map<String,V> record : records) fieldSet.addAll(record.keySet()); List<String> fieldNames = new Vector<String>(fieldSet); // stop if there aren't any records or field names if (records.size() == 0 || fieldNames.size() == 0) return 0; // get full list of ordered query params Object[] queryParams = new Object[fieldNames.size() * records.size()]; int i = 0; for (Map<String, V> record : records) for (String fieldName : fieldNames) queryParams[i++] = record.get(fieldName); // quote field names for (i = 0; i < fieldNames.size(); i++) fieldNames.set(i, quoteSymbol(conn, fieldNames.get(i))); String quotedSchemaTable = quoteSchemaTable(conn, schemaName, tableName); String fieldNamesStr = Strings.join(",", fieldNames); // construct query String recordClause = String.format("(%s)", Strings.mult(",", "?", fieldNames.size())); String valuesClause = Strings.mult(",", recordClause, records.size()); query = String.format( "INSERT INTO %s (%s) VALUES %s", quotedSchemaTable, fieldNamesStr, valuesClause ); // prepare call and set string parameters pstmt = prepareStatement(conn, query.toString(), queryParams); int result = pstmt.executeUpdate(); return result; } catch (SQLException e) { System.err.println(records); throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(pstmt); } } /** * @param conn An existing SQL Connection * @param schema The name of a schema to check for. * @return true if the schema exists * @throws SQLException If the getSchemas query fails. */ public static boolean schemaExists(Connection conn, String schema) throws SQLException { List<String> schemas = getSchemas(conn); for (String existingSchema : schemas) if (existingSchema.equalsIgnoreCase(schema)) return true; return false; } public static void dropTableIfExists(Connection conn, String schema, String table) throws SQLException { String dbms = getDbmsFromConnection(conn); String quotedTable = SQLUtils.quoteSchemaTable(conn, schema, table); String query = ""; if (dbms.equals(SQLSERVER)) { query = "IF OBJECT_ID('" + quotedTable + "','U') IS NOT NULL DROP TABLE " + quotedTable; } else if (dbms.equals(ORACLE)) { // do nothing if table doesn't exist if (!SQLUtils.tableExists(conn, schema, table)) return; query = "DROP TABLE " + quotedTable; } else { query = "DROP TABLE IF EXISTS " + quotedTable; } Statement stmt = conn.createStatement(); stmt.executeUpdate(query); stmt.close(); cleanup(stmt); } /** * This function will delete from a table the rows that have a specified set of column values. * @param conn An existing SQL Connection * @param schemaName A schema name accessible through the given connection * @param tableName A table name existing in the given schema * @param where The conditions to be used in the WHERE clause of the query * @return The number of rows that were deleted. * @throws SQLException If the query fails. */ public static <V> int deleteRows(Connection conn, String schemaName, String tableName, WhereClause<V> where) throws SQLException { // VERY IMPORTANT - do not delete if there are no records specified, because that would delete everything. if (where.params.size() == 0) return 0; PreparedStatement pstmt = null; String query = null; try { query = String.format("DELETE FROM %s %s", SQLUtils.quoteSchemaTable(conn, schemaName, tableName), where.clause); pstmt = prepareStatement(conn, query, where.params); return pstmt.executeUpdate(); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(pstmt); } } /** * This will escape special characters in a SQL search string. * @param conn A SQL Connection. * @param searchString A SQL search string containing special characters to be escaped. * @return The searchString with special characters escaped. * @throws SQLException */ public static String escapeSearchString(Connection conn, String searchString) throws SQLException { String escape = conn.getMetaData().getSearchStringEscape(); StringBuilder sb = new StringBuilder(); int n = searchString.length(); for (int i = 0; i < n; i++) { char c = searchString.charAt(i); if (c == '.' || c == '%' || c == '_' || c == '"' || c == '\'' || c == '`') sb.append(escape); sb.append(c); } return sb.toString(); } /** * @param conn An existing SQL Connection * @param schema The name of a schema to check in. * @param table The name of a table to check for. * @return true if the table exists in the specified schema. * @throws SQLException If either getSchemas() or getTables() fails. */ public static boolean tableExists(Connection conn, String schema, String table) throws SQLException { List<String> tables = getTables(conn, schema); for (String existingTable : tables) if (existingTable.equalsIgnoreCase(table)) return true; return false; } public static void cleanup(ResultSet obj) { if (obj != null) try { obj.close(); } catch (Exception e) { } } public static void cleanup(Statement obj) { if (obj != null) try { obj.close(); } catch (Exception e) { } } public static void cleanup(Connection obj) { if (obj != null) try { obj.close(); } catch (Exception e) { } } public static String getVarcharTypeString(Connection conn, int length) { if (isOracleServer(conn)) return String.format("VARCHAR2(%s CHAR)", length); return String.format("VARCHAR(%s)", length); } public static String getTinyIntTypeString(Connection conn) throws SQLException { String dbms = getDbmsFromConnection(conn); if (dbms.equals(ORACLE)) return "NUMBER(1,0)"; if (dbms.equals(POSTGRESQL)) return "SMALLINT"; // mysql, sqlserver return "TINYINT"; } public static String getIntTypeString(Connection conn) { if (isOracleServer(conn)) return "NUMBER(10,0)"; return "INT"; } public static String getDoubleTypeString(Connection conn) { if (isSQLServer(conn)) return "FLOAT"; // this is an 8 floating point type with 53 bits for the mantissa, the same as an 8 byte double. // but SQL Server's DOUBLE PRECISION type isn't standard return "DOUBLE PRECISION"; } public static String getBigIntTypeString(Connection conn) { if (isOracleServer(conn)) return "NUMBER(20,0)"; return "BIGINT"; } public static String getDateTimeTypeString(Connection conn) { if (isOracleServer(conn)) return "DATE"; return "DATETIME"; } public static String getSerialPrimaryKeyTypeString(Connection conn) throws SQLException { String dbms = getDbmsFromConnection(conn); if (dbms.equals(SQLSERVER)) return "BIGINT PRIMARY KEY IDENTITY"; if (dbms.equals(ORACLE)) return SQLUTILS_SERIAL_TRIGGER_TYPE; // for mysql or postgresql, return the following. return "SERIAL PRIMARY KEY"; } private static String getUnquotedSequenceName(String schema, String table) { return generateSymbolName("sequence", schema, table); } private static String getQuotedSequenceName(String dbms, String schema, String table) { return quoteSchemaTable(dbms, schema, getUnquotedSequenceName(schema, table)); } protected static String getCSVNullValue(Connection conn) { try { String dbms = getDbmsFromConnection(conn); if (dbms.equals(MYSQL)) return "\\N"; else if (dbms.equals(POSTGRESQL) || dbms.equals(SQLSERVER) || dbms.equals(ORACLE)) return ""; // empty string (no quotes) else throw new InvalidParameterException("Unsupported DBMS type: " + dbms); } catch (Exception e) { // this should never happen throw new RuntimeException(e); } } /** * This function should only be called on a SQL Server connection. * @param conn * @param schema * @param table * @param on * @throws SQLException */ public static void setSQLServerIdentityInsert(Connection conn, String schema, String table, boolean on) throws SQLException { if (!isSQLServer(conn)) return; String quotedTable = SQLUtils.quoteSchemaTable(conn, schema, table); String query = String.format("SET IDENTITY_INSERT %s %s", quotedTable, on ? "ON" : "OFF"); Statement stmt = null; try { stmt = conn.createStatement(); stmt.execute(query); } catch (SQLException e) { throw new SQLExceptionWithQuery(query, e); } finally { SQLUtils.cleanup(stmt); } } public static class WhereClause<V> { public String clause; public List<V> params; public static class ColumnFilter { public String field; /** * Contains a list of String values or a list of numeric ranges (Object[] containing two values: min,max) */ public Object[] filters; } /** * @param conn * @param filters Either a list of String values or a list of numeric ranges (Object[] containing two values: min,max) */ public static WhereClause<Object> fromFilters(Connection conn, ColumnFilter[] filters) throws SQLException { WhereClause<Object> result = new WhereClause<Object>("", new Vector<Object>()); StringBuilder sb = new StringBuilder(); for (ColumnFilter filter : filters) { if (filter.filters == null || filter.filters.length == 0) continue; if (sb.length() == 0) sb.append(" WHERE "); else sb.append(" AND "); sb.append("("); String quotedField = quoteSymbol(conn, filter.field); String stringCompare = null; for (int i = 0; i < filter.filters.length; i++) { Object filterValue = filter.filters[i]; if (i > 0) sb.append(" OR "); if (filterValue.getClass() == Object[].class) { // numeric range sb.append(String.format("(? <= %s AND %s <= ?)", quotedField, quotedField)); Object[] range = (Object[])filterValue; result.params.add(range[0]); result.params.add(range[1]); } else { // string value if (stringCompare == null) stringCompare = caseSensitiveCompare(conn, quotedField, "?"); sb.append(stringCompare); result.params.add(filterValue); } } sb.append(")"); } result.clause = sb.toString(); return result; } public WhereClause(String whereClause, List<V> params) { this.clause = whereClause; this.params = params; } /** * @param conn * @param conditions * @param caseSensitiveFields * @param conjunctive Set to <code>true</code> for "AND" logic or <code>false</code> for "OR" logic. * @throws SQLException */ public WhereClause(Connection conn, Map<String,V> conditions, Set<String> caseSensitiveFields, boolean conjunctive) throws SQLException { List<Map<String,V>> list = new Vector<Map<String,V>>(1); list.add(conditions); // we have to negate our conjunctive parameter because we have just nested our conditions init(conn, list, caseSensitiveFields, !conjunctive); } public WhereClause(Connection conn, List<Map<String,V>> conditions, Set<String> caseSensitiveFields, boolean conjunctive) throws SQLException { init(conn, conditions, caseSensitiveFields, conjunctive); } private void init(Connection conn, List<Map<String,V>> conditions, Set<String> caseSensitiveFields, boolean conjunctive) throws SQLException { params = new Vector<V>(); if (caseSensitiveFields == null) caseSensitiveFields = Collections.emptySet(); List<List<Pair>> nestedPairs = new LinkedList<List<Pair>>(); for (Map<String,V> group : conditions) { List<Pair> pairs = new LinkedList<Pair>(); for (Entry<String,V> entry : group.entrySet()) { pairs.add(new Pair(quoteSymbol(conn, entry.getKey()), "?")); params.add(entry.getValue()); } nestedPairs.add(pairs); } Set<String> quotedCSF = new HashSet<String>(); for (String field : caseSensitiveFields) quotedCSF.add(quoteSymbol(conn, field)); String dnf = buildNormalForm(conn, nestedPairs, quotedCSF, conjunctive); if (dnf.length() > 0) clause = String.format(" WHERE %s ", dnf); else clause = ""; } protected static String buildDisjunctiveNormalForm( Connection conn, List<List<Pair>> symbolicArguments, Set<String> caseSensitiveFields ) throws SQLException { return buildNormalForm(conn, symbolicArguments, caseSensitiveFields, false); } protected static String buildNormalForm( Connection conn, List<List<Pair>> nestedPairs, Set<String> caseSensitiveFields, boolean conjunctive ) throws SQLException { String outerJunction = conjunctive ? " AND " : " OR "; String innerJunction = conjunctive ? " OR " : " AND "; List<String> junctions = new LinkedList<String>(); for (List<Pair> juncMap : nestedPairs) { List<String> juncList = new LinkedList<String>(); for (Pair pair : juncMap) { boolean caseSensitive = caseSensitiveFields.contains(pair.a) || caseSensitiveFields.contains(pair.b); juncList.add(buildPredicate(conn, pair.a, pair.b, caseSensitive)); } junctions.add(String.format("(%s)", Strings.join(innerJunction, juncList))); } return Strings.join(outerJunction, junctions); } protected static String buildPredicate(Connection conn, String symbol1, String symbol2, boolean caseSensitive) throws SQLException { if (caseSensitive) { String compare = caseSensitiveCompare(conn, symbol1, symbol2); return new StringBuilder().append('(').append(compare).append(')').toString(); } return new StringBuilder().append('(').append(symbol1).append('=').append(symbol2).append(')').toString(); } protected static class Pair { public String a; public String b; public Pair(String a, String b) { this.a = a; this.b = b; } } } }
package com.exedio.cope; import java.net.InetAddress; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import com.exedio.cope.junit.CopeAssert; import com.exedio.dsmf.Column; import com.exedio.dsmf.Driver; import com.exedio.dsmf.SQLRuntimeException; import com.exedio.dsmf.Schema; import com.exedio.dsmf.Table; public class ReviseTest extends CopeAssert { private static final Revision[] revisions5 = new Revision[]{ new Revision(5, "nonsense5", "nonsense statement causing a test failure if executed for revision 5"), }; private static final Model model5 = new Model(revisions5, ReviseItem1.TYPE); private static final Revision[] revisions7Missing = new Revision[]{ new Revision(7, "nonsense7", "nonsense statement causing a test failure if executed for revision 7"), }; private static final Model model7 = new Model(revisions7Missing, ReviseItem2.TYPE); private static final SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); static { df.setTimeZone(TimeZone.getTimeZone("UTC")); } private String hostname; private com.exedio.cope.ConnectProperties props; @Override protected void setUp() throws Exception { super.setUp(); hostname = InetAddress.getLocalHost().getHostName(); props = new com.exedio.cope.ConnectProperties(com.exedio.cope.ConnectProperties.getSystemPropertyContext()); } String jdbcUrl; String jdbcUser; String databaseName; String databaseVersion; String driverName; String driverVersion; public void testRevise() throws ParseException { jdbcUrl = props.getDatabaseUrl(); jdbcUser = props.getDatabaseUser(); assertTrue(model5.isRevisionEnabled()); assertEquals(5, model5.getRevisionNumber()); assertEqualsUnmodifiable(Arrays.asList(revisions5), model5.getRevisions()); model5.connect(props); model5.tearDownDatabase(); final Properties info = model5.getDatabaseInfo(); databaseName = info.getProperty("database.name"); databaseVersion = info.getProperty("database.version"); driverName = info.getProperty("driver.name"); driverVersion = info.getProperty("driver.version"); final Date createBefore = new Date(); model5.createDatabase(); final Date createAfter = new Date(); assertSchema(model5.getVerifiedSchema(), false, false); final Date createDate; { final Map<Integer, byte[]> logs = model5.getRevisionLogs(); createDate = assertCreate(createBefore, createAfter, logs, 5); assertEquals(1, logs.size()); } model5.disconnect(); assertTrue(model7.isRevisionEnabled()); assertEquals(7, model7.getRevisionNumber()); assertEqualsUnmodifiable(list(revisions7Missing[0]), model7.getRevisions()); model7.connect(props); assertSchema(model7.getVerifiedSchema(), true, false); { final Map<Integer, byte[]> logs = model7.getRevisionLogs(); assertCreate(createDate, logs, 5); assertEquals(1, logs.size()); } try { model7.reviseIfSupported(); fail(); } catch(IllegalArgumentException e) { assertEquals("attempt to revise from 5 to 7, but declared revisions allow from 6 only", e.getMessage()); } assertSchema(model7.getVerifiedSchema(), true, false); { final Map<Integer, byte[]> logs = model7.getRevisionLogs(); assertCreate(createDate, logs, 5); assertEquals(1, logs.size()); } final String blah = " blub blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" + " blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" + " blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" + " blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blob"; final Dialect dialect = model7.getDatabase().dialect; final Driver driver = dialect.driver; // BEWARE: // Never do this in real projects, // always use plain string literals // containing the sql statement! final String body70 = driver.createColumn(driver.protectName(mysqlLower("ReviseItem")), driver.protectName("field7"), dialect.getStringType(100)); final String body60 = driver.createColumn(driver.protectName(mysqlLower("ReviseItem")), driver.protectName("field6"), dialect.getStringType(100)); final String body61 = driver.createColumn(driver.protectName(mysqlLower("ReviseItem")), driver.protectName("field6b"), dialect.getStringType(100)); final Revision[] revisions7 = new Revision[]{ new Revision(7, "add column field7" + blah, body70), new Revision(6, "add column field6", body60, body61), new Revision(5, "nonsense", "nonsense statement causing a test failure if executed for revision 5"), new Revision(4, "nonsense", "nonsense statement causing a test failure if executed for revision 4"), }; model7.setRevisions(revisions7); assertTrue(model7.isRevisionEnabled()); assertEquals(7, model7.getRevisionNumber()); assertEqualsUnmodifiable(Arrays.asList(revisions7), model7.getRevisions()); final Date reviseBefore = new Date(); model7.reviseIfSupported(); final Date reviseAfter = new Date(); assertSchema(model7.getVerifiedSchema(), true, true); final Date reviseDate; { final Map<Integer, byte[]> logs = model7.getRevisionLogs(); assertCreate(createDate, logs, 5); reviseDate = assertRevise(reviseBefore, reviseAfter, revisions7[1], logs, 6); assertRevise(reviseDate, revisions7[0], logs, 7); assertEquals(3, logs.size()); } // test, that revision is not executed again, // causing a SQLException because column does already exist model7.revise(); assertSchema(model7.getVerifiedSchema(), true, true); { final Map<Integer, byte[]> logs = model7.getRevisionLogs(); assertCreate(createDate, logs, 5); assertRevise(reviseDate, revisions7[1], logs, 6); assertRevise(reviseDate, revisions7[0], logs, 7); assertEquals(3, logs.size()); } final Revision[] revisions8 = new Revision[]{ new Revision(8, "nonsense8", "nonsense statement causing a test failure"), }; model7.setRevisions(revisions8); assertTrue(model7.isRevisionEnabled()); assertEquals(8, model7.getRevisionNumber()); assertEqualsUnmodifiable(Arrays.asList(revisions8), model7.getRevisions()); try { model7.reviseIfSupported(); } catch(SQLRuntimeException e) { assertEquals("nonsense statement causing a test failure", e.getMessage()); } assertSchema(model7.getVerifiedSchema(), true, true); { final Map<Integer, byte[]> logs = model7.getRevisionLogs(); assertCreate(createDate, logs, 5); assertRevise(reviseDate, revisions7[1], logs, 6); assertRevise(reviseDate, revisions7[0], logs, 7); assertEquals(3, logs.size()); } try { model7.reviseIfSupported(); } catch(IllegalStateException e) { assertEquals("Revision mutex set: Either a revision is currently underway, or a revision has failed unexpectedly.", e.getMessage()); } assertSchema(model7.getVerifiedSchema(), true, true); { final Map<Integer, byte[]> logs = model7.getRevisionLogs(); assertCreate(createDate, logs, 5); assertRevise(reviseDate, revisions7[1], logs, 6); assertRevise(reviseDate, revisions7[0], logs, 7); assertEquals(3, logs.size()); } model7.tearDownDatabase(); } private void assertSchema(final Schema schema, final boolean model2, final boolean revised) { final Table table = schema.getTable(mysqlLower(("ReviseItem"))); assertEquals(mysqlLower("ReviseItem"), table.getName()); assertEquals(true, table.required()); assertEquals(true, table.exists()); final Iterator<Column> columns = table.getColumns().iterator(); final Column columnThis = columns.next(); assertEquals("this", columnThis.getName()); assertEquals(true, columnThis.required()); assertEquals(true, columnThis.exists()); assertNotNull(columnThis.getType()); final Column column5 = columns.next(); assertEquals("field5", column5.getName()); assertEquals(true, column5.required()); assertEquals(true, column5.exists()); assertNotNull(column5.getType()); if(model2) { final Column column6 = columns.next(); assertEquals("field6", column6.getName()); assertEquals(true, column6.required()); assertEquals(revised, column6.exists()); assertNotNull(column6.getType()); final Column column6b = columns.next(); assertEquals("field6b", column6b.getName()); assertEquals(true, column6b.required()); assertEquals(revised, column6b.exists()); assertNotNull(column6b.getType()); final Column column7 = columns.next(); assertEquals("field7", column7.getName()); assertEquals(true, column7.required()); assertEquals(revised, column7.exists()); assertNotNull(column7.getType()); } assertFalse(columns.hasNext()); final Table revisionTable = schema.getTable("while"); assertEquals("while", revisionTable.getName()); assertEquals(true, revisionTable.required()); assertEquals(true, revisionTable.exists()); } private final Date assertCreate(final Date before, final Date after, final Map<Integer, byte[]> logs, final int revision) throws ParseException { final byte[] log = logs.get(revision); assertNotNull(log); final Properties logProps = parse(log); assertEquals(String.valueOf(revision), logProps.getProperty("revision")); final Date date = df.parse(logProps.getProperty("dateUTC")); assertWithin(before, after, date); assertEquals("true", logProps.getProperty("create")); assertRevisionEnvironment(logProps); assertEquals(14, logProps.size()); return date; } private final void assertCreate(final Date date, final Map<Integer, byte[]> logs, final int revision) throws ParseException { assertEquals(date, assertCreate(date, date, logs, revision)); } private final Date assertRevise(final Date before, final Date after, final Revision revision, final Map<Integer, byte[]> logs, final int number) throws ParseException { final byte[] log = logs.get(number); assertNotNull(log); final Properties logProps = parse(log); assertEquals(String.valueOf(number), logProps.getProperty("revision")); final Date date = df.parse(logProps.getProperty("dateUTC")); assertWithin(before, after, date); assertEquals(null, logProps.getProperty("create")); assertEquals(revision.comment, logProps.getProperty("comment")); for(int i = 0; i<revision.body.length; i++) { assertEquals(revision.body[i], logProps.getProperty("body" + i + ".sql")); assertMinInt(0, logProps.getProperty("body" + i + ".rows")); assertMinInt(0, logProps.getProperty("body" + i + ".elapsed")); } assertRevisionEnvironment(logProps); assertEquals(14 + (3*revision.body.length), logProps.size()); return date; } private final void assertRevise(final Date date, final Revision revision, final Map<Integer, byte[]> logs, final int number) throws ParseException { assertEquals(date, assertRevise(date, date, revision, logs, number)); } private final void assertRevisionEnvironment(final Properties p) { assertNotNull(hostname); assertNotNull(jdbcUrl); assertNotNull(jdbcUser); assertNotNull(databaseName); assertNotNull(databaseVersion); assertNotNull(driverName); assertNotNull(driverVersion); assertEquals(hostname, p.getProperty("hostname")); assertEquals(jdbcUrl, p.getProperty("jdbc.url")); assertEquals(jdbcUser, p.getProperty("jdbc.user")); assertEquals(databaseName, p.getProperty("database.name")); assertEquals(databaseVersion, p.getProperty("database.version") + " (" + p.getProperty("database.version.major") + '.' + p.getProperty("database.version.minor") + ')'); assertEquals(driverName, p.getProperty("driver.name")); assertEquals(driverVersion, p.getProperty("driver.version") + " (" + p.getProperty("driver.version.major") + '.' + p.getProperty("driver.version.minor") + ')'); } private static final Properties parse(final byte[] log) { return Revision.parse(log); } private static final void assertMinInt(final int expectedMinimum, final String actual) { assertTrue(actual, Integer.parseInt(actual)>=expectedMinimum); } final String mysqlLower(final String name) { return props.getMysqlLowerCaseTableNames() ? name.toLowerCase() : name; } }