label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public HttpURLConnection connect() throws IOException { if (url == null) { return null; } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (previousETag != null) { connection.addRequestProperty("If-None-Match", previousETag); } if (previousLastModified != null) { connection.addRequestProperty("If-Modified-Since", previousLastModified); } return connection; }
Code Sample 2:
public static int getNetFileSize(String netFile) throws InvalidActionException { URL url; URLConnection conn; int size; try { url = new URL(netFile); conn = url.openConnection(); size = conn.getContentLength(); conn.getInputStream().close(); if (size < 0) { throw new InvalidActionException("Could not determine file size."); } else { return size; } } catch (Exception e) { throw new InvalidActionException(e.getMessage()); } }
|
00
|
Code Sample 1:
public static void copy(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public void prepareOutput(HttpServletRequest req) { EaasyStreet.logTrace(METHOD_IN + className + OUTPUT_METHOD); super.prepareOutput(req); String content = Constants.EMPTY_STRING; String rawContent = null; List parts = null; try { URL url = new URL(sourceUrl); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); buffer.append(Constants.LF); } rawContent = buffer.toString(); } catch (FileNotFoundException nf) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", nf.getMessage(), nf.toString() })); } catch (Exception e) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", e.getMessage(), e.toString() })); } if (rawContent != null) { if (startDelimiter != null) { parts = StringUtils.split(rawContent, startDelimiter); if (parts != null && parts.size() > 1) { rawContent = (String) parts.get(1); if (parts.size() > 2) { for (int x = 2; x < parts.size(); x++) { rawContent += startDelimiter; rawContent += parts.get(x); } } } else { rawContent = null; } } } if (rawContent != null) { if (endDelimiter != null) { parts = StringUtils.split(rawContent, endDelimiter); if (parts != null && parts.size() > 0) { rawContent = (String) parts.get(0); } else { rawContent = null; } } } if (rawContent != null) { if (replacementValues != null && !replacementValues.isEmpty()) { for (int x = 0; x < replacementValues.size(); x++) { LabelValueBean bean = (LabelValueBean) replacementValues.get(x); rawContent = StringUtils.replace(rawContent, bean.getLabel(), bean.getValue()); } } } if (rawContent != null) { content = rawContent; } req.setAttribute(getFormName(), content); EaasyStreet.logTrace(METHOD_OUT + className + OUTPUT_METHOD); }
|
00
|
Code Sample 1:
private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
Code Sample 2:
private void saveFile(InputStream in, String fullPath) { try { File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(in, out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
Code Sample 2:
@Test public void test_blueprintDetailsForTypeName() throws Exception { URL url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar+Blueprint"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("{\"invBlueprintTypeDto\":{\"blueprintTypeID\":28849,\"blueprintTypeName\":\"Anshar Blueprint\",\"productTypeID\":28848,\"productTypeName\":\"Anshar\",\"productCategoryID\":6,\"parentBlueprintTypeID\":20188,\"parentBlueprintTypeName\":\"Obelisk Blueprint\",\"parentProductTypeID\":20187,\"parentProductTypeName\":\"Obelisk\",\"techLevel\":2,\"productionTime\":1920000,\"researchProductivityTime\":11520000,\"researchMaterialTime\":7680000,\"researchCopyTime\":2560000,\"researchTechTime\":3840000,\"productivityModifier\":384000,\"wasteFactor\":10,\"maxProductionLimit\":10,\"productVolume\":\"17550000\",\"productPortionSize\":1,\"dumpVersion\":\"cru16\"},\"materialDtos\":[{\"materialTypeID\":3828,\"materialTypeName\":\"Construction Blocks\",\"materialTypeCategoryID\":43,\"materialTypeIcon\":\"06_05\",\"materialVolume\":\"1.5\",\"quantity\":1500},{\"materialTypeID\":11399,\"materialTypeName\":\"Morphite\",\"materialTypeCategoryID\":4,\"materialTypeIcon\":\"35_02\",\"materialVolume\":\"0.01\",\"quantity\":2500},{\"materialTypeID\":21025,\"materialTypeName\":\"Capital Jump Drive\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"54_08\",\"materialVolume\":\"10000.0\",\"quantity\":20},{\"materialTypeID\":29041,\"materialTypeName\":\"Capital Crystalline Carbonide Armor Plate\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_14\",\"materialVolume\":\"10.0\",\"quantity\":1013},{\"materialTypeID\":29051,\"materialTypeName\":\"Capital Fusion Reactor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_02\",\"materialVolume\":\"10.0\",\"quantity\":518},{\"materialTypeID\":29061,\"materialTypeName\":\"Capital Ion Thruster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_02\",\"materialVolume\":\"10.0\",\"quantity\":422},{\"materialTypeID\":29069,\"materialTypeName\":\"Capital Magnetometric Sensor Cluster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_06\",\"materialVolume\":\"10.0\",\"quantity\":443},{\"materialTypeID\":29081,\"materialTypeName\":\"Capital Oscillator Capacitor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_06\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29085,\"materialTypeName\":\"Capital Photon Microprocessor\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_10\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29091,\"materialTypeName\":\"Capital Pulse Shield Emitter\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_10\",\"materialVolume\":\"10.0\",\"quantity\":449}],\"manufacturingRequirementDtos\":[{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":3380,\"requiredTypeName\":\"Industry\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":268,\"requiredTypeGroupName\":\"Industry\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11478,\"requiredTypeName\":\"R.A.M.- Starship Tech\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_02\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":20187,\"requiredTypeName\":\"Obelisk\",\"requiredTypeCategoryID\":6,\"requiredTypeGroupID\":513,\"requiredTypeGroupName\":\"Freighter\",\"damagePerJob\":\"1.0\",\"quantity\":1,\"requiredTypeVolume\":\"17550000\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":22242,\"requiredTypeName\":\"Capital Ship Construction\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":269,\"requiredTypeGroupName\":\"Mechanic\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"}],\"timeProductivityRequirementDtos\":[{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3403,\"requiredTypeName\":\"Research\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":120,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.8\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"materialProductivityRequirementDtos\":[{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3409,\"requiredTypeName\":\"Metallurgy\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":140,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.6\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"copyingRequirementDtos\":[{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":3812,\"requiredTypeName\":\"Data Sheets\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":600,\"requiredTypeVolume\":\"1.0\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"}],\"reverseEngineeringRequirementDtos\":[],\"inventionRequirementDtos\":[]}")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><blueprintDetailsDto><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>1.0</damagePerJob><quantity>600</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3812</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Data Sheets</requiredTypeName><requiredTypeVolume>1.0</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></copyingRequirementDtos><invBlueprintTypeDto><blueprintTypeID>28849</blueprintTypeID><blueprintTypeName>Anshar Blueprint</blueprintTypeName><dumpVersion>cru16</dumpVersion><maxProductionLimit>10</maxProductionLimit><parentBlueprintTypeID>20188</parentBlueprintTypeID><parentBlueprintTypeName>Obelisk Blueprint</parentBlueprintTypeName><parentProductTypeID>20187</parentProductTypeID><parentProductTypeName>Obelisk</parentProductTypeName><productCategoryID>6</productCategoryID><productPortionSize>1</productPortionSize><productTypeID>28848</productTypeID><productTypeName>Anshar</productTypeName><productVolume>17550000</productVolume><productionTime>1920000</productionTime><productivityModifier>384000</productivityModifier><researchCopyTime>2560000</researchCopyTime><researchMaterialTime>7680000</researchMaterialTime><researchProductivityTime>11520000</researchProductivityTime><researchTechTime>3840000</researchTechTime><techLevel>2</techLevel><wasteFactor>10</wasteFactor></invBlueprintTypeDto><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>268</requiredTypeGroupID><requiredTypeGroupName>Industry</requiredTypeGroupName><requiredTypeID>3380</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Industry</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11478</requiredTypeID><requiredTypeIcon>41_02</requiredTypeIcon><requiredTypeName>R.A.M.- Starship Tech</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>1.0</damagePerJob><quantity>1</quantity><requiredTypeCategoryID>6</requiredTypeCategoryID><requiredTypeGroupID>513</requiredTypeGroupID><requiredTypeGroupName>Freighter</requiredTypeGroupName><requiredTypeID>20187</requiredTypeID><requiredTypeName>Obelisk</requiredTypeName><requiredTypeVolume>17550000</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>269</requiredTypeGroupID><requiredTypeGroupName>Mechanic</requiredTypeGroupName><requiredTypeID>22242</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Capital Ship Construction</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><materialDtos><materialTypeCategoryID>43</materialTypeCategoryID><materialTypeID>3828</materialTypeID><materialTypeIcon>06_05</materialTypeIcon><materialTypeName>Construction Blocks</materialTypeName><materialVolume>1.5</materialVolume><quantity>1500</quantity></materialDtos><materialDtos><materialTypeCategoryID>4</materialTypeCategoryID><materialTypeID>11399</materialTypeID><materialTypeIcon>35_02</materialTypeIcon><materialTypeName>Morphite</materialTypeName><materialVolume>0.01</materialVolume><quantity>2500</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>21025</materialTypeID><materialTypeIcon>54_08</materialTypeIcon><materialTypeName>Capital Jump Drive</materialTypeName><materialVolume>10000.0</materialVolume><quantity>20</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29041</materialTypeID><materialTypeIcon>37_14</materialTypeIcon><materialTypeName>Capital Crystalline Carbonide Armor Plate</materialTypeName><materialVolume>10.0</materialVolume><quantity>1013</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29051</materialTypeID><materialTypeIcon>39_02</materialTypeIcon><materialTypeName>Capital Fusion Reactor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>518</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29061</materialTypeID><materialTypeIcon>37_02</materialTypeIcon><materialTypeName>Capital Ion Thruster</materialTypeName><materialVolume>10.0</materialVolume><quantity>422</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29069</materialTypeID><materialTypeIcon>37_06</materialTypeIcon><materialTypeName>Capital Magnetometric Sensor Cluster</materialTypeName><materialVolume>10.0</materialVolume><quantity>443</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29081</materialTypeID><materialTypeIcon>39_06</materialTypeIcon><materialTypeName>Capital Oscillator Capacitor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29085</materialTypeID><materialTypeIcon>37_10</materialTypeIcon><materialTypeName>Capital Photon Microprocessor</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29091</materialTypeID><materialTypeIcon>39_10</materialTypeIcon><materialTypeName>Capital Pulse Shield Emitter</materialTypeName><materialVolume>10.0</materialVolume><quantity>449</quantity></materialDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3409</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Metallurgy</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>140</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.6</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></materialProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3403</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Research</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>120</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.8</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></timeProductivityRequirementDtos></blueprintDetailsDto>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar%20Blueprint"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("{\"invBlueprintTypeDto\":{\"blueprintTypeID\":28849,\"blueprintTypeName\":\"Anshar Blueprint\",\"productTypeID\":28848,\"productTypeName\":\"Anshar\",\"productCategoryID\":6,\"parentBlueprintTypeID\":20188,\"parentBlueprintTypeName\":\"Obelisk Blueprint\",\"parentProductTypeID\":20187,\"parentProductTypeName\":\"Obelisk\",\"techLevel\":2,\"productionTime\":1920000,\"researchProductivityTime\":11520000,\"researchMaterialTime\":7680000,\"researchCopyTime\":2560000,\"researchTechTime\":3840000,\"productivityModifier\":384000,\"wasteFactor\":10,\"maxProductionLimit\":10,\"productVolume\":\"17550000\",\"productPortionSize\":1,\"dumpVersion\":\"cru16\"},\"materialDtos\":[{\"materialTypeID\":3828,\"materialTypeName\":\"Construction Blocks\",\"materialTypeCategoryID\":43,\"materialTypeIcon\":\"06_05\",\"materialVolume\":\"1.5\",\"quantity\":1500},{\"materialTypeID\":11399,\"materialTypeName\":\"Morphite\",\"materialTypeCategoryID\":4,\"materialTypeIcon\":\"35_02\",\"materialVolume\":\"0.01\",\"quantity\":2500},{\"materialTypeID\":21025,\"materialTypeName\":\"Capital Jump Drive\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"54_08\",\"materialVolume\":\"10000.0\",\"quantity\":20},{\"materialTypeID\":29041,\"materialTypeName\":\"Capital Crystalline Carbonide Armor Plate\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_14\",\"materialVolume\":\"10.0\",\"quantity\":1013},{\"materialTypeID\":29051,\"materialTypeName\":\"Capital Fusion Reactor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_02\",\"materialVolume\":\"10.0\",\"quantity\":518},{\"materialTypeID\":29061,\"materialTypeName\":\"Capital Ion Thruster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_02\",\"materialVolume\":\"10.0\",\"quantity\":422},{\"materialTypeID\":29069,\"materialTypeName\":\"Capital Magnetometric Sensor Cluster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_06\",\"materialVolume\":\"10.0\",\"quantity\":443},{\"materialTypeID\":29081,\"materialTypeName\":\"Capital Oscillator Capacitor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_06\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29085,\"materialTypeName\":\"Capital Photon Microprocessor\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_10\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29091,\"materialTypeName\":\"Capital Pulse Shield Emitter\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_10\",\"materialVolume\":\"10.0\",\"quantity\":449}],\"manufacturingRequirementDtos\":[{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":3380,\"requiredTypeName\":\"Industry\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":268,\"requiredTypeGroupName\":\"Industry\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11478,\"requiredTypeName\":\"R.A.M.- Starship Tech\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_02\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":20187,\"requiredTypeName\":\"Obelisk\",\"requiredTypeCategoryID\":6,\"requiredTypeGroupID\":513,\"requiredTypeGroupName\":\"Freighter\",\"damagePerJob\":\"1.0\",\"quantity\":1,\"requiredTypeVolume\":\"17550000\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":22242,\"requiredTypeName\":\"Capital Ship Construction\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":269,\"requiredTypeGroupName\":\"Mechanic\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"}],\"timeProductivityRequirementDtos\":[{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3403,\"requiredTypeName\":\"Research\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":120,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.8\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"materialProductivityRequirementDtos\":[{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3409,\"requiredTypeName\":\"Metallurgy\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":140,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.6\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"copyingRequirementDtos\":[{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":3812,\"requiredTypeName\":\"Data Sheets\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":600,\"requiredTypeVolume\":\"1.0\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"}],\"reverseEngineeringRequirementDtos\":[],\"inventionRequirementDtos\":[]}")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><blueprintDetailsDto><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>1.0</damagePerJob><quantity>600</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3812</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Data Sheets</requiredTypeName><requiredTypeVolume>1.0</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></copyingRequirementDtos><invBlueprintTypeDto><blueprintTypeID>28849</blueprintTypeID><blueprintTypeName>Anshar Blueprint</blueprintTypeName><dumpVersion>cru16</dumpVersion><maxProductionLimit>10</maxProductionLimit><parentBlueprintTypeID>20188</parentBlueprintTypeID><parentBlueprintTypeName>Obelisk Blueprint</parentBlueprintTypeName><parentProductTypeID>20187</parentProductTypeID><parentProductTypeName>Obelisk</parentProductTypeName><productCategoryID>6</productCategoryID><productPortionSize>1</productPortionSize><productTypeID>28848</productTypeID><productTypeName>Anshar</productTypeName><productVolume>17550000</productVolume><productionTime>1920000</productionTime><productivityModifier>384000</productivityModifier><researchCopyTime>2560000</researchCopyTime><researchMaterialTime>7680000</researchMaterialTime><researchProductivityTime>11520000</researchProductivityTime><researchTechTime>3840000</researchTechTime><techLevel>2</techLevel><wasteFactor>10</wasteFactor></invBlueprintTypeDto><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>268</requiredTypeGroupID><requiredTypeGroupName>Industry</requiredTypeGroupName><requiredTypeID>3380</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Industry</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11478</requiredTypeID><requiredTypeIcon>41_02</requiredTypeIcon><requiredTypeName>R.A.M.- Starship Tech</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>1.0</damagePerJob><quantity>1</quantity><requiredTypeCategoryID>6</requiredTypeCategoryID><requiredTypeGroupID>513</requiredTypeGroupID><requiredTypeGroupName>Freighter</requiredTypeGroupName><requiredTypeID>20187</requiredTypeID><requiredTypeName>Obelisk</requiredTypeName><requiredTypeVolume>17550000</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>269</requiredTypeGroupID><requiredTypeGroupName>Mechanic</requiredTypeGroupName><requiredTypeID>22242</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Capital Ship Construction</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><materialDtos><materialTypeCategoryID>43</materialTypeCategoryID><materialTypeID>3828</materialTypeID><materialTypeIcon>06_05</materialTypeIcon><materialTypeName>Construction Blocks</materialTypeName><materialVolume>1.5</materialVolume><quantity>1500</quantity></materialDtos><materialDtos><materialTypeCategoryID>4</materialTypeCategoryID><materialTypeID>11399</materialTypeID><materialTypeIcon>35_02</materialTypeIcon><materialTypeName>Morphite</materialTypeName><materialVolume>0.01</materialVolume><quantity>2500</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>21025</materialTypeID><materialTypeIcon>54_08</materialTypeIcon><materialTypeName>Capital Jump Drive</materialTypeName><materialVolume>10000.0</materialVolume><quantity>20</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29041</materialTypeID><materialTypeIcon>37_14</materialTypeIcon><materialTypeName>Capital Crystalline Carbonide Armor Plate</materialTypeName><materialVolume>10.0</materialVolume><quantity>1013</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29051</materialTypeID><materialTypeIcon>39_02</materialTypeIcon><materialTypeName>Capital Fusion Reactor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>518</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29061</materialTypeID><materialTypeIcon>37_02</materialTypeIcon><materialTypeName>Capital Ion Thruster</materialTypeName><materialVolume>10.0</materialVolume><quantity>422</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29069</materialTypeID><materialTypeIcon>37_06</materialTypeIcon><materialTypeName>Capital Magnetometric Sensor Cluster</materialTypeName><materialVolume>10.0</materialVolume><quantity>443</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29081</materialTypeID><materialTypeIcon>39_06</materialTypeIcon><materialTypeName>Capital Oscillator Capacitor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29085</materialTypeID><materialTypeIcon>37_10</materialTypeIcon><materialTypeName>Capital Photon Microprocessor</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29091</materialTypeID><materialTypeIcon>39_10</materialTypeIcon><materialTypeName>Capital Pulse Shield Emitter</materialTypeName><materialVolume>10.0</materialVolume><quantity>449</quantity></materialDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3409</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Metallurgy</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>140</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.6</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></materialProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3403</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Research</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>120</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.8</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></timeProductivityRequirementDtos></blueprintDetailsDto>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar Blueprint"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
|
00
|
Code Sample 1:
@Override public void connect() throws IOException { URL url = getLocator().getURL(); if (url.getProtocol().equals("file")) { final String newUrlStr = URLUtils.createAbsoluteFileUrl(url.toExternalForm()); if (newUrlStr != null) { if (!newUrlStr.toString().equals(url.toExternalForm())) { logger.warning("Changing file URL to absolute for URL.openConnection, from " + url.toExternalForm() + " to " + newUrlStr); url = new URL(newUrlStr); } } } conn = url.openConnection(); if (!url.getProtocol().equals("ftp") && conn.getURL().getProtocol().equals("ftp")) { logger.warning("URL.openConnection() morphed " + url + " to " + conn.getURL()); throw new IOException("URL.openConnection() returned an FTP connection for a non-ftp url: " + url); } if (conn instanceof HttpURLConnection) { final HttpURLConnection huc = (HttpURLConnection) conn; huc.connect(); final int code = huc.getResponseCode(); if (!(code >= 200 && code < 300)) { huc.disconnect(); throw new IOException("HTTP response code: " + code); } logger.finer("URL: " + url); logger.finer("Response code: " + code); logger.finer("Full content type: " + conn.getContentType()); boolean contentTypeSet = false; if (stripTrailer(conn.getContentType()).equals("text/plain")) { final String ext = PathUtils.extractExtension(url.getPath()); if (ext != null) { final String result = MimeManager.getMimeType(ext); if (result != null) { contentTypeStr = ContentDescriptor.mimeTypeToPackageName(result); contentTypeSet = true; logger.fine("Received content type " + conn.getContentType() + "; overriding based on extension, to: " + result); } } } if (!contentTypeSet) contentTypeStr = ContentDescriptor.mimeTypeToPackageName(stripTrailer(conn.getContentType())); } else { conn.connect(); contentTypeStr = ContentDescriptor.mimeTypeToPackageName(conn.getContentType()); } contentType = new ContentDescriptor(contentTypeStr); sources = new URLSourceStream[1]; sources[0] = new URLSourceStream(); connected = true; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public static void contentTrans(String contents, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } try { Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(contents); bufferedWriter.flush(); bufferedWriter.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static void BubbleSortInt2(int[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { int temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
|
00
|
Code Sample 1:
public String upload() throws IOException { int idx = docIndex.incrementAndGet(); String tmpName = "namefinder/doc_" + idx + "__" + fileFileName; File tmpFile = tmpFile(tmpName); if (tmpFile.exists()) { org.apache.commons.io.FileUtils.deleteQuietly(tmpFile); } org.apache.commons.io.FileUtils.touch(tmpFile); InputStream fileStream = new FileInputStream(file); OutputStream bos = new FileOutputStream(tmpFile); IOUtils.copy(fileStream, bos); bos.close(); fileStream.close(); return tmpUrl(tmpName); }
Code Sample 2:
private String readData(URL url) { try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = in.readLine()) != null) { responseBuffer.append(line); } in.close(); return new String(responseBuffer); } catch (Exception e) { System.out.println(e); } return null; }
|
00
|
Code Sample 1:
private String encode(String arg) { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(arg.getBytes()); byte[] md5sum = digest.digest(); final BigInteger bigInt = new BigInteger(1, md5sum); final String output = bigInt.toString(16); return output; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 required: " + e.getMessage(), e); } }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } }
|
11
|
Code Sample 1:
public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (queue == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); getQueue().post(eventObj); return eventDoc.getEvent().getEventId(); }
Code Sample 2:
public static final boolean compressToZip(final String sSource, final String sDest, final boolean bDeleteSourceOnSuccess) { ZipOutputStream os = null; InputStream is = null; try { os = new ZipOutputStream(new FileOutputStream(sDest)); is = new FileInputStream(sSource); final byte[] buff = new byte[1024]; int r; String sFileName = sSource; if (sFileName.indexOf('/') >= 0) sFileName = sFileName.substring(sFileName.lastIndexOf('/') + 1); os.putNextEntry(new ZipEntry(sFileName)); while ((r = is.read(buff)) > 0) os.write(buff, 0, r); is.close(); os.flush(); os.closeEntry(); os.close(); } catch (Throwable e) { Log.log(Log.WARNING, "lazyj.Utils", "compressToZip : cannot compress '" + sSource + "' to '" + sDest + "' because", e); return false; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } if (os != null) { try { os.close(); } catch (IOException ioe) { } } } if (bDeleteSourceOnSuccess) try { if (!(new File(sSource)).delete()) Log.log(Log.WARNING, "lazyj.Utils", "compressToZip: could not delete original file (" + sSource + ")"); } catch (SecurityException se) { Log.log(Log.ERROR, "lazyj.Utils", "compressToZip: security constraints prevents file deletion"); } return true; }
|
11
|
Code Sample 1:
public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } }
Code Sample 2:
private void fileCopy(final File src, final File dest) throws IOException { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
11
|
Code Sample 1:
public void run() { String s; s = ""; try { URL url = new URL("http://www.askoxford.com/concise_oed/" + word.toLowerCase() + "?view=uk"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("<h2>" + word.toLowerCase() + "(.+?)<p><a href", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } button.setEnabled(true); }
Code Sample 2:
public boolean initFile(String filename) { showStatus("Loading the file, please wait..."); x_units = "?"; y_units = "ARBITRARY"; Datatype = "UNKNOWN"; if (filename.toLowerCase().endsWith(".spc")) { try { URL url = new URL(getDocumentBase(), filename); InputStream stream = url.openStream(); DataInputStream fichier = new DataInputStream(stream); byte ftflgs = fichier.readByte(); byte fversn = fichier.readByte(); if (((ftflgs != 0) && (ftflgs != 0x20)) || (fversn != 0x4B)) { Current_Error = ", support only Evenly Spaced new version 4B"; return false; } byte fexp = fichier.readByte(); if (fexp != 0x80) YFactor = Math.pow(2, fexp) / Math.pow(2, 32); Nbpoints = NumericDataUtils.convToIntelInt(fichier.readInt()); if (Firstx == shitty_starting_constant) { Firstx = NumericDataUtils.convToIntelDouble(fichier.readLong()); Lastx = NumericDataUtils.convToIntelDouble(fichier.readLong()); } byte fxtype = fichier.readByte(); switch(fxtype) { case 0: x_units = "Arbitrary"; break; case 1: x_units = "Wavenumber (cm -1)"; break; case 2: x_units = "Micrometers"; break; case 3: x_units = "Nanometers"; break; case 4: x_units = "Seconds"; break; case 5: x_units = "Minuts"; break; case 6: x_units = "Hertz"; break; case 7: x_units = "Kilohertz"; break; case 8: x_units = "Megahertz"; break; case 9: x_units = "Mass (M/z)"; break; case 10: x_units = "Parts per million"; break; case 11: x_units = "Days"; break; case 12: x_units = "Years"; break; case 13: x_units = "Raman Shift (cm -1)"; break; case 14: x_units = "Electron Volt (eV)"; break; case 16: x_units = "Diode Number"; break; case 17: x_units = "Channel"; break; case 18: x_units = "Degrees"; break; case 19: x_units = "Temperature (F)"; break; case 20: x_units = "Temperature (C)"; break; case 21: x_units = "Temperature (K)"; break; case 22: x_units = "Data Points"; break; case 23: x_units = "Milliseconds (mSec)"; break; case 24: x_units = "Microseconds (uSec)"; break; case 25: x_units = "Nanoseconds (nSec)"; break; case 26: x_units = "Gigahertz (GHz)"; break; case 27: x_units = "Centimeters (cm)"; break; case 28: x_units = "Meters (m)"; break; case 29: x_units = "Millimeters (mm)"; break; case 30: x_units = "Hours"; break; case -1: x_units = "(double interferogram)"; break; } byte fytype = fichier.readByte(); switch(fytype) { case 0: y_units = "Arbitrary Intensity"; break; case 1: y_units = "Interfeogram"; break; case 2: y_units = "Absorbance"; break; case 3: y_units = "Kubelka-Munk"; break; case 4: y_units = "Counts"; break; case 5: y_units = "Volts"; break; case 6: y_units = "Degrees"; break; case 7: y_units = "Milliamps"; break; case 8: y_units = "Millimeters"; break; case 9: y_units = "Millivolts"; break; case 10: y_units = "Log (1/R)"; break; case 11: y_units = "Percent"; break; case 12: y_units = "Intensity"; break; case 13: y_units = "Relative Intensity"; break; case 14: y_units = "Energy"; break; case 16: y_units = "Decibel"; break; case 19: y_units = "Temperature (F)"; break; case 20: y_units = "Temperature (C)"; break; case 21: y_units = "Temperature (K)"; break; case 22: y_units = "Index of Refraction [N]"; break; case 23: y_units = "Extinction Coeff. [K]"; break; case 24: y_units = "Real"; break; case 25: y_units = "Imaginary"; break; case 26: y_units = "Complex"; break; case -128: y_units = "Transmission"; break; case -127: y_units = "Reflectance"; break; case -126: y_units = "Arbitrary or Single Beam with Valley Peaks"; break; case -125: y_units = "Emission"; break; } if (ftflgs == 0) { fichier.skipBytes(512 - 30); } else { fichier.skipBytes(188); byte b; int i = 0; x_units = ""; do { b = fichier.readByte(); x_units += (char) b; i++; } while (b != 0); int j = 0; y_units = ""; do { b = fichier.readByte(); y_units += (char) b; j++; } while (b != 0); fichier.skipBytes(512 - 30 - 188 - i - j); } fichier.skipBytes(32); My_ZoneVisu.tableau_points = new double[Nbpoints]; if (fexp == 0x80) { for (int i = 0; i < Nbpoints; i++) { My_ZoneVisu.tableau_points[i] = NumericDataUtils.convToIntelFloat(fichier.readInt()); } } else { for (int i = 0; i < Nbpoints; i++) { My_ZoneVisu.tableau_points[i] = NumericDataUtils.convToIntelInt(fichier.readInt()); } } } catch (Exception e) { Current_Error = "SPC file corrupted"; return false; } Datatype = "XYDATA"; return true; } try { URL url = new URL(getDocumentBase(), filename); InputStream stream = url.openStream(); BufferedReader fichier = new BufferedReader(new InputStreamReader(stream)); texte = new Vector(); String s; while ((s = fichier.readLine()) != null) { texte.addElement(s); } nbLignes = texte.size(); } catch (Exception e) { return false; } int My_Counter = 0; String uneligne = ""; while (My_Counter < nbLignes) { try { StringTokenizer mon_token; do { uneligne = (String) texte.elementAt(My_Counter); My_Counter++; mon_token = new StringTokenizer(uneligne, " "); } while (My_Counter < nbLignes && mon_token.hasMoreTokens() == false); if (mon_token.hasMoreTokens() == true) { String keyword = mon_token.nextToken(); if (StringDataUtils.compareStrings(keyword, "##TITLE=") == 0) TexteTitre = uneligne.substring(9); if (StringDataUtils.compareStrings(keyword, "##FIRSTX=") == 0) Firstx = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##LASTX=") == 0) Lastx = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##YFACTOR=") == 0) YFactor = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##NPOINTS=") == 0) Nbpoints = Integer.valueOf(mon_token.nextToken()).intValue(); if (StringDataUtils.compareStrings(keyword, "##XUNITS=") == 0) x_units = uneligne.substring(10); if (StringDataUtils.compareStrings(keyword, "##YUNITS=") == 0) y_units = uneligne.substring(10); if (StringDataUtils.compareStrings(keyword, "##.OBSERVE") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "FREQUENCY=") == 0) nmr_observe_frequency = Double.valueOf(mon_token.nextToken()).doubleValue(); if (StringDataUtils.compareStrings(keyword, "##XYDATA=") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "(X++(Y..Y))") == 0) Datatype = "XYDATA"; if (StringDataUtils.compareStrings(keyword, "##XYDATA=(X++(Y..Y))") == 0) Datatype = "XYDATA"; if (StringDataUtils.compareStrings(keyword, "##PEAK") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "TABLE=") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "(XY..XY)") == 0) Datatype = "PEAK TABLE"; if (StringDataUtils.compareStrings(keyword, "##PEAK") == 0 && StringDataUtils.compareStrings(mon_token.nextToken(), "TABLE=(XY..XY)") == 0) Datatype = "PEAK TABLE"; } } catch (Exception e) { } } if (Datatype.compareTo("UNKNOWN") == 0) return false; if (Datatype.compareTo("PEAK TABLE") == 0 && x_units.compareTo("?") == 0) x_units = "M/Z"; if (StringDataUtils.truncateEndBlanks(x_units).compareTo("HZ") == 0 && nmr_observe_frequency != shitty_starting_constant) { Firstx /= nmr_observe_frequency; Lastx /= nmr_observe_frequency; x_units = "PPM."; } String resultat_move_points = Move_Points_To_Tableau(); if (resultat_move_points.compareTo("OK") != 0) { Current_Error = resultat_move_points; return false; } return true; }
|
11
|
Code Sample 1:
private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } }
|
11
|
Code Sample 1:
ServiceDescription getServiceDescription() throws ConfigurationException { final XPath pathsXPath = this.xPathFactory.newXPath(); try { final Node serviceDescriptionNode = (Node) pathsXPath.evaluate(ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration, XPathConstants.NODE); final String title = getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.TITLE_ELEMENT); ServiceDescription.Builder builder = new ServiceDescription.Builder(title, Migrate.class.getCanonicalName()); Property[] serviceProperties = getServiceProperties(serviceDescriptionNode); builder.author(getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.CREATOR_ELEMENT)); builder.classname(this.canonicalServiceName); builder.description(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.DESCRIPTION_ELEMENT)); final String serviceVersion = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.VERSION_ELEMENT); final Tool toolDescription = getToolDescriptionElement(serviceDescriptionNode); String identifier = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.IDENTIFIER_ELEMENT); if (identifier == null || "".equals(identifier)) { try { final MessageDigest identDigest = MessageDigest.getInstance("MD5"); identDigest.update(this.canonicalServiceName.getBytes()); final String versionInfo = (serviceVersion != null) ? serviceVersion : ""; identDigest.update(versionInfo.getBytes()); final URI toolIDURI = toolDescription.getIdentifier(); final String toolIdentifier = toolIDURI == null ? "" : toolIDURI.toString(); identDigest.update(toolIdentifier.getBytes()); final BigInteger md5hash = new BigInteger(identDigest.digest()); identifier = md5hash.toString(16); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } } builder.identifier(identifier); builder.version(serviceVersion); builder.tool(toolDescription); builder.instructions(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.INSTRUCTIONS_ELEMENT)); builder.furtherInfo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.FURTHER_INFO_ELEMENT)); builder.logo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.LOGO_ELEMENT)); builder.serviceProvider(this.serviceProvider); final DBMigrationPathFactory migrationPathFactory = new DBMigrationPathFactory(this.configuration); final MigrationPaths migrationPaths = migrationPathFactory.getAllMigrationPaths(); builder.paths(MigrationPathConverter.toPlanetsPaths(migrationPaths)); builder.inputFormats(migrationPaths.getInputFormatURIs().toArray(new URI[0])); builder.parameters(getUniqueParameters(migrationPaths)); builder.properties(serviceProperties); return builder.build(); } catch (XPathExpressionException xPathExpressionException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), xPathExpressionException); } catch (NullPointerException nullPointerException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), nullPointerException); } }
Code Sample 2:
public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
|
00
|
Code Sample 1:
public static void copy(final File src, File dst, final boolean overwrite) throws IOException, IllegalArgumentException { if (!src.isFile() || !src.exists()) { throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); } if (dst.exists()) { if (dst.isDirectory()) { dst = new File(dst, src.getName()); } else if (dst.isFile()) { if (!overwrite) { throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); } } else { throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); } } final File dstParent = dst.getParentFile(); if (!dstParent.exists()) { if (!dstParent.mkdirs()) { throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); } } long fileSize = src.length(); if (fileSize > 20971520l) { final FileInputStream in = new FileInputStream(src); final FileOutputStream out = new FileOutputStream(dst); try { int doneCnt = -1; final int bufSize = 32768; final byte buf[] = new byte[bufSize]; while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) { if (doneCnt == 0) { Thread.yield(); } else { out.write(buf, 0, doneCnt); } } out.flush(); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } } } else { final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } } } }
Code Sample 2:
private static String readGeoJSON(String feature) { StringBuffer content = new StringBuffer(); try { URL url = new URL(feature); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { content.append(line); } conn.disconnect(); } catch (Exception e) { } return content.toString(); }
|
00
|
Code Sample 1:
public static void copyFile(File in, File out) throws FileNotFoundException, IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { sourceChannel.close(); } catch (Exception ex) { } try { destinationChannel.close(); } catch (Exception ex) { } } }
Code Sample 2:
public void submitReport() { String subject = m_Subject.getText(); String description = m_Description.getText(); String email = m_Email.getText(); if (subject.length() == 0) { Util.flashComponent(m_Subject, Color.RED); return; } if (description.length() == 0) { Util.flashComponent(m_Description, Color.RED); return; } DynamicLocalisation loc = m_MainFrame.getLocalisation(); if (email.length() == 0 || email.indexOf("@") == -1 || email.indexOf(".") == -1 || email.startsWith("@")) { email = "anonymous@blaat.com"; } try { String data = URLEncoder.encode("mode", "UTF-8") + "=" + URLEncoder.encode("manual", "UTF-8"); data += "&" + URLEncoder.encode("from", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8"); data += "&" + URLEncoder.encode("subject", "UTF-8") + "=" + URLEncoder.encode(subject, "UTF-8"); data += "&" + URLEncoder.encode("body", "UTF-8") + "=" + URLEncoder.encode(description, "UTF-8"); data += "&" + URLEncoder.encode("jvm", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("java.version"), "UTF-8"); data += "&" + URLEncoder.encode("ocdsver", "UTF-8") + "=" + URLEncoder.encode(Constants.OPENCDS_VERSION, "UTF-8"); data += "&" + URLEncoder.encode("os", "UTF-8") + "=" + URLEncoder.encode(Constants.OS_NAME + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"), "UTF-8"); URL url = new URL(Constants.BUGREPORT_SCRIPT); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); JOptionPane.showMessageDialog(this, loc.getMessage("ReportBug.SentMessage")); } catch (Exception e) { Logger.getInstance().logException(e); } dispose(); }
|
00
|
Code Sample 1:
@Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (!lastVersion.equals(G15LastfmPlayer.getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } }
Code Sample 2:
public InputStream getResourceAsStream(String path) { try { URL url = getResource(path); if (url != null) { return url.openStream(); } else { return null; } } catch (IOException ioe) { return null; } }
|
11
|
Code Sample 1:
public static Chunk updateLastSend(Chunk c) throws Exception { DBConnectionManager dbm = null; Connection conn = null; PreparedStatement stmt = null; Chunk ret = null; String SQL = "UPDATE CHUNK SET SENT=? WHERE FILEHASH=? AND STARTOFF=? AND LENGTH=?"; log.debug("update chunk last sent for chunk " + c.getHash() + " startoff " + c.getStartOffset()); try { dbm = DBConnectionManager.getInstance(); conn = dbm.getConnection("satmule"); stmt = conn.prepareStatement(SQL); stmt.setDate(1, new java.sql.Date(c.getLastSend().getTime())); stmt.setString(2, c.getHash()); stmt.setLong(3, c.getStartOffset()); stmt.setLong(4, c.getSize()); stmt.executeUpdate(); conn.commit(); stmt.close(); dbm.freeConnection("satmule", conn); } catch (Exception e) { log.error("Error while updating chunk " + c.getHash() + "offset:" + c.getStartOffset() + "SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (conn == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { conn.rollback(); excep = new Exception("SQL Error : " + SQL + " error: " + e); dbm.freeConnection("satmule", conn); } throw excep; } return ret; }
Code Sample 2:
public void appendMessage(MimeMessage oMsg) throws FolderClosedException, StoreClosedException, MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.appendMessage()"); DebugFile.incIdent(); } final String EmptyString = ""; if (!((DBStore) getStore()).isConnected()) { if (DebugFile.trace) DebugFile.decIdent(); throw new StoreClosedException(getStore(), "Store is not connected"); } if (0 == (iOpenMode & READ_WRITE)) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open is READ_WRITE mode"); } if ((0 == (iOpenMode & MODE_MBOX)) && (0 == (iOpenMode & MODE_BLOB))) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open in MBOX nor BLOB mode"); } String gu_mimemsg; if (oMsg.getClass().getName().equals("com.knowgate.hipermail.DBMimeMessage")) { gu_mimemsg = ((DBMimeMessage) oMsg).getMessageGuid(); if (((DBMimeMessage) oMsg).getFolder() == null) ((DBMimeMessage) oMsg).setFolder(this); } else { gu_mimemsg = Gadgets.generateUUID(); } String gu_workarea = ((DBStore) getStore()).getUser().getString(DB.gu_workarea); int iSize = oMsg.getSize(); if (DebugFile.trace) DebugFile.writeln("MimeMessage.getSize() = " + String.valueOf(iSize)); String sContentType, sContentID, sMessageID, sDisposition, sContentMD5, sDescription, sFileName, sEncoding, sSubject, sPriority, sMsgCharSeq; long lPosition = -1; try { sMessageID = oMsg.getMessageID(); if (sMessageID == null || EmptyString.equals(sMessageID)) { try { sMessageID = oMsg.getHeader("X-Qmail-Scanner-Message-ID", null); } catch (Exception ignore) { } } if (sMessageID != null) sMessageID = MimeUtility.decodeText(sMessageID); sContentType = oMsg.getContentType(); if (sContentType != null) sContentType = MimeUtility.decodeText(sContentType); sContentID = oMsg.getContentID(); if (sContentID != null) sContentID = MimeUtility.decodeText(sContentID); sDisposition = oMsg.getDisposition(); if (sDisposition != null) sDisposition = MimeUtility.decodeText(sDisposition); sContentMD5 = oMsg.getContentMD5(); if (sContentMD5 != null) sContentMD5 = MimeUtility.decodeText(sContentMD5); sDescription = oMsg.getDescription(); if (sDescription != null) sDescription = MimeUtility.decodeText(sDescription); sFileName = oMsg.getFileName(); if (sFileName != null) sFileName = MimeUtility.decodeText(sFileName); sEncoding = oMsg.getEncoding(); if (sEncoding != null) sEncoding = MimeUtility.decodeText(sEncoding); sSubject = oMsg.getSubject(); if (sSubject != null) sSubject = MimeUtility.decodeText(sSubject); sPriority = null; sMsgCharSeq = null; } catch (UnsupportedEncodingException uee) { throw new MessagingException(uee.getMessage(), uee); } BigDecimal dPgMessage = null; try { dPgMessage = getNextMessage(); } catch (SQLException sqle) { throw new MessagingException(sqle.getMessage(), sqle); } String sBoundary = getPartsBoundary(oMsg); if (DebugFile.trace) DebugFile.writeln("part boundary is \"" + (sBoundary == null ? "null" : sBoundary) + "\""); if (sMessageID == null) sMessageID = gu_mimemsg; else if (sMessageID.length() == 0) sMessageID = gu_mimemsg; Timestamp tsSent; if (oMsg.getSentDate() != null) tsSent = new Timestamp(oMsg.getSentDate().getTime()); else tsSent = null; Timestamp tsReceived; if (oMsg.getReceivedDate() != null) tsReceived = new Timestamp(oMsg.getReceivedDate().getTime()); else tsReceived = new Timestamp(new java.util.Date().getTime()); try { String sXPriority = oMsg.getHeader("X-Priority", null); if (sXPriority == null) sPriority = null; else { sPriority = ""; for (int x = 0; x < sXPriority.length(); x++) { char cAt = sXPriority.charAt(x); if (cAt >= (char) 48 || cAt <= (char) 57) sPriority += cAt; } sPriority = Gadgets.left(sPriority, 10); } } catch (MessagingException msge) { if (DebugFile.trace) DebugFile.writeln("MessagingException " + msge.getMessage()); } boolean bIsSpam = false; try { String sXSpam = oMsg.getHeader("X-Spam-Flag", null); if (sXSpam != null) bIsSpam = (sXSpam.toUpperCase().indexOf("YES") >= 0 || sXSpam.toUpperCase().indexOf("TRUE") >= 0 || sXSpam.indexOf("1") >= 0); } catch (MessagingException msge) { if (DebugFile.trace) DebugFile.writeln("MessagingException " + msge.getMessage()); } if (DebugFile.trace) DebugFile.writeln("MimeMessage.getFrom()"); Address[] aFrom = null; try { aFrom = oMsg.getFrom(); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("From AddressException " + adre.getMessage()); } InternetAddress oFrom; if (aFrom != null) { if (aFrom.length > 0) oFrom = (InternetAddress) aFrom[0]; else oFrom = null; } else oFrom = null; if (DebugFile.trace) DebugFile.writeln("MimeMessage.getReplyTo()"); Address[] aReply = null; InternetAddress oReply; try { aReply = oMsg.getReplyTo(); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("Reply-To AddressException " + adre.getMessage()); } if (aReply != null) { if (aReply.length > 0) oReply = (InternetAddress) aReply[0]; else oReply = null; } else { if (DebugFile.trace) DebugFile.writeln("no reply-to address found"); oReply = null; } if (DebugFile.trace) DebugFile.writeln("MimeMessage.getRecipients()"); Address[] oTo = null; Address[] oCC = null; Address[] oBCC = null; try { oTo = oMsg.getRecipients(MimeMessage.RecipientType.TO); oCC = oMsg.getRecipients(MimeMessage.RecipientType.CC); oBCC = oMsg.getRecipients(MimeMessage.RecipientType.BCC); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("Recipient AddressException " + adre.getMessage()); } Properties pFrom = new Properties(), pTo = new Properties(), pCC = new Properties(), pBCC = new Properties(); if (DebugFile.trace) DebugFile.writeln("MimeMessage.getFlags()"); Flags oFlgs = oMsg.getFlags(); if (oFlgs == null) oFlgs = new Flags(); MimePart oText = null; ByteArrayOutputStream byOutStrm = null; File oFile = null; MboxFile oMBox = null; if ((iOpenMode & MODE_MBOX) != 0) { try { if (DebugFile.trace) DebugFile.writeln("new File(" + Gadgets.chomp(sFolderDir, File.separator) + oCatg.getStringNull(DB.nm_category, "null") + ".mbox)"); oFile = getFile(); lPosition = oFile.length(); if (DebugFile.trace) DebugFile.writeln("message position is " + String.valueOf(lPosition)); oMBox = new MboxFile(oFile, MboxFile.READ_WRITE); if (DebugFile.trace) DebugFile.writeln("new ByteArrayOutputStream(" + String.valueOf(iSize > 0 ? iSize : 16000) + ")"); byOutStrm = new ByteArrayOutputStream(iSize > 0 ? iSize : 16000); oMsg.writeTo(byOutStrm); sMsgCharSeq = byOutStrm.toString("ISO8859_1"); byOutStrm.close(); } catch (IOException ioe) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(ioe.getMessage(), ioe); } } try { if (oMsg.getClass().getName().equals("com.knowgate.hipermail.DBMimeMessage")) oText = ((DBMimeMessage) oMsg).getBody(); else { oText = new DBMimeMessage(oMsg).getBody(); } if (DebugFile.trace) DebugFile.writeln("ByteArrayOutputStream byOutStrm = new ByteArrayOutputStream(" + oText.getSize() + ")"); byOutStrm = new ByteArrayOutputStream(oText.getSize() > 0 ? oText.getSize() : 8192); oText.writeTo(byOutStrm); if (null == sContentMD5) { MD5 oMd5 = new MD5(); oMd5.Init(); oMd5.Update(byOutStrm.toByteArray()); sContentMD5 = Gadgets.toHexString(oMd5.Final()); oMd5 = null; } } catch (IOException ioe) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("IOException " + ioe.getMessage(), ioe); } catch (OutOfMemoryError oom) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("OutOfMemoryError " + oom.getMessage()); } String sSQL = "INSERT INTO " + DB.k_mime_msgs + "(gu_mimemsg,gu_workarea,gu_category,id_type,id_content,id_message,id_disposition,len_mimemsg,tx_md5,de_mimemsg,file_name,tx_encoding,tx_subject,dt_sent,dt_received,tx_email_from,nm_from,tx_email_reply,nm_to,id_priority,bo_answered,bo_deleted,bo_draft,bo_flagged,bo_recent,bo_seen,bo_spam,pg_message,nu_position,by_content) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); PreparedStatement oStmt = null; try { oStmt = oConn.prepareStatement(sSQL); oStmt.setString(1, gu_mimemsg); oStmt.setString(2, gu_workarea); if (oCatg.isNull(DB.gu_category)) oStmt.setNull(3, Types.CHAR); else oStmt.setString(3, oCatg.getString(DB.gu_category)); oStmt.setString(4, Gadgets.left(sContentType, 254)); oStmt.setString(5, Gadgets.left(sContentID, 254)); oStmt.setString(6, Gadgets.left(sMessageID, 254)); oStmt.setString(7, Gadgets.left(sDisposition, 100)); if ((iOpenMode & MODE_MBOX) != 0) { iSize = sMsgCharSeq.length(); oStmt.setInt(8, iSize); } else { if (iSize >= 0) oStmt.setInt(8, iSize); else oStmt.setNull(8, Types.INTEGER); } oStmt.setString(9, Gadgets.left(sContentMD5, 32)); oStmt.setString(10, Gadgets.left(sDescription, 254)); oStmt.setString(11, Gadgets.left(sFileName, 254)); oStmt.setString(12, Gadgets.left(sEncoding, 16)); oStmt.setString(13, Gadgets.left(sSubject, 254)); oStmt.setTimestamp(14, tsSent); oStmt.setTimestamp(15, tsReceived); if (null == oFrom) { oStmt.setNull(16, Types.VARCHAR); oStmt.setNull(17, Types.VARCHAR); } else { oStmt.setString(16, Gadgets.left(oFrom.getAddress(), 254)); oStmt.setString(17, Gadgets.left(oFrom.getPersonal(), 254)); } if (null == oReply) oStmt.setNull(18, Types.VARCHAR); else oStmt.setString(18, Gadgets.left(oReply.getAddress(), 254)); Address[] aRecipients; String sRecipientName; aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.TO); if (null != aRecipients) if (aRecipients.length == 0) aRecipients = null; if (null != aRecipients) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else { aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.CC); if (null != aRecipients) { if (aRecipients.length > 0) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else oStmt.setNull(19, Types.VARCHAR); } else { aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.BCC); if (null != aRecipients) { if (aRecipients.length > 0) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else oStmt.setNull(19, Types.VARCHAR); } else { oStmt.setNull(19, Types.VARCHAR); } } } if (null == sPriority) oStmt.setNull(20, Types.VARCHAR); else oStmt.setString(20, sPriority); if (oConn.getDataBaseProduct() == JDCConnection.DBMS_ORACLE) { if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBigDecimal(21, ...)"); oStmt.setBigDecimal(21, new BigDecimal(oFlgs.contains(Flags.Flag.ANSWERED) ? "1" : "0")); oStmt.setBigDecimal(22, new BigDecimal(oFlgs.contains(Flags.Flag.DELETED) ? "1" : "0")); oStmt.setBigDecimal(23, new BigDecimal(0)); oStmt.setBigDecimal(24, new BigDecimal(oFlgs.contains(Flags.Flag.FLAGGED) ? "1" : "0")); oStmt.setBigDecimal(25, new BigDecimal(oFlgs.contains(Flags.Flag.RECENT) ? "1" : "0")); oStmt.setBigDecimal(26, new BigDecimal(oFlgs.contains(Flags.Flag.SEEN) ? "1" : "0")); oStmt.setBigDecimal(27, new BigDecimal(bIsSpam ? "1" : "0")); oStmt.setBigDecimal(28, dPgMessage); if ((iOpenMode & MODE_MBOX) != 0) oStmt.setBigDecimal(29, new BigDecimal(lPosition)); else oStmt.setNull(29, Types.NUMERIC); if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBinaryStream(30, new ByteArrayInputStream(" + String.valueOf(byOutStrm.size()) + "))"); if (byOutStrm.size() > 0) oStmt.setBinaryStream(30, new ByteArrayInputStream(byOutStrm.toByteArray()), byOutStrm.size()); else oStmt.setNull(30, Types.LONGVARBINARY); } else { if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setShort(21, ...)"); oStmt.setShort(21, (short) (oFlgs.contains(Flags.Flag.ANSWERED) ? 1 : 0)); oStmt.setShort(22, (short) (oFlgs.contains(Flags.Flag.DELETED) ? 1 : 0)); oStmt.setShort(23, (short) (0)); oStmt.setShort(24, (short) (oFlgs.contains(Flags.Flag.FLAGGED) ? 1 : 0)); oStmt.setShort(25, (short) (oFlgs.contains(Flags.Flag.RECENT) ? 1 : 0)); oStmt.setShort(26, (short) (oFlgs.contains(Flags.Flag.SEEN) ? 1 : 0)); oStmt.setShort(27, (short) (bIsSpam ? 1 : 0)); oStmt.setBigDecimal(28, dPgMessage); if ((iOpenMode & MODE_MBOX) != 0) oStmt.setBigDecimal(29, new BigDecimal(lPosition)); else oStmt.setNull(29, Types.NUMERIC); if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBinaryStream(30, new ByteArrayInputStream(" + String.valueOf(byOutStrm.size()) + "))"); if (byOutStrm.size() > 0) oStmt.setBinaryStream(30, new ByteArrayInputStream(byOutStrm.toByteArray()), byOutStrm.size()); else oStmt.setNull(30, Types.LONGVARBINARY); } if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); oStmt.close(); oStmt = null; } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(DB.k_mime_msgs + " " + sqle.getMessage(), sqle); } if ((iOpenMode & MODE_BLOB) != 0) { try { byOutStrm.close(); } catch (IOException ignore) { } byOutStrm = null; } try { Object oContent = oMsg.getContent(); if (oContent instanceof MimeMultipart) { try { saveMimeParts(oMsg, sMsgCharSeq, sBoundary, gu_mimemsg, sMessageID, dPgMessage.intValue(), 0); } catch (MessagingException msge) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(msge.getMessage(), msge.getNextException()); } } } catch (Exception xcpt) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException("MimeMessage.getContent() " + xcpt.getMessage(), xcpt); } sSQL = "SELECT " + DB.gu_contact + "," + DB.gu_company + "," + DB.tx_name + "," + DB.tx_surname + "," + DB.tx_surname + " FROM " + DB.k_member_address + " WHERE " + DB.tx_email + "=? AND " + DB.gu_workarea + "=? UNION SELECT " + DB.gu_user + ",'****************************USER'," + DB.nm_user + "," + DB.tx_surname1 + "," + DB.tx_surname2 + " FROM " + DB.k_users + " WHERE (" + DB.tx_main_email + "=? OR " + DB.tx_alt_email + "=?) AND " + DB.gu_workarea + "=?"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); PreparedStatement oAddr = null; try { oAddr = oConn.prepareStatement(sSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet oRSet; InternetAddress oInetAdr; String sTxEmail, sGuCompany, sGuContact, sGuUser, sTxName, sTxSurname1, sTxSurname2, sTxPersonal; if (oFrom != null) { oAddr.setString(1, oFrom.getAddress()); oAddr.setString(2, gu_workarea); oAddr.setString(3, oFrom.getAddress()); oAddr.setString(4, oFrom.getAddress()); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pFrom.put(oFrom.getAddress(), sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pFrom.put(oFrom.getAddress(), "null,null,null"); oRSet.close(); } if (DebugFile.trace) DebugFile.writeln("from count = " + pFrom.size()); if (oTo != null) { for (int t = 0; t < oTo.length; t++) { oInetAdr = (InternetAddress) oTo[t]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pTo.put(sTxEmail, sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pTo.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("to count = " + pTo.size()); if (oCC != null) { for (int c = 0; c < oCC.length; c++) { oInetAdr = (InternetAddress) oCC[c]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pCC.put(sTxEmail, sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pCC.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("cc count = " + pCC.size()); if (oBCC != null) { for (int b = 0; b < oBCC.length; b++) { oInetAdr = (InternetAddress) oBCC[b]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pBCC.put(sTxEmail, sGuContact + "," + sGuCompany); } else pBCC.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("bcc count = " + pBCC.size()); oAddr.close(); sSQL = "INSERT INTO " + DB.k_inet_addrs + " (gu_mimemsg,id_message,tx_email,tp_recipient,gu_user,gu_contact,gu_company,tx_personal) VALUES ('" + gu_mimemsg + "','" + sMessageID + "',?,?,?,?,?,?)"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); oStmt = oConn.prepareStatement(sSQL); java.util.Enumeration oMailEnum; String[] aRecipient; if (!pFrom.isEmpty()) { oMailEnum = pFrom.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pFrom.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "from"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pTo.isEmpty()) { oMailEnum = pTo.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pTo.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "to"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pCC.isEmpty()) { oMailEnum = pCC.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pCC.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "cc"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setString(4, null); oStmt.setString(5, null); } else { oStmt.setString(3, null); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pBCC.isEmpty()) { oMailEnum = pBCC.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pBCC.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "bcc"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); oStmt.executeUpdate(); } } oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iSize) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; if ((iOpenMode & MODE_MBOX) != 0) { if (DebugFile.trace) DebugFile.writeln("MboxFile.appendMessage(" + (oMsg.getContentID() != null ? oMsg.getContentID() : "") + ")"); oMBox.appendMessage(sMsgCharSeq); oMBox.close(); oMBox = null; } if (DebugFile.trace) DebugFile.writeln("Connection.commit()"); oConn.commit(); } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oAddr) oAddr.close(); oAddr = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(sqle.getMessage(), sqle); } catch (IOException ioe) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oAddr) oAddr.close(); oAddr = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(ioe.getMessage(), ioe); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.appendMessage() : " + gu_mimemsg); } }
|
00
|
Code Sample 1:
public VeecheckResult performRequest(VeecheckVersion version, String uri) throws ClientProtocolException, IOException, IllegalStateException, SAXException { HttpClient client = new DefaultHttpClient(); HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT); HttpGet request = new HttpGet(version.substitute(uri)); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); try { StatusLine line = response.getStatusLine(); if (line.getStatusCode() != 200) throw new IOException("Request failed: " + line.getReasonPhrase()); Header header = response.getFirstHeader(HTTP.CONTENT_TYPE); Encoding encoding = identityEncoding(header); VeecheckResult handler = new VeecheckResult(version); Xml.parse(entity.getContent(), encoding, handler); return handler; } finally { entity.consumeContent(); } }
Code Sample 2:
public static String encrypt(String algorithm, String[] input) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.reset(); for (int i = 0; i < input.length; i++) { if (input[i] != null) md.update(input[i].getBytes("UTF-8")); } byte[] messageDigest = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString((0xf0 & messageDigest[i]) >> 4)); hexString.append(Integer.toHexString(0x0f & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (NullPointerException e) { return new StringBuffer().toString(); } }
|
00
|
Code Sample 1:
public static String generateDigest(String message, String DigestAlgorithm) { try { MessageDigest md = MessageDigest.getInstance(DigestAlgorithm); md.update(message.getBytes(), 0, message.length()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException nsae) { return null; } }
Code Sample 2:
public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }
|
11
|
Code Sample 1:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
Code Sample 2:
protected String decrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PrivateKey pk = getPrivateKey(key); if (pk == null) { throw new CryptographicFailureException("PrivateKeyNotFound", String.format("Cannot find private key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes())); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(bout.toByteArray()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
|
00
|
Code Sample 1:
public void addButtons() { BufferedImage bufImage = null; BufferedImage bufImage1 = null; for (int i = 0; i < urls.size(); i++) { String url = (String) urls.elementAt(i); if (url.contains(java.util.ResourceBundle.getBundle("com/jjcp/resources/Strings").getString("IHERETRIEVEDOCUMENT"))) { return; } try { URL url1 = new URL(url); URLConnection conn = null; conn = url1.openConnection(); InputStream in = conn.getInputStream(); in.close(); bufImage = ImageIO.read(url1); bufImage1 = resizeAnImage(bufImage, 0.25); ImageIcon icon = new ImageIcon(bufImage1); ImageButton imageButton = new ImageButton(icon, this, i); imageButton.setIndex(i); jPanel1.add(imageButton); jPanel1.setPreferredSize(new Dimension(imageButton.getWidth() * urls.size(), imageButton.getHeight() + 20)); } catch (Exception exception) { exception.printStackTrace(); } } this.setVisible(true); this.repaint(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; }
Code Sample 2:
public static void main(String[] args) { CookieManager cm = new CookieManager(); try { URL url = new URL("http://www.hccp.org/test/cookieTest.jsp"); URLConnection conn = url.openConnection(); conn.connect(); cm.storeCookies(conn); cm.setCookies(url.openConnection()); } catch (IOException ioe) { ioe.printStackTrace(); } }
|
11
|
Code Sample 1:
public static final String encryptSHA(String decrypted) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(decrypted.getBytes()); byte hash[] = sha.digest(); sha.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
Code Sample 2:
public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); }
|
00
|
Code Sample 1:
protected static String fileName2md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes("iso-8859-1")); byte[] byteHash = md.digest(); md.reset(); StringBuffer resultString = new StringBuffer(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int i = 0; i < ex.getStackTrace().length; i++) Logger.error(" " + ex.getStackTrace()[i].toString()); ex.printStackTrace(); } return String.valueOf(Math.random() * Long.MAX_VALUE); }
Code Sample 2:
public static boolean copy(final File from, final File to) { if (from.isDirectory()) { to.mkdirs(); for (final String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { if (COPY_DEBUG) { System.out.println("Failed to copy " + name + " from " + from + " to " + to); } return false; } } } else { try { final FileInputStream is = new FileInputStream(from); final FileChannel ifc = is.getChannel(); final FileOutputStream os = makeFile(to); if (USE_NIO) { final FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (final IOException ex) { if (COPY_DEBUG) { System.out.println("Failed to copy " + from + " to " + to + ": " + ex); } return false; } } final long time = from.lastModified(); setLastModified(to, time); final long newtime = to.lastModified(); if (COPY_DEBUG) { if (newtime != time) { System.out.println("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime)); to.setLastModified(time); final long morenewtime = to.lastModified(); return false; } else { System.out.println("Timestamp for " + to + " set successfully."); } } return time == newtime; }
|
00
|
Code Sample 1:
public static byte[] MD5(String... strings) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); for (String string : strings) { digest.update(string.getBytes("UTF-8")); } return digest.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.toString(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString(), e); } }
Code Sample 2:
public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
|
11
|
Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new OutputStream() { @Override public void write(byte[] b, int off, int len) { } @Override public void write(int b) { } @Override public void write(byte[] b) throws IOException { } }); } finally { IOUtils.closeQuietly(in); } return checksum; }
Code Sample 2:
private void performDownload() { List<String> selected = filesPane.getSelectedValuesList(); if (selected == null || selected.isEmpty() || selected.size() != 1) { JOptionPane.showMessageDialog(this, "Please select one path"); return; } RFile file = new RFile(selected.get(0)); if (!file.isFile()) { JOptionPane.showMessageDialog(this, "file does not exist anymore"); return; } chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName())); int ok = chooser.showSaveDialog(this); if (ok != JFileChooser.APPROVE_OPTION) { return; } FileOutputStream fout = null; RFileInputStream in = null; try { fout = new FileOutputStream(chooser.getSelectedFile()); in = new RFileInputStream(file); IOUtils.copy(in, fout); JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE); } catch (IOException iOException) { JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } }
|
11
|
Code Sample 1:
public Transaction() throws Exception { Connection Conn = null; Statement Stmt = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Conn = DriverManager.getConnection(DBUrl); Conn.setAutoCommit(true); Stmt = Conn.createStatement(); try { Stmt.executeUpdate("DROP TABLE trans_test"); } catch (SQLException sqlEx) { } Stmt.executeUpdate("CREATE TABLE trans_test (id int not null primary key, decdata double) type=BDB"); Conn.setAutoCommit(false); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.0)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Conn.rollback(); System.out.println("Roll Ok"); ResultSet RS = Stmt.executeQuery("SELECT * from trans_test"); if (!RS.next()) { System.out.println("Ok"); } else { System.out.println("Rollback failed"); } Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.485115)"); Conn.commit(); RS = Stmt.executeQuery("SELECT * from trans_test where id=2"); if (RS.next()) { System.out.println(RS.getDouble(2)); System.out.println("Ok"); } else { System.out.println("Rollback failed"); } } catch (Exception ex) { throw ex; } finally { if (Stmt != null) { try { Stmt.close(); } catch (SQLException SQLEx) { } } if (Conn != null) { try { Conn.close(); } catch (SQLException SQLEx) { } } } }
Code Sample 2:
public static void importDocumentLines(Connection conn, String originDocumentID, String destinationDocumentID) throws SQLException { boolean defaultAutoCommit = conn.getAutoCommit(); String sqlQuery = "select ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice from tbl_DocumentItem where DocumentID=?"; String sqlInsert = "insert into tbl_DocumentItem (ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice,DocumentID) values (?,?,?,?,?,?,?,?,?)"; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; try { pstmt1 = conn.prepareStatement(sqlQuery); pstmt2 = conn.prepareStatement(sqlInsert); conn.setAutoCommit(false); pstmt1.setString(1, originDocumentID); ResultSet rs = pstmt1.executeQuery(); while (rs.next()) { pstmt2.setInt(1, rs.getInt(1)); pstmt2.setString(2, rs.getString(2)); pstmt2.setDouble(3, rs.getDouble(3)); pstmt2.setDouble(4, rs.getDouble(4)); pstmt2.setDouble(5, rs.getDouble(5)); pstmt2.setDouble(6, rs.getDouble(6)); pstmt2.setDouble(7, rs.getDouble(7)); pstmt2.setDouble(8, rs.getDouble(8)); pstmt2.setString(9, destinationDocumentID); pstmt2.executeUpdate(); } rs.close(); conn.commit(); } catch (SQLException ex) { conn.rollback(); } finally { conn.setAutoCommit(defaultAutoCommit); if (pstmt1 != null) pstmt1.close(); if (pstmt2 != null) pstmt2.close(); } }
|
11
|
Code Sample 1:
public void onCreate() { window = ((Window) getFellow("win")); userName = ((Textbox) getFellow("user")); password = ((Textbox) getFellow("password")); session = window.getDesktop().getSession(); if (Executions.getCurrent().getParameter("login") != null) { login = Executions.getCurrent().getParameter("login"); session.setAttribute("login", login); } if (Executions.getCurrent().getParameter("password") != null) { passwordu = Executions.getCurrent().getParameter("password"); } if (Executions.getCurrent().getParameter("option") != null) { option = Executions.getCurrent().getParameter("option"); session.setAttribute("option", option); } if (Executions.getCurrent().getParameter("organization") != null) { organization = Executions.getCurrent().getParameter("organization"); session.setAttribute("organization", organization); } if (Executions.getCurrent().getParameter("project") != null) { project = Executions.getCurrent().getParameter("project"); session.setAttribute("project", project); } if (login != null) { User user = UserDAO.getUserByUserName(login); if (user != null) { String encodedPassword = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(user.getPassword().getBytes()); BASE64Encoder encoder = new BASE64Encoder(); encodedPassword = encoder.encode(digest.digest()); } catch (Exception e) { } if (passwordu.compareTo(encodedPassword) == 0) { session.setAttribute("user", user); session.setAttribute("numero", 5); session.setAttribute("option", option); session.setAttribute("organization", organization); session.setAttribute("project", project); Executions.sendRedirect("menu.zul"); } } } }
Code Sample 2:
public void actionPerformed(ActionEvent e) { String digest = null; try { MessageDigest m = MessageDigest.getInstance("sha1"); m.reset(); String pw = String.copyValueOf(this.login.getPassword()); m.update(pw.getBytes()); byte[] digestByte = m.digest(); BigInteger bi = new BigInteger(digestByte); digest = bi.toString(); System.out.println(digest); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } this.model.login(this.login.getHost(), this.login.getPort(), this.login.getUser(), digest); }
|
11
|
Code Sample 1:
public void copyFile2(String src, String dest) throws IOException { String newLine = System.getProperty("line.separator"); FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + QZ.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(QZ.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
Code Sample 2:
@Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
|
00
|
Code Sample 1:
public boolean refresh() { try { synchronized (text) { stream = (new URL(url)).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } text = sb.toString(); } price = 0; date = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return false; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; }
Code Sample 2:
public static void copyResource(String args) { try { URL url = copyURL.class.getResource(args); InputStream is = url.openStream(); System.out.flush(); FileOutputStream fos = null; fos = new FileOutputStream(System.getProperty("user.home") + "/JavaCPC/" + args); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); } catch (MalformedURLException e) { System.err.println(e.toString()); } catch (IOException e) { System.err.println(e.toString()); } }
|
11
|
Code Sample 1:
void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } }
Code Sample 2:
public static List<String> unZip(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream); ZipArchiveEntry entry = in.getNextZipEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextZipEntry(); } in.close(); return result; }
|
00
|
Code Sample 1:
private void writeFile(String name, URL url) throws IOException { Location location = resourcesHome.resolve(name); InputStream input = url.openStream(); OutputStream output = location.getOutputStream(); try { byte buf[] = new byte[1024]; int read; while (true) { read = input.read(buf); if (read == -1) break; output.write(buf, 0, read); } } finally { try { input.close(); } finally { output.close(); } } }
Code Sample 2:
public static void main(String args[]) { try { URL url = new URL("http://www.hungry.com/"); InputStream stream = url.openStream(); int size = 0; while (-1 != stream.read()) { size++; } stream.close(); System.out.println("PASSED: new URL() size=" + size); } catch (Exception e) { System.out.println("FAILED: " + e); } }
|
11
|
Code Sample 1:
public static int unzipFile(File file_input, File dir_output) { ZipInputStream zip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); zip_in_stream = new ZipInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; do { try { ZipEntry zip_entry = zip_in_stream.getNextEntry(); if (zip_entry == null) break; File output_file = new File(dir_output, zip_entry.getName()); FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = zip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } } while (true); try { zip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
@Test public void testStandardTee() throws Exception { final byte[] test = "test".getBytes(); final InputStream source = new ByteArrayInputStream(test); final ByteArrayOutputStream destination1 = new ByteArrayOutputStream(); final ByteArrayOutputStream destination2 = new ByteArrayOutputStream(); final TeeOutputStream tee = new TeeOutputStream(destination1, destination2); org.apache.commons.io.IOUtils.copy(source, tee); tee.close(); assertArrayEquals("the two arrays are equals", test, destination1.toByteArray()); assertArrayEquals("the two arrays are equals", test, destination2.toByteArray()); assertEquals("byte count", test.length, tee.getSize()); }
|
00
|
Code Sample 1:
public long add(T t) throws BaseException { Connection conn = null; PreparedStatement pstmt = null; long result = -1L; boolean flag = false; try { conn = getConnection(); if (conn != null) { flag = true; } else { conn = ConnectionManager.getConn(getStrConnection()); conn.setAutoCommit(false); } pstmt = getAdd(conn, t, this.getTableName()); pstmt.executeUpdate(); result = t.getId(); } catch (SQLException e) { try { if (!flag) { conn.rollback(); } } catch (Exception ex) { log.error("add(T " + t.toString() + ")回滚出错,错误信息:" + ex.getMessage()); } log.error("add(T " + t.toString() + ")方法出错:" + e.getMessage()); } catch (BaseException e) { throw e; } finally { try { if (!flag) { conn.setAutoCommit(true); } } catch (Exception e) { log.error("add(T " + t.toString() + ")方法设置自动提交出错,信息为:" + e.getMessage()); } ConnectionManager.closePreparedStatement(pstmt); if (!flag) { ConnectionManager.closeConn(conn); } } return result; }
Code Sample 2:
public boolean copy(String file, String target, int tag) { try { File file_in = new File(file); File file_out = new File(target); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
|
00
|
Code Sample 1:
@Override public void run() { try { if (!Util.isSufficienDataForUpload(recordedGeoPoints)) return; final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes()); final HttpClient httpClient = new DefaultHttpClient(); final HttpPost request = new HttpPost(UPLOADSCRIPT_URL); final MultipartEntity requestEntity = new MultipartEntity(); requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx")); httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false); request.setEntity(requestEntity); final HttpResponse response = httpClient.execute(request); final int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { logger.error("GPXUploader", "status != HttpStatus.SC_OK"); } else { final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent())); final char[] buf = new char[8 * 1024]; int read; final StringBuilder sb = new StringBuilder(); while ((read = r.read(buf)) != -1) sb.append(buf, 0, read); logger.debug("GPXUploader", "Response: " + sb.toString()); } } catch (final Exception e) { } }
Code Sample 2:
private CharBuffer decodeToFile(ReplayInputStream inStream, String backingFilename, String encoding) throws IOException { CharBuffer charBuffer = null; BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, encoding)); File backingFile = new File(backingFilename); this.decodedFile = File.createTempFile(backingFile.getName(), WRITE_ENCODING, backingFile.getParentFile()); FileOutputStream fos; fos = new FileOutputStream(this.decodedFile); IOUtils.copy(reader, fos, WRITE_ENCODING); fos.close(); charBuffer = getReadOnlyMemoryMappedBuffer(this.decodedFile).asCharBuffer(); return charBuffer; }
|
00
|
Code Sample 1:
public void get(final String remoteFilePath, final String remoteFileName, final String localName) { final FTPClient ftp = new FTPClient(); final FTPMessageCollector listener = new FTPMessageCollector(); try { final String localDirName = localName.substring(0, localName.lastIndexOf(File.separator)); System.out.println("ftp:"); System.out.println(" remoteDir " + remoteFilePath); System.out.println(" localDir " + localDirName); final File localDir = new File(localDirName); if (!localDir.exists()) { System.out.println(" create Dir " + localDirName); localDir.mkdir(); } ftp.setTimeout(10000); ftp.setRemoteHost(host); ftp.setMessageListener(listener); } catch (final UnknownHostException e) { showConnectError(); return; } catch (final Exception e) { e.printStackTrace(); } final TileInfoManager tileInfoMgr = TileInfoManager.getInstance(); final Job downloadJob = new Job(Messages.job_name_ftpDownload) { @Override protected IStatus run(final IProgressMonitor monitor) { try { showTileInfo(remoteFileName, -1); System.out.println(" connect " + host); ftp.connect(); showTileInfo(remoteFileName, -2); System.out.println(" login " + user + " " + password); ftp.login(user, password); System.out.println(" set passive mode"); ftp.setConnectMode(FTPConnectMode.PASV); System.out.println(" set type binary"); ftp.setType(FTPTransferType.BINARY); showTileInfo(remoteFileName, -3); System.out.println(" chdir " + remoteFilePath); ftp.chdir(remoteFilePath); ftp.setProgressMonitor(new FTPProgressMonitor() { public void bytesTransferred(final long count) { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_LOADING_MONITOR, remoteFileName, count); } }); showTileInfo(remoteFileName, -4); System.out.println(" get " + remoteFileName + " -> " + localName + " ..."); ftp.get(localName, remoteFileName); System.out.println(" quit"); ftp.quit(); } catch (final UnknownHostException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_cannotConnectToServer, host), e); } catch (final SocketTimeoutException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_timeoutWhenConnectingToServer, host), e); } catch (final Exception e) { e.printStackTrace(); tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_ERROR_LOADING, remoteFileName, 0); } finally { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_END_LOADING, remoteFileName, 0); } return Status.OK_STATUS; } }; downloadJob.schedule(); try { downloadJob.join(); } catch (final InterruptedException e) { e.printStackTrace(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); in.seek(0); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
|
00
|
Code Sample 1:
public String digestPassword(String password) { StringBuffer hexString = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); byte[] messageDigest = algorithm.digest(); for (byte b : messageDigest) { hexString.append(Integer.toHexString(0xFF & b)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); }
Code Sample 2:
public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
|
00
|
Code Sample 1:
public String fetch(final String address) throws EncoderException { final String escapedAddress = new URLCodec().encode(address); final String requestUrl = GeoCodeFetch.urlXmlPath + "&" + "address=" + escapedAddress; this.log.debug("requestUrl: {}", requestUrl); try { final StringBuffer sb = new StringBuffer(); final URL url = new URL(requestUrl); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { this.log.debug("line: {}", line); sb.append(line); } reader.close(); return (sb.toString()); } catch (final MalformedURLException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } catch (final IOException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } return (""); }
Code Sample 2:
public void initGet() throws Exception { cl = new FTPClient(); cl.connect(getHostName()); Authentication auth = AuthManager.getAuth(getSite()); if (auth == null) auth = new FTPAuthentication(getSite()); while (!cl.login(auth.getUser(), auth.getPassword())) { ap.setSite(getSite()); auth = ap.promptAuthentication(); if (auth == null) throw new Exception("User Cancelled Auth Operation"); } cl.connect(getHostName()); cl.login(auth.getUser(), auth.getPassword()); cl.enterLocalPassiveMode(); cl.setFileType(FTP.BINARY_FILE_TYPE); cl.setRestartOffset(getPosition()); setInputStream(cl.retrieveFileStream(new URL(getURL()).getFile())); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
|
11
|
Code Sample 1:
public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); }
Code Sample 2:
public void deployDir(File srcDir, String destDir) { File[] dirFiles = srcDir.listFiles(); for (int k = 0; dirFiles != null && k < dirFiles.length; k++) { if (!dirFiles[k].getName().startsWith(".")) { if (dirFiles[k].isFile()) { File deployFile = new File(destDir + File.separator + dirFiles[k].getName()); if (dirFiles[k].lastModified() != deployFile.lastModified() || dirFiles[k].length() != deployFile.length()) { IOUtils.copy(dirFiles[k], deployFile); } } else if (dirFiles[k].isDirectory()) { String newDestDir = destDir + File.separator + dirFiles[k].getName(); deployDir(dirFiles[k], newDestDir); } } } }
|
11
|
Code Sample 1:
public JSONObject getSourceGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph src = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { src = manager.getSourceGraph(); if (src != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(src); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No source graph loaded."); } } catch (Exception e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Cannot load source graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
Code Sample 2:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
|
11
|
Code Sample 1:
public static void main(String[] args) { File file = null; try { file = File.createTempFile("TestFileChannel", ".dat"); final ByteBuffer buffer = ByteBuffer.allocateDirect(4); final ByteChannel output = new FileOutputStream(file).getChannel(); buffer.putInt(MAGIC_INT); buffer.flip(); output.write(buffer); output.close(); final ByteChannel input = new FileInputStream(file).getChannel(); buffer.clear(); while (buffer.hasRemaining()) { input.read(buffer); } input.close(); buffer.flip(); final int file_int = buffer.getInt(); if (file_int != MAGIC_INT) { System.out.println("TestFileChannel FAILURE"); System.out.println("Wrote " + Integer.toHexString(MAGIC_INT) + " but read " + Integer.toHexString(file_int)); } else { System.out.println("TestFileChannel SUCCESS"); } } catch (Exception e) { System.out.println("TestFileChannel FAILURE"); e.printStackTrace(System.out); } finally { if (null != file) { file.delete(); } } }
Code Sample 2:
public void onUpload$btnFileUpload(UploadEvent ue) { BufferedInputStream in = null; BufferedOutputStream out = null; if (ue == null) { System.out.println("unable to upload file"); return; } else { System.out.println("fileUploaded()"); } try { Media m = ue.getMedia(); System.out.println("m.getContentType(): " + m.getContentType()); System.out.println("m.getFormat(): " + m.getFormat()); try { InputStream is = m.getStreamData(); in = new BufferedInputStream(is); File baseDir = new File(UPLOAD_PATH); if (!baseDir.exists()) { baseDir.mkdirs(); } final File file = new File(UPLOAD_PATH + m.getName()); OutputStream fout = new FileOutputStream(file); out = new BufferedOutputStream(fout); IOUtils.copy(in, out); if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) { final String filename = m.getName(); Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() { @Override public void onEvent(Event event) throws Exception { try { int response = ((Integer) event.getData()).intValue(); if (response == Messagebox.YES) { System.out.println("unzipping file to: " + UPLOAD_PATH); boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false); if (success) { Messagebox.show("File unzipped: '" + filename + "'"); } else { Messagebox.show("Unable to unzip '" + filename + "' "); } } else { System.out.println("leaving archive file alone"); } } catch (NumberFormatException nfe) { System.out.println("Not a valid response"); } } }); } else { Messagebox.show("File '" + m.getName() + "' successfully uploaded"); } } catch (IOException e) { System.out.println("IO Exception while saving file: "); e.printStackTrace(System.out); } catch (Exception e) { System.out.println("General Exception: "); e.printStackTrace(System.out); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { System.out.println("IO Exception while closing stream: "); e.printStackTrace(System.out); } } } catch (Exception e) { System.out.println("Error uploading file."); e.printStackTrace(System.out); } }
|
11
|
Code Sample 1:
private static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IOException("Destination file cannot be created: " + destFile.getPath()); } } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void copyFromOffset(long offset, File exe, File cab) throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(exe)); FileOutputStream out = new FileOutputStream(cab); byte[] buffer = new byte[4096]; int bytes_read; in.skipBytes((int) offset); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); in = null; out = null; }
|
00
|
Code Sample 1:
private static void upload(String login, String password, String file) throws ApiException { System.out.println("Trying to login to 4shared........"); File f = new File(file); if (!f.exists() || !f.canRead() || f.isDirectory()) { System.out.println("File does not exist, unreadable or not a file"); return; } DesktopAppJax2 da = new DesktopAppJax2Service().getDesktopAppJax2Port(); String loginRes = da.login(login, password); if (!loginRes.isEmpty()) { System.out.println("Login failed: " + loginRes); return; } if (!da.hasRightUpload()) { System.out.println("Uploading is temporarily disabled"); return; } System.out.println("4shared Login successful :)"); long newFileId = da.uploadStartFile(login, password, -1, f.getName(), f.length()); System.out.println("File id : " + newFileId); String sessionKey = da.createUploadSessionKey(login, password, -1); long dcId = da.getNewFileDataCenter(login, password); String url = da.getUploadFormUrl((int) dcId, sessionKey); try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); MultipartEntity me = new MultipartEntity(); StringBody rfid = new StringBody("" + newFileId); StringBody rfb = new StringBody("" + 0); InputStreamBody isb = new InputStreamBody(new BufferedInputStream(new FileInputStream(f)), "FilePart"); me.addPart("resumableFileId", rfid); me.addPart("resumableFirstByte", rfb); me.addPart("FilePart", isb); post.setEntity(me); HttpResponse resp = client.execute(post); HttpEntity resEnt = resp.getEntity(); String res = da.uploadFinishFile(login, password, newFileId, DigestUtils.md5Hex(new FileInputStream(f))); if (res.isEmpty()) { System.out.println("File uploaded."); downloadlink = da.getFileDownloadLink(login, password, newFileId); System.out.println("Download link : " + downloadlink); } else { System.out.println("Upload failed: " + res); } } catch (Exception ex) { System.out.println("Upload failed: " + ex.getMessage()); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; }
Code Sample 2:
public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
|
00
|
Code Sample 1:
private List<String> getContainedFilePaths(URL url) throws Exception { JarInputStream jis = new JarInputStream(url.openStream()); ZipEntry zentry = null; ArrayList<String> fullNames = new ArrayList<String>(); while ((zentry = jis.getNextEntry()) != null) { String name = zentry.getName(); if (!zentry.isDirectory()) { fullNames.add(name); } } jis.close(); return (fullNames); }
Code Sample 2:
public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReader.getAudioInputStream(URL): begin"); } long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED; URLConnection conn = url.openConnection(); boolean isShout = false; int toRead = 4; byte[] head = new byte[toRead]; conn.setRequestProperty("Icy-Metadata", "1"); BufferedInputStream bInputStream = new BufferedInputStream(conn.getInputStream()); bInputStream.mark(toRead); int read = bInputStream.read(head, 0, toRead); if ((read > 2) && (((head[0] == 'I') | (head[0] == 'i')) && ((head[1] == 'C') | (head[1] == 'c')) && ((head[2] == 'Y') | (head[2] == 'y')))) isShout = true; bInputStream.reset(); InputStream inputStream = null; if (isShout == true) { IcyInputStream icyStream = new IcyInputStream(bInputStream); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { String metaint = conn.getHeaderField("icy-metaint"); if (metaint != null) { IcyInputStream icyStream = new IcyInputStream(bInputStream, metaint); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { inputStream = bInputStream; } } AudioInputStream audioInputStream = null; try { audioInputStream = getAudioInputStream(inputStream, lFileLengthInBytes); } catch (UnsupportedAudioFileException e) { inputStream.close(); throw e; } catch (IOException e) { inputStream.close(); throw e; } if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReader.getAudioInputStream(URL): end"); } return audioInputStream; }
|
11
|
Code Sample 1:
boolean createSessionArchive(String archiveFilename) { byte[] buffer = new byte[1024]; try { ZipOutputStream archive = new ZipOutputStream(new FileOutputStream(archiveFilename)); for (mAnnotationsCursor.moveToFirst(); !mAnnotationsCursor.isAfterLast(); mAnnotationsCursor.moveToNext()) { FileInputStream in = new FileInputStream(mAnnotationsCursor.getString(ANNOTATIONS_FILE_NAME)); archive.putNextEntry(new ZipEntry("audio" + (mAnnotationsCursor.getPosition() + 1) + ".3gpp")); int length; while ((length = in.read(buffer)) > 0) archive.write(buffer, 0, length); archive.closeEntry(); in.close(); } archive.close(); } catch (IOException e) { Toast.makeText(mActivity, mActivity.getString(R.string.error_zip) + " " + e.getMessage(), Toast.LENGTH_SHORT).show(); return false; } return true; }
Code Sample 2:
private Dataset(File f, Properties p, boolean ro) throws DatabaseException { folder = f; logger.debug("Opening dataset [" + ((ro) ? "readOnly" : "read/write") + " mode]"); readOnly = ro; logger = Logger.getLogger(Dataset.class); logger.debug("Opening environment: " + f); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(false); envConfig.setAllowCreate(!readOnly); envConfig.setReadOnly(readOnly); env = new Environment(f, envConfig); File props = new File(folder, "dataset.properties"); if (!ro && p != null) { this.properties = p; try { FileOutputStream fos = new FileOutputStream(props); p.store(fos, null); fos.close(); } catch (IOException e) { logger.warn("Error saving dataset properties", e); } } else { if (props.exists()) { try { Properties pr = new Properties(); FileInputStream fis = new FileInputStream(props); pr.load(fis); fis.close(); this.properties = pr; } catch (IOException e) { logger.warn("Error reading dataset properties", e); } } } getPaths(); getNamespaces(); getTree(); pathDatabases = new HashMap(); frequencyDatabases = new HashMap(); lengthDatabases = new HashMap(); clustersDatabases = new HashMap(); pathMaps = new HashMap(); frequencyMaps = new HashMap(); lengthMaps = new HashMap(); clustersMaps = new HashMap(); }
|
00
|
Code Sample 1:
public static File downloadFile(Proxy proxy, URL url, File path) throws IOException { URLConnection conn = null; if (null == proxy) { conn = url.openConnection(); } else { conn = url.openConnection(proxy); } conn.connect(); File destFile = null; if (conn instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) conn; String filename = null; String hv = hc.getHeaderField("Content-Disposition"); if (null == hv) { String str = url.toString(); int index = str.lastIndexOf("/"); filename = str.substring(index + 1); } else { int index = hv.indexOf("filename="); filename = hv.substring(index).replace("\"", "").trim(); } destFile = new File(path, filename); } else { destFile = new File(path, "downloadfile" + url.toString().hashCode()); } if (destFile.exists()) { return destFile; } FileOutputStream fos = new FileOutputStream(destFile); byte[] buffer = new byte[2048]; try { while (true) { int len = conn.getInputStream().read(buffer); if (len < 0) { break; } else { fos.write(buffer, 0, len); } } fos.close(); } catch (IOException e) { destFile.delete(); throw e; } return destFile; }
Code Sample 2:
private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
void loadSVG(String svgFileURL) { try { URL url = new URL(svgFileURL); URLConnection c = url.openConnection(); c.setRequestProperty("Accept-Encoding", "gzip"); InputStream is = c.getInputStream(); String encoding = c.getContentEncoding(); if ("gzip".equals(encoding) || "x-gzip".equals(encoding) || svgFileURL.toLowerCase().endsWith(".svgz")) { is = new GZIPInputStream(is); } is = new BufferedInputStream(is); Document svgDoc = AppletUtils.parse(is, false); if (svgDoc != null) { if (grMngr.mainView.isBlank() == null) { grMngr.mainView.setBlank(cfgMngr.backgroundColor); } SVGReader.load(svgDoc, grMngr.mSpace, true, svgFileURL); grMngr.seekBoundingBox(); grMngr.buildLogicalStructure(); ConfigManager.defaultFont = VText.getMainFont(); grMngr.reveal(); if (grMngr.previousLocations.size() == 1) { grMngr.previousLocations.removeElementAt(0); } if (grMngr.rView != null) { grMngr.rView.getGlobalView(grMngr.mSpace.getCamera(1), 100); } grMngr.cameraMoved(null, null, 0); } else { System.err.println("An error occured while loading file " + svgFileURL); } } catch (Exception ex) { grMngr.reveal(); ex.printStackTrace(); } }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") public static void main(String[] args) { System.out.println("Starting encoding test...."); Properties p = new Properties(); try { InputStream pStream = ClassLoader.getSystemResourceAsStream("sample_weather.properties"); p.load(pStream); } catch (Exception e) { System.err.println("Could not load properties file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } if (WeatherUpdater.DEBUG) { System.out.println("hostname: " + p.getProperty("weather.hostname")); } if (WeatherUpdater.DEBUG) { System.out.println("database: " + p.getProperty("weather.database")); } if (WeatherUpdater.DEBUG) { System.out.println("username: " + p.getProperty("weather.username")); } if (WeatherUpdater.DEBUG) { System.out.println("password: " + p.getProperty("weather.password")); } SqlAccount sqlAccount = new SqlAccount(p.getProperty("weather.hostname"), p.getProperty("weather.database"), p.getProperty("weather.username"), p.getProperty("weather.password")); DatabaseInterface dbi = null; try { dbi = new DatabaseInterface(sqlAccount); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Established connection to database."); String query = "SELECT * FROM Current_Weather WHERE ZipCode = '99702'"; ResultTable results; System.out.println("Executing query: " + query); try { results = dbi.executeQuery(query); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Got results from query."); System.out.println("Converted results into the following table:"); System.out.println(results); System.out.println(); Class<? extends ResultEncoder> encoder_class; Class<? extends ResultDecoder> decoder_class; try { encoder_class = (Class<? extends ResultEncoder>) Class.forName(p.getProperty("mysms.coding.resultEncoder")); decoder_class = (Class<? extends ResultDecoder>) Class.forName(p.getProperty("mysms.coding.resultDecoder")); } catch (Exception e) { System.err.println("Could not find specified encoder: " + p.getProperty("result.encoder")); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Found class of encoder: " + encoder_class); System.out.println("Found class of decoder: " + decoder_class); ResultEncoder encoder; ResultDecoder decoder; try { encoder = encoder_class.newInstance(); if (encoder_class.equals(decoder_class) && decoder_class.isInstance(encoder)) { decoder = (ResultDecoder) encoder; } else { decoder = decoder_class.newInstance(); } } catch (Exception e) { System.err.println("Could not create instances of encoder and decoder."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Created instances of encoder and decoder."); if (decoder.equals(encoder)) { System.out.println("Decoder and encoder are same object."); } ByteBuffer buffer; try { buffer = encoder.encode(null, results); } catch (Exception e) { System.err.println("Could not encode results."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Encoded results to ByteBuffer with size: " + buffer.capacity()); File temp; try { temp = File.createTempFile("encoding_test", ".results"); temp.deleteOnExit(); FileChannel out = new FileOutputStream(temp).getChannel(); out.write(buffer); out.close(); } catch (Exception e) { System.err.println("Could not write buffer to file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Wrote buffer to file: \"" + temp.getName() + "\" with length: " + temp.length()); ByteBuffer re_buffer; try { FileInputStream in = new FileInputStream(temp.getAbsolutePath()); byte[] temp_buffer = new byte[(int) temp.length()]; int totalRead = 0; int numRead = 0; while (totalRead < temp_buffer.length) { numRead = in.read(temp_buffer, totalRead, temp_buffer.length - totalRead); if (numRead < 0) { break; } else { totalRead += numRead; } } re_buffer = ByteBuffer.wrap(temp_buffer); in.close(); } catch (Exception e) { System.err.println("Could not read from temporary file into buffer."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Read file back into buffer with length: " + re_buffer.capacity()); ResultTable re_results; try { re_results = decoder.decode(null, re_buffer); } catch (Exception e) { System.err.println("Could not decode buffer into a ResultTable."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Decoded buffer back into the following table:"); System.out.println(re_results); System.out.println(); System.out.println("... encoding test complete."); }
Code Sample 2:
public static String md5encrypt(String toEncrypt) { if (toEncrypt == null) { throw new IllegalArgumentException("null is not a valid password to encrypt"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncrypt.getBytes()); byte[] hash = md.digest(); return new String(dumpBytes(hash)); } catch (NoSuchAlgorithmException nsae) { return toEncrypt; } }
|
11
|
Code Sample 1:
private static void copy(File in, File out) throws IOException { if (!out.getParentFile().isDirectory()) out.getParentFile().mkdirs(); FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
Code Sample 2:
public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
|
11
|
Code Sample 1:
public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public Boolean compress(String sSourceDir, ArrayList<String> aFiles, String sDestinationFilename) { logger.debug("compress(%s, %s, %s)", sSourceDir, aFiles, sDestinationFilename); BufferedInputStream oOrigin = null; FileOutputStream oDestination; ZipOutputStream oOutput = null; Iterator<String> oIterator; byte[] aData; try { oDestination = new FileOutputStream(sDestinationFilename); oOutput = new ZipOutputStream(new BufferedOutputStream(oDestination)); aData = new byte[BUFFER_SIZE]; oIterator = aFiles.iterator(); while (oIterator.hasNext()) { try { String sFilename = (String) oIterator.next(); FileInputStream fisInput = new FileInputStream(sSourceDir + File.separator + sFilename); oOrigin = new BufferedInputStream(fisInput, BUFFER_SIZE); ZipEntry oEntry = new ZipEntry(sFilename.replace('\\', '/')); oOutput.putNextEntry(oEntry); int iCount; while ((iCount = oOrigin.read(aData, 0, BUFFER_SIZE)) != -1) oOutput.write(aData, 0, iCount); } finally { StreamHelper.close(oOrigin); } } } catch (Exception oException) { logger.error(oException.getMessage(), oException); return false; } finally { StreamHelper.close(oOutput); } return true; }
|
00
|
Code Sample 1:
public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load " + name); return classList; } while (services.hasMoreElements()) { URL url = (URL) services.nextElement(); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: " + url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: " + url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String) names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: " + className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: " + className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: " + className); } catch (NoClassDefFoundError e) { System.err.println("Service: " + e + " for " + className); } catch (Exception e) { System.err.println("Service: exception for: " + className + " " + e); } } return classList; }
Code Sample 2:
@Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } }
|
00
|
Code Sample 1:
public void checkin(Object _document) { this.document = (Document) _document; synchronized (url) { OutputStream outputStream = null; try { if ("file".equals(url.getProtocol())) { outputStream = new FileOutputStream(url.getFile()); } else { URLConnection connection = url.openConnection(); connection.setDoOutput(true); outputStream = connection.getOutputStream(); } new XMLOutputter(" ", true).output(this.document, outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
Code Sample 2:
@NotNull public Set<Class<?>> in(Package pack) { String packageName = pack.getName(); String packageOnly = pack.getName(); final boolean recursive = true; Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); String packageDirName = packageOnly.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); } catch (IOException e) { throw new PackageScanFailedException("Could not read from package directory: " + packageDirName, e); } while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { try { findClassesInDirPackage(packageOnly, URLDecoder.decode(url.getFile(), "UTF-8"), recursive, classes); } catch (UnsupportedEncodingException e) { throw new PackageScanFailedException("Could not read from file: " + url, e); } } else if ("jar".equals(protocol)) { JarFile jar; try { jar = ((JarURLConnection) url.openConnection()).getJarFile(); } catch (IOException e) { throw new PackageScanFailedException("Could not read from jar url: " + url, e); } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.charAt(0) == '/') { name = name.substring(1); } if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); if (idx != -1) { packageName = name.substring(0, idx).replace('/', '.'); } if ((idx != -1) || recursive) { if (name.endsWith(".class") && !entry.isDirectory()) { String className = name.substring(packageName.length() + 1, name.length() - 6); add(packageName, classes, className); } } } } } } return classes; }
|
11
|
Code Sample 1:
private String computeHash(String str) { StringBuffer hexBuffer = new StringBuffer(); byte[] bytes; int i; try { MessageDigest hashAlgorithm = MessageDigest.getInstance(hashAlgorithmName); hashAlgorithm.reset(); hashAlgorithm.update(str.getBytes()); bytes = hashAlgorithm.digest(); } catch (NoSuchAlgorithmException e) { return null; } for (i = 0; i < bytes.length; i++) hexBuffer.append(((bytes[i] >= 0 && bytes[i] <= 15) ? "0" : "") + Integer.toHexString(bytes[i] & 0xFF)); return hexBuffer.toString(); }
Code Sample 2:
public static String makeMD5(String input) throws Exception { String dstr = null; byte[] digest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); digest = md.digest(); dstr = new BigInteger(1, digest).toString(16); if (dstr.length() % 2 > 0) { dstr = "0" + dstr; } } catch (Exception e) { throw new Exception("Erro inesperado em makeMD5(): " + e.toString(), e); } return dstr; }
|
11
|
Code Sample 1:
public int update(BusinessObject o) throws DAOException { int update = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ITEM")); pst.setString(1, item.getDescription()); pst.setDouble(2, item.getUnit_price()); pst.setInt(3, item.getQuantity()); pst.setDouble(4, item.getVat()); pst.setInt(5, item.getIdProject()); if (item.getIdBill() == 0) pst.setNull(6, java.sql.Types.INTEGER); else pst.setInt(6, item.getIdBill()); pst.setInt(7, item.getIdCurrency()); pst.setInt(8, item.getId()); System.out.println("item => " + item.getDescription() + " " + item.getUnit_price() + " " + item.getQuantity() + " " + item.getVat() + " " + item.getIdProject() + " " + item.getIdBill() + " " + item.getIdCurrency() + " " + item.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; }
Code Sample 2:
public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
00
|
Code Sample 1:
public static boolean isSameHttpContent(final String url, final File localFile, UsernamePasswordCredentials creds) throws IOException { if (localFile.isFile()) { long localContentLength = localFile.length(); long localLastModified = localFile.lastModified() / 1000; long contentLength = -1; long lastModified = -1; HttpClient httpclient = createHttpClient(creds); try { HttpHead httphead = new HttpHead(url); HttpResponse response = httpclient.execute(httphead); if (response != null) { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode() / 100; if (status == 2) { Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (lastModifiedHeader != null) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US)); try { lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime() / 1000; } catch (ParseException e) { logger.error(e); } } } else { return true; } } } finally { httpclient.getConnectionManager().shutdown(); } if (logger.isDebugEnabled()) { logger.debug("local:" + localContentLength + " " + localLastModified); logger.debug("remote:" + contentLength + " " + lastModified); } if (contentLength != -1 && localContentLength != contentLength) return false; if (lastModified != -1 && lastModified != localLastModified) return false; if (contentLength == -1 && lastModified == -1) return false; return true; } return false; }
Code Sample 2:
public static final int executeSql(final Connection conn, final String sql, final boolean rollback) throws SQLException { if (null == sql) return 0; Statement stmt = null; try { stmt = conn.createStatement(); final int updated = stmt.executeUpdate(sql); return updated; } catch (final SQLException e) { if (rollback) conn.rollback(); throw e; } finally { closeAll(null, stmt, null); } }
|
11
|
Code Sample 1:
public void writeFile(String resource, InputStream is) throws IOException { File f = prepareFsReferenceAsFile(resource); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); try { IOUtils.copy(is, bos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); } }
Code Sample 2:
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
|
11
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
private void copy(File source, File dest) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { close(in); close(out); } }
Code Sample 2:
public void write(URL output, String model, String mainResourceClass) throws InfoUnitIOException { InfoUnitXMLData iur = new InfoUnitXMLData(STRUCTURE_RDF); rdf = iur.load("rdf"); rdfResource = rdf.ft("resource"); rdfParseType = rdf.ft("parse type"); try { PrintWriter outw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output.getFile()), "UTF-8")); URL urlModel = new URL(model); BufferedReader inr = new BufferedReader(new InputStreamReader(urlModel.openStream())); String finalTag = "</" + rdf.ft("main") + ">"; String line = inr.readLine(); while (line != null && !line.equalsIgnoreCase(finalTag)) { outw.println(line); line = inr.readLine(); } inr.close(); InfoNode nodeType = infoRoot.path(rdf.ft("constraint")); String type = null; if (nodeType != null) { type = nodeType.getValue().toString(); try { infoRoot.removeChildNode(nodeType); } catch (InvalidChildInfoNode error) { } } else if (mainResourceClass != null) type = mainResourceClass; else type = rdf.ft("description"); outw.println(" <" + type + " " + rdf.ft("about") + "=\"" + ((infoNamespaces == null) ? infoRoot.getLabel() : infoNamespaces.convertEntity(infoRoot.getLabel().toString())) + "\">"); Set<InfoNode> nl = infoRoot.getChildren(); writeNodeList(nl, outw, 5); outw.println(" </" + type + ">"); if (line != null) outw.println(finalTag); outw.close(); } catch (IOException error) { throw new InfoUnitIOException(error.getMessage()); } }
|
11
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
Code Sample 2:
public static String md5Encrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] md5hash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } md5hash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < md5hash.length; i++) { if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
|
11
|
Code Sample 1:
public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); }
Code Sample 2:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version_" + datastream + ".xml\""); } String xmlContent = URLDecoder.decode(req.getParameterValues(Constants.PARAM_CONTENT)[0], "UTF-8"); InputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8")); ServletOutputStream os = resp.getOutputStream(); IOUtils.copyStreams(is, os); os.flush(); }
|
00
|
Code Sample 1:
public static Set<Street> getVias(String pURL) { Set<Street> result = new HashSet<Street>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniVia = "<calle>"; String finVia = "</calle>"; String iniCodVia = "<cv>"; String finCodVia = "</cv>"; String iniTipoVia = "<tv>"; String finTipoVia = "</tv>"; String iniNomVia = "<nv>"; String finNomVia = "</nv>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Street via; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniVia)) { via = new Street(); while ((str = br.readLine()) != null && !str.contains(finVia)) { if (str.contains(iniCodVia)) { ini = str.indexOf(iniCodVia) + iniCodVia.length(); fin = str.indexOf(finCodVia); via.setCodeStreet(Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniTipoVia)) { TypeStreet tipo = new TypeStreet(); if (!str.contains(finTipoVia)) tipo.setCodetpStreet(""); else { ini = str.indexOf(iniTipoVia) + iniTipoVia.length(); fin = str.indexOf(finTipoVia); tipo.setCodetpStreet(str.substring(ini, fin)); } tipo.setDescription(getDescripcionTipoVia(tipo.getCodetpStreet())); via.setTypeStreet(tipo); } if (str.contains(iniNomVia)) { ini = str.indexOf(iniNomVia) + iniNomVia.length(); fin = str.indexOf(finNomVia); via.setStreetName(str.substring(ini, fin).trim()); } } result.add(via); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
Code Sample 2:
public static String encrypt(String text) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String result = ""; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes()); byte[] hash = digest.digest(); char buffer[] = new char[hash.length * 2]; for (int i = 0, x = 0; i < hash.length; i++) { buffer[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; buffer[x++] = HEX_CHARS[hash[i] & 0xf]; } result = new String(buffer); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
|
11
|
Code Sample 1:
private static void readIzvestiyaArticles() throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';'); reader.setTrimWhitespace(true); try { while (reader.readRecord()) { String id = reader.get(0); String filename = reader.get(1); StringTokenizer st = new StringTokenizer(filename, "-."); String name = st.nextToken(); String volume = st.nextToken(); String year = st.nextToken(); String extension = st.nextToken(); String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension); id2filename.put(id, filepath); } } finally { reader.close(); } for (Map.Entry<String, String> entry : id2filename.entrySet()) { String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue()); filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX"); if (new File(filepath).exists()) { InputStream in = new FileInputStream(filepath); FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false); try { org.apache.commons.io.IOUtils.copy(in, out); } catch (Exception e) { org.apache.commons.io.IOUtils.closeQuietly(in); org.apache.commons.io.IOUtils.closeQuietly(out); } } else { logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist"); } } }
Code Sample 2:
private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); }
|
11
|
Code Sample 1:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
Code Sample 2:
private ArrayList<Stock> fetchStockData(Stock[] stocks) throws IOException { Log.d(TAG, "Fetching stock data from Yahoo"); ArrayList<Stock> newStocks = new ArrayList<Stock>(stocks.length); if (stocks.length > 0) { StringBuilder sb = new StringBuilder(); for (Stock stock : stocks) { sb.append(stock.getSymbol()); sb.append('+'); } sb.deleteCharAt(sb.length() - 1); String urlStr = "http://finance.yahoo.com/d/quotes.csv?f=sb2n&s=" + sb.toString(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlStr.toString()); HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); int i = 0; Log.d(TAG, "Parsing stock data from Yahoo"); while (line != null) { Log.d(TAG, "Parsing: " + line); String[] values = line.split(","); Stock stock = new Stock(stocks[i], stocks[i].getId()); stock.setCurrentPrice(Double.parseDouble(values[1])); stock.setName(values[2]); Log.d(TAG, "Parsed Stock: " + stock); newStocks.add(stock); line = reader.readLine(); i++; } } return newStocks; }
|
11
|
Code Sample 1:
public final boolean login(String user, String pass) { if (user == null || pass == null) return false; connectionInfo.setData("com.tensegrity.palojava.pass#" + user, pass); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); pass = asHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { throw new PaloException("Failed to create encrypted password for " + "user '" + user + "'!", ex); } connectionInfo.setUser(user); connectionInfo.setPassword(pass); return loginInternal(user, pass); }
Code Sample 2:
public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } }
|
00
|
Code Sample 1:
public String readTemplateToString(String fileName) { URL url = null; url = classLoader.getResource(fileName); StringBuffer content = new StringBuffer(); if (url == null) { String error = "Template file could not be found: " + fileName; throw new RuntimeException(error); } try { BufferedReader breader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String strLine = ""; while ((strLine = breader.readLine()) != null) { content.append(strLine).append("\n"); } breader.close(); } catch (Exception e) { throw new RuntimeException("Problem while loading file: " + fileName); } return content.toString(); }
Code Sample 2:
@Override public void aggregate() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("aggregate table <" + origin + "> start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + origin); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (logger.isInfoEnabled()) logger.info("found " + currentRows + " record"); prestm = connection.prepareStatement("select max(d_insDate) from " + destination); rs = prestm.executeQuery(); Date from = null; if (rs.next()) from = rs.getTimestamp(1); rs.close(); prestm.close(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String fromStr = null; if (from != null) fromStr = sdf.format(from); if (logger.isInfoEnabled()) logger.info("last record date:" + fromStr); if (currentRows > 0) { connection.setAutoCommit(false); if (from != null && fromStr != null) { prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'"); if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'"); } else { prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin); if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin); } int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(" > " + rows + " rows aggregated"); connection.commit(); } else if (logger.isInfoEnabled()) logger.info("no aggregation need"); if (logger.isInfoEnabled()) logger.info("aggregate table " + origin + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante l'aggregazione dei dati della tabella " + origin, e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante l'aggregazione dei dati della tabella " + origin, e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
|
00
|
Code Sample 1:
public void createControl(Composite parent) { top = new Composite(parent, SWT.NONE); top.setLayout(new GridLayout()); top.setLayoutData(new GridData(GridData.FILL_BOTH)); ComposedAdapterFactory factories = new ComposedAdapterFactory(); factories.addAdapterFactory(new EcoreItemProviderAdapterFactory()); factories.addAdapterFactory(new NotationAdapterFactory()); factories.addAdapterFactory(new ResourceItemProviderAdapterFactory()); modelViewer = new TreeViewer(top, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); modelViewer.getTree().setLayoutData(new GridData(GridData.FILL_BOTH)); modelViewer.setContentProvider(new AdapterFactoryContentProvider(factories) { public boolean hasChildren(Object object) { boolean result = super.hasChildren(object); if (object instanceof Diagram) { result = false; } if (object instanceof EPackage && result == false) { result = !DiagramUtil.getDiagrams((EPackage) object, editor.getDiagram().eResource()).isEmpty(); } return result; } public Object[] getChildren(Object object) { Object[] result = super.getChildren(object); if (object instanceof EPackage) { List<Diagram> list = DiagramUtil.getDiagrams((EPackage) object, editor.getDiagram().eResource()); if (list.size() != 0) { Object[] newResult = new Object[result.length + list.size()]; for (int i = 0; i < result.length; i++) { newResult[i] = result[i]; } for (int i = 0; i < list.size(); i++) { newResult[result.length + i] = list.get(i); } return newResult; } } return result; } }); modelViewer.setLabelProvider(new AdapterFactoryLabelProvider(factories) { public String getText(Object element) { String result = super.getText(element); if (element instanceof Diagram) { if (editor.getDiagram() == element) { result += " *"; } } return result; } public String getColumnText(Object object, int columnIndex) { String result = super.getText(object); if (object instanceof Diagram) { if (editor.getDiagram() == object) { result += " (active)"; } } return result; } }); modelViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { setDiagramSelection(modelViewer.getSelection()); } }); modelViewer.addDragSupport(DND.DROP_COPY, new Transfer[] { LocalTransfer.getInstance() }, new TreeDragListener()); modelViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); Object selectedObject = selection.getFirstElement(); if (selectedObject instanceof Diagram) { openDiagram((Diagram) selectedObject); } } }); createContextMenuFor(modelViewer); editor.getDiagramGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { selectionInDiagramChange(event); } }); this.getSite().setSelectionProvider(modelViewer); setInput(); }
Code Sample 2:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
00
|
Code Sample 1:
public int executeUpdateJT(String sql, Object[][] paramsList) { Connection connection = null; connection = this.getConnection(); try { connection.setAutoCommit(false); } catch (SQLException e1) { e1.printStackTrace(); } PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < paramsList.length; i++) { if (connection != null && !connection.isClosed()) { InputStream is = null; if (paramsList[i].length > 0) { for (int j = 0; j < paramsList[i].length; j++) { Object obj = paramsList[i][j]; if (obj.getClass().equals(Class.forName("java.io.File"))) { File file = (File) obj; is = new FileInputStream(file); preparedStatement.setBinaryStream(j + 1, is, (int) file.length()); } else if (obj.getClass().equals(Class.forName("java.util.Date"))) { java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); preparedStatement.setString(j + 1, sdf.format((Date) obj)); } else { preparedStatement.setObject(j + 1, obj); } } } preparedStatement.executeUpdate(); if (is != null) { is.close(); } ; } } } catch (Exception e) { System.out.println("发生错误,数据回滚!"); e.printStackTrace(); try { connection.rollback(); return 0; } catch (SQLException e1) { e1.printStackTrace(); } } try { connection.commit(); return 1; } catch (SQLException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { log.error("未能正确关闭数据库连接!", e); System.out.println("未能正确关闭数据库连接!"); e.printStackTrace(); } } return -1; }
Code Sample 2:
private String getAuthUrlString(String account, String password) throws IOException, NoSuchAlgorithmException { Map<String, String> dict = retrieveLoginPage(); if (dict == null) { return null; } StringBuilder url = new StringBuilder("/config/login?login="); url.append(account); url.append("&passwd="); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); byte[] result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } String md5chal = dict.get(".challenge"); md5 = MessageDigest.getInstance("MD5"); md5.update(md5chal.getBytes(), 0, md5chal.length()); result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } Iterator<String> j = dict.keySet().iterator(); while (j.hasNext()) { String key = j.next(); String value = dict.get(key); if (!key.equals("passwd")) { if (key.equals(".save") || key.equals(".js")) { url.append("&" + key + "=1"); } else if (key.equals(".challenge")) { url.append("&" + key + "=" + value); } else { String u = URLEncoder.encode(value, "UTF-8"); url.append("&" + key + "=" + u); } } } url.append("&"); url.append(".hash=1"); url.append("&"); url.append(".md5=1"); return url.toString(); }
|
00
|
Code Sample 1:
private byte[] download(String URL) { byte[] result = null; HttpEntity httpEntity = null; try { HttpGet httpGet = new HttpGet(URL); httpGet.addHeader("Accept-Language", "zh-cn,zh,en"); httpGet.addHeader("Accept-Encoding", "gzip,deflate"); HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != 200) { return null; } Header header = response.getFirstHeader("content-type"); if (header == null || header.getValue().indexOf("text/html") < 0) { return null; } int pos = header.getValue().indexOf("charset="); if (pos >= 0) { detectedEncoding = header.getValue().substring(pos + 8); } httpEntity = response.getEntity(); InputStream in = null; in = httpEntity.getContent(); header = response.getFirstHeader("Content-Encoding"); if (null != header) { if (header.getValue().indexOf("gzip") >= 0) { in = new GZIPInputStream(in); } else if (header.getValue().indexOf("deflate") >= 0) { in = new InflaterInputStream(in, new Inflater(true)); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } result = out.toByteArray(); } catch (IOException ex) { LOG.warn("downloading error,abandon"); result = null; } return result; }
Code Sample 2:
public static String getMD5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); String salt = "UseTheForce4"; password = salt + password; md5.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, md5.digest()).toString(16); } catch (Exception e) { } return password; }
|
00
|
Code Sample 1:
public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
Code Sample 2:
public void writeToFtp(String login, String password, String address, String directory, String filename) { String newline = System.getProperty("line.separator"); try { URL url = new URL("ftp://" + login + ":" + password + "@ftp." + address + directory + filename + ".html" + ";type=i"); URLConnection urlConn = url.openConnection(); urlConn.setDoOutput(true); OutputStreamWriter stream = new OutputStreamWriter(urlConn.getOutputStream()); stream.write("<html><title>" + title + "</title>" + newline); stream.write("<h1><b>" + title + "</b></h1>" + newline); stream.write("<h2>Table Of Contents:</h2><ul>" + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<li><i><a href=\"#"); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k)); stream.write("</a></i></li>" + newline); } stream.write("</ul><hr>" + newline + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<h3><b>"); stream.write("<a name=\""); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k) + "</a>"); stream.write("</b></h3>" + newline); stream.write(readNoteBody(k) + newline); } stream.write(newline + "<br><hr><a>This was created using Scribe, a free crutch editor.</a></html>"); stream.close(); } catch (IOException error) { System.out.println("There was an error: " + error); } }
|
00
|
Code Sample 1:
protected List<? extends SearchResult> searchVideo(String words, int number, int offset, CancelMonitor cancelMonitor) { List<VideoSearchResult> resultsList = new ArrayList<>(); try { // set up the HTTP request factory HttpTransport transport = new NetHttpTransport(); HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { // set the parser JsonCParser parser = new JsonCParser(); parser.jsonFactory = JSON_FACTORY; request.addParser(parser); // set up the Google headers GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("OGLExplorer/1.0"); headers.gdataVersion = "2"; request.headers = headers; } }); // build the YouTube URL YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos"); url.maxResults = number; url.words = words; url.startIndex = offset + 1; // build HttpRequest request = factory.buildGetRequest(url); // execute HttpResponse response = request.execute(); VideoFeed feed = response.parseAs(VideoFeed.class); if (feed.items == null) { return null; } // browse result and convert them to the local generic object model for (int i = 0; i < feed.items.size() && !cancelMonitor.isCanceled(); i++) { Video result = feed.items.get(i); VideoSearchResult modelResult = new VideoSearchResult(offset + i + 1); modelResult.setTitle(result.title); modelResult.setDescription(result.description); modelResult.setThumbnailURL(new URL(result.thumbnail.lowThumbnailURL)); modelResult.setPath(result.player.defaultUrl); resultsList.add(modelResult); } } catch (Exception e) { e.printStackTrace(); } if (cancelMonitor.isCanceled()) { return null; } return resultsList; }
Code Sample 2:
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception { String attachmentName = request.getParameter("attachment"); String virtualWiki = getVirtualWiki(request); File uploadPath = getEnvironment().uploadPath(virtualWiki, attachmentName); response.reset(); response.setHeader("Content-Disposition", getEnvironment().getStringSetting(Environment.PROPERTY_ATTACHMENT_TYPE) + ";filename=" + attachmentName + ";"); int dotIndex = attachmentName.indexOf('.'); if (dotIndex >= 0 && dotIndex < attachmentName.length() - 1) { String extension = attachmentName.substring(attachmentName.lastIndexOf('.') + 1); logger.fine("Extension: " + extension); String mimetype = (String) getMimeByExtension().get(extension.toLowerCase()); logger.fine("MIME: " + mimetype); if (mimetype != null) { logger.fine("Setting content type to: " + mimetype); response.setContentType(mimetype); } } FileInputStream in = null; ServletOutputStream out = null; try { in = new FileInputStream(uploadPath); out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
|
11
|
Code Sample 1:
public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public static void main(String[] args) { FTPClient client = new FTPClient(); try { File l_file = new File("C:/temp/testLoribel.html"); String l_url = "http://www.loribel.com/index.html"; GB_HttpTools.loadUrlToFile(l_url, l_file, ENCODING.ISO_8859_1); System.out.println("Try to connect..."); client.connect("ftp://ftp.phpnet.org"); System.out.println("Connected to server"); System.out.println("Try to connect..."); boolean b = client.login("fff", "ddd"); System.out.println("Login: " + b); String[] l_names = client.listNames(); GB_DebugTools.debugArray(GB_FtpDemo2.class, "names", l_names); b = client.makeDirectory("test02/toto"); System.out.println("Mkdir: " + b); String l_remote = "test02/test.xml"; InputStream l_local = new StringInputStream("Test111111111111111"); b = client.storeFile(l_remote, l_local); System.out.println("Copy file: " + b); } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
public List<Template> getTemplates(boolean fromPrivate) { String shared = fromPrivate ? "private" : "public"; List<Template> templates = new ArrayList<Template>(); String restURL = configuration.getBeehiveRESTRootUrl() + "account/" + userService.getAccount().getOid() + "/templates/" + shared; HttpGet httpGet = new HttpGet(restURL); httpGet.setHeader("Accept", "application/json"); this.addAuthentication(httpGet); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) { throw new NotAuthenticatedException("User " + userService.getCurrentUser().getUsername() + " not authenticated! "); } throw new BeehiveNotAvailableException("Beehive is not available right now! "); } InputStreamReader reader = new InputStreamReader(response.getEntity().getContent()); BufferedReader buffReader = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = buffReader.readLine()) != null) { sb.append(line); sb.append("\n"); } String result = sb.toString(); TemplateList templateList = buildTemplateListFromJson(result); List<TemplateDTO> dtoes = templateList.getTemplates(); for (TemplateDTO dto : dtoes) { templates.add(dto.toTemplate()); } } catch (IOException e) { throw new BeehiveNotAvailableException("Failed to get template list, The beehive is not available right now ", e); } return templates; }
|
00
|
Code Sample 1:
private static URLConnection connectToNCBIValidator() throws IOException { final URL url = new URL(NCBI_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", CONTENT_TYPE); return connection; }
Code Sample 2:
public static Object GET(String url, String[][] props) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); for (int i = 0; i < props.length; ++i) { conn.addRequestProperty(props[i][0], URLEncoder.encode(props[i][1], "UTF-8")); } conn.connect(); try { return conn.getContent(); } finally { conn.disconnect(); } }
|
00
|
Code Sample 1:
private String doOAIQuery(String request) throws IOException, ProtocolException { DannoClient ac = getClient(); HttpGet get = new HttpGet(request); get.setHeader("Accept", "application/xml"); HttpResponse response = ac.execute(get); if (!ac.isOK()) { throw new DannoRequestFailureException("GET", response); } return massage(new BasicResponseHandler().handleResponse(response)); }
Code Sample 2:
protected String readUrl(String urlString) throws IOException { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String inputLine; while ((inputLine = in.readLine()) != null) response += inputLine; in.close(); return response; }
|
11
|
Code Sample 1:
public static String genDigest(String info) { MessageDigest alga; byte[] digesta = null; try { alga = MessageDigest.getInstance("SHA-1"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return byte2hex(digesta); }
Code Sample 2:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
11
|
Code Sample 1:
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
Code Sample 2:
public static void zipFile(String file, String entry) throws IOException { FileInputStream in = new FileInputStream(file); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file + ".zip")); out.putNextEntry(new ZipEntry(entry)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.closeEntry(); out.close(); File fin = new File(file); fin.delete(); }
|
00
|
Code Sample 1:
public static Map getFile(DispatchContext dctx, Map context) { String localFilename = (String) context.get("localFilename"); OutputStream localFile = null; try { localFile = new FileOutputStream(localFilename); } catch (IOException ioe) { Debug.logError(ioe, "[getFile] Problem opening local file", module); return ServiceUtil.returnError("ERROR: Could not open local file"); } List errorList = new ArrayList(); FTPClient ftp = new FTPClient(); try { ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { errorList.add("Server refused connection"); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); if (!ftp.login(username, password)) { errorList.add("Login failed (" + username + ", " + password + ")"); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) { errorList.add("File not received succesfully: " + ftp.getReplyString()); } } ftp.logout(); } } catch (IOException ioe) { errorList.add("Problem with FTP transfer: " + ioe.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException dce) { Debug.logWarning(dce, "[getFile] Problem with FTP disconnect", module); } } } try { localFile.close(); } catch (IOException ce) { Debug.logWarning(ce, "[getFile] Problem closing local file", module); } if (errorList.size() > 0) { Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } return ServiceUtil.returnSuccess(); }
Code Sample 2:
public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&") != -1) { String syn1 = syn.substring(0, syn.indexOf("&")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } }
|
11
|
Code Sample 1:
private Attachment setupSimpleAttachment(Context context, long messageId, boolean withBody) throws IOException { Attachment attachment = new Attachment(); attachment.mFileName = "the file.jpg"; attachment.mMimeType = "image/jpg"; attachment.mSize = 0; attachment.mContentId = null; attachment.mContentUri = "content://com.android.email/1/1"; attachment.mMessageKey = messageId; attachment.mLocation = null; attachment.mEncoding = null; if (withBody) { InputStream inStream = new ByteArrayInputStream(TEST_STRING.getBytes()); File cacheDir = context.getCacheDir(); File tmpFile = File.createTempFile("setupSimpleAttachment", "tmp", cacheDir); OutputStream outStream = new FileOutputStream(tmpFile); IOUtils.copy(inStream, outStream); attachment.mContentUri = "file://" + tmpFile.getAbsolutePath(); } return attachment; }
Code Sample 2:
private void copyXsl(File aTargetLogDir) { Trace.println(Trace.LEVEL.UTIL, "copyXsl( " + aTargetLogDir.getName() + " )", true); if (myXslSourceDir == null) { return; } File[] files = myXslSourceDir.listFiles(); for (int i = 0; i < files.length; i++) { File srcFile = files[i]; if (!srcFile.isDirectory()) { File tgtFile = new File(aTargetLogDir + File.separator + srcFile.getName()); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(srcFile).getChannel(); outChannel = new FileOutputStream(tgtFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IOError(e); } finally { if (inChannel != null) try { inChannel.close(); } catch (IOException exc) { throw new IOError(exc); } if (outChannel != null) try { outChannel.close(); } catch (IOException exc) { throw new IOError(exc); } } } } }
|
00
|
Code Sample 1:
private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
Code Sample 2:
void readData() { String[] nextLine; int line; double value; URL url = null; String FileToRead; try { for (int i = 0; i < names.length; i++) { FileToRead = "data/" + names[i] + ".csv"; url = new URL(ja.getCodeBase(), FileToRead); System.out.println(url.toString()); InputStream in = url.openStream(); CSVReader reader = new CSVReader(new InputStreamReader(in)); line = 0; while ((nextLine = reader.readNext()) != null) { allset.months[line] = Integer.parseInt(nextLine[0].substring(0, 2)); allset.years[line] = Integer.parseInt(nextLine[0].substring(6, 10)); value = Double.parseDouble(nextLine[1]); allset.values.getDataRef()[line][i] = value; line++; } } } catch (IOException e) { System.err.println("File Read Exception"); } }
|
00
|
Code Sample 1:
public void doUpdate(String version) { try { final String hyperlink_url = "http://xnavigator.sourceforge.net/dist/"; JFrame updateInfoFrame = null; try { JPanel panel = new JPanel(); panel.setLayout(null); panel.setBackground(new java.awt.Color(255, 255, 255)); panel.setBorder(new TitledBorder("")); ClassLoader cl = this.getClass().getClassLoader(); int BORDER_TOP = 10; int PANEL_WIDTH = 400; int TEXT_WIDTH = 360; int TEXT_HEIGHT = 50; int TEXT_LEFT = 20; int y = BORDER_TOP; I3Label title = new I3Label("XNavigator Update"); title.setBounds(30, y, 350, 25); panel.add(title); ImageIcon splash3 = new ImageIcon(Toolkit.getDefaultToolkit().getImage(cl.getResource("resources/splash3.jpg"))); JButton left = new JButton(splash3); left.setBounds(20, y += 30, 350, 235); left.setBorder(null); left.setFocusPainted(false); panel.add(left); JTextPane informText = new JTextPane(); informText.setLayout(null); informText.setBounds(TEXT_LEFT, y += 235, TEXT_WIDTH, TEXT_HEIGHT); informText.setBackground(new java.awt.Color(255, 255, 255)); informText.setEditable(false); informText.setFocusable(false); panel.add(informText); JTextPane progressText = new JTextPane(); progressText.setLayout(null); progressText.setBounds(TEXT_LEFT, y += TEXT_HEIGHT, TEXT_WIDTH, TEXT_HEIGHT); progressText.setBackground(new java.awt.Color(255, 255, 255)); progressText.setEditable(false); progressText.setFocusable(false); panel.add(progressText); updateInfoFrame = new JFrame(); updateInfoFrame.setUndecorated(false); updateInfoFrame.setTitle("XNavigator Update"); updateInfoFrame.setSize(400, 430); updateInfoFrame.getContentPane().add(panel); updateInfoFrame.setVisible(true); updateInfoFrame.setEnabled(true); updateInfoFrame.setResizable(false); updateInfoFrame.setLocation(300, 150); updateInfoFrame.addWindowListener(this); panel.repaint(); informText.setText(i18n.getString("UPDATE_CHECK_INSTANCES")); String message0 = i18n.getString("UPDATE_INSTANCES"); JLabel label01 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: bold;}--></style></head><body><span class=\"Stil2\">XNavigator Update</span></body></html>"); JLabel label02 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + message0 + " " + "</span></body></html>"); Object[] objects0 = { label01, label02 }; Object[] options0 = { i18n.getString("CONTINUE"), i18n.getString("CANCEL") }; int option = JOptionPane.showOptionDialog(null, objects0, "Update", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options0, options0[0]); if (option == 0) { } else { updateInfoFrame.dispose(); return; } informText.setText(i18n.getString("UPDATE_CHECK_ENVIRONMENT")); if ((new File(".project")).exists()) { Object[] objects = { "Im Eclipse Projekt solltest Du besser die neueste Version aus dem SVN ziehen -Arne-", "Update abgebrochen" }; JOptionPane.showMessageDialog(null, objects, "Update Error", JOptionPane.ERROR_MESSAGE); updateInfoFrame.dispose(); return; } Object[] objects1 = { i18n.getString("UPDATE_WARNING") }; Object[] options1 = { i18n.getString("CONTINUE"), i18n.getString("CANCEL") }; int opt = JOptionPane.showOptionDialog(null, objects1, i18n.getString("WARNING"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options1, options1[0]); if (opt == 1) { updateInfoFrame.dispose(); return; } updateInfoFrame.requestFocus(); updateInfoFrame.requestFocusInWindow(); informText.setText(i18n.getString("UPDATE_DOWNLOADING")); String updateFile = "XNavigator-" + version + ".zip"; URL url = new URL(hyperlink_url + updateFile); URLConnection conn = url.openConnection(); int fileSize = conn.getContentLength(); String urlString = url.toString(); progressText.setText("Download " + urlString + " ... 0%"); java.io.BufferedInputStream in = new java.io.BufferedInputStream(url.openStream()); java.io.FileOutputStream fos = new java.io.FileOutputStream(updateFile); java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); int BUFFER_SIZE = 1024; byte data[] = new byte[BUFFER_SIZE]; int count = 0; int size = 0; int prev_perc = 0; while ((count = in.read(data, 0, BUFFER_SIZE)) > 0) { bout.write(data, 0, count); size += count; int perc = (100 * size) / fileSize; if (perc > prev_perc) { progressText.setText("Download " + urlString + " ... " + perc + "%"); prev_perc = perc; } } bout.close(); fos.close(); in.close(); progressText.setText("Download " + url.toString() + " ... ok."); informText.setText(i18n.getString("UPDATE_EXTRACTING")); boolean deleted = deleteFiles(new File("./lib"), false); if (!deleted) { updateInfoFrame.dispose(); return; } extractZipFile(updateFile, progressText); progressText.setText(i18n.getString("UPDATE_COMPLETE")); Object[] objects = { i18n.getString("UPDATE_COMPLETE") }; Object[] options = { i18n.getString("OK") }; JOptionPane.showOptionDialog(null, objects, "Success", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); System.exit(0); } catch (Exception e) { e.printStackTrace(); String message = ""; String hyperlink = ""; message = i18n.getString("UPDATE_FAILED"); hyperlink = "<a href='" + hyperlink_url + "'>" + hyperlink_url + "</a>"; JLabel label2 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + message + " " + "</span></body></html>"); JLabel label3 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + hyperlink + "<br>" + "</span></body></html>"); JLabel label4 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + version + "</span></body></html>"); label3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); label3.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 0) { try { javax.jnlp.BasicService basicService; basicService = (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService"); basicService.showDocument(new URL(hyperlink_url)); } catch (Exception e1) { e1.printStackTrace(); try { Runtime.getRuntime().exec("cmd.exe /c start " + hyperlink_url); } catch (IOException e2) { e2.printStackTrace(); } } } } }); Object[] objects = { label2, label3, label4 }; Object[] options = { i18n.getString("OK") }; updateInfoFrame.dispose(); JOptionPane.showOptionDialog(null, objects, "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); } updateInfoFrame.setVisible(false); updateInfoFrame.dispose(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void readData(int choice) throws IOException { for (i = 0; i < max; i++) for (j = 0; j < max; j++) { phase_x[i][j] = 0.0; phase_y[i][j] = 0.0; } URL url; InputStream is; InputStreamReader isr; if (choice == 0) { url = getClass().getResource("resources/Phase_623_620_Achromat.dat"); is = url.openStream(); isr = new InputStreamReader(is); } else { url = getClass().getResource("resources/Phase_623_620_NoAchromat.dat"); is = url.openStream(); isr = new InputStreamReader(is); } BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); i = 0; j = 0; phase_x[i][j] = 4 * Double.parseDouble(st.nextToken()); phase_y[i][j] = 4 * Double.parseDouble(st.nextToken()); xgridmin = phase_x[i][j]; ygridmin = phase_y[i][j]; temp_prev = phase_x[i][j]; kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = 4 * Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } phase_x[i][j] = temp_new; phase_y[i][j] = 4 * Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } xgridmax = phase_x[i][j - 1]; ygridmax = phase_y[i][j - 1]; }
|
00
|
Code Sample 1:
public boolean isValid(WizardContext context) { if (serviceSelection < 0) { return false; } ServiceReference selection = (ServiceReference) serviceList.getElementAt(serviceSelection); if (selection == null) { return false; } String function = (String) context.getAttribute(ServiceWizard.ATTRIBUTE_FUNCTION); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE_REFERENCE, selection); URL url = selection.getResourceURL(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); JdbcService service = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE, service); return true; } catch (IOException error) { if (!ServiceWizard.FUNCTION_DELETE.equals(function)) { String loc = url.toExternalForm(); String message = messages.format("SelectServiceStep.failed_to_load_service_from_url", loc); context.showErrorDialog(error, message); } else { return true; } } catch (Exception error) { String message = messages.format("SelectServiceStep.service_load_error", url.toExternalForm()); context.showErrorDialog(error, message); } return false; }
Code Sample 2:
private ByteArrayInputStream fetchUrl(String urlString, Exception[] outException) { URL url; try { url = new URL(urlString); InputStream is = null; int inc = 65536; int curr = 0; byte[] result = new byte[inc]; try { is = url.openStream(); int n; while ((n = is.read(result, curr, result.length - curr)) != -1) { curr += n; if (curr == result.length) { byte[] temp = new byte[curr + inc]; System.arraycopy(result, 0, temp, 0, curr); result = temp; } } return new ByteArrayInputStream(result, 0, curr); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } catch (Exception e) { outException[0] = e; } return null; }
|
11
|
Code Sample 1:
public void load(String filename) throws VisbardException { String defaultFilename = VisbardMain.getSettingsDir() + File.separator + DEFAULT_SETTINGS_FILE; File defaultFile = new File(defaultFilename); InputStream settingsInStreamFromFile = null; try { sLogger.info("Loading settings from : " + defaultFilename); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (FileNotFoundException fnf) { sLogger.info("Unable to load custom settings from user's settings directory (" + fnf.getMessage() + "); reverting to default settings"); try { InputStream settingsInStreamFromJar = VisbardMain.class.getClassLoader().getResourceAsStream(filename); FileOutputStream settingsOutStream = new FileOutputStream(defaultFile); int c; while ((c = settingsInStreamFromJar.read()) != -1) settingsOutStream.write(c); settingsInStreamFromJar.close(); settingsOutStream.close(); settingsInStreamFromFile = new FileInputStream(defaultFile); } catch (IOException ioe) { sLogger.warn("Unable to copy default settings to user's settings directory (" + ioe.getMessage() + "); using default settings from ViSBARD distribution package"); settingsInStreamFromFile = VisbardMain.class.getClassLoader().getResourceAsStream(filename); } } this.processSettingsFile(settingsInStreamFromFile, filename); }
Code Sample 2:
private void dumpFile(File repository, File copy) { try { if (copy.exists() && !copy.delete()) { throw new RuntimeException("can't delete copy: " + copy); } printFile("Real Archive File", repository); new ZipArchive(repository.getPath()); IOUtils.copyFiles(repository, copy); printFile("Copy Archive File", copy); new ZipArchive(copy.getPath()); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void init(IWorkbench workbench) { preferences.setFilename(CorePlugin.getDefault().getStateLocation().append("log4j.properties").toOSString()); registry = Platform.getExtensionRegistry(); extensionPoint = registry.getExtensionPoint(CorePlugin.LOGGER_PREFERENCES_EXTENSION_POINT); IConfigurationElement[] members = extensionPoint.getConfigurationElements(); for (int i = 0; i < members.length; i++) { IConfigurationElement element = members[i]; if (element.getName().equals("logger")) { if (element.getAttribute("defaultValue") != null) { String[] item = element.getAttribute("name").split(";"); for (int x = 0; x < item.length; x++) preferences.setDefault("log4j.logger." + item[x], element.getAttribute("defaultValue")); } } } try { URL url = CorePlugin.getDefault().getBundle().getResource("log4j.properties"); Properties properties = new Properties(); properties.load(url.openStream()); for (Iterator iter = properties.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); preferences.setDefault(key, (String) properties.get(key)); } File file = CorePlugin.getDefault().getStateLocation().append("log4j.properties").toFile(); if (file.exists()) preferences.load(new FileInputStream(file)); } catch (Exception e) { CorePlugin.logException(e); } }
Code Sample 2:
private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
11
|
Code Sample 1:
static void sort(int[] a) { int i = 0; while (i < a.length - 1) { int j = 0; while (j < (a.length - i) - 1) { if (a[j] > a[j + 1]) { int aux = a[j]; a[j] = a[j + 1]; a[j + 1] = aux; } j = j + 1; } i = i + 1; } }
Code Sample 2:
public void sort(int[] order, double[] values) { int temp = 0; boolean done = false; for (int i = 0; i < values.length; i++) { order[i] = i; } if (desendingValues) { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] < values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } else { while (!done) { done = true; for (int i = values.length - 2; i >= 0; i--) { if (values[order[i]] > values[order[i + 1]]) { done = false; temp = order[i]; order[i] = order[i + 1]; order[i + 1] = temp; } } } } }
|
00
|
Code Sample 1:
public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } }
Code Sample 2:
protected long getURLLastModified(final URL url) throws IOException { final URLConnection con = url.openConnection(); long lastModified = con.getLastModified(); try { con.getInputStream().close(); } catch (IOException ignored) { } return lastModified; }
|
00
|
Code Sample 1:
private void createTree(DefaultMutableTreeNode top) throws MalformedURLException, ParserConfigurationException, SAXException, IOException { InputStream stream; URL url = new URL(SHIPS_URL + view.getBaseurl()); try { stream = url.openStream(); } catch (Exception e) { stream = getClass().getResourceAsStream("ships.xml"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(stream); NodeList races = doc.getElementsByTagName("race"); for (int i = 0; i < races.getLength(); i++) { Element race = (Element) races.item(i); top.add(buildRaceTree(race)); } top.setUserObject("Ships"); view.getShipTree().repaint(); view.getShipTree().expandRow(0); }
Code Sample 2:
protected String getCache() throws IOException { if (cache == null) { URL url = ((URI) hasContent()).toURL(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) ; in.close(); cache = inputLine; } return cache; }
|
11
|
Code Sample 1:
public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); }
Code Sample 2:
@RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) { InputStream input = null; ServletOutputStream output = null; try { String savePath = request.getSession().getServletContext().getRealPath("/upload"); String fileType = ".log"; String dbFileName = "83tomcat日志测试哦"; String downloadFileName = dbFileName + fileType; String finalPath = "\\2011-12\\01\\8364b45f-244d-41b6-bbf48df32064a935"; downloadFileName = new String(downloadFileName.getBytes("GBK"), "ISO-8859-1"); File downloadFile = new File(savePath + finalPath); if (!downloadFile.getParentFile().exists()) { downloadFile.getParentFile().mkdirs(); } if (!downloadFile.isFile()) { FileUtils.touch(downloadFile); } response.setContentType("aapplication/vnd.ms-excel ;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("content-disposition", "attachment; filename=" + downloadFileName); input = new FileInputStream(downloadFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { logger.error("Exception: ", e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
|
00
|
Code Sample 1:
public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
Code Sample 2:
public static String calculateHash(String data, String algorithm) { if (data == null) { return null; } algorithm = (algorithm == null ? INTERNAL : algorithm.toUpperCase()); if (algorithm.equals(PLAIN)) { return data; } if (algorithm.startsWith("{RSA}")) { return encode(data, algorithm.substring(5), "RSA"); } try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data.getBytes("UTF-8")); return getHashString(md.digest()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { logger.error(nsae.getMessage()); return null; } }
|
11
|
Code Sample 1:
public static void exportDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = input + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); HashMap<Integer, String> languageIDs = new HashMap<Integer, String>(); HashMap<Integer, String> typeIDs = new HashMap<Integer, String>(); long tiempoInicio = System.currentTimeMillis(); Element dataBaseXML = new Element("database"); Element languages = new Element("languages"); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select * from language order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); languageIDs.put(id, name); Element language = new Element("language"); language.setText(name); languages.addContent(language); } dataBaseXML.addContent(languages); rs = stat.executeQuery("select * from type order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); typeIDs.put(id, name); } rs = stat.executeQuery("select distinct name from main order by name"); while (rs.next()) { String name = rs.getString("name"); Element image = new Element("image"); image.setAttribute("id", name); Statement stat2 = G.conn.createStatement(); ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL"); while (rs2.next()) { int idL = rs2.getInt("idL"); Element language = new Element("language"); language.setAttribute("id", languageIDs.get(idL)); Statement stat3 = G.conn.createStatement(); ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT"); while (rs3.next()) { int idT = rs3.getInt("idT"); String word = rs3.getString("word"); Element wordE = new Element("word"); wordE.setAttribute("type", typeIDs.get(idT)); wordE.setText(word); language.addContent(wordE); String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name; String pathDst = output + File.separator + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } rs3.close(); stat3.close(); image.addContent(language); } rs2.close(); stat2.close(); dataBaseXML.addContent(image); } rs.close(); stat.close(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName); out.output(dataBaseXML, f); f.flush(); f.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
|
11
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String pluginPathInfo = pathInfo.substring(prefix.length()); String gwtPathInfo = pluginPathInfo.substring(pluginKey.length() + 1); String clPath = CLASSPATH_PREFIX + gwtPathInfo; InputStream input = cl.getResourceAsStream(clPath); if (input != null) { try { OutputStream output = resp.getOutputStream(); IOUtils.copy(input, output); } finally { input.close(); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Code Sample 2:
public void copyTo(Bean bean, OutputStream out, int offset, int length) throws Exception { BeanInfo beanInfo = getBeanInfo(bean.getClass()); validate(bean, beanInfo, "copyTo"); if (blobCache != null && length < MAX_BLOB_CACHE_LENGHT) { byte[] bytes = null; synchronized (this) { String key = makeUniqueKey(bean, beanInfo, offset, length); if (blobCache.contains(key)) bytes = (byte[]) blobCache.get(key); else blobCache.put(key, bytes = toByteArray(bean, offset, length, beanInfo)); } InputStream in = new ByteArrayInputStream(bytes); IOUtils.copy(in, out); in.close(); } else { jdbcManager.queryScript(beanInfo.getBlobInfo(jdbcManager.getDb()).getReadScript(), bean, new JdbcOutputStreamRowMapper(out, offset, length)); } }
|
11
|
Code Sample 1:
public static boolean insert(final Funcionario objFuncionario) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into funcionario " + "(nome, cpf, telefone, email, senha, login, id_cargo)" + " values (?, ?, ?, ?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, objFuncionario.getNome()); pst.setString(2, objFuncionario.getCpf()); pst.setString(3, objFuncionario.getTelefone()); pst.setString(4, objFuncionario.getEmail()); pst.setString(5, objFuncionario.getSenha()); pst.setString(6, objFuncionario.getLogin()); pst.setLong(7, (objFuncionario.getCargo()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { System.out.println("[FuncionarioDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[FuncionarioDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
|
11
|
Code Sample 1:
private String hash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); }
Code Sample 2:
public static String encrypt(String password, Long digestSeed) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes("UTF-8")); algorithm.update(digestSeed.toString().getBytes("UTF-8")); byte[] messageDigest = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xff & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public static String encryptPassword(String username, String realm, String password) throws GeneralSecurityException { MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] hash = md.digest(); return toHex(hash, hash.length); }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
00
|
Code Sample 1:
public String getInternetData() throws Exception { BufferedReader in = null; String data = null; try { HttpClient client = new DefaultHttpClient(); URI website = new URI("http://code.google.com/p/gadi-works"); HttpGet request = new HttpGet(); request.setURI(website); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String l = ""; String nl = System.getProperty("line.separator"); while ((l = in.readLine()) != null) { sb.append(l + nl); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } }
Code Sample 2:
public static String[] bubbleSort(String[] unsortedString, boolean ascending) { if (unsortedString.length < 2) return unsortedString; String[] sortedString = new String[unsortedString.length]; for (int i = 0; i < unsortedString.length; i++) { sortedString[i] = unsortedString[i]; } if (ascending) { for (int i = 0; i < sortedString.length - 1; i++) { for (int j = 1; j < sortedString.length - 1 - i; j++) if (sortedString[j + 1].compareToIgnoreCase(sortedString[j]) < 0) { String swap = sortedString[j]; sortedString[j] = sortedString[j + 1]; sortedString[j + 1] = swap; } } } else { for (int i = sortedString.length - 2; i >= 0; i--) { for (int j = sortedString.length - 2 - i; j >= 0; j--) if (sortedString[j + 1].compareToIgnoreCase(sortedString[j]) > 0) { String swap = sortedString[j]; sortedString[j] = sortedString[j + 1]; sortedString[j + 1] = swap; } } } return sortedString; }
|
11
|
Code Sample 1:
public static boolean copy(String source, String dest) { int bytes; byte array[] = new byte[BUFFER_LEN]; try { InputStream is = new FileInputStream(source); OutputStream os = new FileOutputStream(dest); while ((bytes = is.read(array, 0, BUFFER_LEN)) > 0) os.write(array, 0, bytes); is.close(); os.close(); return true; } catch (IOException e) { return false; } }
Code Sample 2:
private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.