List of usage examples for java.util HashMap isEmpty
public boolean isEmpty()
From source file:it.eng.spagobi.commons.presentation.tags.ListTag.java
/** * Builds Table list rows, reading all query information. * //from ww w .j a v a 2 s. c o m * @throws JspException If any Exception occurs. */ protected void makeRows() throws JspException { List rows = _content.getAttributeAsList("PAGED_LIST.ROWS.ROW"); //gets the eventual map for the checklist Map subreportMap = new HashMap(); for (int i = 0; i < rows.size(); i++) { SourceBean subreport = (SourceBean) rows.get(i); Integer id = (Integer) subreport.getAttribute("SUBREPORT_ID"); if (id != null) { logger.debug("ListTag::makeRows:request: SUBREPORT_ID = " + id); subreportMap.put(id.toString(), id); } } // js function for item action confirm _htmlStream.append(" <script>\n"); _htmlStream.append(" function actionConfirm(message, url, functionToEval){\n"); _htmlStream.append(" if (confirm(message + '?')){\n"); _htmlStream.append(" if (functionToEval) eval(functionToEval);\n"); _htmlStream.append(" location.href = url;\n"); _htmlStream.append(" }\n"); _htmlStream.append(" }\n"); _htmlStream.append(" </script>\n"); int prog = 0; for (int i = 0; i < rows.size(); i++) { prog++; SourceBean row = (SourceBean) rows.get(i); _htmlStream.append(" <tr onMouseOver=\"this.bgColor='" + rowColor + "';\" onMouseOut=\"this.bgColor='#FFFFFF';\">\n"); for (int j = 0; j < _columns.size(); j++) { String nameColumn = (String) ((SourceBean) _columns.elementAt(j)).getAttribute("NAME"); Object fieldObject = row.getAttribute(nameColumn); String field = null; if (fieldObject != null) field = fieldObject.toString(); else field = " "; // if an horizontal-align is specified it is considered, otherwise the defualt is align='left' String align = (String) ((SourceBean) _columns.elementAt(j)).getAttribute("horizontal-align"); if (align == null || align.trim().equals("")) align = "left"; if (field.equalsIgnoreCase(" ")) { _htmlStream.append(" <td>" + field + "</td>\n"); } else { _htmlStream.append(" <td>" + StringEscapeUtils.escapeHtml(field) + "</td>\n"); } } SourceBean captionsSB = (SourceBean) _layout.getAttribute("CAPTIONS"); List captions = captionsSB.getContainedSourceBeanAttributes(); Iterator iter = captions.iterator(); while (iter.hasNext()) { SourceBeanAttribute captionSBA = (SourceBeanAttribute) iter.next(); SourceBean captionSB = (SourceBean) captionSBA.getValue(); String captionName = captionSB.getName(); SourceBean conditionsSB = (SourceBean) captionSB.getAttribute("CONDITIONS"); boolean conditionsVerified = verifyConditions(conditionsSB, row); //verifies if it's a checklist String checklist = (String) captionSB.getAttribute("checkList"); boolean isChecklist = false; if (checklist != null && checklist.equalsIgnoreCase("true")) isChecklist = true; //gets the parameters for the pop up window String popupStr = (String) captionSB.getAttribute("popup"); String popupWidth = (String) captionSB.getAttribute("popupW"); String popupHeight = (String) captionSB.getAttribute("popupH"); String popupCloseRefresh = (String) captionSB.getAttribute("popupCandR"); String popupSaveStr = (String) captionSB.getAttribute("popupSave"); String popupSaveFunction = (String) captionSB.getAttribute("popupSaveFunc"); boolean popup = false; boolean popupSave = false; boolean closeRefresh = false; if (popupStr != null && popupStr.equalsIgnoreCase("true")) popup = true; if (popupSaveStr != null && popupSaveStr.equalsIgnoreCase("true")) popupSave = true; if (popupCloseRefresh != null && popupCloseRefresh.equalsIgnoreCase("true")) closeRefresh = true; if (!conditionsVerified) { // if conditions are not verified puts an empty column _htmlStream.append(" <td width='40px' > </td>\n"); continue; } // onclick function SourceBean onClickSB = (SourceBean) captionSB.getAttribute("ONCLICK"); String onClickFunction = readOnClickFunction(onClickSB, row); String onClickFunctionName = onClickSB != null ? captionSB.getName() + i + requestIdentity : null; if (onClickFunction != null) { _htmlStream.append(" <script type='text/javascript'>\n"); _htmlStream.append(" function " + onClickFunctionName + "() {\n"); _htmlStream.append(onClickFunction + "\n"); _htmlStream.append(" }\n"); _htmlStream.append(" </script>\n"); } List parameters = captionSB.getAttributeAsList("PARAMETER"); if (parameters == null || parameters.size() == 0) { // creates a checklist if (isChecklist) { // gets the value of the current row and puts it as id of the input type checkbox SourceBean rowVal = (SourceBean) captionSB.getAttribute("ROWVALUE"); String rowValue = readOnClickFunction(rowVal, row); _htmlStream.append(" <td width='20'>\n"); if (onClickFunctionName != null) { _htmlStream.append("<input onclick='" + onClickFunctionName + "()' type='checkbox' id='" + rowValue + "' name='checkbox:" + rowValue + "'>"); } else { _htmlStream.append("<input type='checkbox' id='" + rowValue + "' name='checkbox:" + rowValue + "' >"); } _htmlStream.append(" </td>\n"); // sets the js function that controls if the actual row has already been checked and if yes checks it SourceBean clicked = (SourceBean) captionSB.getAttribute("CLICKED"); String clickedFunction = readOnClickFunction(clicked, row); if (clickedFunction != null) { _htmlStream.append(" <script type='text/javascript'>\n"); //_htmlStream.append(" function check" + rowValue + "() {\n"); _htmlStream.append(clickedFunction + "\n"); //_htmlStream.append(" }\n"); //_htmlStream.append(" check" + rowValue + "() ;\n"); _htmlStream.append(" </script>\n"); } } else { // if there are no parameters puts an empty column String img = (String) captionSB.getAttribute("image"); String labelCode = (String) captionSB.getAttribute("label"); String label = msgBuilder.getMessage(labelCode, _bundle, httpRequest); _htmlStream.append(" <td width='40px'>\n"); _htmlStream.append(" <a name=\"" + label + "\" " + (onClickFunctionName != null ? " href='javascript:void(0);' onclick='" + onClickFunctionName + "()' " : "") + " >\n"); _htmlStream.append(" <img title=\"" + label + "\" alt=\"" + label + "\" src='" + urlBuilder.getResourceLinkByTheme(httpRequest, img, currTheme) + "' />\n"); _htmlStream.append(" </a>\n"); _htmlStream.append(" </td>\n"); } } else { HashMap paramsMap = getParametersMap(parameters, row); String img = (String) captionSB.getAttribute("image"); String labelCode = (String) captionSB.getAttribute("label"); //String label = PortletUtilities.getMessage(labelCode, "messages"); String label = msgBuilder.getMessage(labelCode, _bundle, httpRequest); String buttonUrl = null; if (!paramsMap.isEmpty()) { buttonUrl = createUrl(paramsMap); } boolean confirm = false; // If caption's 'confirm' attribute is true, then all rows will have the confirmation alert // with message code that is specified in the 'label' attribute of the caption tag); // if there is also a CONFIRM_CONDITION tag, then the alert message code will be overwritten by // 'msg' attribute of CONFIRM_CONDITION tag (with the bundle specified in 'bundle' attribute). // If caption's 'confirm' attribute is false, only rows that satisfy CONFIRM_CONDITION will have // the confirmation alert with 'msg' attribute of CONFIRM_CONDITION tag as alert message. if (captionSB.getAttribute("confirm") != null && ((String) captionSB.getAttribute("confirm")).equalsIgnoreCase("TRUE")) { confirm = true; } _htmlStream.append(" <td width='40px' >\n"); String msg = label; SourceBean confirmConditionSB = (SourceBean) captionSB.getAttribute("CONFIRM_CONDITION"); if (confirmConditionSB != null) { if (verifyConditions(confirmConditionSB, row)) { String msgCode = (String) confirmConditionSB.getAttribute("msg"); String bundle = (String) confirmConditionSB.getAttribute("bundle"); if (bundle == null || bundle.trim().equals("")) bundle = _bundle; msg = msgBuilder.getMessage(msgCode, bundle, httpRequest); confirm = true; } } if (confirm && buttonUrl != null) { if (onClickFunctionName != null) { _htmlStream.append(" <a href='javascript:actionConfirm(\"" + msg + "\", \"" + buttonUrl + "\", '" + onClickFunctionName + "()');'>\n"); } else if (popup) { _htmlStream.append(" <a id='linkDetail_" + captionName + "_" + prog + "' >\n"); // insert javascript for open popup _htmlStream.append(" <script>\n"); _htmlStream.append("Ext.get('linkDetail_" + captionName + "_" + prog + "').on('click', function(){ \n"); _htmlStream.append(" if (confirm(\"" + msg + "\") and win" + captionName + "_" + prog + " == null ) {\n"); _htmlStream.append(" var win" + captionName + "_" + prog + "; \n"); _htmlStream.append(" win" + captionName + "_" + prog + "=new Ext.Window({id:'win" + captionName + "_" + prog + "',\n"); _htmlStream.append(" bodyCfg:{"); _htmlStream.append(" tag:'div'"); _htmlStream.append(" ,cls:'x-panel-body'"); _htmlStream.append(" ,children:[{"); _htmlStream.append(" tag:'iframe',"); _htmlStream.append( " name: 'dynamicIframe" + captionName + "_" + prog + "',"); _htmlStream.append( " id : 'dynamicIframe" + captionName + "_" + prog + "',"); _htmlStream.append(" src: '" + createUrl_popup(paramsMap) + "',"); _htmlStream.append(" frameBorder:0,"); _htmlStream.append(" width:'100%',"); _htmlStream.append(" height:'100%',"); _htmlStream.append(" style: {overflow:'auto'} "); _htmlStream.append(" }]"); _htmlStream.append(" },"); _htmlStream.append(" modal: true,\n"); _htmlStream.append(" layout:'fit',\n"); if (popupHeight != null) { _htmlStream.append(" height:" + popupHeight + ",\n"); } else { _htmlStream.append(" height:200,\n"); } if (popupWidth != null) { _htmlStream.append(" width:" + popupWidth + ",\n"); } else { _htmlStream.append(" width:500,\n"); } _htmlStream.append(" closeAction:'hide',\n"); if (closeRefresh == true) { _htmlStream.append(" closable : false ,\n"); } _htmlStream.append(" scripts: true, \n"); if (closeRefresh == true || popupSave == true) { _htmlStream.append(" buttons: [ \n"); if (popupSave == true) { _htmlStream.append(" { text: 'Save', \n"); _htmlStream.append(" handler: function(){ \n"); _htmlStream.append(" dynamicIframe" + captionName + "_" + prog + "." + popupSaveFunction + "(); \n"); _htmlStream.append(" } } "); } if (closeRefresh == true && popupSave == true) _htmlStream.append(","); if (closeRefresh == true) { _htmlStream.append(" {text: 'Close', \n"); _htmlStream.append(" handler: function(){ \n"); _htmlStream.append(" refresh(); \n"); _htmlStream.append( " win" + captionName + "_" + prog + ".hide(); \n"); _htmlStream.append(" }} \n"); } _htmlStream.append(" ], \n"); } _htmlStream.append(" buttonAlign : 'left',\n"); _htmlStream.append(" plain: true \n"); _htmlStream.append(" });\n"); _htmlStream.append(" };\n"); _htmlStream.append(" win" + captionName + "_" + prog + ".show() \n"); _htmlStream.append(" }\n"); _htmlStream.append(");\n"); _htmlStream.append(" </script>\n"); } else { _htmlStream.append(" <a href='javascript:actionConfirm(\"" + msg + "\", \"" + buttonUrl + "\");'>\n"); } } else { if (popup) { _htmlStream.append(" <a id='linkDetail_" + captionName + "_" + prog + "' >\n"); // insert javascript for open popup _htmlStream.append(" <script>\n"); _htmlStream.append(" var win" + captionName + "_" + prog + "; \n"); _htmlStream.append("Ext.get('linkDetail_" + captionName + "_" + prog + "').on('click', function(){ \n"); _htmlStream.append(" if ( win" + captionName + "_" + prog + " == null ) {win" + captionName + "_" + prog + "=new Ext.Window({id:'win" + captionName + "_" + prog + "',\n"); _htmlStream.append(" bodyCfg:{ \n"); _htmlStream.append(" tag:'div' \n"); _htmlStream.append(" ,cls:'x-panel-body' \n"); _htmlStream.append(" ,children:[{ \n"); _htmlStream.append(" tag:'iframe', \n"); _htmlStream.append(" name: 'dynamicIframe" + captionName + "_" + prog + "', \n"); _htmlStream.append(" id : 'dynamicIframe" + captionName + "_" + prog + "', \n"); _htmlStream.append(" src: '" + createUrl_popup(paramsMap) + "', \n"); _htmlStream.append(" frameBorder:0, \n"); _htmlStream.append(" width:'100%', \n"); _htmlStream.append(" height:'100%', \n"); _htmlStream.append(" style: {overflow:'auto'} \n "); _htmlStream.append(" }] \n"); _htmlStream.append(" }, \n"); _htmlStream.append(" modal: true,\n"); _htmlStream.append(" layout:'fit',\n"); if (popupHeight != null) { _htmlStream.append(" height:" + popupHeight + ",\n"); } else { _htmlStream.append(" height:200,\n"); } if (popupWidth != null) { _htmlStream.append(" width:" + popupWidth + ",\n"); } else { _htmlStream.append(" width:500,\n"); } _htmlStream.append(" closeAction:'hide',\n"); if (closeRefresh == true) { _htmlStream.append(" closable : false ,\n"); } _htmlStream.append(" scripts: true, \n"); if (closeRefresh == true || popupSave == true) { _htmlStream.append(" buttons: [ \n"); if (popupSave == true) { _htmlStream.append(" { text: 'Save', \n"); _htmlStream.append(" handler: function(){ \n"); _htmlStream.append(" dynamicIframe" + captionName + "_" + prog + "." + popupSaveFunction + "(); \n"); _htmlStream.append(" } } "); } if (closeRefresh == true && popupSave == true) _htmlStream.append(","); if (closeRefresh == true) { _htmlStream.append(" {text: 'Close', \n"); _htmlStream.append(" handler: function(){ \n"); _htmlStream.append(" refresh(); \n"); _htmlStream.append( " win" + captionName + "_" + prog + ".hide(); \n"); _htmlStream.append(" }} \n"); } _htmlStream.append(" ], \n"); } _htmlStream.append(" buttonAlign : 'left',\n"); _htmlStream.append(" plain: true \n"); _htmlStream.append(" }); }; \n"); _htmlStream.append(" win" + captionName + "_" + prog + ".show(); \n"); _htmlStream.append(" } \n"); _htmlStream.append(");\n"); _htmlStream.append(" </script>\n"); } else { if (buttonUrl != null) { if (onClickFunctionName != null) { _htmlStream.append(" <a href='javascript:" + onClickFunctionName + "();location.href=\"" + buttonUrl + "\"'>\n"); } else { _htmlStream.append(" <a href='" + buttonUrl + "'>\n"); } } } } _htmlStream.append(" <img title=\"" + label + "\" alt=\"" + label + "\" src='" + urlBuilder.getResourceLinkByTheme(httpRequest, img, currTheme) + "' />\n"); _htmlStream.append(" </a>\n"); _htmlStream.append(" </td>\n"); } } _htmlStream.append(" </tr>\n"); } _htmlStream.append(" </table>\n"); _htmlStream.append(" <script>\n"); _htmlStream.append(" function refresh(){ \n"); _htmlStream.append(" location.href = '" + _refreshUrl + "' ; \n"); _htmlStream.append(" } \n"); _htmlStream.append(" </script>\n"); }
From source file:org.mskcc.cbio.portal.servlet.CrossCancerJSON.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request// www . ja v a 2 s. co m * @param response servlet response * @throws javax.servlet.ServletException if a servlet-specific error occurs * @throws java.io.IOException if an I/O error occurs */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { XDebug xdebug = new XDebug(); xdebug.startTimer(); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); try { List resultsList = new LinkedList(); // Get the gene list String geneList = request.getParameter(QueryBuilder.GENE_LIST); if (request instanceof XssRequestWrapper) { geneList = ((XssRequestWrapper) request).getRawParameter(QueryBuilder.GENE_LIST); } String cancerStudyIdListString = request.getParameter(QueryBuilder.CANCER_STUDY_LIST); String[] cancerStudyIdList = cancerStudyIdListString.split(","); // Get the priority Integer dataTypePriority; try { dataTypePriority = Integer.parseInt(request.getParameter(QueryBuilder.DATA_PRIORITY).trim()); } catch (NumberFormatException e) { dataTypePriority = 0; } // Cancer All Cancer Studies List<CancerStudy> cancerStudiesList = accessControl.getCancerStudies(); HashMap<String, Boolean> studyMap = new HashMap<>(); for (String studyId : cancerStudyIdList) { studyMap.put(studyId, Boolean.TRUE); } for (CancerStudy cancerStudy : cancerStudiesList) { String cancerStudyId = cancerStudy.getCancerStudyStableId(); if (!studyMap.containsKey(cancerStudyId)) { continue; } if (cancerStudyId.equalsIgnoreCase("all")) continue; Map cancerMap = new LinkedHashMap(); cancerMap.put("studyId", cancerStudyId); cancerMap.put("typeOfCancer", cancerStudy.getTypeOfCancerId()); // Get all Genetic Profiles Associated with this Cancer Study ID. ArrayList<GeneticProfile> geneticProfileList = GetGeneticProfiles.getGeneticProfiles(cancerStudyId); // Get all Patient Lists Associated with this Cancer Study ID. ArrayList<SampleList> sampleSetList = GetSampleLists.getSampleLists(cancerStudyId); // Get the default patient set AnnotatedSampleSets annotatedSampleSets = new AnnotatedSampleSets(sampleSetList, dataTypePriority); SampleList defaultSampleSet = annotatedSampleSets.getDefaultSampleList(); if (defaultSampleSet == null) { continue; } List<String> sampleIds = defaultSampleSet.getSampleList(); // Get the default genomic profiles CategorizedGeneticProfileSet categorizedGeneticProfileSet = new CategorizedGeneticProfileSet( geneticProfileList); HashMap<String, GeneticProfile> defaultGeneticProfileSet = null; switch (dataTypePriority) { case 2: defaultGeneticProfileSet = categorizedGeneticProfileSet.getDefaultCopyNumberMap(); break; case 1: defaultGeneticProfileSet = categorizedGeneticProfileSet.getDefaultMutationMap(); break; case 0: default: defaultGeneticProfileSet = categorizedGeneticProfileSet.getDefaultMutationAndCopyNumberMap(); } String mutationProfile = "", cnaProfile = ""; for (GeneticProfile geneticProfile : defaultGeneticProfileSet.values()) { GeneticAlterationType geneticAlterationType = geneticProfile.getGeneticAlterationType(); if (geneticAlterationType.equals(GeneticAlterationType.COPY_NUMBER_ALTERATION)) { cnaProfile = geneticProfile.getStableId(); } else if (geneticAlterationType.equals(GeneticAlterationType.MUTATION_EXTENDED)) { mutationProfile = geneticProfile.getStableId(); } } cancerMap.put("mutationProfile", mutationProfile); cancerMap.put("cnaProfile", cnaProfile); cancerMap.put("caseSetId", defaultSampleSet.getStableId()); cancerMap.put("caseSetLength", sampleIds.size()); ProfileDataSummary genomicData = getGenomicData(cancerStudyId, defaultGeneticProfileSet, defaultSampleSet, geneList, sampleSetList, request, response); ArrayList<GeneWithScore> geneFrequencyList = genomicData.getGeneFrequencyList(); ArrayList<String> genes = new ArrayList<String>(); for (GeneWithScore geneWithScore : geneFrequencyList) genes.add(geneWithScore.getGene()); int noOfMutated = 0, noOfCnaUp = 0, noOfCnaDown = 0, noOfCnaLoss = 0, noOfCnaGain = 0, noOfOther = 0, noOfAll = 0; boolean skipStudy = defaultGeneticProfileSet.isEmpty(); if (!skipStudy) { for (String sampleId : sampleIds) { if (sampleId == null) { continue; } if (!genomicData.isCaseAltered(sampleId)) continue; boolean isAnyMutated = false, isAnyCnaUp = false, isAnyCnaDown = false, isAnyCnaLoss = false, isAnyCnaGain = false; for (String gene : genes) { isAnyMutated |= genomicData.isGeneMutated(gene, sampleId); GeneticTypeLevel cnaLevel = genomicData.getCNALevel(gene, sampleId); boolean isCnaUp = cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.Amplified); isAnyCnaUp |= isCnaUp; boolean isCnaDown = cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.HomozygouslyDeleted); isAnyCnaDown |= isCnaDown; boolean isCnaLoss = cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.HemizygouslyDeleted); isAnyCnaLoss |= isCnaLoss; boolean isCnaGain = cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.Gained); isAnyCnaGain |= isCnaGain; } boolean isAnyCnaChanged = isAnyCnaUp || isAnyCnaDown; if (isAnyMutated && !isAnyCnaChanged) noOfMutated++; else if (isAnyMutated && isAnyCnaChanged) noOfOther++; else if (isAnyCnaUp) noOfCnaUp++; else if (isAnyCnaDown) noOfCnaDown++; else if (isAnyCnaGain) noOfCnaGain++; else if (isAnyCnaLoss) noOfCnaLoss++; noOfAll++; } } Map alterations = new LinkedHashMap(); cancerMap.put("alterations", alterations); alterations.put("all", noOfAll); alterations.put("mutation", noOfMutated); alterations.put("cnaUp", noOfCnaUp); alterations.put("cnaDown", noOfCnaDown); alterations.put("cnaLoss", noOfCnaLoss); alterations.put("cnaGain", noOfCnaGain); alterations.put("other", noOfOther); cancerMap.put("genes", genes); cancerMap.put("skipped", skipStudy); resultsList.add(cancerMap); } JSONValue.writeJSONString(resultsList, writer); } catch (DaoException e) { throw new ServletException(e); } catch (ProtocolException e) { throw new ServletException(e); } finally { writer.close(); } }
From source file:edu.amc.sakai.user.JLDAPDirectoryProvider.java
/** * Similar to iterating over <code>users</code> passing * each element to {@link #getUser(UserEdit)}, removing the * {@link org.sakaiproject.user.api.UserEdit} if that method * returns <code>false</code>. * /*w w w. ja va 2 s .c om*/ * <p>Adds search retry capability if any one lookup fails * with a directory error. Empties <code>users</code> and * returns if a retry exits exceptionally * <p> */ public void getUsers(Collection<UserEdit> users) { if (M_log.isDebugEnabled()) { M_log.debug("getUsers(): [Collection size = " + users.size() + "]"); } LDAPConnection conn = null; boolean abortiveSearch = false; int maxQuerySize = getMaxObjectsToQueryFor(); UserEdit userEdit = null; HashMap<String, UserEdit> usersToSearchInLDAP = new HashMap<String, UserEdit>(); List<UserEdit> usersToRemove = new ArrayList<UserEdit>(); try { int cnt = 0; for (Iterator<UserEdit> userEdits = users.iterator(); userEdits.hasNext();) { userEdit = (UserEdit) userEdits.next(); String eid = userEdit.getEid(); if (!(isSearchableEid(eid))) { userEdits.remove(); //proceed ahead with this (perhaps the final) iteration //usersToSearchInLDAP needs to be processed unless empty } else { usersToSearchInLDAP.put(eid, userEdit); cnt++; } // We need to make sure this query isn't larger than maxQuerySize if ((!userEdits.hasNext() || cnt == maxQuerySize) && !usersToSearchInLDAP.isEmpty()) { if (conn == null) { conn = ldapConnectionManager.getConnection(); } String filter = ldapAttributeMapper.getManyUsersInOneSearch(usersToSearchInLDAP.keySet()); List<LdapUserData> ldapUsers = searchDirectory(filter, null, null, null, null, maxQuerySize); for (LdapUserData ldapUserData : ldapUsers) { String ldapEid = ldapUserData.getEid(); if (StringUtils.isEmpty(ldapEid)) { continue; } ldapEid = ldapEid.toLowerCase(); UserEdit ue = usersToSearchInLDAP.get(ldapEid); mapUserDataOntoUserEdit(ldapUserData, ue); usersToSearchInLDAP.remove(ldapEid); } // see if there are any users that we could not find in the LDAP query for (Map.Entry<String, UserEdit> entry : usersToSearchInLDAP.entrySet()) { usersToRemove.add(entry.getValue()); } // clear the HashMap and reset the counter usersToSearchInLDAP.clear(); cnt = 0; } } // Finally clean up the original collection and remove and users we could not find for (UserEdit userRemove : usersToRemove) { if (M_log.isDebugEnabled()) { M_log.debug("JLDAP getUsers could not find user: " + userRemove.getEid()); } users.remove(userRemove); } } catch (LDAPException e) { abortiveSearch = true; throw new RuntimeException("getUsers(): LDAPException during search [eid = " + (userEdit == null ? null : userEdit.getEid()) + "][result code = " + e.resultCodeToString() + "][error message = " + e.getLDAPErrorMessage() + "]", e); } catch (Exception e) { abortiveSearch = true; throw new RuntimeException("getUsers(): RuntimeException during search eid = " + (userEdit == null ? null : userEdit.getEid()) + "]", e); } finally { if (conn != null) { if (M_log.isDebugEnabled()) { M_log.debug("getUsers(): returning connection to connection manager"); } ldapConnectionManager.returnConnection(conn); } // no sense in returning a partially complete search result if (abortiveSearch) { if (M_log.isDebugEnabled()) { M_log.debug("getUsers(): abortive search, clearing received users collection"); } users.clear(); } } }
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); }/* www .j av a 2s .c o m*/ } } } } 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:org.n52.wps.ags.GenericAGSProcessDelegator.java
public Map<String, IData> run(Map<String, List<IData>> inputData) { //initialize arcObjects AGSProperties.getInstance().bootstrapArcobjectsJar(); //create the workspace this.workspace = new AGSWorkspace(instanceWorkspace); //Assign the parameters for (int i = 0; i < this.parameterCount; i++) { ToolParameter currentParam = this.parameterDescriptions[i]; // input parameters if (currentParam.isInput) { if (inputData.containsKey(currentParam.wpsInputID)) { //open the IData list and iterate through it List<IData> dataItemList = inputData.get(currentParam.wpsInputID); Iterator<IData> it = dataItemList.iterator(); ArrayList<String> valueList = new ArrayList<String>(); while (it.hasNext()) { IData currentItem = it.next(); valueList.add(this.loadSingleDataItem(currentItem)); }/* w w w .j a v a 2 s. c o m*/ String[] valueArray = valueList.toArray(new String[0]); //TODO verify: isnt the input separator acutally an " ; "? this.toolParameters[i] = this.calcToolParameterString(" ", valueArray); } else { if (currentParam.isOptional) { this.toolParameters[i] = null; } else { errors.add("Error while allocating input parameter " + currentParam.wpsInputID); throw new RuntimeException( "Error while allocating input parameter " + currentParam.wpsInputID); } } } //output only parameters else if (currentParam.isOutput && !currentParam.isInput) { if (currentParam.isComplex) { String extension = ""; if (currentParam.schema != null && currentParam.schema.length() > 0) { //we have vector data. So use a shp file. extension = "shp"; } else { extension = GenericFileDataConstants.mimeTypeFileTypeLUT().get(currentParam.mimeType); } String fileName = UUID.randomUUID().toString().substring(0, 7) + "." + extension; // geoprocessor can't handle points, dashes etc in output file name fileName = this.addOutputFile(fileName); this.toolParameters[i] = fileName; } } } //execute String toolName = this.processDescription.getTitle().getStringValue(); LOGGER.info("Executing ArcGIS tool " + toolName + " . Parameter array contains " + this.parameterCount + " parameters."); try { workspace.executeGPTool(toolName, null, this.toolParameters); } catch (IOException e1) { LOGGER.error(e1.getMessage()); errors.add(e1.getMessage()); throw new RuntimeException(e1.getMessage()); // otherwise WPS tries to zip and return non-existing files => null pointer } //create the output HashMap<String, IData> result = new HashMap<String, IData>(); for (int i = 0; i < this.parameterCount; i++) { ToolParameter currentParam = this.parameterDescriptions[i]; if (currentParam != null // Otherwise, nullpointer exception when trying to process outputs! && currentParam.isOutput) { if (currentParam.isComplex) { String fileName = this.toolParameters[i]; //GenericFileData outputFileData = new GenericFileData(this.workspace.getFileAsStream(fileName), currentParam.mimeType); File currentFile = new File(fileName); GenericFileDataWithGT outputFileData; try { if (currentParam.schema != null && currentParam.schema.length() > 0) { //we have vector data. So use a shp file. outputFileData = new GenericFileDataWithGT(currentFile, GenericFileDataConstants.MIME_TYPE_ZIPPED_SHP); } else { outputFileData = new GenericFileDataWithGT(currentFile, currentParam.mimeType); } result.put(currentParam.wpsOutputID, new GenericFileDataWithGTBinding(outputFileData)); } catch (FileNotFoundException e) { LOGGER.error("Could not read output file: " + fileName); errors.add("Could not read output file: " + fileName); throw new RuntimeException( "No files found. Probably the process did not create any output files."); } catch (IOException e) { LOGGER.error("Could not create output file from: " + fileName); errors.add("Could not create output file from: " + fileName); e.printStackTrace(); } } if (currentParam.isLiteral) { // not implemented } if (currentParam.isCRS) { // not implemented } } } //Handle if no result was created if (result.isEmpty()) { String message = ""; for (String error : errors) { message = message.concat(error + " - "); } message = message.concat("ArcGIS Backend Process " + this.processID + " did not return any output" + " data or the output data could not be processed."); throw new RuntimeException(message); } return result; }
From source file:org.lansir.beautifulgirls.proxy.ProxyInvocationHandler.java
/** * Dynamic proxy invoke/*w w w.j ava 2 s . c o m*/ */ public Object invoke(Object proxy, Method method, Object[] args) throws AkInvokeException, AkServerStatusException, AkException, Exception { AkPOST akPost = method.getAnnotation(AkPOST.class); AkGET akGet = method.getAnnotation(AkGET.class); AkAPI akApi = method.getAnnotation(AkAPI.class); Annotation[][] annosArr = method.getParameterAnnotations(); String invokeUrl = akApi.url(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); // AkApiParams to hashmap, filter out of null-value HashMap<String, File> filesToSend = new HashMap<String, File>(); HashMap<String, String> paramsMapOri = new HashMap<String, String>(); HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri); // Record this invocation ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo(); apiInvokeInfo.apiName = method.getName(); apiInvokeInfo.paramsMap.putAll(paramsMap); apiInvokeInfo.url = invokeUrl; // parse '{}'s in url invokeUrl = parseUrlbyParams(invokeUrl, paramsMap); // cleared hashmap to params, and filter out of the null value Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> entry = iter.next(); params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } // get the signature string if using AkSignature akSig = method.getAnnotation(AkSignature.class); if (akSig != null) { Class<?> clazzSignature = akSig.using(); if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) { InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance(); String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri); String sigParamName = is.getSignatureParamName(); if (sigValue != null && sigParamName != null && sigValue.length() > 0 && sigParamName.length() > 0) { params.add(new BasicNameValuePair(sigParamName, sigValue)); } } } // choose POST GET PUT DELETE to use for this invoke String retString = ""; if (akGet != null) { StringBuilder sbUrl = new StringBuilder(invokeUrl); if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) { sbUrl.append("?"); } for (NameValuePair nvp : params) { sbUrl.append(nvp.getName()); sbUrl.append("="); sbUrl.append(nvp.getValue()); sbUrl.append("&"); } // now default using UTF-8, maybe improved later retString = HttpInvoker.get(sbUrl.toString()); } else if (akPost != null) { if (filesToSend.isEmpty()) { retString = HttpInvoker.post(invokeUrl, params); } else { retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend); } } else { // use POST for default retString = HttpInvoker.post(invokeUrl, params); } // invoked, then add to history //ApiStats.addApiInvocation(apiInvokeInfo); //Log.d(TAG, retString); // parse the return-string Class<?> returnType = method.getReturnType(); try { if (String.class.equals(returnType)) { // the result return raw string return retString; } else { // return object using json decode return JsonMapper.json2pojo(retString, returnType); } } catch (IOException e) { throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, e.getMessage(), e); } /* * also can use gson like this eg. * Gson gson = new Gson(); * return gson.fromJson(HttpInvoker.post(url, params), returnType); */ }
From source file:org.akita.proxy.ProxyInvocationHandler.java
/** * Dynamic proxy invoke/*from ww w . j a v a 2 s .c om*/ */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { AkPOST akPost = method.getAnnotation(AkPOST.class); AkGET akGet = method.getAnnotation(AkGET.class); AkAPI akApi = method.getAnnotation(AkAPI.class); Annotation[][] annosArr = method.getParameterAnnotations(); String invokeUrl = akApi.url(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); // AkApiParams to hashmap, filter out of null-value HashMap<String, File> filesToSend = new HashMap<String, File>(); HashMap<String, String> paramsMapOri = new HashMap<String, String>(); HashMap<String, String> paramsMap = getRawApiParams2HashMap(annosArr, args, filesToSend, paramsMapOri); // Record this invocation ApiInvokeInfo apiInvokeInfo = new ApiInvokeInfo(); apiInvokeInfo.apiName = method.getName(); apiInvokeInfo.paramsMap.putAll(paramsMapOri); apiInvokeInfo.url = invokeUrl; // parse '{}'s in url invokeUrl = parseUrlbyParams(invokeUrl, paramsMap); // cleared hashmap to params, and filter out of the null value Iterator<Entry<String, String>> iter = paramsMap.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> entry = iter.next(); params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } // get the signature string if using AkSignature akSig = method.getAnnotation(AkSignature.class); if (akSig != null) { Class<?> clazzSignature = akSig.using(); if (clazzSignature.getInterfaces().length > 0 // TODO: NEED VERIFY WHEN I HAVE TIME && InvokeSignature.class.getName().equals(clazzSignature.getInterfaces()[0].getName())) { InvokeSignature is = (InvokeSignature) clazzSignature.getConstructors()[0].newInstance(); String sigValue = is.signature(akSig, invokeUrl, params, paramsMapOri); String sigParamName = is.getSignatureParamName(); if (sigValue != null && sigParamName != null && sigValue.length() > 0 && sigParamName.length() > 0) { params.add(new BasicNameValuePair(sigParamName, sigValue)); } } } // choose POST GET PUT DELETE to use for this invoke String retString = ""; if (akGet != null) { StringBuilder sbUrl = new StringBuilder(invokeUrl); if (!(invokeUrl.endsWith("?") || invokeUrl.endsWith("&"))) { sbUrl.append("?"); } for (NameValuePair nvp : params) { sbUrl.append(nvp.getName()); sbUrl.append("="); sbUrl.append(nvp.getValue()); sbUrl.append("&"); } // now default using UTF-8, maybe improved later retString = HttpInvoker.get(sbUrl.toString()); } else if (akPost != null) { if (filesToSend.isEmpty()) { retString = HttpInvoker.post(invokeUrl, params); } else { retString = HttpInvoker.postWithFilesUsingURLConnection(invokeUrl, params, filesToSend); } } else { // use POST for default retString = HttpInvoker.post(invokeUrl, params); } // invoked, then add to history //ApiStats.addApiInvocation(apiInvokeInfo); //Log.d(TAG, retString); // parse the return-string final Class<?> returnType = method.getReturnType(); try { if (String.class.equals(returnType)) { // the result return raw string return retString; } else { // return object using json decode return JsonMapper.json2pojo(retString, returnType); } } catch (Exception e) { Log.e(TAG, retString, e); // log can print the error return-string throw new AkInvokeException(AkInvokeException.CODE_JSONPROCESS_EXCEPTION, e.getMessage(), e); } }
From source file:com.wasteofplastic.askygrid.commands.Challenges.java
/** * Checks if a player has enough for a challenge. Supports two types of * checks, inventory and collect. Removes items if required. * //from w w w .j ava 2s .c om * @param player * @param challenge * @param type * @return true if the player has everything required */ 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); String desc = ChatColor.translateAlternateColorCodes('&', getChallengeConfig().getString("challenges.challengeList." + challenge + ".description") .replace("[label]", Settings.ISLANDCOMMAND)); List<String> result = new ArrayList<String>(); if (desc.contains("|")) { result.addAll(Arrays.asList(desc.split("\\|"))); } else { result.add(desc); } for (String line : result) { player.sendMessage(ChatColor.RED + line); } 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(); // If the item is enchanted, skip - it doesn't count if (i.hasItemMeta()) { continue; } // 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 // 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]); ItemStack item = new ItemStack(reqItem); // Item item.setDurability((short) reqDurability); // 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.hasItemMeta()) { continue; } 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); } else if (part.length == 6 && part[0].contains("POTION")) { // Run through player's inventory for the item ItemStack[] playerInv = player.getInventory().getContents(); try { reqAmount = Integer.parseInt(part[5]); //plugin.getLogger().info("DEBUG: required amount is " + reqAmount); } catch (Exception e) { plugin.getLogger().severe("Could not parse the quantity of the potion item " + s); return false; } int count = reqAmount; for (ItemStack i : playerInv) { // Catches all POTION, LINGERING_POTION and SPLASH_POTION if (i != null && i.getType().toString().contains("POTION")) { //plugin.getLogger().info("DEBUG:6 part potion check!"); // POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY if (plugin.getServer().getVersion().contains("(MC: 1.8") || plugin.getServer().getVersion().contains("(MC: 1.7")) { // Test potion Potion potion = Potion.fromItemStack(i); PotionType potionType = potion.getType(); boolean match = true; // plugin.getLogger().info("DEBUG: name check " + part[1]); // Name check if (!part[1].isEmpty()) { // There is a name if (PotionType.valueOf(part[1]) != null) { if (!potionType.name().equalsIgnoreCase(part[1])) { match = false; // plugin.getLogger().info("DEBUG: name does not match"); } else { // plugin.getLogger().info("DEBUG: name matches"); } } else { plugin.getLogger() .severe("Potion type is unknown. Please pick from the following:"); for (PotionType pt : PotionType.values()) { plugin.getLogger().severe(pt.name()); } match = false; } } // Level check (upgraded) // plugin.getLogger().info("DEBUG: level check " + part[2]); if (!part[2].isEmpty()) { // There is a level declared - check it if (StringUtils.isNumeric(part[2])) { int level = Integer.valueOf(part[2]); if (level != potion.getLevel()) { // plugin.getLogger().info("DEBUG: level does not match"); match = false; } } } // Extended check // plugin.getLogger().info("DEBUG: extended check " + part[3]); if (!part[3].isEmpty()) { if (part[3].equalsIgnoreCase("EXTENDED") && !potion.hasExtendedDuration()) { match = false; // plugin.getLogger().info("DEBUG: extended does not match"); } if (part[3].equalsIgnoreCase("NOTEXTENDED") && potion.hasExtendedDuration()) { match = false; // plugin.getLogger().info("DEBUG: extended does not match"); } } // Splash check // plugin.getLogger().info("DEBUG: splash/linger check " + part[4]); if (!part[4].isEmpty()) { if (part[4].equalsIgnoreCase("SPLASH") && !potion.isSplash()) { match = false; // plugin.getLogger().info("DEBUG: not splash"); } if (part[4].equalsIgnoreCase("NOSPLASH") && potion.isSplash()) { match = false; // plugin.getLogger().info("DEBUG: not no splash"); } } // Quantity check if (match) { // plugin.getLogger().info("DEBUG: potion matches!"); ItemStack removeItem = i.clone(); if (removeItem.getAmount() > reqAmount) { // plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv"); removeItem.setAmount(reqAmount); } count = count - removeItem.getAmount(); // plugin.getLogger().info("DEBUG: " + count + " left"); toBeRemoved.add(removeItem); } } else { // V1.9 and above PotionMeta potionMeta = (PotionMeta) i.getItemMeta(); // If any of the settings above are missing, then any is okay boolean match = true; // plugin.getLogger().info("DEBUG: name check " + part[1]); // Name check if (!part[1].isEmpty()) { // There is a name if (PotionType.valueOf(part[1]) != null) { if (!potionMeta.getBasePotionData().getType().name() .equalsIgnoreCase(part[1])) { match = false; // plugin.getLogger().info("DEBUG: name does not match"); } else { // plugin.getLogger().info("DEBUG: name matches"); } } else { plugin.getLogger() .severe("Potion type is unknown. Please pick from the following:"); for (PotionType pt : PotionType.values()) { plugin.getLogger().severe(pt.name()); } match = false; } } // Level check (upgraded) // plugin.getLogger().info("DEBUG: level check " + part[2]); if (!part[2].isEmpty()) { // There is a level declared - check it if (StringUtils.isNumeric(part[2])) { int level = Integer.valueOf(part[2]); if (level == 1 && potionMeta.getBasePotionData().isUpgraded()) { // plugin.getLogger().info("DEBUG: level does not match"); match = false; } if (level != 1 && !potionMeta.getBasePotionData().isUpgraded()) { match = false; // plugin.getLogger().info("DEBUG: level does not match"); } } } // Extended check // plugin.getLogger().info("DEBUG: extended check " + part[3]); if (!part[3].isEmpty()) { if (part[3].equalsIgnoreCase("EXTENDED") && !potionMeta.getBasePotionData().isExtended()) { match = false; // plugin.getLogger().info("DEBUG: extended does not match"); } if (part[3].equalsIgnoreCase("NOTEXTENDED") && potionMeta.getBasePotionData().isExtended()) { match = false; // plugin.getLogger().info("DEBUG: extended does not match"); } } // Splash or Linger check // plugin.getLogger().info("DEBUG: splash/linger check " + part[4]); if (!part[4].isEmpty()) { if (part[4].equalsIgnoreCase("SPLASH") && !i.getType().equals(Material.SPLASH_POTION)) { match = false; // plugin.getLogger().info("DEBUG: not splash"); } if (part[4].equalsIgnoreCase("NOSPLASH") && i.getType().equals(Material.SPLASH_POTION)) { match = false; // plugin.getLogger().info("DEBUG: not no splash"); } if (part[4].equalsIgnoreCase("LINGER") && !i.getType().equals(Material.LINGERING_POTION)) { match = false; // plugin.getLogger().info("DEBUG: not linger"); } if (part[4].equalsIgnoreCase("NOLINGER") && i.getType().equals(Material.LINGERING_POTION)) { match = false; // plugin.getLogger().info("DEBUG: not no linger"); } } // Quantity check if (match) { // plugin.getLogger().info("DEBUG: potion matches!"); ItemStack removeItem = i.clone(); if (removeItem.getAmount() > reqAmount) { // plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv"); removeItem.setAmount(reqAmount); } count = count - removeItem.getAmount(); // plugin.getLogger().info("DEBUG: " + count + " left"); toBeRemoved.add(removeItem); } } } if (count <= 0) { // plugin.getLogger().info("DEBUG: Player has enough"); break; } // plugin.getLogger().info("DEBUG: still need " + count + " to complete"); } if (count > 0) { // plugin.getLogger().info("DEBUG: Player does not have enough"); return false; } } else { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); 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("collect")) { 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(); // Get search radius - min is 10, max is 50 int searchRadius = getChallengeConfig() .getInt("challenges.challengeList." + challenge + ".searchRadius", 10); if (searchRadius < 10) { searchRadius = 10; } else if (searchRadius > 50) { searchRadius = 50; } for (int x = -searchRadius; x <= searchRadius; x++) { for (int y = -searchRadius; y <= searchRadius; y++) { for (int z = -searchRadius; z <= searchRadius; 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(searchRadius, searchRadius, searchRadius)) { // 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:elh.eus.absa.Features.java
private void loadClusterFeatures(String clname) throws IOException { // Load clark cluster category info from files HashMap<String, Integer> clMap = new HashMap<String, Integer>(); if (params.containsKey("clark")) { int featPos = this.featNum; clMap = loadAttributeMapFromFile(params.getProperty(clname), clname + "ClId_"); if (clMap.isEmpty()) { params.remove(clname);//from w w w. j ava2s . co m } else { attributeSets.put(clname + "Cl", clMap); } System.err.println("Features : loadClusterFeatures() - " + clname + " cluster features -> " + (this.featNum - featPos)); System.out.println("Features : loadClusterFeatures() - " + clname + " cluster features -> " + (this.featNum - featPos)); } }
From source file:de.uzk.hki.da.sb.SIPFactory.java
/** * Creates a list of source folders/*from w w w . java 2 s. c o m*/ * * @param folderPath * The main source folder path * @throws Exception */ HashMap<File, String> createFolderList(String folderPath) throws Exception { HashMap<File, String> folderListWithFolderNames = new HashMap<File, String>(); File sourceFolder = new File(folderPath); switch (kindofSIPBuilding) { case MULTIPLE_FOLDERS: List<File> folderContent = Arrays.asList(sourceFolder.listFiles()); for (File file : folderContent) { if (!file.isHidden() && file.isDirectory()) folderListWithFolderNames.put(file, null); } break; case SINGLE_FOLDER: folderListWithFolderNames.put(sourceFolder, null); break; case NESTED_FOLDERS: NestedContentStructure ncs; try { TreeMap<File, String> metadataFileWithType = new FormatDetectionService(sourceFolder) .getMetadataFileWithType(); if (!metadataFileWithType.isEmpty() && (!metadataFileWithType.get(metadataFileWithType.firstKey()) .equals(C.CB_PACKAGETYPE_METS))) { messageWriter.showMessage("Es wurde eine Metadatendatei des Typs " + metadataFileWithType.get(metadataFileWithType.firstKey()) + " auf der obersten Ebene gefunden. " + "\nBitte whlen Sie diese Option ausschlielich fr die Erstellung von SIPs des Typs METS."); } else { ncs = new NestedContentStructure(sourceFolder); folderListWithFolderNames = ncs.getSipCandidates(); if (folderListWithFolderNames.isEmpty()) { messageWriter.showMessage( "Es wurde kein Unterverzeichnis mit einer METS-Metadatendatei gefunden."); } break; } } catch (IOException e) { throw new Exception(e); } default: break; } return folderListWithFolderNames; }