List of usage examples for java.util Map clear
void clear();
From source file:it.greenvulcano.gvesb.virtual.gv_multipart.MultipartCallOperation.java
/** * Adds on a Map the key and the value the given NodeList * /*from w w w . j a v a2 s . co m*/ * @param sourceNodeList * @param destinationMap */ private void fillMap(NodeList sourceNodeList, Map<String, String> destinationMap) { if (sourceNodeList.getLength() == 0) { destinationMap.clear(); } else { IntStream.range(0, sourceNodeList.getLength()).mapToObj(sourceNodeList::item).forEach(node -> { try { destinationMap.put(XMLConfig.get(node, "@name"), XMLConfig.get(node, "@value")); } catch (Exception e) { logger.error("Fail to read configuration", e); } }); } }
From source file:org.kiji.bento.box.tools.UpgradeInstallTool.java
/** * Perform an upgrade to the compatible version specified by the upgrade response. * * @param currentVersion of the BentoBox. * @param upgradeInfo from the checkin server specifying where the new version is. * @return an exit status code of 0 for success, nonzero for error. * @throws IOException if there's a problem downloading the package. * @throws InterruptedException if there's an interrupt while waiting for a script to run. *//*ww w . ja va 2s . co m*/ private int runUpgrade(String currentVersion, UpgradeResponse upgradeInfo) throws IOException, InterruptedException { // If the upgrade information refers to a later version than the one currently running, and // if it's time to give a reminder, do so. if (!upgradeInfo.isCompatibleNewer(currentVersion)) { System.out.println("You are already running the latest BentoBox."); return 0; // Nothing to do. } System.out.println("A new update is available!"); System.out.println("Current BentoBox version: " + currentVersion); System.out.println("Beginning upgrade to version: " + upgradeInfo.getCompatibleVersion()); final File workingDir = makeWorkDir(); final File targetFile = makeDownloadTarget(upgradeInfo, workingDir); final URL upgradeUrl = upgradeInfo.getCompatibleVersionURL(); LOG.info("Downloading: " + upgradeUrl.toString()); final HttpClient httpClient = new DefaultHttpClient(); final HttpGet getReq = new HttpGet(upgradeUrl.toString()); try { HttpResponse downloadResponse = httpClient.execute(getReq); int statusCode = downloadResponse.getStatusLine().getStatusCode(); LOG.debug("Status code: " + statusCode); if (statusCode != HttpStatus.SC_OK) { System.out.println("Received error from HTTP server:\n"); System.out.println(downloadResponse.getStatusLine().getReasonPhrase()); return 1; } HttpEntity entity = downloadResponse.getEntity(); if (null == entity) { System.out.println("Empty HTTP response when downloading from server."); System.out.println("Cannot automatically upgrade."); return 1; } OutputStream targetStream = new FileOutputStream(targetFile); try { entity.writeTo(targetStream); } finally { targetStream.close(); } } finally { getReq.releaseConnection(); httpClient.getConnectionManager().shutdown(); } // Run tar vzxf on the tarball. final String unzippedDirName = getUnzippedDir(targetFile); unzip(workingDir, targetFile); LOG.info("Running bootstrap command in new instance..."); // Run the upgrade bootstrap script from this tarball. final String[] command = { makeBootstrapCmd(workingDir, unzippedDirName).toString(), mBentoRootPath, currentVersion, }; debugLogStringArray("Bootstrap command:", command); final ProcessBuilder bootstrapProcBuilder = new ProcessBuilder(command).redirectErrorStream(true) .directory(workingDir); // Configure the environment for this process to run in. // We want to do so in as minimal an environment as possible. final Map<String, String> env = bootstrapProcBuilder.environment(); final String javaHome = env.get("JAVA_HOME"); env.clear(); // Run script in pure/empty environment. env.put("USER", System.getProperty("user.name")); env.put("HOME", System.getProperty("user.home")); if (javaHome != null) { env.put("JAVA_HOME", javaHome); } final Process bootstrapProcess = bootstrapProcBuilder.start(); printProcessOutput(bootstrapProcess); return bootstrapProcess.waitFor(); // Return its exit code. }
From source file:fi.aalto.drumbeat.apicalls.bimserver.BIMServerJSONApi.java
@SuppressWarnings("unchecked") public void getProjects(ComboBox selection, Map<String, Long> projects) { if (token == null) { System.err.println("No login"); return;//from w ww . ja v a 2 s .c o m } try { if (selection.isVisible()) selection.removeAllItems(); } catch (Exception e) { //update before table initalization? return; } projects.clear(); JSONObject getAllProjects = new JSONObject(); JSONObject parameters = new JSONObject(); // parameters.put( "onlyTopLevel","true"); JSONObject request = new JSONObject(); request.put("interface", "ServiceInterface"); request.put("method", "getAllReadableProjects"); request.put("parameters", parameters); getAllProjects.put("token", token); getAllProjects.put("request", request); System.out.println(getAllProjects); System.out.println("Result:"); JSONObject result = http(bimserver_api_url, getAllProjects.toJSONString()); JSONObject response = (JSONObject) result.get("response"); if (response != null) { JSONArray get_result = (JSONArray) response.get("result"); if (get_result != null) { for (Object obj : get_result) { // Add a row the hard way JSONObject project = (JSONObject) obj; String name = (String) project.get("name"); if (name != null) selection.addItem(name); Long project_id = (Long) project.get("oid"); if (project_id != null) { projects.put(name, project_id); } else System.err.println("ERROR no project ID!"); } } else { JSONObject bs_exception = (JSONObject) response.get("exception"); if (bs_exception != null) { String bs_message = (String) bs_exception.get("message"); System.err.println("ERROR " + bs_message); } } } }
From source file:com.bluexml.side.Framework.alfresco.dataGenerator.webscript.Generate.java
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { model.clear();/* w ww. ja v a 2 s .c om*/ //get and fill generator parameters String numOfContentsParameterValue = req.getParameter(NUMBER_OF_CONTENTS_PARAMETER_NAME); String numOfOutPutArcsParameterValue = req.getParameter(NUMBER_OF_OUTPUT_ARCS_PARAMETER_NAME); String scenarioParameterValue = req.getParameter(SCENARIO); String indexesParameterValue = req.getParameter(INDEXES); String loginParameterValue = req.getParameter(LOGIN); String passwordParameterValue = req.getParameter(PASSWORD); String foldersParameterValue = req.getParameter(FOLDERS_STRUCTURE); generator.setNumberOfNodes(Integer.valueOf(numOfContentsParameterValue)); generator.setNumberOfOutputArcs(Integer.valueOf(numOfOutPutArcsParameterValue)); generator.setScenario(scenarioParameterValue); if (!("").equals(indexesParameterValue)) { generator.setSavedStartIndexAttribute(Integer.valueOf(indexesParameterValue)); } else { generator.setSavedStartIndexAttribute(Integer.valueOf(0)); } String modelParameterValue = req.getParameter(MODEL_PARAMETER_NAME); dictionary.setQnameStringModel(modelParameterValue); String pathToDocuments = req.getParameter(PATH_TO_DOCUMENTS); nativeGenerator.setPathToDocumentsFolder(pathToDocuments); importer.setLogin(loginParameterValue); importer.setPassword(passwordParameterValue); //get model structure IStructure structure = null; try { structure = dictionary.getStructure(dictionary.getQnameStringModel()); } catch (ParserConfigurationException e2) { model.put("error", e2); logger.error("Error getting model's structure:", e2); } catch (SAXException e2) { model.put("error", e2); logger.error("Error getting model's structure:", e2); } catch (IOException e2) { model.put("error", e2); logger.error("Error getting model's structure:", e2); } //genarate datas boolean generated = false; try { generated = generator.generateNodesInstances(structure); } catch (Exception e1) { model.put("error", e1); logger.error("Error generating nodes instances: ", e1); } try { if (generated) { generated = generator.generateArcsInstances(structure); } } catch (Exception e1) { model.put("error", e1); logger.error("Error generating arcs instances: ", e1); } boolean deleted = false; try { if (generated) { deleted = generator.getGeneratorServices().deleteExceededNodes(); } } catch (Exception e1) { model.put("error", e1); logger.error("Error deleting isolated nodes: ", e1); } //serialize xml for acp boolean serialized = false; serializer.setFileName(XML_FILE_NAME); try { if (deleted) { serialized = serializer.serializeXml(); } } catch (Exception e) { model.put("error", e); logger.error("Error creating xml file: ", e); } //package to alfresco repository (with contents) packager.setArchiveName(ACP_FILE_NAME); File acp = null; try { if (serialized) { acp = packager.packageACP(); } } catch (IOException e) { model.put("error", e); logger.error("Error packaging ACP: ", e); } //manage import repository String pathToAlfrescoRepository = req.getParameter(PATH_TO_ALFRESCO_REPOSITORY); pathToAlfrescoRepository = "/app:company_home/" + pathToAlfrescoRepository; NodeRef repository = null; try { repository = importer.manageAlfrescoRepository(pathToAlfrescoRepository); } catch (Exception e1) { model.put("error", e1); logger.error("Error with managment of Alfresco repository: ", e1); } //import (and deploy) acp to Alfresco repository boolean saved = false; boolean imported = false; boolean clean = false; if (acp != null && repository != null) { try { saved = importer.saveACP(acp, repository); } catch (IOException e) { model.put("error", e); logger.error("Error saving ACP: ", e); } // Brice : First save (in case of problem during import in order to analyze the situation), next import try { if (saved) { imported = importer.importACP(acp, repository); } } catch (Exception e) { model.put("error", e); logger.error("Error importing ACP: ", e); } try { if (imported) { clean = packager.clean(acp); } } catch (Exception e) { model.put("error", e); logger.error("Error cleaning generated files: ", e); } if (("on").equals(foldersParameterValue)) { try { folders.manageFolders(repository); } catch (Exception e) { model.put("error", e); logger.error("Error creating folders: ", e); } } } if (clean && scenarioParameterValue.equals("incremental")) { model.put("incremental", new Object()); Integer maxAttributeIndex; try { maxAttributeIndex = Integer.valueOf(generator.getGeneratorServices().getMaxAttributeIndex()); model.put("attributeIndex", maxAttributeIndex); Map<TypeDefinition, Map<PropertyDefinition, Integer>> index = AlfrescoModelRandomDataGenerator .getIndex(); index.clear(); AlfrescoModelRandomDataGenerator.setIndex(index); Map<TypeDefinition, Integer> indexType = AlfrescoModelRandomDataGenerator.getIndexType(); indexType.clear(); AlfrescoModelRandomDataGenerator.setIndexType(indexType); } catch (Exception e) { model.put("error", e); logger.error("Error creating post parameters: ", e); } } return model; }
From source file:com.microsoft.projectoxford.vision.VisionServiceRestClient.java
@Override public byte[] getThumbnail(int width, int height, boolean smartCropping, String url) throws VisionServiceException, IOException { Map<String, Object> params = new HashMap<>(); params.put("width", width); params.put("height", height); params.put("smartCropping", smartCropping); String path = apiRoot + "/generateThumbnails"; String uri = WebServiceRequest.getUrl(path, params); params.clear(); params.put("url", url); InputStream is = (InputStream) this.restCall.request(uri, "POST", params, null, true); byte[] image = IOUtils.toByteArray(is); if (is != null) { is.close();/*from w w w.j a v a 2 s. com*/ } return image; }
From source file:com.microsoft.projectoxford.vision.VisionServiceRestClient.java
@Override public byte[] getThumbnail(int width, int height, boolean smartCropping, InputStream stream) throws VisionServiceException, IOException { Map<String, Object> params = new HashMap<>(); params.put("width", width); params.put("height", height); params.put("smartCropping", smartCropping); String path = apiRoot + "/generateThumbnails"; String uri = WebServiceRequest.getUrl(path, params); params.clear(); byte[] data = IOUtils.toByteArray(stream); params.put("data", data); InputStream is = (InputStream) this.restCall.request(uri, "POST", params, "application/octet-stream", true); byte[] image = IOUtils.toByteArray(is); if (is != null) { is.close();/*from ww w. j a v a 2 s .c om*/ } return image; }
From source file:hoot.services.osm.OsmTestUtils.java
public static Set<Long> createTestRelationsNoWays(final long changesetId, final Set<Long> nodeIds) throws Exception { Set<Long> relationIds = new LinkedHashSet<Long>(); final Long[] nodeIdsArr = nodeIds.toArray(new Long[] {}); Map<String, String> tags = new HashMap<String, String>(); List<RelationMember> members = new ArrayList<RelationMember>(); members.add(new RelationMember(nodeIdsArr[0], ElementType.Node, "role1")); members.add(new RelationMember(nodeIdsArr[2], ElementType.Node)); tags.put("key 1", "val 1"); final long firstRelationId = Relation.insertNew(changesetId, mapId, members, tags, conn); relationIds.add(firstRelationId);//from w ww . j a v a 2s . com tags.clear(); members.clear(); tags.put("key 2", "val 2"); tags.put("key 3", "val 3"); members.add(new RelationMember(nodeIdsArr[4], ElementType.Node, "role1")); members.add(new RelationMember(firstRelationId, ElementType.Relation, "role1")); relationIds.add(Relation.insertNew(changesetId, mapId, members, tags, conn)); tags.clear(); members.clear(); tags.put("key 4", "val 4"); members.add(new RelationMember(nodeIdsArr[2], ElementType.Node, "role1")); relationIds.add(Relation.insertNew(changesetId, mapId, members, tags, conn)); tags.clear(); members.clear(); return relationIds; }
From source file:com.silverwrist.dynamo.security.SRMObject.java
public DynamoAcl getAcl(int aclid) throws DatabaseException, AclNotFoundException { Integer key = new Integer(aclid); DynamoAcl rc = null;/*from ww w. j a va 2s .c o m*/ synchronized (m_cache_sync) { // look in the ACL cache first rc = (DynamoAcl) (m_cache.get(key)); if (rc == null) { // call down to the database to get the basic information Map acl_data = m_ops.getAclData(aclid); rc = new AclObject(m_ops.getAclOperations(), m_ns_cache, m_proxy, m_ace, acl_data); m_cache.put(key, rc); // cache the result acl_data.clear(); } // end if } // end synchronized block return rc; }
From source file:gxu.software_engineering.shen10.market.service.impl.UserServiceImpl.java
@Override @Transactional(readOnly = false)/* w ww . j av a2 s. co m*/ public User register(User user, String confirmedPassword) { // ???? Assert.equals(user.getPassword(), confirmedPassword, "????"); Map<String, Object> params = new HashMap<String, Object>(); params.put("account", user.getAccount()); // ?account? User u = userDao.find("User.account", params); if (u != null) { throw new RuntimeException("?account " + user.getAccount() + " ??"); } // ?nick? params.clear(); params.put("nick", user.getNick()); u = userDao.find("User.nick", params); if (u != null) { throw new RuntimeException("?nick " + user.getNick() + " ??"); } // md5? user.setPassword(Encryptor.MD5(confirmedPassword)); user.setRegisterTime(new Date()); user.setLastLoginTime(user.getRegisterTime()); user.setLoginTimes(0); // ??? userDao.persist(user); return user; }
From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImplTest.java
/** * Validate that alias paths are fixed-up. Paths added to map should: * <ol>/*w ww. java 2 s . c o m*/ * <li>Start with '/'</li> * <li>End without '/'</li> * <li>Remove duplicate '/'</li> * </ol> * @throws Exception */ @Test public void testAddAlias_pathDelimFixup() throws Exception { TestAggregatorImpl aggregator = EasyMock.createMockBuilder(TestAggregatorImpl.class).createMock(); Map<String, URI> map = new HashMap<String, URI>(); URI res = new URI("/test/resource"); aggregator.addAlias("/test", res, "", map); Assert.assertTrue(map.containsKey("/test")); map.clear(); aggregator.addAlias("test", res, "", map); Assert.assertTrue(map.containsKey("/test")); map.clear(); aggregator.addAlias("test/", res, "", map); Assert.assertTrue(map.containsKey("/test")); map.clear(); aggregator.addAlias("/test/", res, "", map); Assert.assertTrue(map.containsKey("/test")); map.clear(); aggregator.addAlias("test/foo//bar/", res, "", map); Assert.assertTrue(map.containsKey("/test/foo/bar")); }