List of usage examples for java.util HashMap values
public Collection<V> values()
From source file:com.googlesource.gerrit.plugins.supermanifest.JiriManifestParser.java
public static JiriProjects getProjects(GerritRemoteReader reader, String repoKey, String ref, String manifest) throws ConfigInvalidException, IOException { try (RepoMap<String, Repository> repoMap = new RepoMap<>()) { repoMap.put(repoKey, reader.openRepository(repoKey)); Queue<ManifestItem> q = new LinkedList<>(); q.add(new ManifestItem(repoKey, manifest, ref, "", false)); HashMap<String, HashSet<String>> processedRepoFiles = new HashMap<>(); HashMap<String, JiriProjects.Project> projectMap = new HashMap<>(); while (q.size() != 0) { ManifestItem mi = q.remove(); Repository repo = repoMap.get(mi.repoKey); if (repo == null) { repo = reader.openRepository(mi.repoKey); repoMap.put(mi.repoKey, repo); }/*from www . j a v a2s . c om*/ HashSet<String> processedFiles = processedRepoFiles.get(mi.repoKey); if (processedFiles == null) { processedFiles = new HashSet<String>(); processedRepoFiles.put(mi.repoKey, processedFiles); } if (processedFiles.contains(mi.manifest)) { continue; } processedFiles.add(mi.manifest); JiriManifest m; try { m = parseManifest(repo, mi.ref, mi.manifest); } catch (JAXBException | XMLStreamException e) { throw new ConfigInvalidException("XML parse error", e); } for (JiriProjects.Project project : m.projects.getProjects()) { project.fillDefault(); if (mi.revisionPinned && project.Key().equals(mi.projectKey)) { project.setRevision(mi.ref); } if (projectMap.containsKey(project.Key())) { if (!projectMap.get(project.Key()).equals(project)) throw new ConfigInvalidException(String.format( "Duplicate conflicting project %s in manifest %s\n%s\n%s", project.Key(), mi.manifest, project.toString(), projectMap.get(project.Key()).toString())); } else { projectMap.put(project.Key(), project); } } URI parentURI; try { parentURI = new URI(mi.manifest); } catch (URISyntaxException e) { throw new ConfigInvalidException("Invalid parent URI", e); } for (JiriManifest.LocalImport l : m.imports.getLocalImports()) { ManifestItem tw = new ManifestItem(mi.repoKey, parentURI.resolve(l.getFile()).getPath(), mi.ref, mi.projectKey, mi.revisionPinned); q.add(tw); } for (JiriManifest.Import i : m.imports.getImports()) { i.fillDefault(); URI uri; try { uri = new URI(i.getRemote()); } catch (URISyntaxException e) { throw new ConfigInvalidException("Invalid URI", e); } String iRepoKey = new Project.NameKey(StringUtils.strip(uri.getPath(), "/")).toString(); String iRef = i.getRevision(); boolean revisionPinned = true; if (iRef.isEmpty()) { iRef = REFS_HEADS + i.getRemotebranch(); revisionPinned = false; } ManifestItem tmi = new ManifestItem(iRepoKey, i.getManifest(), iRef, i.Key(), revisionPinned); q.add(tmi); } } return new JiriProjects(projectMap.values().toArray(new JiriProjects.Project[0])); } }
From source file:de.tudarmstadt.ukp.dariah.pipeline.DARIAHWriter.java
private void convert(JCas aJCas, PrintWriter aOut) { int paragraphId = 0, sentenceId = 0, tokenId = 0; aOut.printf("%s\n", StringUtils.join(getHeader(), "\t")); Map<Token, Collection<NamedEntity>> neCoveringMap = JCasUtil.indexCovering(aJCas, Token.class, NamedEntity.class); Map<Token, Collection<DirectSpeech>> directSpeechCoveringMap = JCasUtil.indexCovering(aJCas, Token.class, DirectSpeech.class); for (Paragraph para : select(aJCas, Paragraph.class)) { for (Sentence sentence : selectCovered(Sentence.class, para)) { HashMap<Token, Row> ctokens = new LinkedHashMap<Token, Row>(); // Tokens List<Token> tokens = selectCovered(Token.class, sentence); // Check if we should try to include the FEATS in output List<Morpheme> morphology = selectCovered(Morpheme.class, sentence); boolean useFeats = tokens.size() == morphology.size(); //Parsing information String[] parseFragments = null; List<ROOT> root = selectCovered(ROOT.class, sentence); if (root.size() == 1) { PennTreeNode rootNode = PennTreeUtils.convertPennTree(root.get(0)); if ("ROOT".equals(rootNode.getLabel())) { rootNode.setLabel("TOP"); }//from w w w .j av a 2 s . c o m parseFragments = toPrettyPennTree(rootNode); } boolean useParseFragements = (parseFragments != null && parseFragments.length == tokens.size()); for (int i = 0; i < tokens.size(); i++) { Row row = new Row(); row.paragraphId = paragraphId; row.sentenceId = sentenceId; row.tokenId = tokenId; row.token = tokens.get(i); if (useParseFragements) { row.parseFragment = parseFragments[i]; } if (useFeats) { row.morphology = morphology.get(i); } // Named entities Collection<NamedEntity> ne = neCoveringMap.get(row.token); if (ne.size() > 0) row.ne = ne.toArray(new NamedEntity[0])[0]; Collection<DirectSpeech> ds = directSpeechCoveringMap.get(row.token); if (ds.size() > 0) row.directSpeech = ds.toArray(new DirectSpeech[0])[0]; ctokens.put(row.token, row); tokenId++; } // Dependencies for (Dependency rel : selectCovered(Dependency.class, sentence)) { ctokens.get(rel.getDependent()).deprel = rel; } // Write sentence for (Row row : ctokens.values()) { String[] output = getData(ctokens, row); aOut.printf("%s\n", StringUtils.join(output, "\t")); } sentenceId++; } paragraphId++; } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.conll.Conll2008Writer.java
private void convert(JCas aJCas, PrintWriter aOut) { Map<Token, Collection<SemPred>> predIdx = indexCovered(aJCas, Token.class, SemPred.class); Map<SemArg, Collection<Token>> argIdx = indexCovered(aJCas, SemArg.class, Token.class); for (Sentence sentence : select(aJCas, Sentence.class)) { HashMap<Token, Row> ctokens = new LinkedHashMap<Token, Row>(); // Tokens List<Token> tokens = selectCovered(Token.class, sentence); // Check if we should try to include the FEATS in output List<MorphologicalFeatures> morphology = selectCovered(MorphologicalFeatures.class, sentence); boolean useFeats = tokens.size() == morphology.size(); List<SemPred> preds = selectCovered(SemPred.class, sentence); for (int i = 0; i < tokens.size(); i++) { Row row = new Row(); row.id = i + 1;// ww w .j a va2s. co m row.token = tokens.get(i); row.args = new SemArgLink[preds.size()]; if (useFeats) { row.feats = morphology.get(i); } // If there are multiple semantic predicates for the current token, then // we keep only the first Collection<SemPred> predsForToken = predIdx.get(row.token); if (predsForToken != null && !predsForToken.isEmpty()) { row.pred = predsForToken.iterator().next(); } ctokens.put(row.token, row); } // Dependencies List<Dependency> basicDeps = selectCovered(Dependency.class, sentence).stream() .filter(dep -> dep.getFlavor() == null || DependencyFlavor.BASIC.equals(dep.getFlavor())) .collect(Collectors.toList()); for (Dependency rel : basicDeps) { Row row = ctokens.get(rel.getDependent()); if (row.deprel != null) { throw new IllegalStateException("Illegal basic dependency structure - token [" + row.token.getCoveredText() + "] is dependent of more than one dependency."); } row.deprel = rel; } // Semantic arguments for (int p = 0; p < preds.size(); p++) { FSArray args = preds.get(p).getArguments(); for (SemArgLink arg : select(args, SemArgLink.class)) { for (Token t : argIdx.get(arg.getTarget())) { Row row = ctokens.get(t); row.args[p] = arg; } } } // Write sentence in CONLL 2009 format for (Row row : ctokens.values()) { int id = row.id; String form = row.token.getCoveredText(); String lemma = UNUSED; if (writeLemma && (row.token.getLemma() != null)) { lemma = row.token.getLemma().getValue(); } String gpos = UNUSED; if (writePos && (row.token.getPos() != null)) { POS posAnno = row.token.getPos(); gpos = posAnno.getPosValue(); } String ppos = UNUSED; String split_form = UNUSED; String split_lemma = UNUSED; String pposs = UNUSED; int headId = UNUSED_INT; String deprel = UNUSED; if (writeDependency && (row.deprel != null)) { deprel = row.deprel.getDependencyType(); headId = ctokens.get(row.deprel.getGovernor()).id; if (headId == row.id) { // ROOT dependencies may be modeled as a loop, ignore these. headId = 0; } } String head = UNUSED; if (headId != UNUSED_INT) { head = Integer.toString(headId); } String pred = UNUSED; StringBuilder apreds = new StringBuilder(); if (writeSemanticPredicate) { if (row.pred != null) { pred = row.pred.getCategory(); } for (SemArgLink arg : row.args) { if (apreds.length() > 0) { apreds.append('\t'); } apreds.append(arg != null ? arg.getRole() : UNUSED); } } aOut.printf("%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", id, form, lemma, gpos, ppos, split_form, split_lemma, pposs, head, deprel, pred, apreds); } aOut.println(); } }
From source file:org.apache.openejb.assembler.classic.Assembler.java
public AppContext createApplication(AppInfo appInfo, ClassLoader classLoader, boolean start) throws OpenEJBException, IOException, NamingException { // The path is used in the UrlCache, command line deployer, JNDI name templates, tomcat integration and a few other places if (appInfo.appId == null) throw new IllegalArgumentException("AppInfo.appId cannot be null"); if (appInfo.path == null) appInfo.path = appInfo.appId;//w w w.j a v a2s .c om logger.info("createApplication.start", appInfo.path); // try { // Thread.sleep(5000); // } catch (InterruptedException e) { // e.printStackTrace(); // Thread.interrupted(); // } // To start out, ensure we don't already have any beans deployed with duplicate IDs. This // is a conflict we can't handle. List<String> used = new ArrayList<String>(); for (EjbJarInfo ejbJarInfo : appInfo.ejbJars) { for (EnterpriseBeanInfo beanInfo : ejbJarInfo.enterpriseBeans) { if (containerSystem.getBeanContext(beanInfo.ejbDeploymentId) != null) { used.add(beanInfo.ejbDeploymentId); } } } if (used.size() > 0) { String message = logger.error("createApplication.appFailedDuplicateIds", appInfo.path); for (String id : used) { logger.debug("createApplication.deploymentIdInUse", id); message += "\n " + id; } throw new DuplicateDeploymentIdException(message); } //Construct the global and app jndi contexts for this app final InjectionBuilder injectionBuilder = new InjectionBuilder(classLoader); Set<Injection> injections = new HashSet<Injection>(); injections.addAll(injectionBuilder.buildInjections(appInfo.globalJndiEnc)); injections.addAll(injectionBuilder.buildInjections(appInfo.appJndiEnc)); final JndiEncBuilder globalBuilder = new JndiEncBuilder(appInfo.globalJndiEnc, injections, null, null, GLOBAL_UNIQUE_ID, classLoader); final Map<String, Object> globalBindings = globalBuilder.buildBindings(JndiEncBuilder.JndiScope.global); final Context globalJndiContext = globalBuilder.build(globalBindings); final JndiEncBuilder appBuilder = new JndiEncBuilder(appInfo.appJndiEnc, injections, appInfo.appId, null, appInfo.appId, classLoader); final Map<String, Object> appBindings = appBuilder.buildBindings(JndiEncBuilder.JndiScope.app); final Context appJndiContext = appBuilder.build(appBindings); try { // Generate the cmp2/cmp1 concrete subclasses CmpJarBuilder cmpJarBuilder = new CmpJarBuilder(appInfo, classLoader); File generatedJar = cmpJarBuilder.getJarFile(); if (generatedJar != null) { classLoader = ClassLoaderUtil.createClassLoader(appInfo.path, new URL[] { generatedJar.toURI().toURL() }, classLoader); } final AppContext appContext = new AppContext(appInfo.appId, SystemInstance.get(), classLoader, globalJndiContext, appJndiContext, appInfo.standaloneModule); appContext.getInjections().addAll(injections); appContext.getBindings().putAll(globalBindings); appContext.getBindings().putAll(appBindings); containerSystem.addAppContext(appContext); final Context containerSystemContext = containerSystem.getJNDIContext(); if (!SystemInstance.get().hasProperty("openejb.geronimo")) { // Bean Validation // ValidatorFactory needs to be put in the map sent to the entity manager factory // so it has to be constructed before final List<CommonInfoObject> vfs = new ArrayList<CommonInfoObject>(); for (ClientInfo clientInfo : appInfo.clients) { vfs.add(clientInfo); } for (ConnectorInfo connectorInfo : appInfo.connectors) { vfs.add(connectorInfo); } for (EjbJarInfo ejbJarInfo : appInfo.ejbJars) { vfs.add(ejbJarInfo); } for (WebAppInfo webAppInfo : appInfo.webApps) { vfs.add(webAppInfo); } final Map<String, ValidatorFactory> validatorFactories = new HashMap<String, ValidatorFactory>(); for (CommonInfoObject info : vfs) { ValidatorFactory factory = null; try { factory = ValidatorBuilder.buildFactory(classLoader, info.validationInfo); } catch (ValidationException ve) { logger.warning("can't build the validation factory for module " + info.uniqueId, ve); } if (factory != null) { validatorFactories.put(info.uniqueId, factory); } } moduleIds.addAll(validatorFactories.keySet()); // validators bindings for (Entry<String, ValidatorFactory> validatorFactory : validatorFactories.entrySet()) { String id = validatorFactory.getKey(); ValidatorFactory factory = validatorFactory.getValue(); try { containerSystemContext.bind(VALIDATOR_FACTORY_NAMING_CONTEXT + id, factory); containerSystemContext.bind(VALIDATOR_NAMING_CONTEXT + id, factory.usingContext().getValidator()); } catch (NameAlreadyBoundException e) { throw new OpenEJBException("ValidatorFactory already exists for module " + id, e); } catch (Exception e) { throw new OpenEJBException(e); } } } // JPA - Persistence Units MUST be processed first since they will add ClassFileTransformers // to the class loader which must be added before any classes are loaded Map<String, String> units = new HashMap<String, String>(); PersistenceBuilder persistenceBuilder = new PersistenceBuilder(persistenceClassLoaderHandler); for (PersistenceUnitInfo info : appInfo.persistenceUnits) { ReloadableEntityManagerFactory factory; try { factory = persistenceBuilder.createEntityManagerFactory(info, classLoader); containerSystem.getJNDIContext().bind(PERSISTENCE_UNIT_NAMING_CONTEXT + info.id, factory); units.put(info.name, PERSISTENCE_UNIT_NAMING_CONTEXT + info.id); } catch (NameAlreadyBoundException e) { throw new OpenEJBException("PersistenceUnit already deployed: " + info.persistenceUnitRootUrl); } catch (Exception e) { throw new OpenEJBException(e); } factory.register(); } // Connectors for (ConnectorInfo connector : appInfo.connectors) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { // todo add undeployment code for these if (connector.resourceAdapter != null) { createResource(connector.resourceAdapter); } for (ResourceInfo outbound : connector.outbound) { createResource(outbound); } for (MdbContainerInfo inbound : connector.inbound) { createContainer(inbound); } for (ResourceInfo adminObject : connector.adminObject) { createResource(adminObject); } } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } List<BeanContext> allDeployments = new ArrayList<BeanContext>(); // EJB EjbJarBuilder ejbJarBuilder = new EjbJarBuilder(props, appContext); for (EjbJarInfo ejbJar : appInfo.ejbJars) { HashMap<String, BeanContext> deployments = ejbJarBuilder.build(ejbJar, injections); JaccPermissionsBuilder jaccPermissionsBuilder = new JaccPermissionsBuilder(); PolicyContext policyContext = jaccPermissionsBuilder.build(ejbJar, deployments); jaccPermissionsBuilder.install(policyContext); TransactionPolicyFactory transactionPolicyFactory = createTransactionPolicyFactory(ejbJar, classLoader); for (BeanContext beanContext : deployments.values()) { beanContext.setTransactionPolicyFactory(transactionPolicyFactory); } MethodTransactionBuilder methodTransactionBuilder = new MethodTransactionBuilder(); methodTransactionBuilder.build(deployments, ejbJar.methodTransactions); MethodConcurrencyBuilder methodConcurrencyBuilder = new MethodConcurrencyBuilder(); methodConcurrencyBuilder.build(deployments, ejbJar.methodConcurrency); for (BeanContext beanContext : deployments.values()) { containerSystem.addDeployment(beanContext); } //bind ejbs into global jndi jndiBuilder.build(ejbJar, deployments); // setup timers/asynchronous methods - must be after transaction attributes are set for (BeanContext beanContext : deployments.values()) { if (beanContext.getComponentType() != BeanType.STATEFUL) { Method ejbTimeout = beanContext.getEjbTimeout(); boolean timerServiceRequired = false; if (ejbTimeout != null) { // If user set the tx attribute to RequiresNew change it to Required so a new transaction is not started if (beanContext.getTransactionType(ejbTimeout) == TransactionType.RequiresNew) { beanContext.setMethodTransactionAttribute(ejbTimeout, TransactionType.Required); } timerServiceRequired = true; } for (Iterator<Map.Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it .hasNext();) { Map.Entry<Method, MethodContext> entry = it.next(); MethodContext methodContext = entry.getValue(); if (methodContext.getSchedules().size() > 0) { timerServiceRequired = true; Method method = entry.getKey(); //TODO Need ? if (beanContext.getTransactionType(method) == TransactionType.RequiresNew) { beanContext.setMethodTransactionAttribute(method, TransactionType.Required); } } } if (timerServiceRequired) { // Create the timer EjbTimerServiceImpl timerService = new EjbTimerServiceImpl(beanContext); //Load auto-start timers TimerStore timerStore = timerService.getTimerStore(); for (Iterator<Map.Entry<Method, MethodContext>> it = beanContext .iteratorMethodContext(); it.hasNext();) { Map.Entry<Method, MethodContext> entry = it.next(); MethodContext methodContext = entry.getValue(); for (ScheduleData scheduleData : methodContext.getSchedules()) { timerStore.createCalendarTimer(timerService, (String) beanContext.getDeploymentID(), null, entry.getKey(), scheduleData.getExpression(), scheduleData.getConfig()); } } beanContext.setEjbTimerService(timerService); } else { beanContext.setEjbTimerService(new NullEjbTimerServiceImpl()); } } //set asynchronous methods transaction //TODO ??? for (Iterator<Entry<Method, MethodContext>> it = beanContext.iteratorMethodContext(); it .hasNext();) { Entry<Method, MethodContext> entry = it.next(); if (entry.getValue().isAsynchronous() && beanContext.getTransactionType(entry.getKey()) == TransactionType.RequiresNew) { beanContext.setMethodTransactionAttribute(entry.getKey(), TransactionType.Required); } } } // process application exceptions for (ApplicationExceptionInfo exceptionInfo : ejbJar.applicationException) { try { Class exceptionClass = classLoader.loadClass(exceptionInfo.exceptionClass); for (BeanContext beanContext : deployments.values()) { beanContext.addApplicationException(exceptionClass, exceptionInfo.rollback, exceptionInfo.inherited); } } catch (ClassNotFoundException e) { logger.error("createApplication.invalidClass", e, exceptionInfo.exceptionClass, e.getMessage()); } } allDeployments.addAll(deployments.values()); } allDeployments = sort(allDeployments); appContext.getBeanContexts().addAll(allDeployments); new CdiBuilder().build(appInfo, appContext, allDeployments); ensureWebBeansContext(appContext); appJndiContext.bind("app/BeanManager", appContext.getBeanManager()); appContext.getBindings().put("app/BeanManager", appContext.getBeanManager()); // now that everything is configured, deploy to the container if (start) { // deploy for (BeanContext deployment : allDeployments) { try { Container container = deployment.getContainer(); container.deploy(deployment); if (!((String) deployment.getDeploymentID()).endsWith(".Comp") && !deployment.isHidden()) { logger.info("createApplication.createdEjb", deployment.getDeploymentID(), deployment.getEjbName(), container.getContainerID()); } if (logger.isDebugEnabled()) { for (Map.Entry<Object, Object> entry : deployment.getProperties().entrySet()) { logger.info("createApplication.createdEjb.property", deployment.getEjbName(), entry.getKey(), entry.getValue()); } } } catch (Throwable t) { throw new OpenEJBException("Error deploying '" + deployment.getEjbName() + "'. Exception: " + t.getClass() + ": " + t.getMessage(), t); } } // start for (BeanContext deployment : allDeployments) { try { Container container = deployment.getContainer(); container.start(deployment); if (!((String) deployment.getDeploymentID()).endsWith(".Comp") && !deployment.isHidden()) { logger.info("createApplication.startedEjb", deployment.getDeploymentID(), deployment.getEjbName(), container.getContainerID()); } } catch (Throwable t) { throw new OpenEJBException("Error starting '" + deployment.getEjbName() + "'. Exception: " + t.getClass() + ": " + t.getMessage(), t); } } } // App Client for (ClientInfo clientInfo : appInfo.clients) { // determine the injections List<Injection> clientInjections = injectionBuilder.buildInjections(clientInfo.jndiEnc); // build the enc JndiEncBuilder jndiEncBuilder = new JndiEncBuilder(clientInfo.jndiEnc, clientInjections, "Bean", clientInfo.moduleId, null, clientInfo.uniqueId, classLoader); // if there is at least a remote client classes // or if there is no local client classes // then, we can set the client flag if ((clientInfo.remoteClients.size() > 0) || (clientInfo.localClients.size() == 0)) { jndiEncBuilder.setClient(true); } jndiEncBuilder.setUseCrossClassLoaderRef(false); Context context = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp); // Debug.printContext(context); containerSystemContext.bind("openejb/client/" + clientInfo.moduleId, context); if (clientInfo.path != null) { context.bind("info/path", clientInfo.path); } if (clientInfo.mainClass != null) { context.bind("info/mainClass", clientInfo.mainClass); } if (clientInfo.callbackHandler != null) { context.bind("info/callbackHandler", clientInfo.callbackHandler); } context.bind("info/injections", clientInjections); for (String clientClassName : clientInfo.remoteClients) { containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId); } for (String clientClassName : clientInfo.localClients) { containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId); logger.getChildLogger("client").info("createApplication.createLocalClient", clientClassName, clientInfo.moduleId); } } SystemInstance systemInstance = SystemInstance.get(); // WebApp WebAppBuilder webAppBuilder = systemInstance.getComponent(WebAppBuilder.class); if (webAppBuilder != null) { webAppBuilder.deployWebApps(appInfo, classLoader); } if (start) { EjbResolver globalEjbResolver = systemInstance.getComponent(EjbResolver.class); globalEjbResolver.addAll(appInfo.ejbJars); } // bind all global values on global context for (Map.Entry<String, Object> value : appContext.getBindings().entrySet()) { String path = value.getKey(); if (!path.startsWith("global") || path.equalsIgnoreCase("global/dummy")) { // dummy bound for each app continue; } // a bit weird but just to be consistent if user doesn't lookup directly the resource Context lastContext = ContextUtil.mkdirs(containerSystemContext, path); try { lastContext.bind(path.substring(path.lastIndexOf("/") + 1, path.length()), value.getValue()); } catch (NameAlreadyBoundException nabe) { nabe.printStackTrace(); } containerSystemContext.rebind(path, value.getValue()); } logger.info("createApplication.success", appInfo.path); deployedApplications.put(appInfo.path, appInfo); fireAfterApplicationCreated(appInfo); return appContext; } catch (ValidationException ve) { throw ve; } catch (Throwable t) { try { destroyApplication(appInfo); } catch (Exception e1) { logger.debug("createApplication.undeployFailed", e1, appInfo.path); } throw new OpenEJBException(messages.format("createApplication.failed", appInfo.path), t); } }
From source file:com.wasteofplastic.acidisland.commands.Challenges.java
/** * Checks if a player has enough for a challenge. Supports two types of * checks, inventory and island. Removes items if required. * /*from w w w. ja v a2s . c om*/ * @param player * @param challenge * @param type * @return true if the player has everything required */ @SuppressWarnings("deprecation") public boolean hasRequired(final Player player, final String challenge, final String type) { // Check money double moneyReq = 0D; if (Settings.useEconomy) { moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney", 0D); if (moneyReq > 0D) { if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) { player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems); player.sendMessage(ChatColor.RED + getChallengeConfig() .getString("challenges.challengeList." + challenge + ".description")); return false; } } } final String[] reqList = getChallengeConfig() .getString("challenges.challengeList." + challenge + ".requiredItems").split(" "); // The format of the requiredItems is as follows: // Material:Qty // or // Material:DamageModifier:Qty // This second one is so that items such as potions or variations on // standard items can be collected if (type.equalsIgnoreCase("inventory")) { List<ItemStack> toBeRemoved = new ArrayList<ItemStack>(); Material reqItem; int reqAmount = 0; for (final String s : reqList) { final String[] part = s.split(":"); // Material:Qty if (part.length == 2) { try { // Correct some common mistakes if (part[0].equalsIgnoreCase("potato")) { part[0] = "POTATO_ITEM"; } else if (part[0].equalsIgnoreCase("brewing_stand")) { part[0] = "BREWING_STAND_ITEM"; } else if (part[0].equalsIgnoreCase("carrot")) { part[0] = "CARROT_ITEM"; } else if (part[0].equalsIgnoreCase("cauldron")) { part[0] = "CAULDRON_ITEM"; } else if (part[0].equalsIgnoreCase("skull")) { part[0] = "SKULL_ITEM"; } // TODO: add netherwart vs. netherstalk? if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[1]); ItemStack item = new ItemStack(reqItem); // plugin.getLogger().info("DEBUG: required item = " + // reqItem.toString()); // plugin.getLogger().info("DEBUG: item amount = " + // reqAmount); if (!player.getInventory().contains(reqItem)) { return false; } else { // check amount int amount = 0; // plugin.getLogger().info("DEBUG: Amount in inventory = " // + player.getInventory().all(reqItem).size()); // Go through all the inventory and try to find // enough required items for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem) .entrySet()) { // Get the item ItemStack i = en.getValue(); // Map needs special handling because the // durability increments every time a new one is // made by the player // TODO: if there are any other items that act // in the same way, they need adding too... if (i.getDurability() == 0 || (reqItem == Material.MAP && i.getType() == Material.MAP)) { // Clear any naming, or lore etc. i.setItemMeta(null); player.getInventory().setItem(en.getKey(), i); // #1 item stack qty + amount is less than // required items - take all i // #2 item stack qty + amount = required // item - // take all // #3 item stack qty + amount > req items - // take // portion of i // amount += i.getAmount(); if ((amount + i.getAmount()) < reqAmount) { // Remove all of this item stack - clone // otherwise it will keep a reference to // the // original toBeRemoved.add(i.clone()); amount += i.getAmount(); // plugin.getLogger().info("DEBUG: amount is <= req Remove " // + i.toString() + ":" + // i.getDurability() + " x " + // i.getAmount()); } else if ((amount + i.getAmount()) == reqAmount) { // plugin.getLogger().info("DEBUG: amount is = req Remove " // + i.toString() + ":" + // i.getDurability() + " x " + // i.getAmount()); toBeRemoved.add(i.clone()); amount += i.getAmount(); break; } else { // Remove a portion of this item // plugin.getLogger().info("DEBUG: amount is > req Remove " // + i.toString() + ":" + // i.getDurability() + " x " + // i.getAmount()); item.setAmount(reqAmount - amount); item.setDurability(i.getDurability()); toBeRemoved.add(item); amount += i.getAmount(); break; } } } // plugin.getLogger().info("DEBUG: amount "+ // amount); if (amount < reqAmount) { return false; } } } catch (Exception e) { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady); String materialList = ""; boolean hint = false; for (Material m : Material.values()) { materialList += m.toString() + ","; if (m.toString().contains(s.substring(0, 3).toUpperCase())) { plugin.getLogger().severe("Did you mean " + m.toString() + "?"); hint = true; } } if (!hint) { plugin.getLogger() .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:"); plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1)); } else { plugin.getLogger().severe("Correct challenges.yml with the correct material."); } return false; } } else if (part.length == 3) { // This handles items with durability or potions try { // Correct some common mistakes if (part[0].equalsIgnoreCase("potato")) { part[0] = "POTATO_ITEM"; } else if (part[0].equalsIgnoreCase("brewing_stand")) { part[0] = "BREWING_STAND_ITEM"; } else if (part[0].equalsIgnoreCase("carrot")) { part[0] = "CARROT_ITEM"; } else if (part[0].equalsIgnoreCase("cauldron")) { part[0] = "CAULDRON_ITEM"; } else if (part[0].equalsIgnoreCase("skull")) { part[0] = "SKULL_ITEM"; } if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[2]); int reqDurability = Integer.parseInt(part[1]); int count = reqAmount; // plugin.getLogger().info("DEBUG: 3 part " + // reqItem.toString() + ":" + reqDurability + " x " + // reqAmount); ItemStack item = new ItemStack(reqItem); // Check for potions if (reqItem.equals(Material.POTION)) { //Logger.logger(2,"DEBUG: Potion"); // Contains at least does not work for potions ItemStack[] playerInv = player.getInventory().getContents(); for (ItemStack i : playerInv) { if (i != null && i.getType().equals(Material.POTION)) { // plugin.getLogger().info("DEBUG: Potion found, durability = "+ // i.getDurability()); // Potion type was given by number // Only included for backward compatibility if (i.getDurability() == reqDurability) { item = i.clone(); if (item.getAmount() > reqAmount) { item.setAmount(reqAmount); } count = count - item.getAmount(); // plugin.getLogger().info("Matched! count = " // + count); // If the item stack has more in it than // required, just take the minimum // plugin.getLogger().info("DEBUG: Found " // + item.toString() + ":" + // item.getDurability() + " x " + // item.getAmount()); toBeRemoved.add(item); } } if (count == 0) { break; } } if (count > 0) { return false; } // They have enough } else { // Item item.setDurability((short) reqDurability); // plugin.getLogger().info("DEBUG: item with durability " // + item.toString()); // item.setAmount(reqAmount); /* * if (!player.getInventory().containsAtLeast(item, * reqAmount)) { * plugin.getLogger().info( * "DEBUG: item with durability not enough"); * return false; * } */ // check amount int amount = 0; // Go through all the inventory and try to find // enough required items for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem) .entrySet()) { // Get the item ItemStack i = en.getValue(); if (i.getDurability() == reqDurability) { // Clear any naming, or lore etc. i.setItemMeta(null); player.getInventory().setItem(en.getKey(), i); // #1 item stack qty + amount is less than // required items - take all i // #2 item stack qty + amount = required // item - // take all // #3 item stack qty + amount > req items - // take // portion of i // amount += i.getAmount(); if ((amount + i.getAmount()) < reqAmount) { // Remove all of this item stack - clone // otherwise it will keep a reference to // the // original toBeRemoved.add(i.clone()); amount += i.getAmount(); // plugin.getLogger().info("DEBUG: amount is <= req Remove " // + i.toString() + ":" + // i.getDurability() // + " x " + i.getAmount()); } else if ((amount + i.getAmount()) == reqAmount) { toBeRemoved.add(i.clone()); amount += i.getAmount(); break; } else { // Remove a portion of this item // plugin.getLogger().info("DEBUG: amount is > req Remove " // + i.toString() + ":" + // i.getDurability() // + " x " + i.getAmount()); item.setAmount(reqAmount - amount); item.setDurability(i.getDurability()); toBeRemoved.add(item); amount += i.getAmount(); break; } } } // plugin.getLogger().info("DEBUG: amount is " + // amount); // plugin.getLogger().info("DEBUG: req amount is " + // reqAmount); if (amount < reqAmount) { return false; } } // plugin.getLogger().info("DEBUG: before set amount " + // item.toString() + ":" + item.getDurability() + " x " // + item.getAmount()); // item.setAmount(reqAmount); // plugin.getLogger().info("DEBUG: after set amount " + // item.toString() + ":" + item.getDurability() + " x " // + item.getAmount()); // toBeRemoved.add(item); } catch (Exception e) { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady); if (part[0].equalsIgnoreCase("POTION")) { plugin.getLogger() .severe("Format POTION:TYPE:QTY where TYPE is the number of the following:"); for (PotionType p : PotionType.values()) { plugin.getLogger().info(p.toString() + ":" + p.getDamageValue()); } } else { String materialList = ""; boolean hint = false; for (Material m : Material.values()) { materialList += m.toString() + ","; if (m.toString().contains(s.substring(0, 3))) { plugin.getLogger().severe("Did you mean " + m.toString() + "?"); hint = true; } } if (!hint) { plugin.getLogger() .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:"); plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1)); } else { plugin.getLogger().severe("Correct challenges.yml with the correct material."); } return false; } return false; } } else if (part.length == 6) { //plugin.getLogger().info("DEBUG:6 part potion check!"); // POTION:Name:Level:Extended:Splash:Qty try { if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[5]); ItemStack item = new ItemStack(reqItem); int count = reqAmount; // Compare if (reqItem == Material.POTION) { //plugin.getLogger().info("DEBUG: required item is a potion"); ItemStack[] playerInv = player.getInventory().getContents(); for (ItemStack i : playerInv) { if (i != null && i.getType().equals(Material.POTION)) { //plugin.getLogger().info("DEBUG: Item in inventory = " + i.toString()); Potion p = fromDamage(i.getDurability()); // Check type //Potion p = Potion.fromItemStack(i); //plugin.getLogger().info("DEBUG: " + p.getType() + ":" + p.getLevel() + ":" + p.hasExtendedDuration() + ":" + p.isSplash() ); // Check type PotionType typeCheck = PotionType.valueOf(part[1].toUpperCase()); //plugin.getLogger().info("DEBUG: potion type is:" + p.getType().toString() + " desired is:" + part[1].toUpperCase()); //if (p.getType().toString().equalsIgnoreCase(part[1].toUpperCase())) { if (p.getType().equals(typeCheck)) { //plugin.getLogger().info("DEBUG: potion type is the same"); // Check level //plugin.getLogger().info("DEBUG: check level " + part[2] + " = " + p.getLevel()); if (part[2].isEmpty() || p.getLevel() == Integer.valueOf(part[2])) { //plugin.getLogger().info("DEBUG: level is ok "); //plugin.getLogger().info("DEBUG: check splash = " + part[4] + " = " + p.isSplash()); if (part[4].isEmpty() || (p.isSplash() && part[4].equalsIgnoreCase("SPLASH")) || (!p.isSplash() && part[4].equalsIgnoreCase("NOSPLASH"))) { //plugin.getLogger().info("DEBUG: splash is ok = " + part[4] + " = " + p.isSplash()); //plugin.getLogger().info("DEBUG: check extended = " + part[4] + " = " + p.hasExtendedDuration()); if (part[3].isEmpty() || (p.hasExtendedDuration() && part[3].equalsIgnoreCase("EXTENDED")) || (!p.hasExtendedDuration() && part[3].equalsIgnoreCase("NOTEXTENDED"))) { //plugin.getLogger().info("DEBUG: Everything is matching"); item = i.clone(); if (item.getAmount() > reqAmount) { item.setAmount(reqAmount); } count = count - item.getAmount(); toBeRemoved.add(item); } } } } } if (count <= 0) { break; } } if (count > 0) { return false; } } else { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); } } catch (Exception e) { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); //e.printStackTrace(); player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady); if (part[0].equalsIgnoreCase("POTION")) { plugin.getLogger().severe( "Format POTION:NAME:<LEVEL>:<EXTENDED/NOTEXTENDED>:<SPLASH/NOSPLASH>:QTY"); plugin.getLogger().severe("LEVEL, EXTENDED and SPLASH are optional"); plugin.getLogger().severe("LEVEL is a number"); plugin.getLogger().severe("Examples:"); plugin.getLogger().severe("POTION:STRENGTH:1:EXTENDED:SPLASH:1"); plugin.getLogger().severe("POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1"); plugin.getLogger().severe("POTION:WEAKNESS::::1 - any weakness potion"); plugin.getLogger().severe("Available names are:"); String potionNames = ""; for (PotionType p : PotionType.values()) { potionNames += p.toString() + ", "; } plugin.getLogger().severe(potionNames.substring(0, potionNames.length() - 2)); } return false; } } } // Build up the items in the inventory and remove them if they are // all there. if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) { // checkChallengeItems(player, challenge); // int qty = 0; // plugin.getLogger().info("DEBUG: Removing items"); for (ItemStack i : toBeRemoved) { // qty += i.getAmount(); // plugin.getLogger().info("DEBUG: Remove " + i.toString() + // "::" + i.getDurability() + " x " + i.getAmount()); HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i); if (!leftOver.isEmpty()) { plugin.getLogger().warning("Exploit? Could not remove the following in challenge " + challenge + " for player " + player.getName() + ":"); for (ItemStack left : leftOver.values()) { plugin.getLogger().info(left.toString()); } return false; } } // Remove money if (moneyReq > 0D) { EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq); if (!er.transactionSuccess()) { plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq) + " from " + player.getName() + " in challenge " + challenge); plugin.getLogger().warning("Player's balance is " + VaultHelper.econ.format(VaultHelper.econ.getBalance(player))); } } // plugin.getLogger().info("DEBUG: total = " + qty); } return true; } if (type.equalsIgnoreCase("island")) { final HashMap<Material, Integer> neededItem = new HashMap<Material, Integer>(); final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>(); for (int i = 0; i < reqList.length; i++) { final String[] sPart = reqList[i].split(":"); // Parse the qty required first try { final int qty = Integer.parseInt(sPart[1]); // Find out if the needed item is a Material or an Entity boolean isEntity = false; for (EntityType entityType : EntityType.values()) { if (entityType.toString().equalsIgnoreCase(sPart[0])) { isEntity = true; break; } } if (isEntity) { // plugin.getLogger().info("DEBUG: Item " + // sPart[0].toUpperCase() + " is an entity"); EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase()); if (entityType != null) { neededEntities.put(entityType, qty); // plugin.getLogger().info("DEBUG: Needed entity is " // + Integer.parseInt(sPart[1]) + " x " + // EntityType.valueOf(sPart[0].toUpperCase()).toString()); } } else { Material item; if (StringUtils.isNumeric(sPart[0])) { item = Material.getMaterial(Integer.parseInt(sPart[0])); } else { item = Material.getMaterial(sPart[0].toUpperCase()); } if (item != null) { neededItem.put(item, qty); // plugin.getLogger().info("DEBUG: Needed item is " // + Integer.parseInt(sPart[1]) + " x " + // Material.getMaterial(sPart[0]).toString()); } else { plugin.getLogger().warning("Problem parsing required item for challenge " + challenge + " in challenges.yml!"); return false; } } } catch (Exception intEx) { plugin.getLogger().warning("Problem parsing required items for challenge " + challenge + " in challenges.yml - skipping"); return false; } } // We now have two sets of required items or entities // Check the items first final Location l = player.getLocation(); // if (!neededItem.isEmpty()) { final int px = l.getBlockX(); final int py = l.getBlockY(); final int pz = l.getBlockZ(); for (int x = -10; x <= 10; x++) { for (int y = -10; y <= 10; y++) { for (int z = -10; z <= 10; z++) { final Material b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getType(); if (neededItem.containsKey(b)) { if (neededItem.get(b) == 1) { neededItem.remove(b); } else { // Reduce the require amount by 1 neededItem.put(b, neededItem.get(b) - 1); } } } } } // } // Check if all the needed items have been amassed if (!neededItem.isEmpty()) { // plugin.getLogger().info("DEBUG: Insufficient items around"); for (Material missing : neededItem.keySet()) { player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededItem.get(missing) + " x " + Util.prettifyText(missing.toString())); } return false; } else { // plugin.getLogger().info("DEBUG: Items are there"); // Check for needed entities for (Entity entity : player.getNearbyEntities(10, 10, 10)) { // plugin.getLogger().info("DEBUG: Entity found:" + // entity.getType().toString()); if (neededEntities.containsKey(entity.getType())) { // plugin.getLogger().info("DEBUG: Entity in list"); if (neededEntities.get(entity.getType()) == 1) { neededEntities.remove(entity.getType()); // plugin.getLogger().info("DEBUG: Entity qty satisfied"); } else { neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1); // plugin.getLogger().info("DEBUG: Entity qty reduced by 1"); } } else { // plugin.getLogger().info("DEBUG: Entity not in list"); } } if (neededEntities.isEmpty()) { return true; } else { for (EntityType missing : neededEntities.keySet()) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString())); } return false; } } } return true; }
From source file:es.caib.seycon.ng.servei.AutoritzacioServiceImpl.java
protected Collection<AutoritzacioRol> handleGetDescriptionUserAuthorizations(String codiUsuari) throws Exception { Collection autoritzacionsRolUsuari = handleGetUserAuthorizations(codiUsuari); // IMPORTANT: la seva clau es el nom del rol + codiAutoritzacio + // descripci [valor_domini] HashMap<String, AutoritzacioRol> autoritzacionsSenseRepeticions = new HashMap(); // Afegim informaci addicional: if (autoritzacionsRolUsuari != null) { for (Iterator it = autoritzacionsRolUsuari.iterator(); it.hasNext();) { AutoritzacioRol auto = (AutoritzacioRol) it.next(); AutoritzacioSEU autoSEU = (AutoritzacioSEU) getAuthorizations().get(auto.getAutoritzacio()); if (autoSEU != null) { // formategem els valor de domini String valorDominiUsuari = ""; //$NON-NLS-1$ if (auto.getValorDominiRolUsuari() != null && auto.getValorDominiRolUsuari().size() > 0) { HashSet valors = new HashSet(); for (Iterator vit = auto.getValorDominiRolUsuari().iterator(); vit.hasNext();) { ValorDomini vd = (ValorDomini) vit.next(); valors.add(vd.getValor()); }//w ww . j a v a 2 s. co m if (valors.size() == 1 && valors.contains("*")) //$NON-NLS-1$ ; else valorDominiUsuari = " " + valors.toString(); //$NON-NLS-1$ } auto.setDescripcio(autoSEU.getDescripcio() //$NON-NLS-1$ + valorDominiUsuari); auto.setTipusDomini(autoSEU.getTipusDomini()); auto.setScope(autoSEU.getScope()); auto.setAmbit(autoSEU.getAmbit()); auto.setHereta(autoSEU.getHereta()); // separat per comes autoritzacionsSenseRepeticions .put(auto.getRol().getNom() + auto.getAutoritzacio() + auto.getDescripcio(), auto); } } // Les ordenem LinkedList autosOrdenades = new LinkedList(autoritzacionsSenseRepeticions.values()); Collections.sort(autosOrdenades, new ComparaAutos()); return autosOrdenades; } return autoritzacionsSenseRepeticions.values(); }
From source file:hydrograph.ui.graph.editor.JobDeleteParticipant.java
@Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { final HashMap<IFile, DeleteResourceChange> changes = new HashMap<IFile, DeleteResourceChange>(); if (modifiedResource.getParent() != null) { List<IResource> iResources = new ArrayList<IResource>(); if ((modifiedResource.getProjectRelativePath() != null && StringUtils.equalsIgnoreCase( modifiedResource.getProjectRelativePath().segment(0), CustomMessages.ProjectSupport_JOBS)) || StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(), CustomMessages.ProjectSupport_PARAM)) { List<IResource> memberList = new ArrayList<IResource>(modifiedResource.getProject() .getFolder(CustomMessages.ProjectSupport_PARAM).members().length + getJobsFolderMembers(iResources, modifiedResource.getProject() .getFolder(CustomMessages.ProjectSupport_JOBS).members()).size()); ResourceChangeUtil.addMembersToList(memberList, modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_JOBS)); ResourceChangeUtil.addMembersToList(memberList, modifiedResource.getProject().getFolder(CustomMessages.ProjectSupport_PARAM)); final String fileName = ResourceChangeUtil.removeExtension(modifiedResource.getName()); for (IResource resource : memberList) { //check particular job name exists into list for job deletion if (fileName.equals(resource.getName().replaceAll(Regex, ""))) { if ((StringUtils.equalsIgnoreCase(Messages.XML_EXT, resource.getFileExtension()) || StringUtils.equalsIgnoreCase(Messages.PROPERTIES_EXT, resource.getFileExtension()) || StringUtils.equalsIgnoreCase(Messages.JOB_EXT, resource.getFileExtension())) && !(StringUtils.equalsIgnoreCase(modifiedResource.getName(), resource.getName()))) { getDeleteChanges(changes, resource); }// w w w . j a v a 2 s .com } } } } if (changes.isEmpty()) { return null; } CompositeChange result = new CompositeChange("Delete Job Related Files"); for (Iterator<DeleteResourceChange> iter = changes.values().iterator(); iter.hasNext();) { result.add((Change) iter.next()); } return result; }
From source file:edu.ku.brc.specify.ui.LoanReturnDlg.java
/** * @return//from w w w.j a va2 s . c o m */ public boolean createUI() { DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance().createSession(); loan = session.merge(loan); setTitle(getResourceString("LOANRET_TITLE")); validator.addValidationListener(new ValidationListener() { public void wasValidated(UIValidator val) { doEnableOKBtn(); } }); JPanel contentPanel = new JPanel(new BorderLayout()); JPanel mainPanel = new JPanel(); System.out.println("Num Loan Preps for Loan: " + loan.getLoanPreparations()); HashMap<Integer, Pair<CollectionObject, Vector<LoanPreparation>>> colObjHash = new HashMap<Integer, Pair<CollectionObject, Vector<LoanPreparation>>>(); for (LoanPreparation loanPrep : loan.getLoanPreparations()) { CollectionObject colObj = loanPrep.getPreparation().getCollectionObject(); System.out.println("For LoanPrep ColObj Is: " + colObj.getIdentityTitle()); Vector<LoanPreparation> list = null; Pair<CollectionObject, Vector<LoanPreparation>> pair = colObjHash.get(colObj.getId()); if (pair == null) { list = new Vector<LoanPreparation>(); colObjHash.put(colObj.getId(), new Pair<CollectionObject, Vector<LoanPreparation>>(colObj, list)); } else { list = pair.second; } list.add(loanPrep); } int colObjCnt = colObjHash.size(); String rowDef = UIHelper.createDuplicateJGoodiesDef("p", "1px,p,4px", (colObjCnt * 2) - 1); PanelBuilder pbuilder = new PanelBuilder(new FormLayout("f:p:g", rowDef), mainPanel); CellConstraints cc = new CellConstraints(); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent ae) { doEnableOKBtn(); } }; ChangeListener cl = new ChangeListener() { public void stateChanged(ChangeEvent ae) { doEnableOKBtn(); } }; int i = 0; int y = 1; Vector<Pair<CollectionObject, Vector<LoanPreparation>>> pairList = new Vector<Pair<CollectionObject, Vector<LoanPreparation>>>( colObjHash.values()); Collections.sort(pairList, new Comparator<Pair<CollectionObject, Vector<LoanPreparation>>>() { @Override public int compare(Pair<CollectionObject, Vector<LoanPreparation>> o1, Pair<CollectionObject, Vector<LoanPreparation>> o2) { return o1.first.getIdentityTitle().compareTo(o2.first.getIdentityTitle()); } }); for (Pair<CollectionObject, Vector<LoanPreparation>> pair : pairList) { CollectionObject co = pair.first; if (i > 0) { pbuilder.addSeparator("", cc.xy(1, y)); y += 2; } ColObjPanel panel = new ColObjPanel(session, this, co, colObjHash.get(co.getId()).second); colObjPanels.add(panel); panel.addActionListener(al, cl); pbuilder.add(panel, cc.xy(1, y)); y += 2; i++; } JButton selectAllBtn = createButton(getResourceString("SELECTALL")); okBtn = createButton(getResourceString("SAVE")); JButton cancel = createButton(getResourceString("CANCEL")); PanelBuilder pb = new PanelBuilder(new FormLayout("p,2px,p,2px,p,2px,p,2px,p,2px,p", "p")); dateClosed = new ValFormattedTextFieldSingle("Date", false, false, 10); dateClosed.setNew(true); dateClosed.setValue(null, ""); dateClosed.setRequired(true); validator.hookupTextField(dateClosed, "2", true, UIValidator.Type.Changed, "", false); summaryLabel = createLabel(""); pb.add(summaryLabel, cc.xy(1, 1)); pb.add(createI18NLabel("LOANRET_AGENT"), cc.xy(3, 1)); pb.add(agentCBX = createAgentCombobox(), cc.xy(5, 1)); pb.add(createI18NLabel("ON"), cc.xy(7, 1)); pb.add(dateClosed, cc.xy(9, 1)); contentPanel.add(pb.getPanel(), BorderLayout.NORTH); contentPanel.add(new JScrollPane(mainPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)); JPanel p = new JPanel(new BorderLayout()); p.setBorder(BorderFactory.createEmptyBorder(5, 0, 2, 0)); p.add(ButtonBarFactory.buildOKCancelApplyBar(okBtn, cancel, selectAllBtn), BorderLayout.CENTER); contentPanel.add(p, BorderLayout.SOUTH); contentPanel.setBorder(BorderFactory.createEmptyBorder(4, 12, 2, 12)); setContentPane(contentPanel); doEnableOKBtn(); //setIconImage(IconManager.getIcon("Preparation", IconManager.IconSize.Std16).getImage()); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); doEnableOKBtn(); okBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { setVisible(false); isCancelled = false; } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { setVisible(false); } }); selectAllBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { selectAllItems(); } }); pack(); Dimension size = getPreferredSize(); size.width += 20; size.height = size.height > 500 ? 500 : size.height; setSize(size); return true; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LoanReturnDlg.class, ex); // Error Dialog ex.printStackTrace(); } finally { if (session != null) { session.close(); } } return false; }
From source file:org.agnitas.web.NewImportWizardAction.java
/** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed.<br>//from w w w . j a va 2 s .c o m * Error and success messages are set during the action to give the user * a feedback in the forwarded web component.<br> * <br> * ACTION_START: Loads the list of all available profiles for import and ID of default import profile for current user.<br> * Resets import status and resultPagePrepared property of form. Forwards to "start". * <br><br> * ACTION_PREVIEW: performs general validation before starting recipients import.<br> * Initializes import helper with initial values; <br> * Created unique import ID and sets it to import profile; <br> * If csv-file is missing or there are no import profiles in system - forwards to "start" with corresponding * error messages.<br> * If import profile doesn't match the csv-file or has no key column in its column mappings forwards to * "profile_edit" with corresponding error messages.<br> * If validation is passed loads first 20 recipients from csv-file for preview, loads mailinglists into form, * chooses mailinglist message according to import mode, forwards to "preview".<br> * If the session parameter "IMPORT_KEY_COLUMNS" is set - import ignores key column from import profile and uses * list of key columns from "IMPORT_KEY_COLUMNS" (example "email, firstname, lastname"). The values from this * session parameter is set to import profile. * <br><br> * ACTION_PROCEED:<br> * In general performs recipient import using settings from selected import profile.<br><br> * If the FutureHolder doesn't contain yet the recipient import worker:<br> * Checks if there are mailinglists selected. If the current import mode needs mailinglists and no list is * selected - forwards to "preview" with appropriate error message. Stores the list of mailinglists to assign in * form. Creates import recipient worker and puts it to FutureHolder. Stores import parameters (importMode, * separator, delimiter etc.) to status property of form.<br><br> * If FutureHolder is finished and there are errors for edit error page - forwards to error editing page and * also checks for import limits.<br><br> * If FutureHolder is finished and there are no errors for edit error page: puts worker for assigning * mailinglists into FutureHolder (and forwards to "progress"), if that FutureHolder is finished - removes * temporary table of import recipients from DB, removes stored csv, forwards to "result_page"; if it is still * running - increases refresh rate and forwards to "progress". Also checks for import limits.<br><br> * If FutureHolder is still running - increases refresh time and forwards to "progress"<br><br> * If there were errors during the import - removed the recipient import worker from the FutureHolder and * forwards to "preview" page with error messages. * <br><br> * ACTION_ERROR_EDIT: * If the FutureHolder doesn't have task running and there's attribute "recipientsInCurrentTable" in request - * validates recipient fixed on error edit page and performs the import for fixed recipients.<br> * If there are still errors for error-edit-page - forwards to error-edit page. If there are no errors left - * prepares result page: calls future holder for assigning mailing lists and forwards to "progress" or * "result_page" depending on FutureHolder finished or not. * <br><br> * ACTION_MLISTS: puts worker for assigning mailinglists into FutureHolder (and forwards to "progress"), if that * FutureHolder is finished - removes temporary table of import recipients from DB, removes stored csv, * forwards to "result_page"; if it is still running - increases refresh rate and forwards to "progress". * <br><br> * ACTION_DOWNLOAD_CSV_FILE: checks what type of file user wants to download. Gets the file depending on that type. * Writes that file to response (for user to download). Forwards to null destination. * <br><br> * Any other ACTION_* would cause a forward to null * <br><br> * If current destination is "error_edit":<br> * If the FutureHolder is not running yet - puts there a worker for getting invalid recipients from temporary table * containing beans of import-recipients from csv-file<br> * If the FutureHolder is not finished yet - increases refresh time and forwards to "loading"<br> * If FutureHolder is finished - puts found invalid recipients to request and to session attribute * "recipientsInCurrentTable", sets the total number of invalid recipients to form, removes current task from * FutureHolder * <br><br> * @param form data for the action filled by the jsp * @param req request from jsp <br> * If the request parameter "start_proceed" is set - changes action to ACTION_PREVIEW.<br> * If the request parameter "preview_back" is set - changes action to ACTION_START.<br> * If the request parameter "preview_proceed" is set - changes action to ACTION_PROCEED.<br> * If the request parameter "edit_page_save" is set - changes action to ACTION_ERROR_EDIT.<br> * @param res response * @param mapping * The ActionMapping used to select this instance * @exception IOException * if an input/output error occurs * @exception ServletException * if a servlet exception occurs * @return destination specified in struts-config.xml to forward to next jsp */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { super.execute(mapping, form, req, res); AbstractMap<String, Object> futureHolder = (AbstractMap<String, Object>) getBean("futureHolder"); String futureKeyList = FUTURE_TASK1 + "@" + req.getSession(false).getId(); String futureKeyProcess = FUTURE_TASK2 + "@" + req.getSession(false).getId(); String futureKeyWorker = FUTURE_TASK3 + "@" + req.getSession(false).getId(); // Validate the request parameters specified by the user NewImportWizardForm aForm = null; ActionMessages errors = new ActionMessages(); ActionForward destination = null; ApplicationContext aContext = this.getWebApplicationContext(); if (!AgnUtils.isUserLoggedIn(req)) { return mapping.findForward("logon"); } if (form != null) { aForm = (NewImportWizardForm) form; } else { aForm = new NewImportWizardForm(); } if (logger.isInfoEnabled()) logger.info("NewImportWizard action: " + aForm.getAction()); if (AgnUtils.parameterNotEmpty(req, "start_proceed")) { aForm.setAction(NewImportWizardAction.ACTION_PREVIEW); } if (AgnUtils.parameterNotEmpty(req, "preview_back")) { aForm.setAction(NewImportWizardAction.ACTION_START); } if (AgnUtils.parameterNotEmpty(req, "preview_proceed")) { aForm.setAction(NewImportWizardAction.ACTION_PROCEED); } if (req.getParameter("edit_page_save") != null) { aForm.setAction(NewImportWizardAction.ACTION_ERROR_EDIT); } if (!allowed("wizard.import", req)) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied")); saveErrors(req, errors); return null; } try { NewImportWizardService importWizardHelper = aForm.getImportWizardHelper(); switch (aForm.getAction()) { case NewImportWizardAction.ACTION_START: final Map<Integer, String> importProfiles = new HashMap<Integer, String>(); aForm.setDefaultProfileId(AgnUtils.getAdmin(req).getDefaultImportProfileID()); final List<ImportProfile> importProfileList = getProfileList(req); for (ImportProfile importProfile : importProfileList) { importProfiles.put(importProfile.getId(), importProfile.getName()); } aForm.setImportProfiles(importProfiles); aForm.setStatus((CustomerImportStatus) getWebApplicationContext().getBean("CustomerImportStatus")); destination = mapping.findForward("start"); aForm.setResultPagePrepared(false); break; case NewImportWizardAction.ACTION_PREVIEW: if (!aForm.getHasFile() && (aForm.getCsvFile() == null || StringUtils.isEmpty(aForm.getCsvFile().getFileName()))) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.import.no_file")); destination = mapping.findForward("start"); } else if (aForm.getImportProfiles().size() == 0) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.import.no_profile")); destination = mapping.findForward("start"); } else { boolean profileFits = initImportWizardHelper(req, aForm, errors); boolean keyColumnValid = isProfileKeyColumnValid(aForm, errors); logImportStart(aForm); if ((!profileFits || !keyColumnValid) && !errors.isEmpty()) { HttpSession session = req.getSession(); session.setAttribute(ImportProfileAction.IMPORT_PROFILE_ERRORS_KEY, errors); session.setAttribute(ImportProfileAction.IMPORT_PROFILE_ID_KEY, aForm.getDefaultProfileId()); destination = mapping.findForward("profile_edit"); } else if (!errors.isEmpty()) { destination = mapping.findForward("start"); } else { aForm.setPreviewParsedContent(importWizardHelper.getPreviewParsedContent(errors)); if (!errors.isEmpty()) { destination = mapping.findForward("start"); break; } aForm.setAllMailingLists(getAllMailingLists(req)); aForm.setMailinglistAddMessage(createMailinglistAddMessage(aForm)); destination = mapping.findForward("preview"); } } break; case NewImportWizardAction.ACTION_PROCEED: aForm.setAction(NewImportWizardAction.ACTION_PROCEED); destination = mapping.findForward("progress"); if (!futureHolder.containsKey(futureKeyProcess) && aForm.getErrorsDuringImport() == null) { List<Integer> assignedLists = getAssignedMailingLists(req, aForm); if (!ignoreEmptyAssignedList()) { int importMode = aForm.getImportWizardHelper().getImportProfile().getImportMode(); if ((importMode == ImportMode.ADD.getIntValue() || importMode == ImportMode.ADD_AND_UPDATE.getIntValue()) && assignedLists.size() == 0) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.import.no_mailinglist")); destination = mapping.findForward("preview"); break; } } aForm.setListsToAssign(assignedLists); final ImportRecipientsProcessWorker worker = new ImportRecipientsProcessWorker( importWizardHelper); ImportProfile importProfile = aForm.getImportWizardHelper().getImportProfile(); futureHolder.put(futureKeyProcess, importRecipientsProcess(aForm, req, aContext, worker, importProfile)); futureHolder.put(futureKeyWorker, worker); String charset = Charset.getPublicValue(importProfile.getCharset()); String separator = Separator.getValue(importProfile.getSeparator()); int mode = importProfile.getImportMode(); int doublette = importProfile.getCheckForDuplicates(); int nullValues = importProfile.getNullValuesAction(); String recognitionChar = TextRecognitionChar.getValue(importProfile.getTextRecognitionChar()); aForm.getStatus().setCharset(charset); aForm.getStatus().setSeparator(separator); aForm.getStatus().setMode(mode); aForm.getStatus().setDoubleCheck(doublette); aForm.getStatus().setIgnoreNull(nullValues); aForm.getStatus().setDelimiter(recognitionChar); } if (aForm.getErrorsDuringImport() != null) { errors.add(aForm.getErrorsDuringImport()); destination = mapping.findForward("preview"); futureHolder.remove(futureKeyProcess); futureHolder.remove(futureKeyWorker); aForm.setRefreshMillis(RecipientForm.DEFAULT_REFRESH_MILLIS); aForm.setErrorsDuringImport(null); break; } if (futureHolder.containsKey(futureKeyWorker) && futureHolder.get(futureKeyWorker) != null) { final ActionMessage message = ((ImportRecipientsProcessWorker) futureHolder .get(futureKeyWorker)).getMessage(); if (message != null) { errors.add(ActionMessages.GLOBAL_MESSAGE, message); futureHolder.remove(futureKeyProcess); futureHolder.remove(futureKeyWorker); aForm.setRefreshMillis(RecipientForm.DEFAULT_REFRESH_MILLIS); destination = mapping.findForward("preview"); break; } } if (futureHolder.containsKey(futureKeyProcess) && ((Future) futureHolder.get(futureKeyProcess)).isDone()) { futureHolder.remove(futureKeyProcess); futureHolder.remove(futureKeyWorker); if (importWizardHelper.isPresentErrorForErrorEditPage()) { destination = mapping.findForward("error_edit"); } else { destination = prepareResultPage(mapping, req, aForm, futureHolder, futureKeyProcess); } destination = checkImportLimits(mapping, errors, destination, importWizardHelper, aForm, req, futureHolder, futureKeyProcess); if ("start".equals(destination.getName())) { futureHolder.remove(futureKeyProcess); futureHolder.remove(futureKeyWorker); } aForm.setRefreshMillis(RecipientForm.DEFAULT_REFRESH_MILLIS); } else { if (aForm.getRefreshMillis() < 100000) { // raise the refresh time aForm.setRefreshMillis(aForm.getRefreshMillis() + 50); } //aForm.set } break; case NewImportWizardAction.ACTION_ERROR_EDIT: if (!futureHolder.containsKey(futureKeyList) && (PaginatedList) req.getSession().getAttribute("recipientsInCurrentTable") != null) { final HashMap<String, ProfileRecipientFields> mapRecipientsFromTable = new HashMap<String, ProfileRecipientFields>(); final PaginatedList recipientsFromTable = (PaginatedList) req.getSession() .getAttribute("recipientsInCurrentTable"); for (Object object : recipientsFromTable.getList()) { final Map dynaBean = (Map) object; final ProfileRecipientFields recipient = (ProfileRecipientFields) dynaBean .get(NewImportWizardService.ERROR_EDIT_RECIPIENT_EDIT_RESERVED); mapRecipientsFromTable.put(recipient.getTemporaryId(), recipient); } final Map<String, String> changedRecipients = getChangedRecipients(req); for (String key : changedRecipients.keySet()) { final String temporaryId = key.substring(0, key.indexOf("/RESERVED/")); final String propertyName = key.substring(key.indexOf("/RESERVED/") + 10, key.length()); final ProfileRecipientFields recipient = mapRecipientsFromTable.get(temporaryId); Toolkit.setValueFromBean(recipient, propertyName, changedRecipients.get(key)); } importWizardHelper.setBeansAfterEditOnErrorEditPage( new ArrayList<ProfileRecipientFields>(mapRecipientsFromTable.values())); importWizardHelper.doValidate(true); } if (importWizardHelper.isPresentErrorForErrorEditPage()) { destination = mapping.findForward("error_edit"); } else { destination = prepareResultPage(mapping, req, aForm, futureHolder, futureKeyProcess); } destination = checkImportLimits(mapping, errors, destination, importWizardHelper, aForm, req, futureHolder, futureKeyProcess); break; case NewImportWizardAction.ACTION_MLISTS: destination = prepareResultPage(mapping, req, aForm, futureHolder, futureKeyProcess); break; case NewImportWizardAction.ACTION_DOWNLOAD_CSV_FILE: File outfile = null; if (aForm.getDownloadFileType() == NewImportWizardService.RECIPIENT_TYPE_VALID) { outfile = aForm.getValidRecipientsFile(); } else if (aForm.getDownloadFileType() == NewImportWizardService.RECIPIENT_TYPE_INVALID) { outfile = aForm.getInvalidRecipientsFile(); } else if (aForm.getDownloadFileType() == NewImportWizardService.RECIPIENT_TYPE_FIXED_BY_HAND) { outfile = aForm.getFixedRecipientsFile(); } else if (aForm .getDownloadFileType() == NewImportWizardService.RECIPIENT_TYPE_DUPLICATE_RECIPIENT) { outfile = aForm.getDuplicateRecipientsFile(); } else if (aForm.getDownloadFileType() == NewImportWizardService.RESULT_TYPE) { outfile = aForm.getResultFile(); } transferFile(res, errors, outfile); destination = null; break; } } catch (Exception e) { logger.error("execute: " + e + "\n" + AgnUtils.getStackTrace(e)); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception")); } if (destination != null && "error_edit".equals(destination.getName())) { try { setNumberOfRows(req, aForm); destination = mapping.findForward("loading"); if (!futureHolder.containsKey(futureKeyList)) { futureHolder.put(futureKeyList, getRecipientListFuture(req, aContext, aForm)); } if (futureHolder.containsKey(futureKeyList) && ((Future) futureHolder.get(futureKeyList)).isDone()) { req.setAttribute("recipientList", ((Future) futureHolder.get(futureKeyList)).get()); req.getSession().setAttribute("recipientsInCurrentTable", ((Future) futureHolder.get(futureKeyList)).get()); destination = mapping.findForward("error_edit"); aForm.setAll( ((PaginatedList) ((Future) futureHolder.get(futureKeyList)).get()).getFullListSize()); futureHolder.remove(futureKeyList); aForm.setRefreshMillis(RecipientForm.DEFAULT_REFRESH_MILLIS); } else { if (aForm.getRefreshMillis() < 1000) { // raise the refresh time aForm.setRefreshMillis(aForm.getRefreshMillis() + 50); } aForm.setError(false); } } catch (Exception e) { logger.error("recipientList: " + e + "\n" + AgnUtils.getStackTrace(e)); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception")); aForm.setError(true); // do not refresh when an error has been occurred } } // Report any errors we have discovered back to the original form if (!errors.isEmpty() && destination != null) { saveErrors(req, errors); if (destination.getName().equals("progress")) { aForm.setErrorsDuringImport(errors); } // return new ActionForward(mapping.getForward()); } return destination; }
From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java
private Collection<MoleculeEntry> getUniprotEntriesXML(String location, boolean waitAndRetryOnFailure) throws BridgesRemoteAccessException { String url = location + "&format=xml"; ArrayList<MoleculeEntry> uniprotEntries = new ArrayList<>(); try {//from w ww . j a v a 2 s . c om HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE); HttpGet request = new HttpGet(url); // add request header request.addHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(request); if (response.getEntity().getContentLength() == 0) { // No result return uniprotEntries; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(response.getEntity().getContent())); // optional, but recommended // read this - // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); // interaction structure NodeList entryList = doc.getElementsByTagName("entry"); for (int i = 0; i < entryList.getLength(); i++) { Element entryElement = (Element) entryList.item(i); String dataset = entryElement.getAttribute("dataset"); String ac = entryElement.getElementsByTagName("accession").item(0).getFirstChild().getNodeValue(); MoleculeEntry uniprotEntry = new MoleculeEntry(ac); uniprotEntry.setDataset(dataset); // Taxid Element organism = (Element) entryElement.getElementsByTagName("organism").item(0); String organismCommonName = null; String organismScientificName = null; String organismOtherName = null; NodeList organismNames = organism.getElementsByTagName("name"); for (int j = 0; j < organismNames.getLength(); j++) { Element reference = (Element) organismNames.item(j); switch (reference.getAttribute("type")) { case "scientific": organismScientificName = reference.getTextContent(); break; case "common": organismCommonName = reference.getTextContent(); break; default: organismOtherName = reference.getTextContent(); break; } } if (null != organismCommonName) { uniprotEntry.setOrganism(organismCommonName); } else if (null != organismScientificName) { uniprotEntry.setOrganism(organismScientificName); } else if (null != organismOtherName) { uniprotEntry.setOrganism(organismOtherName); } NodeList organismReferences = organism.getElementsByTagName("dbReference"); for (int j = 0; j < organismReferences.getLength(); j++) { Element reference = (Element) organismReferences.item(j); if (reference.hasAttribute("type") && "NCBI Taxonomy".equals(reference.getAttribute("type"))) { String proteinTaxid = reference.getAttribute("id"); uniprotEntry.setTaxid(proteinTaxid); } } // GENE NodeList geneNames = entryElement.getElementsByTagName("gene"); for (int j = 0; j < geneNames.getLength(); j++) { Element gene = (Element) geneNames.item(j); NodeList nameList = gene.getElementsByTagName("name"); for (int k = 0; k < nameList.getLength(); k++) { Element name = (Element) nameList.item(k); uniprotEntry.addGeneName(name.getFirstChild().getNodeValue()); } } // modified residues HashMap<String, ModifiedResidue> modifiedResidues = new HashMap<>(); NodeList features = entryElement.getElementsByTagName("feature"); for (int j = 0; j < features.getLength(); j++) { Element feature = (Element) features.item(j); if (false == entryElement.equals(feature.getParentNode())) { continue; } // ensembl if (feature.hasAttribute("type") && "modified residue".equals(feature.getAttribute("type"))) { String description = feature.getAttribute("description").split(";")[0]; if (false == modifiedResidues.containsKey(description)) { modifiedResidues.put(description, new ModifiedResidue(description)); } NodeList locations = feature.getElementsByTagName("location"); for (int k = 0; k < locations.getLength(); k++) { Element loc = (Element) locations.item(k); NodeList positions = loc.getElementsByTagName("position"); for (int l = 0; l < positions.getLength(); l++) { Element position = (Element) positions.item(l); modifiedResidues.get(description).addPosition( new UniprotPosition(Integer.parseInt(position.getAttribute("position")))); } } } } uniprotEntry.getModifications().addAll(modifiedResidues.values()); // Xrefs: NodeList dbReferences = entryElement.getElementsByTagName("dbReference"); for (int j = 0; j < dbReferences.getLength(); j++) { Element dbReference = (Element) dbReferences.item(j); if (false == entryElement.equals(dbReference.getParentNode())) { continue; } NodeList molecules = dbReference.getElementsByTagName("molecule"); // ensembl if (dbReference.hasAttribute("type") && "Ensembl".equals(dbReference.getAttribute("type"))) { // transcript ID String id = dbReference.getAttribute("id"); for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) { Element molecule = (Element) molecules.item(iMolecule); uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id")); } uniprotEntry.addEnsemblGene(id); NodeList properties = dbReference.getElementsByTagName("property"); for (int k = 0; k < properties.getLength(); k++) { Element property = (Element) properties.item(k); if (property.hasAttribute("type") && "gene ID".equals(property.getAttribute("type"))) { uniprotEntry.addEnsemblGene(property.getAttribute("value")); } } } // refseq if (dbReference.hasAttribute("type") && "RefSeq".equals(dbReference.getAttribute("type"))) { NodeList properties = dbReference.getElementsByTagName("property"); for (int k = 0; k < properties.getLength(); k++) { Element property = (Element) properties.item(k); if (property.hasAttribute("type") && "nucleotide sequence ID".equals(property.getAttribute("type"))) { String id = property.getAttribute("value"); if (molecules.getLength() > 0) { for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) { Element molecule = (Element) molecules.item(iMolecule); // If refseq, add also without the version uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id")); uniprotEntry.addXrefToVarSplice(id.split("\\.")[0], molecule.getAttribute("id")); } } else { // If refseq, add also without the version uniprotEntry.addXrefToVarSplice(id, ac); uniprotEntry.addXrefToVarSplice(id.split("\\.")[0], ac); } uniprotEntry.addRefseq(id); } } } /* PDB chains will be imported from the webservice */ // PDB if (dbReference.hasAttribute("type") && "PDB".equals(dbReference.getAttribute("type"))) { NodeList properties = dbReference.getElementsByTagName("property"); String method = null; String chains = null; for (int k = 0; k < properties.getLength(); k++) { Element property = (Element) properties.item(k); if (property.hasAttribute("type") && "method".equals(property.getAttribute("type"))) { method = property.getAttribute("value"); } else if (property.hasAttribute("type") && "chains".equals(property.getAttribute("type"))) { chains = property.getAttribute("value"); } } if (method != null && "Model".equals(method)) { continue; } if (chains == null) { continue; } String pdb = dbReference.getAttribute("id"); uniprotEntry.addPDB(pdb, method); for (String chainElement : chains.split(",")) { try { String chainNames = chainElement.split("=")[0]; int start = Integer.parseInt(chainElement.split("=")[1].trim().split("-")[0]); int end = Integer .parseInt(chainElement.split("=")[1].trim().split("-")[1].replace(".", "")); for (String chainName : chainNames.split("/")) { uniprotEntry.addChain(pdb, new ChainMapping(pdb, chainName.trim(), start, end), method); } } catch (ArrayIndexOutOfBoundsException aiobe) { // IGBLogger.getInstance().warning( // "Cannot parse chain: " + chainElement // + ", skip"); } } } } // Sequence NodeList sequenceElements = entryElement.getElementsByTagName("sequence"); for (int j = 0; j < sequenceElements.getLength(); j++) { Element sequenceElement = (Element) sequenceElements.item(j); if (false == sequenceElement.getParentNode().equals(entryElement)) { continue; } String sequence = sequenceElement.getFirstChild().getNodeValue().replaceAll("\n", ""); uniprotEntry.setSequence(sequence); } // Diseases NodeList diseases = entryElement.getElementsByTagName("disease"); for (int j = 0; j < diseases.getLength(); j++) { Element disease = (Element) diseases.item(j); NodeList nameList = disease.getElementsByTagName("name"); for (int k = 0; k < nameList.getLength(); k++) { Element name = (Element) nameList.item(k); uniprotEntry.addDisease(name.getFirstChild().getNodeValue()); } } // Get fasta for all varsplice String fastaQuery = "http://www.uniprot.org/uniprot/" + uniprotEntry.getUniprotAc() + ".fasta?include=yes"; try { //HttpClient fastaClient = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE); HttpGet fastaRequest = new HttpGet(fastaQuery); // add request header request.addHeader("User-Agent", USER_AGENT); HttpResponse fastaResponse = client.execute(fastaRequest); if (fastaResponse.getEntity().getContentLength() == 0) { continue; } InputStream is = fastaResponse.getEntity().getContent(); try { LinkedHashMap<String, ProteinSequence> fasta = FastaReaderHelper .readFastaProteinSequence(is); boolean mainSequence = true; for (ProteinSequence seq : fasta.values()) { // logger.info("Add sequence: " + seq.getAccession().getID() + " : " + seq.getSequenceAsString()); uniprotEntry.addSequence(seq.getAccession().getID(), seq.getSequenceAsString()); if (mainSequence) { uniprotEntry.setMainIsoform(seq.getAccession().getID()); mainSequence = false; } } } catch (Exception e) { logger.error("Cannot retrieve fasta for : " + uniprotEntry.getUniprotAc()); } } catch (IOException | IllegalStateException ex) { logger.error(null, ex); } uniprotEntries.add(uniprotEntry); } } catch (SAXParseException se) { // Nothing was return // IGBLogger.getInstance() // .error("Uniprot returns empty result: " + url); } catch (IOException | ParserConfigurationException | IllegalStateException | SAXException | DOMException | NumberFormatException e) { if (waitAndRetryOnFailure && allowedUniprotFailures > 0) { try { allowedUniprotFailures--; Thread.sleep(5000); return getUniprotEntriesXML(location, false); } catch (InterruptedException e1) { logger.error("Fail to retrieve data from " + location); throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location); } } else { logger.error("Problem with Uniprot: " + url); throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location); } } for (MoleculeEntry entry : uniprotEntries) { addToCache(entry); } return uniprotEntries; }