label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private List<String[]> retrieveData(String query) { List<String[]> data = new Vector<String[]>(); query = query.replaceAll("\\s", "+"); String q = "http://www.uniprot.org/uniprot/?query=" + query + "&format=tab&columns=id,protein%20names,organism"; try { URL url = new URL(q); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; reader.readLine(); while ((line = reader.readLine()) != null) { String[] st = line.split("\t"); String[] d = new String[] { st[0], st[1], st[2] }; data.add(d); } reader.close(); if (data.size() == 0) { JOptionPane.showMessageDialog(this, "No data found for query"); } } catch (MalformedURLException e) { System.err.println("Query " + q + " caused exception: "); e.printStackTrace(); } catch (Exception e) { System.err.println("Query " + q + " caused exception: "); e.printStackTrace(); } return data; } Code Sample 2: public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; }
11
Code Sample 1: @Test public void testCopy() throws IOException { final byte[] input = { 0x00, 0x01, 0x7F, 0x03, 0x40 }; final byte[] verification = input.clone(); Assert.assertNotSame("Expecting verification to be a new array.", input, verification); final ByteArrayInputStream in = new ByteArrayInputStream(input); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); final byte[] output = out.toByteArray(); Assert.assertTrue("Expecting input to be unchanged.", Arrays.equals(verification, input)); Assert.assertTrue("Expecting output to be like input.", Arrays.equals(verification, output)); Assert.assertNotSame("Expecting output to be a new array.", input, output); Assert.assertNotSame("Expecting output to be a new array.", verification, output); } Code Sample 2: public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
11
Code Sample 1: public void initForEncryption() throws CryptographyException, IOException { String ownerPassword = pdDocument.getOwnerPasswordForEncryption(); String userPassword = pdDocument.getUserPasswordForEncryption(); if (ownerPassword == null) { ownerPassword = ""; } if (userPassword == null) { userPassword = ""; } PDStandardEncryption encParameters = (PDStandardEncryption) pdDocument.getEncryptionDictionary(); int permissionInt = encParameters.getPermissions(); int revision = encParameters.getRevision(); int length = encParameters.getLength() / 8; COSArray idArray = document.getDocumentID(); if (idArray == null || idArray.size() < 2) { idArray = new COSArray(); try { MessageDigest md = MessageDigest.getInstance("MD5"); BigInteger time = BigInteger.valueOf(System.currentTimeMillis()); md.update(time.toByteArray()); md.update(ownerPassword.getBytes()); md.update(userPassword.getBytes()); md.update(document.toString().getBytes()); byte[] id = md.digest(this.toString().getBytes()); COSString idString = new COSString(); idString.append(id); idArray.add(idString); idArray.add(idString); document.setDocumentID(idArray); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e); } } COSString id = (COSString) idArray.getObject(0); encryption = new PDFEncryption(); byte[] o = encryption.computeOwnerPassword(ownerPassword.getBytes("ISO-8859-1"), userPassword.getBytes("ISO-8859-1"), revision, length); byte[] u = encryption.computeUserPassword(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encryptionKey = encryption.computeEncryptedKey(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encParameters.setOwnerKey(o); encParameters.setUserKey(u); document.setEncryptionDictionary(encParameters.getCOSDictionary()); } Code Sample 2: public static final String getHash(int iterationNb, String password, String salt) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes("UTF-8")); byte[] input = digest.digest(password.getBytes("UTF-8")); for (int i = 0; i < iterationNb; i++) { digest.reset(); input = digest.digest(input); } String hashedValue = encoder.encode(input); LOG.finer("Creating hash '" + hashedValue + "' with iterationNb '" + iterationNb + "' and password '" + password + "' and salt '" + salt + "'!!"); return hashedValue; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("Problem in the getHash method.", ex); } }
11
Code Sample 1: public void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } } Code Sample 2: private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
00
Code Sample 1: @Override public Representation getRepresentation(Variant variant) { Representation representation = null; MediaType requestMediaType = variant.getMediaType(); if (MediaType.TEXT_XML.equals(requestMediaType)) { try { representation = new DomRepresentation(MediaType.TEXT_XML); } catch (IOException e) { e.printStackTrace(); return null; } } String strJobsUrl = ((ResourceApplication) getApplication()).getJobsUrl(); org.dom4j.Document reportDoc = null; try { SAXReader reader = new SAXReader(); reportDoc = reader.read(strJobsUrl + "/" + strJobId + "/report.xml"); } catch (DocumentException e) { String strErrMsg = "Unable to find job, " + strJobId + ": " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.CLIENT_ERROR_NOT_FOUND, null, "JobNotFound", strErrMsg, null); return rep; } if (MediaType.TEXT_XML.equals(requestMediaType)) { log.debug("XML Media Type requested"); try { reportDoc.removeProcessingInstruction("xml-stylesheet"); DOMWriter writer = new DOMWriter(); Document doc = writer.write(reportDoc); doc.normalizeDocument(); ((DomRepresentation) representation).setDocument(doc); return representation; } catch (DocumentException e) { String strErrMsg = "Error display job's report: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.CLIENT_ERROR_CONFLICT, null, "ClientConflict", strErrMsg, null); return rep; } } else if (MediaType.TEXT_HTML.equals(requestMediaType)) { log.debug("HTML Media Type requested"); try { ProcessingInstruction pi = reportDoc.processingInstruction("xml-stylesheet"); if (pi != null) { String strXslHref = pi.getValue("href"); URL url = new URL(strXslHref); XSLTransformer reportDocTransformer = new XSLTransformer(); log.debug("constructed the reportDocTransformer"); reportDoc = reportDocTransformer.transform(reportDoc, url.openStream()); } } catch (MalformedURLException e) { String strErrMsg = "Error accessing referenced XSL-STYLESHEET: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.SERVER_ERROR_INTERNAL, null, "InternalError", strErrMsg, null); return rep; } catch (IOException e) { String strErrMsg = "Error accessing referenced XSL-STYLESHEET: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.SERVER_ERROR_INTERNAL, null, "InternalError", strErrMsg, null); return rep; } catch (FedoraAPIException e) { String strErrMsg = "Error accessing referenced XSL-STYLESHEET: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.SERVER_ERROR_INTERNAL, null, "InternalError", strErrMsg, null); return rep; } representation = new StringRepresentation(reportDoc.asXML(), MediaType.TEXT_HTML); return representation; } return null; } Code Sample 2: public void openUrlActionPerformed(ActionEvent event) { RemoteFileChooser fileChooser = new RemoteFileChooser(this, getAppName()); fileChooser.getDialog().setVisible(true); if (fileChooser.getResult() == JOptionPane.OK_OPTION) { setCursorBusy(true); URL url = fileChooser.getSelectedUrl(); String filename = fileChooser.getSelectedFilename(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); openFile(filename, reader); } catch (IOException e) { handleException(e); } setCursorBusy(false); } checkActions(); }
00
Code Sample 1: public static String getSignature(String s) { try { final AsciiEncoder coder = new AsciiEncoder(); final MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(s.getBytes("UTF-8")); final byte[] digest = msgDigest.digest(); return coder.encode(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalStateException(); } } Code Sample 2: public void run() throws Exception { Properties buildprops = new Properties(); try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("build.properties"); InputStream is = url.openStream(); ; buildprops.load(is); } catch (Exception ex) { log.error("Problem getting build props", ex); } System.out.println("Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown")); validate(); if (log.isInfoEnabled()) { log.info("Starting Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown")); } MainConfig config = MainConfig.newInstance(); basedir = config.getBaseDirectory(); if (log.isInfoEnabled()) { log.info("basedir = " + basedir); } SchedulerFactory schedFact = new StdSchedulerFactory(); sched = schedFact.getScheduler(); NodeList reports = config.getReports(); for (int x = 0; x < reports.getLength(); x++) { try { if (log.isInfoEnabled()) { log.info("Adding report at index " + x); } Node report = reports.item(x); runReport(report); } catch (Exception ex) { if (log.isErrorEnabled()) { log.error("Can't add a report at report index " + x, ex); } } } addStatsJob(); sched.start(); WebServer webserver = new WebServer(8080); webserver.setParanoid(false); webserver.start(); }
11
Code Sample 1: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
11
Code Sample 1: public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); } Code Sample 2: public static void main(String[] args) throws IOException { System.setProperty("java.protocol.xfile", "com.luzan.common.nfs"); if (args.length < 1) usage(); final String cmd = args[0]; if ("delete".equalsIgnoreCase(cmd)) { final String path = getParameter(args, 1); XFile xfile = new XFile(path); if (!xfile.exists()) { System.out.print("File doean't exist.\n"); System.exit(1); } xfile.delete(); } else if ("copy".equalsIgnoreCase(cmd)) { final String pathFrom = getParameter(args, 1); final String pathTo = getParameter(args, 2); final XFile xfileFrom = new XFile(pathFrom); final XFile xfileTo = new XFile(pathTo); if (!xfileFrom.exists()) { System.out.print("File doesn't exist.\n"); System.exit(1); } final String mime = getParameter(args, 3, null); final XFileInputStream in = new XFileInputStream(xfileFrom); final XFileOutputStream xout = new XFileOutputStream(xfileTo); if (!StringUtils.isEmpty(mime)) { final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfileTo.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType(mime); xfa.setContentLength(xfileFrom.length()); } } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); } }
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 void lookupAllFactories() throws IOException { Enumeration setOfFactories = null; ClassLoader classLoader = null; InputStream inputStream = null; classLoader = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } return cl; } }); if (classLoader == null) { return; } try { setOfFactories = classLoader.getResources("META-INF/services/javax.print.StreamPrintServiceFactory"); } catch (IOException e) { e.printStackTrace(); throw new IOException("IOException during resource finding"); } try { while (setOfFactories.hasMoreElements()) { URL url = (URL) setOfFactories.nextElement(); inputStream = url.openStream(); getFactoryClasses(inputStream); } } catch (IOException e1) { e1.printStackTrace(); throw new IOException("IOException during resource reading"); } }
11
Code Sample 1: public String getHash(String key, boolean base64) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(key.getBytes()); if (base64) return new String(new Base64().encode(md.digest()), "UTF8"); else return new String(md.digest(), "UTF8"); } Code Sample 2: private String createHash() { String hash = ""; try { final java.util.Calendar c = java.util.Calendar.getInstance(); String day = "" + c.get(java.util.Calendar.DATE); day = (day.length() == 1) ? '0' + day : day; String month = "" + (c.get(java.util.Calendar.MONTH) + 1); month = (month.length() == 1) ? '0' + month : month; final String hashString = getStringProperty("hashkey") + day + "." + month + "." + c.get(java.util.Calendar.YEAR); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(hashString.getBytes()); final byte digest[] = md.digest(); hash = ""; for (int i = 0; i < digest.length; i++) { final String s = Integer.toHexString(digest[i] & 0xFF); hash += ((s.length() == 1) ? "0" + s : s); } } catch (final NoSuchAlgorithmException e) { bot.getLogger().log(e); } return hash; }
00
Code Sample 1: public static Bitmap[] getMaps(double lat, double lon, int zoom) throws MalformedURLException, IOException { int latitudeTileNumber = lat2tile(lat, zoom); int longitudeTileNumber = lon2tile(lon, zoom); Bitmap[] maps = new Bitmap[10]; int cpt = 0; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { try { URL url = new URL(("http://tile.openstreetmap.org/" + zoom + "/" + (longitudeTileNumber + j) + "/" + (latitudeTileNumber + i) + ".png")); Bitmap bmImg = BitmapFactory.decodeStream(url.openStream()); maps[cpt] = bmImg; cpt++; } catch (IOException e) { e.printStackTrace(); } } } return maps; } Code Sample 2: public static void get_PK_data() { try { FileWriter file_writer = new FileWriter("xml_data/PK_data_dump.xml"); BufferedWriter file_buffered_writer = new BufferedWriter(file_writer); URL fdt = new URL("http://opendata.5t.torino.it/get_pk"); URLConnection url_connection = fdt.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(url_connection.getInputStream())); String input_line; int num_lines = 0; while ((input_line = in.readLine()) != null) { file_buffered_writer.write(input_line + "\n"); num_lines++; } System.out.println("Parking :: Writed " + num_lines + " lines."); in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
00
Code Sample 1: @Override protected RequestLogHandler createRequestLogHandler() { try { File logbackConf = File.createTempFile("logback-access", ".xml"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("logback-access.xml"), new FileOutputStream(logbackConf)); RequestLogHandler requestLogHandler = new RequestLogHandler(); RequestLogImpl requestLog = new RequestLogImpl(); requestLog.setFileName(logbackConf.getPath()); requestLogHandler.setRequestLog(requestLog); } catch (FileNotFoundException e) { log.error("Could not create request log handler", e); } catch (IOException e) { log.error("Could not create request log handler", e); } return null; } Code Sample 2: public void removeRoom(int thisRoom) { DBConnection con = null; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String query = "DELETE FROM cafe_Chat_Category WHERE cafe_Chat_Category_id=? "; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); query = "DELETE FROM cafe_Chatroom WHERE cafe_chatroom_category=? "; ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); con.commit(); con.setAutoCommit(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException sqle) { } } finally { if (con != null) con.release(); } }
11
Code Sample 1: private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } } Code Sample 2: public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException { final Properties properties = new Properties(); properties.put("archetypeGroupId", "org.nexopenframework.plugins"); properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule"); final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion(); properties.put("archetypeVersion", version); properties.put("artifactId", moduleExtension.getArtifact()); properties.put("groupId", moduleExtension.getGroup()); properties.put("version", moduleExtension.getVersion()); final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact()); final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); final File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (final IOException e) { } } String goalName = "archetype:create"; boolean offline = false; try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin"); final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]); offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline"); } catch (final ClassNotFoundException e) { Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e); } catch (final NoSuchMethodException e) { Logger.logException("No method getDefault", e); } catch (final Throwable e) { Logger.logException(e); } if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } if (!offline) { final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore(); final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES); final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR); final StringBuffer sbRepos = new StringBuffer(); for (int k = 0; k < repos.length; k++) { sbRepos.append(repos[k]); if (k != repos.length - 1) { sbRepos.append(","); } } properties.put("remoteRepositories", sbRepos.toString()); } workingCopy.setAttribute(ATTR_GOALS, goalName); workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location)); FileUtils.deleteDirectory(new File(location + "/src")); FileUtils.forceDelete(new File(location, "pom.xml")); project.refreshLocal(IResource.DEPTH_INFINITE, null); } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } }
00
Code Sample 1: public FileReader(String filePath, Configuration aConfiguration) throws IOException { file = new File(URLDecoder.decode(filePath, "UTF-8")).getCanonicalFile(); readerConf = aConfiguration; if (file.isDirectory()) { File indexFile = new File(file, "index.php"); File indexFile_1 = new File(file, "index.html"); if (indexFile.exists() && !indexFile.isDirectory()) { file = indexFile; } else if (indexFile_1.exists() && !indexFile_1.isDirectory()) { file = indexFile_1; } else { if (!readerConf.getOption("showFolders").equals("Yes")) { makeErrorPage(503, "Permision denied"); } else { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); File[] files = file.listFiles(); makeHeader(200, -1, new Date(System.currentTimeMillis()).toString(), "text/html"); String title = "Index of " + file; out.write(("<html><head><title>" + title + "</title></head><body><h3>Index of " + file + "</h3><p>\n").getBytes()); for (int i = 0; i < files.length; i++) { file = files[i]; String filename = file.getName(); String description = ""; if (file.isDirectory()) { description = "&lt;DIR&gt;"; } out.write(("<a href=\"" + file.getPath().substring(readerConf.getOption("wwwPath").length()) + "\">" + filename + "</a> " + description + "<br>\n").getBytes()); } out.write(("</p><hr><p>yawwwserwer</p></body><html>").getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } } } else if (!file.exists()) { makeErrorPage(404, "File Not Found."); } else if (getExtension() == ".exe" || getExtension().contains(".py")) { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); out.write((runCommand(filePath)).getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } else { System.out.println(getExtension()); makeHeader(200, file.length(), new Date(file.lastModified()).toString(), TYPES.get(getExtension()).toString()); } System.out.println(file); } Code Sample 2: public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
11
Code Sample 1: private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file " + file + " (type: " + type + ")"); } try { File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); int result = preprocess(reader, writer, ebms, eems, ims, efms); reader.close(); writer.close(); switch(result) { case OVERWRITE: if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file " + target + " with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File " + preprocFile.getName() + " modified."); } modifiedCnt++; break; case REMOVE: if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file " + target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } if (verbose) { System.out.println("File " + preprocFile.getName() + " removed."); } removedCnt++; break; case KEEP: if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file " + preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } Code Sample 2: private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); }
00
Code Sample 1: public void putChunk(String chunk) throws JacsonException { try { URL url = new URL(chunk); InputStream is = url.openStream(); if (inverse) drain.putChunk(chunk); is.close(); } catch (IOException broken) { if (!inverse) drain.putChunk(chunk); } } Code Sample 2: public static GenericDocumentTransformer<? extends GenericDocument> getTranformer(URL url) throws IOException { setDefaultImplementation(); if ("text/xml".equals(url.openConnection().getContentType()) || "application/xml".equals(url.openConnection().getContentType())) { return null; } else if ("text/html".equals(url.openConnection().getContentType())) { return null; } return null; }
00
Code Sample 1: private void storeFieldMap(Content c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (java.util.Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } } Code Sample 2: private void addEMInformation() { try { long emDate = System.currentTimeMillis(); if (_local == true) { File emFile = new File("emprotz.dat"); if (!emFile.exists()) { return; } emDate = emFile.lastModified(); } if (emDate > this._emFileDate) { this._emFileDate = emDate; this._emDate = emDate; for (int ii = 0; ii < this._projectInfo.size(); ii++) { Information info = getInfo(ii); if (info != null) { info._emDeadline = null; info._emFrames = null; info._emValue = null; } } Reader reader = null; if (_local == true) { reader = new FileReader("emprotz.dat"); } else { StringBuffer urlName = new StringBuffer(); urlName.append("http://home.comcast.net/"); urlName.append("~wxdude1/emsite/download/"); urlName.append("emprotz.zip"); try { URL url = new URL(urlName.toString()); InputStream stream = url.openStream(); ZipInputStream zip = new ZipInputStream(stream); zip.getNextEntry(); reader = new InputStreamReader(zip); } catch (MalformedURLException mue) { mue.printStackTrace(); } } BufferedReader file = new BufferedReader(reader); try { String line1 = null; int count = 0; while ((line1 = file.readLine()) != null) { String line2 = (line1 != null) ? file.readLine() : null; String line3 = (line2 != null) ? file.readLine() : null; String line4 = (line3 != null) ? file.readLine() : null; count++; if ((count > 1) && (line1 != null) && (line2 != null) && (line3 != null) && (line4 != null)) { if (line1.length() > 2) { int posBegin = line1.indexOf("\"", 0); int posEnd = line1.indexOf("\"", posBegin + 1); if ((posBegin >= 0) && (posEnd >= 0)) { String project = line1.substring(posBegin + 1, posEnd - posBegin); int projectNum = Integer.parseInt(project); Integer deadline = Integer.valueOf(line2.trim()); Double value = Double.valueOf(line3.trim()); Integer frames = Integer.valueOf(line4.trim()); Information info = getInfo(projectNum); if (info == null) { info = createInfo(projectNum); } if (info._emValue == null) { info._emDeadline = deadline; info._emFrames = frames; info._emValue = value; } } } } } } catch (Exception e) { e.printStackTrace(); } finally { file.close(); } } } catch (FileNotFoundException e) { } catch (IOException e) { } }
00
Code Sample 1: public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } } Code Sample 2: public synchronized DASMetaData fillInDASMetaData(URL url) throws DASException { try { con = (HttpURLConnection) url.openConnection(); dasRespVersion = con.getHeaderField("X-DAS-Version"); dasSchema = con.getHeaderField("X-DAS-SchemaName"); dasSchemaVersion = con.getHeaderField("X-DAS-SchemaVersion"); String dasStatusString = con.getHeaderField("X-DAS-Status"); if (dasStatusString == null) { throw new DASException("Temporary DAS Error"); } if (dasStatusString.indexOf(" ") != -1) { dasStatusString = dasStatusString.substring(0, dasStatusString.indexOf(" ")); } dasStatus = Integer.parseInt(dasStatusString); if (dasStatus != 200) { throw new DASException("Command cannot be executed: Error was " + Integer.toString(dasStatus)); } } catch (IOException e) { throw new DASException("Cannot connect to data source"); } if (dasSchema != null && dasSchemaVersion != null) { headers.put("X-DAS-Version", dasRespVersion); headers.put("X-DAS-SchemaName", dasSchema); headers.put("X-DAS-SchemaVersion", dasSchemaVersion); dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); theMetaData = new DASMetaDataImpl(dasVersion, Float.parseFloat(dasSchemaVersion), dasSchema); } else { dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); headers.put("X-DAS-Version", dasRespVersion); theMetaData = new DASMetaDataImpl(dasVersion); } String lengthStr = con.getHeaderField("content-length"); if (lengthStr != null) headers.put("content-length", lengthStr); theMetaData.setDASHeaders(headers); return theMetaData; }
11
Code Sample 1: @Override public LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; } Code Sample 2: public static File extract(File source, String filename, File target) { if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null; boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1); try { Map contents = (Map) jarContents.get(source.getPath()); if (contents == null) { contents = new HashMap(); jarContents.put(source.getPath(), contents); ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; contents.put(zipEntry.getName(), zipEntry); } input.close(); } if (isDirectory) { Iterator it = contents.keySet().iterator(); while (it.hasNext()) { String next = (String) it.next(); if (next.startsWith(filename)) { ZipEntry zipEntry = (ZipEntry) contents.get(next); int n = filename.length(); File newTarget = new File(target, zipEntry.getName().substring(n)); extract(source, next, newTarget); } } return target; } ZipEntry entry = (ZipEntry) contents.get(filename); ZipFile input = new ZipFile(source); InputStream in = input.getInputStream(entry); target.getParentFile().mkdirs(); int bytesRead; byte[] buffer = new byte[1024]; FileOutputStream output = new FileOutputStream(target); while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.close(); return target; } catch (Exception ex) { ex.printStackTrace(); } return null; }
00
Code Sample 1: private void storeConfigurationPropertiesFile(java.net.URL url, String comp) { java.util.Properties p; try { p = new java.util.Properties(); p.load(url.openStream()); } catch (java.io.IOException ie) { System.err.println("error opening: " + url.getPath() + ": " + ie.getMessage()); return; } storeConfiguration(p, comp); return; } Code Sample 2: @Override public void create(DisciplinaDTO disciplina) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "insert into Disciplina select nextval('sq_Disciplina') as id, ? as nome"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setString(1, disciplina.getNome()); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de inserir dados de Disciplina no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } }
11
Code Sample 1: public static int gunzipFile(File file_input, File dir_output) { GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } String file_input_name = file_input.getName(); String file_output_name = file_input_name.substring(0, file_input_name.length() - 3); File output_file = new File(dir_output, file_output_name); byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = gzip_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; } try { gzip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public static Image load(final InputStream input, String format, Point dimension) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); dotOutput.delete(); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); ImageLoader loader = new ImageLoader(); ImageData[] imageData = loader.load(dotOutput.getAbsolutePath()); return new Image(Display.getDefault(), imageData[0]); } } catch (SWTException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
00
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out, null); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } Code Sample 2: public List<BoardObject> favBoard() throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_FAV); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response) && HTTPUtil.isXmlContentType(response)) { Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parseFavBoardList(doc); } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
00
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: protected ResourceManager(URL url, String s) { try { properties.load(url.openStream()); path = s; } catch (Exception e) { throw new Error(e.getMessage() + ": trying to load url \"" + url + "\"", e); } }
11
Code Sample 1: boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; } 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 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: public static Search Search(String searchString) throws Exception { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.authority("www.goodreads.com"); builder.path("search/search"); builder.appendQueryParameter("format", "xml"); builder.appendQueryParameter("key", _ConsumerKey); builder.appendQueryParameter("q", searchString); HttpClient httpClient = new DefaultHttpClient(); HttpGet getSearchResponse = new HttpGet(builder.build().toString()); HttpResponse searchResponse = httpClient.execute(getSearchResponse); Response searchResponseData = ResponseParser.parse(searchResponse.getEntity().getContent()); return searchResponseData.get_Search(); }
00
Code Sample 1: public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } Code Sample 2: public static BufferedReader getUserInfoStream(String name) throws IOException { BufferedReader in; try { URL url = new URL("http://www.spoj.pl/users/" + name.toLowerCase() + "/"); in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException e) { in = null; throw e; } return in; }
11
Code Sample 1: private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.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(); }
00
Code Sample 1: private List<String> getHashesFrom(String webPage) { Vector<String> out = new Vector(); try { URL url = new URL(webPage); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = r.readLine()) != null) { out.add(line); } } catch (Exception X) { return null; } return out; } Code Sample 2: public static <T extends Comparable<T>> void BubbleSortComparable2(T[] 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].compareTo(num[j + 1]) > 0) { T temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
11
Code Sample 1: public static boolean copyFile(final File src, final File dst) throws FileNotFoundException { if (src == null || dst == null || src.equals(dst)) { return false; } boolean result = false; if (src.exists()) { if (dst.exists() && !dst.canWrite()) { return false; } final FileInputStream srcStream = new FileInputStream(src); final FileOutputStream dstStream = new FileOutputStream(dst); final FileChannel srcChannel = srcStream.getChannel(); final FileChannel dstChannel = dstStream.getChannel(); FileLock dstLock = null; FileLock srcLock = null; try { srcLock = srcChannel.tryLock(0, Long.MAX_VALUE, true); dstLock = dstChannel.tryLock(); if (srcLock != null && dstLock != null) { int maxCount = 64 * 1024 * 1024 - 32 * 1024; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, maxCount, dstChannel); } } } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } finally { if (srcChannel != null) { try { if (srcLock != null) { srcLock.release(); } srcChannel.close(); srcStream.close(); } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } if (dstChannel != null) { try { if (dstLock != null) { dstLock.release(); } dstChannel.close(); dstStream.close(); result = true; } catch (IOException ex) { Logger.getLogger(FileUtils.class.getName()).log(Level.SEVERE, null, ex); } } } } return result; } Code Sample 2: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("summarysort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("summarysort :: INPATH not given."); return 3; } final String outS = (String) parser.getOptionValue(outputDirOpt); final Path wrkDir = new Path(args.get(0)), in = new Path(args.get(1)), out = outS == null ? null : new Path(outS); final boolean verbose = parser.getBoolean(verboseOpt); final Configuration conf = getConf(); final Timer t = new Timer(); try { @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = sortOne(conf, in, wrkDir, "summarysort", ""); System.out.printf("summarysort :: Waiting for job completion...\n"); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("summarysort :: Job failed."); return 4; } System.out.printf("summarysort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("summarysort :: Merging output..."); t.start(); final FileSystem srcFS = wrkDir.getFileSystem(conf); final FileSystem dstFS = out.getFileSystem(conf); final OutputStream outs = dstFS.create(out); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, in.getName() + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("summarysort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarysort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Output merging failed: %s\n", e); return 5; } return 0; } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
11
Code Sample 1: public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); } Code Sample 2: private void copyResources(File oggDecDir, String[] resources, String resPrefix) throws FileNotFoundException, IOException { for (int i = 0; i < resources.length; i++) { String res = resPrefix + resources[i]; InputStream is = this.getClass().getResourceAsStream(res); if (is == null) throw new IllegalArgumentException("cannot find resource '" + res + "'"); File file = new File(oggDecDir, resources[i]); if (!file.exists() || file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copyStreams(is, fos); } finally { fos.close(); } } } }
11
Code Sample 1: public static String cryptSha(String target) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(target.getBytes("UTF-16")); BigInteger res = new BigInteger(1, md.digest(key.getBytes())); return res.toString(16); } Code Sample 2: public static String generateNonce(boolean is32) { Random random = new Random(); String result = String.valueOf(random.nextInt(9876599) + 123400); if (is32) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(result.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; }
00
Code Sample 1: @Override public String toString() { if (byteArrayOutputStream == null) return "<Unparsed binary data: Content-Type=" + getHeader("Content-Type") + " >"; String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } } Code Sample 2: public long saveDB(Connection con, long id, boolean commit) throws SQLException { StringBuffer SQL = null; Statement statement = null; ResultSet result_set = null; try { statement = con.createStatement(); if (id < 0) { id = QueryUtils.sequenceGetNextID(con, "PATTERN_OUTLINE"); } else { deleteDB(con, id); } SQL = new StringBuffer("insert into "); SQL.append("PATTERN_OUTLINE values ("); SQL.append(id); SQL.append(","); SQL.append(XColor.toInt(pattern.getPatternColor())); SQL.append(","); SQL.append(pattern.getPatternStyle()); SQL.append(","); SQL.append(pattern.getPatternDensity()); SQL.append(","); SQL.append(XColor.toInt(pattern.getBackgroundColor())); SQL.append(","); SQL.append(XColor.toInt(outline.getColor())); SQL.append(","); SQL.append(outline.getStyle()); SQL.append(","); SQL.append(outline.getWidth()); SQL.append(")"); statement.executeUpdate(new String(SQL)); SQL = null; if (commit) { con.commit(); } } catch (SQLException e) { System.err.println(getClass().getName() + ":" + e + " SQL:=" + SQL); if (commit) { con.rollback(); } throw e; } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { } } } return saveDB(con, id, false); }
00
Code Sample 1: private void copyLocalFile(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 Set<Municipality> getMunicipios(String pURL) { Set<Municipality> result = new HashSet<Municipality>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniMun = "<muni>"; String finMun = "</muni>"; String iniNomMun = "<nm>"; String finNomMun = "</nm>"; String iniCarto = "<carto>"; String iniCodDelMEH = "<cd>"; String finCodDelMEH = "</cd>"; String iniCodMunMEH = "<cmc>"; String finCodMunMEH = "</cmc>"; String iniCodProvINE = "<cp>"; String finCodProvINE = "</cp>"; String iniCodMunINE = "<cm>"; String finCodMunINE = "</cm>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Municipality municipio; 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(iniMun)) { municipio = new Municipality(); municipio.setCodemunicipalityine(0); municipio.setCodemunicipalitydgc(0); while ((str = br.readLine()) != null && !str.contains(finMun)) { if (str.contains(iniNomMun)) { ini = str.indexOf(iniNomMun) + iniNomMun.length(); fin = str.indexOf(finNomMun); municipio.setMuniName(str.substring(ini, fin).trim()); } if (str.contains(iniCarto)) { if (str.contains("URBANA")) municipio.setIsurban(true); if (str.contains("RUSTICA")) municipio.setIsrustic(true); } if (str.contains(iniCodDelMEH)) { ini = str.indexOf(iniCodDelMEH) + iniCodDelMEH.length(); fin = str.indexOf(finCodDelMEH); municipio.setCodemunicipalitydgc(municipio.getCodemunicipalitydgc() + Integer.parseInt(str.substring(ini, fin)) * 1000); } if (str.contains(iniCodMunMEH)) { ini = str.indexOf(iniCodMunMEH) + iniCodMunMEH.length(); fin = str.indexOf(finCodMunMEH); municipio.setCodemunicipalitydgc(municipio.getCodemunicipalitydgc() + Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniCodProvINE)) { ini = str.indexOf(iniCodProvINE) + iniCodProvINE.length(); fin = str.indexOf(finCodProvINE); municipio.setCodemunicipalityine(municipio.getCodemunicipalityine() + Integer.parseInt(str.substring(ini, fin)) * 1000); } if (str.contains(iniCodMunINE)) { ini = str.indexOf(iniCodMunINE) + iniCodMunINE.length(); fin = str.indexOf(finCodMunINE); municipio.setCodemunicipalityine(municipio.getCodemunicipalityine() + Integer.parseInt(str.substring(ini, fin))); } municipio.setDescription(); } result.add(municipio); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
11
Code Sample 1: public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } } Code Sample 2: public void command() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(dir)); int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { filename = chooser.getSelectedFile().getAbsolutePath(); String f2 = ""; for (int i = 0; i < filename.length(); ++i) { if (filename.charAt(i) != '\\') { f2 = f2 + filename.charAt(i); } else f2 = f2 + '/'; } filename = f2; if (filename.contains(dir)) { filename = filename.substring(dir.length()); } else { try { FileChannel srcFile = new FileInputStream(filename).getChannel(); FileChannel dstFile; filename = "ueditor_files/" + chooser.getSelectedFile().getName(); File newFile; if (!(newFile = new File(dir + filename)).createNewFile()) { dstFile = new FileInputStream(dir + filename).getChannel(); newFile = null; } else { dstFile = new FileOutputStream(newFile).getChannel(); } dstFile.transferFrom(srcFile, 0, srcFile.size()); srcFile.close(); dstFile.close(); System.out.println("file copyed to: " + dir + filename); } catch (Exception e) { e.printStackTrace(); label.setIcon(InputText.iconX); filename = null; for (Group g : groups) { g.updateValidity(true); } return; } } label.setIcon(InputText.iconV); for (Group g : groups) { g.updateValidity(true); } } }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { Vector vret = this.uniformtitlepanel.getEnteredValuesKeys(); String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveUniformTitleSH("2", vret, patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "UniformTitleSubjectHeadingServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } Code Sample 2: public static String encrypt(String algorithm, String str) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(str.getBytes()); StringBuffer sb = new StringBuffer(); byte[] bytes = md.digest(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception e) { return ""; } }
00
Code Sample 1: public final String hashPassword(final String password) { try { if (salt == null) { salt = new byte[16]; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(System.currentTimeMillis()); sr.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] hash = md.digest(); for (int i = 0; i < (1999); i++) { md.reset(); hash = md.digest(hash); } return byteToString(hash, 60); } catch (Exception exception) { log.error(exception); return null; } } Code Sample 2: private void invokeTest(String queryfile, String target) { try { String query = IOUtils.toString(XPathMarkBenchmarkTest.class.getResourceAsStream(queryfile)).trim(); String args = EXEC_CMD + " \"" + query + "\" \"" + target + '"'; System.out.println("Invoke command: \n " + args); Process proc = Runtime.getRuntime().exec(args, null, benchmarkDir); InputStream is = proc.getInputStream(); File outFile = new File(outDir, queryfile + ".result"); IOUtils.copy(is, new FileOutputStream(outFile)); is.close(); int ret = proc.waitFor(); if (ret != 0) { System.out.println("process exited with value : " + ret); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (InterruptedException irre) { throw new IllegalStateException(irre); } }
11
Code Sample 1: private void copyTemplate(String resource, OutputStream outputStream) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); } Code Sample 2: public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; }
11
Code Sample 1: public static String generateMD5(String str) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { logger.log(Level.SEVERE, null, nsae); } return hashword; } Code Sample 2: protected String encrypt(String text) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: public void copyFilesIntoProject(HashMap<String, String> files) { Set<String> filenames = files.keySet(); for (String key : filenames) { String realPath = files.get(key); if (key.equals("fw4ex.xml")) { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + bundle.getString("Stem") + STEM_FILE_EXETENSION)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } else { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + key)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } } } Code Sample 2: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: @SuppressWarnings("deprecation") public static final ReturnCode runCommand(IOBundle io, String[] args) { if ((args.length < 3) || (args.length > 4)) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 3) && (!args[1].equals("show"))) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 4) && (!(args[2].equals("training") || args[2].equals("log") || args[2].equals("configuration")))) return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Access denied to directory: " + args[2]); if (args[1].equals("open")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); io.println(fileName); io.println(file.length() + " bytes"); while (dis.available() != 0) { io.println(dis.readLine()); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_NOT_FOUND, "File " + fileName + " doesn't exist"); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error reading File " + fileName); } } else if (args[1].equals("save")) { final String fileName = args[2] + "/" + args[3]; String line; try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); line = io.readLine(); int count = Integer.parseInt(line.trim()); while (count > 0) { out.write(io.read()); count = count - 1; } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error writing File " + fileName); } } else if (args[1].equals("delete")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); if (!file.exists()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such file or directory: " + fileName); if (!file.canWrite()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "File is write-protected: " + fileName); if (file.isDirectory()) { String[] files = file.list(); if (files.length > 0) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Directory is not empty: " + fileName); } if (!file.delete()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Deletion failed: " + fileName); } else if (args[1].equals("show")) { File directory = new File(args[2]); String[] files; if ((!directory.isDirectory()) || (!directory.exists())) { return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such directory: " + directory); } int count = 0; files = directory.list(); io.println("Files in directory \"" + directory + "\":"); for (int i = 0; i < files.length; i++) { directory = new File(files[i]); if (!directory.isDirectory()) { count++; io.println(" " + files[i]); } } io.println("Total " + count + " files"); } else return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Unrecognized command"); return ReturnCode.makeReturnCode(ReturnCode.RET_OK); } Code Sample 2: public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
11
Code Sample 1: private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); } Code Sample 2: public ServiceAdapterIfc deploy(String session, String name, byte jarBytes[], String jarName, String serviceClass, String serviceInterface) throws RemoteException, MalformedURLException, StartServiceException, SessionException { try { File jarFile = new File(jarName); jarName = jarFile.getName(); String jarName2 = jarName; jarFile = new File(jarName2); int n = 0; while (jarFile.exists()) { jarName2 = jarName + n++; jarFile = new File(jarName2); } FileOutputStream fos = new FileOutputStream(jarName2); IOUtils.copy(new ByteArrayInputStream(jarBytes), fos); SCClassLoader cl = new SCClassLoader(new URL[] { new URL("file://" + jarFile.getAbsolutePath()) }, getMasterNode().getSCClassLoaderCounter()); return startService(session, name, serviceClass, serviceInterface, cl); } catch (SessionException e) { throw e; } catch (Exception e) { throw new StartServiceException("Could not deploy service: " + e.getMessage(), e); } }
00
Code Sample 1: public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); } Code Sample 2: public final Matrix2D<E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { MatrixIOUtils.closeQuietly(inputStream); } }
11
Code Sample 1: private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } Code Sample 2: public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.out.println("test"); URL url = new URL(addr); System.out.println("test2"); IOUtils.copy(url.openStream(), output); return output.toString(); }
11
Code Sample 1: public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } } Code Sample 2: @SuppressWarnings("unchecked") public static void unzip(String input, String output) { try { if (!output.endsWith("/")) output = output + "/"; ZipFile zip = new ZipFile(input); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { FileUtils.forceMkdir(new File(output + entry.getName())); } else { FileOutputStream out = new FileOutputStream(output + entry.getName()); IOUtils.copy(zip.getInputStream(entry), out); IOUtils.closeQuietly(out); } } } catch (Exception e) { log.error("�����ҵ��ļ�:" + output, e); throw new RuntimeException("�����ҵ��ļ�:" + output, e); } }
00
Code Sample 1: public List<String[]> getCSV(String name) { return new ResourceLoader<List<String[]>>(name) { @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } } }.get(); } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; }
00
Code Sample 1: 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!"); } Code Sample 2: @SuppressWarnings("unchecked") protected void initializeGraphicalViewer() { GraphicalViewer viewer = getGraphicalViewer(); ScalableRootEditPart rootEditPart = new ScalableRootEditPart(); viewer.setEditPartFactory(new DBEditPartFactory()); viewer.setRootEditPart(rootEditPart); ZoomManager manager = rootEditPart.getZoomManager(); double[] zoomLevels = new double[] { 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 20.0 }; manager.setZoomLevels(zoomLevels); List<String> zoomContributions = new ArrayList<String>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); manager.setZoomLevelContributions(zoomContributions); getActionRegistry().registerAction(new ZoomInAction(manager)); getActionRegistry().registerAction(new ZoomOutAction(manager)); PrintAction printAction = new PrintAction(this); printAction.setText(DBPlugin.getResourceString("action.print")); printAction.setImageDescriptor(DBPlugin.getImageDescriptor("icons/print.gif")); getActionRegistry().registerAction(printAction); IFile file = ((IFileEditorInput) getEditorInput()).getFile(); RootModel root = null; try { root = VisualDBSerializer.deserialize(file.getContents()); } catch (Exception ex) { DBPlugin.logException(ex); root = new RootModel(); root.setDialectName(DialectProvider.getDialectNames()[0]); } viewer.setContents(root); final DeleteAction deleteAction = new DeleteAction((IWorkbenchPart) this); deleteAction.setSelectionProvider(getGraphicalViewer()); getActionRegistry().registerAction(deleteAction); getGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { deleteAction.update(); } }); MenuManager menuMgr = new MenuManager(); menuMgr.add(new QuickOutlineAction()); menuMgr.add(new Separator()); menuMgr.add(getActionRegistry().getAction(ActionFactory.UNDO.getId())); menuMgr.add(getActionRegistry().getAction(ActionFactory.REDO.getId())); menuMgr.add(new Separator()); PasteAction pasteAction = new PasteAction(this); getActionRegistry().registerAction(pasteAction); getSelectionActions().add(pasteAction.getId()); menuMgr.add(pasteAction); CopyAction copyAction = new CopyAction(this, pasteAction); getActionRegistry().registerAction(copyAction); getSelectionActions().add(copyAction.getId()); menuMgr.add(copyAction); menuMgr.add(getActionRegistry().getAction(ActionFactory.DELETE.getId())); menuMgr.add(new Separator()); menuMgr.add(new AutoLayoutAction(viewer)); menuMgr.add(new DommainEditAction(viewer)); MenuManager convertMenu = new MenuManager(DBPlugin.getResourceString("action.convert")); menuMgr.add(convertMenu); UppercaseAction uppercaseAction = new UppercaseAction(this); convertMenu.add(uppercaseAction); getActionRegistry().registerAction(uppercaseAction); getSelectionActions().add(uppercaseAction.getId()); LowercaseAction lowercaseAction = new LowercaseAction(this); convertMenu.add(lowercaseAction); getActionRegistry().registerAction(lowercaseAction); getSelectionActions().add(lowercaseAction.getId()); Physical2LogicalAction physical2logicalAction = new Physical2LogicalAction(this); convertMenu.add(physical2logicalAction); getActionRegistry().registerAction(physical2logicalAction); getSelectionActions().add(physical2logicalAction.getId()); Logical2PhysicalAction logical2physicalAction = new Logical2PhysicalAction(this); convertMenu.add(logical2physicalAction); getActionRegistry().registerAction(logical2physicalAction); getSelectionActions().add(logical2physicalAction.getId()); menuMgr.add(new ToggleModelAction(viewer)); menuMgr.add(new ChangeDBTypeAction(viewer)); menuMgr.add(new Separator()); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_IN)); menuMgr.add(getActionRegistry().getAction(GEFActionConstants.ZOOM_OUT)); menuMgr.add(new Separator()); menuMgr.add(new CopyAsImageAction(viewer)); menuMgr.add(getActionRegistry().getAction(ActionFactory.PRINT.getId())); menuMgr.add(new Separator()); MenuManager validation = new MenuManager(DBPlugin.getResourceString("action.validation")); validation.add(new ValidateAction(viewer)); validation.add(new DeleteMarkerAction(viewer)); menuMgr.add(validation); MenuManager importMenu = new MenuManager(DBPlugin.getResourceString("action.import")); importMenu.add(new ImportFromJDBCAction(viewer)); importMenu.add(new ImportFromDiagramAction(viewer)); menuMgr.add(importMenu); MenuManager generate = new MenuManager(DBPlugin.getResourceString("action.export")); IGenerator[] generaters = GeneratorProvider.getGeneraters(); for (int i = 0; i < generaters.length; i++) { generate.add(new GenerateAction(generaters[i], viewer, this)); } menuMgr.add(generate); menuMgr.add(new SelectedTablesDDLAction(viewer)); viewer.setContextMenu(menuMgr); viewer.getControl().addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent e) { IStructuredSelection selection = (IStructuredSelection) getGraphicalViewer().getSelection(); Object obj = selection.getFirstElement(); if (obj != null && obj instanceof IDoubleClickSupport) { ((IDoubleClickSupport) obj).doubleClicked(); } } }); outlinePage = new VisualDBOutlinePage(viewer, getEditDomain(), root, getSelectionSynchronizer()); applyPreferences(); viewer.getControl().addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.stateMask == SWT.CTRL && e.keyCode == 'o') { new QuickOutlineAction().run(); } } }); }
00
Code Sample 1: public TapdocContextImpl(Registry registry, FileObject javaDom, List<String> javadocLinks, List<String> libraryLocations, FileObject outputDirectory, List<String> tapdocLinks, DocumentGenerator documentGenerator) { this.registry = registry; this.documentGenerator = documentGenerator; try { if (javaDom == null) { javaDom = outputDirectory.resolveFile("tapdoc-javadom.xml"); } if (!javaDom.exists()) { javaDom.createFile(); javaDom.close(); IOUtils.copy(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><tapdoc-javadom></tapdoc-javadom>"), javaDom.getContent().getOutputStream()); } this.javaDom = javaDom; this.javadocLinks = javadocLinks; this.tapdocLinks = tapdocLinks; this.libraryLocations = libraryLocations; this.outputDirectory = outputDirectory; } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public Resource get(URL serviceUrl, String resourceId) throws Exception { Resource resource = new Resource(); String openurl = serviceUrl.toString() + "?url_ver=Z39.88-2004" + "&rft_id=" + URLEncoder.encode(resourceId, "UTF-8") + "&svc_id=" + SVCID_ADORE4; log.debug("OpenURL Request: " + openurl); URL url; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { InputStream is = huc.getInputStream(); resource.setBytes(StreamUtil.getByteArray(is)); resource.setContentType(huc.getContentType()); } else { log.error("An error of type " + code + " occurred for " + url.toString()); throw new Exception("Cannot get " + url.toString()); } } catch (MalformedURLException e) { throw new Exception("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new Exception("An IOException occurred attempting to connect to " + openurl); } return resource; }
00
Code Sample 1: @Override public void remove(int disciplinaId) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "delete from Disciplina where id = ?"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setInt(1, disciplinaId); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de Revendedor no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } } Code Sample 2: public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
00
Code Sample 1: public boolean checkLogin(String pMail, String pMdp) { boolean vLoginOk = false; if (pMail == null || pMdp == null) { throw new IllegalArgumentException("Login and password are mandatory. Null values are forbidden."); } try { Criteria crit = ((Session) this.entityManager.getDelegate()).createCriteria(Client.class); crit.add(Restrictions.ilike("email", pMail)); MessageDigest vMd5Instance; try { vMd5Instance = MessageDigest.getInstance("MD5"); vMd5Instance.reset(); vMd5Instance.update(pMdp.getBytes()); byte[] vDigest = vMd5Instance.digest(); BigInteger vBigInt = new BigInteger(1, vDigest); String vHashPassword = vBigInt.toString(16); crit.add(Restrictions.eq("mdp", vHashPassword)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } Client pClient = (Client) crit.uniqueResult(); vLoginOk = (pClient != null); } catch (DataAccessException e) { mLogger.error("Exception - DataAccessException occurs : {} on complete checkLogin( {}, {} )", new Object[] { e.getMessage(), pMail, pMdp }); } return vLoginOk; } Code Sample 2: @SuppressWarnings("unchecked") public void handle(Map<String, Object> data, String urlPath) { try { URL url = new URL(urlPath); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; CMGroup currentGroup = null; List<CMGroup> groups = (List<CMGroup>) data.get(CMConstants.GROUP); List<CMTag> tags = (List<CMTag>) data.get(CMConstants.TAG); List<CMTagGroup> tagGroups = (List<CMTagGroup>) data.get(CMConstants.TAG_GROUP); while ((line = reader.readLine()) != null) { CMGroup group = null; try { group = FetchUtil.getCMGroup(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMGroup error:" + line); } if (group != null) { if (currentGroup != null) { groups.add(currentGroup); } currentGroup = group; } CMTag tag = null; try { tag = FetchUtil.getCMTag(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMTag error:" + line); } if (tag != null) { CMTagGroup tagGroup = new CMTagGroup(); tagGroup.setGroupName(currentGroup.getName()); tagGroup.setTagName(tag.getName()); tags.add(tag); tagGroups.add(tagGroup); } } groups.add(currentGroup); reader.close(); } catch (MalformedURLException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } catch (IOException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } }
00
Code Sample 1: public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException { InputStream input = null; BufferedOutputStream bos = null; File tempUnit = null; try { URL url = null; int total = 0; try { url = new URL(urlStr); input = url.openStream(); URLConnection urlConnection; urlConnection = url.openConnection(); total = urlConnection.getContentLength(); } catch (IOException e) { throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e); } String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1); tempUnit = null; try { if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit"); File parent = tempUnit.getParentFile(); FileUtils.forceMkdir(parent); if (!tempUnit.exists()) FileUtils.touch(tempUnit); bos = new BufferedOutputStream(new FileOutputStream(tempUnit)); } catch (FileNotFoundException e) { throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (IOException e) { throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (DeployToolException e) { throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e); } logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr)); int size = -1; try { size = IOUtils.copy(input, bos); bos.flush(); } catch (IOException e) { logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit)); } if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr)); } finally { if (input != null) IOUtils.closeQuietly(input); if (bos != null) IOUtils.closeQuietly(bos); } logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath())); return tempUnit.getAbsolutePath(); } Code Sample 2: @Override public int run() { Enumeration<?> e; try { e = About.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { final URL url = (URL) e.nextElement(); if (url.toString().indexOf("renaissance") != -1) { final InputStream is = url.openStream(); Properties p = new Properties(); p.load(is); for (Entry<?, ?> entry : p.entrySet()) { System.err.println(entry); } } } } catch (IOException e1) { logger.fatal("Caught an exception " + e1); return 1; } System.err.println("Classpath is " + System.getProperty("java.class.path")); return 0; }
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: private static void copy(File source, File target) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: public static Image getPluginImage(final Object plugin, final String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } 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 void downloadPage(final URL url, final File file) { try { long size = 0; final byte[] buffer = new byte[BotUtil.BUFFER_SIZE]; final File tempFile = new File(file.getParentFile(), "temp.tmp"); int length; int lastUpdate = 0; FileOutputStream fos = new FileOutputStream(tempFile); final InputStream is = url.openStream(); do { length = is.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Downloading... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); if (url.toString().toLowerCase().endsWith(".gz")) { final FileInputStream fis = new FileInputStream(tempFile); final GZIPInputStream gis = new GZIPInputStream(fis); fos = new FileOutputStream(file); size = 0; lastUpdate = 0; do { length = gis.read(buffer); if (length >= 0) { fos.write(buffer, 0, length); size += length; } if (lastUpdate > UPDATE_TIME) { report(0, (int) (size / Format.MEMORY_MEG), "Uncompressing... " + Format.formatMemory(size)); lastUpdate = 0; } lastUpdate++; } while (length >= 0); fos.close(); fis.close(); gis.close(); tempFile.delete(); } else { file.delete(); tempFile.renameTo(file); } } catch (final IOException e) { throw new AnalystError(e); } } Code Sample 2: private Element getXmlFromGeoNetwork(String urlIn, Session userSession) throws FailedActionException { Element results = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); String cookie = (String) userSession.getAttribute("usercookie.object"); if (cookie != null) conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); } finally { in.close(); } } catch (Exception e) { throw new FailedActionException(FailedActionReason.SYSTEM_ERROR); } return results; }
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: protected static void clearTables() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } }
11
Code Sample 1: public static String hexSHA1(String value) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); md.update(value.getBytes("utf-8")); byte[] digest = md.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } } Code Sample 2: @Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtils.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, compareResponse.getMessage(), compareResponse.getControls()); }
11
Code Sample 1: private void copyImage(ProjectElement e) throws Exception { String fn = e.getName(); if (!fn.toLowerCase().endsWith(".png")) { if (fn.contains(".")) { fn = fn.substring(0, fn.lastIndexOf('.')) + ".png"; } else { fn += ".png"; } } File img = new File(resFolder, fn); File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib"); boolean copy = true; if (img.exists() && config.containsKey(img.getName())) { long modified = Long.parseLong(config.get(img.getName())); if (modified >= img.lastModified()) { copy = false; } } if (copy) { convertImage(e.getFile(), img); config.put(img.getName(), String.valueOf(img.lastModified())); } DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(img)); int read; while ((read = in.read()) != -1) { out.write(read); } out.close(); in.close(); imageFiles.add(imgz); imageNames.put(imgz, e.getName()); } Code Sample 2: private void preprocessImages(GeoImage[] detailedImages) throws IOException { for (int i = 0; i < detailedImages.length; i++) { BufferedImage img = loadImage(detailedImages[i].getPath()); detailedImages[i].setLatDim(img.getHeight()); detailedImages[i].setLonDim(img.getWidth()); freeImage(img); String fileName = detailedImages[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("filename " + tmp); File worldFile = new File(tmp); if (!worldFile.exists()) { System.out.println("Rez: Could not find file: " + tmp); debug("Rez: Could not find directory: " + tmp); throw new IOException("File not Found"); } BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLonSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLonExtent(detailedImages[i].getLonSpacing() * ((double) detailedImages[i].getLonDim() - 1d)); System.out.println("setLonExtent " + detailedImages[i].getLonExtent()); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLatSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLatExtent(detailedImages[i].getLatSpacing() * ((double) detailedImages[i].getLatDim() - 1d)); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); detailedImages[i].setPath(tmp); DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } else { System.out.println("Rez: ERROR: World file for image is null"); } } }
11
Code Sample 1: @Override public void writeTo(final TrackRepresentation t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws WebApplicationException { if (mediaType.isCompatible(MediaType.APPLICATION_OCTET_STREAM_TYPE)) { InputStream is = null; try { httpHeaders.add("Content-Type", "audio/mp3"); IOUtils.copy(is = t.getInputStream(mediaType), entityStream); } catch (final IOException e) { LOG.warn("IOException : maybe remote client has disconnected"); } finally { IOUtils.closeQuietly(is); } } } Code Sample 2: protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Session session = HibernateUtil.getInstance().getSession(); response.setBufferSize(65536); ServletOutputStream outStream = response.getOutputStream(); File file = null; FileData fileData = null; try { String fileParameter = request.getParameter("file"); String disposition = request.getParameter("disposition"); if (fileParameter == null || fileParameter.equals("")) { String pi = request.getPathInfo(); int lastSlashIndex = pi.lastIndexOf("/") + 1; fileParameter = pi.substring(lastSlashIndex, pi.indexOf("_", pi.lastIndexOf("/"))); } if (fileParameter == null || fileParameter.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.flushBuffer(); Logger.log("file parameter not specified"); return; } if (disposition == null || disposition.equals("")) { String pi = request.getPathInfo(); String filename = pi.substring(pi.lastIndexOf("/") + 1); int underscoreIndex = filename.indexOf("_") + 1; disposition = filename.substring(underscoreIndex, filename.indexOf("_", underscoreIndex)); } file = (File) session.load(File.class, new Long(fileParameter)); Logger.log("Content requested=" + file.getName() + ":" + fileParameter + " Referral: " + request.getParameter("referer")); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long fileDate = file.getLastModifiedDate() - (file.getLastModifiedDate() % 1000); if (fileDate <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } response.setContentType(file.getContentType()); response.setHeader("Content-Description", file.getName()); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); response.flushBuffer(); Logger.log("Conditional GET: " + file.getName()); return; } User authUser = baseService.getAuthenticatedUser(session, request, response); if (!SecurityHelper.doesUserHavePermission(session, authUser, file, Permission.PERM.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); Logger.log("Forbidden content requested: " + fileParameter); return; } String contentType = file.getContentType(); response.setContentType(contentType); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } String name = file.getName(); response.setHeader("Content-Description", name); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); java.io.File possibleDataFile = new java.io.File(BaseSystem.getTempDir() + file.getNameOnDisk()); if (possibleDataFile.exists()) { Logger.log("File exists in " + BaseSystem.getTempDir() + " pulling " + possibleDataFile.getName()); FileInputStream fileInputStream = new FileInputStream(possibleDataFile); try { IOUtils.copy(fileInputStream, outStream); } finally { try { fileInputStream.close(); } catch (Throwable t) { } } } else { List<FileData> fileDataList = HibernateUtil.getInstance().executeQuery(session, "from " + FileData.class.getSimpleName() + " where permissibleObject.id = " + file.getId()); if (fileDataList.size() == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); Logger.log("Requested content not found: " + fileParameter); response.flushBuffer(); return; } fileData = (FileData) fileDataList.get(0); FileOutputStream fileOutputStream = null; try { java.io.File tmpDir = new java.io.File(BaseSystem.getTempDir()); tmpDir.mkdirs(); fileOutputStream = new FileOutputStream(possibleDataFile); IOUtils.write(fileData.getData(), fileOutputStream); } catch (Throwable t) { Logger.log(t); } finally { try { fileOutputStream.close(); } catch (Throwable t) { } } IOUtils.write(fileData.getData(), outStream); } } catch (Throwable t) { Logger.log(t); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.flushBuffer(); } catch (Throwable tt) { } try { response.reset(); response.resetBuffer(); } catch (Throwable tt) { } } finally { file = null; fileData = null; try { outStream.flush(); } catch (Throwable t) { } try { outStream.close(); } catch (Throwable t) { } try { session.close(); } catch (Throwable t) { } } }
11
Code Sample 1: 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!"); } Code Sample 2: @Override @Transactional public FileData store(FileData data, InputStream stream) { try { FileData file = save(data); file.setPath(file.getGroup() + File.separator + file.getId()); file = save(file); File folder = new File(PATH, file.getGroup()); if (!folder.exists()) folder.mkdirs(); File filename = new File(folder, file.getId() + ""); IOUtils.copyLarge(stream, new FileOutputStream(filename)); return file; } catch (IOException e) { throw new ServiceException("storage", e); } }
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: public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); CompressionOutputStream out = codec.createOutputStream(System.out); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); }
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) { logger.error(Logger.SECURITY_FAILURE, "Problem decoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; }
11
Code Sample 1: public RandomGUID() { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage()); } try { long time = System.currentTimeMillis(); long rand = 0; rand = myRand.nextLong(); StringBuffer sb = new StringBuffer(); sb.append(s_id); sb.append(":"); sb.append(Long.toString(time)); sb.append(":"); sb.append(Long.toString(rand)); md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); sb.setLength(0); 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) { throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage()); } } Code Sample 2: private boolean keysMatch(String keyNMinusOne, String keyN) { boolean match = false; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(keyNMinusOne.getBytes()); byte[] hashedBytes = digest.digest(); String encodedHashedKey = new String(com.Ostermiller.util.Base64.encode(hashedBytes)); match = encodedHashedKey.equals(keyN); } catch (NoSuchAlgorithmException e) { } return match; }
11
Code Sample 1: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } Code Sample 2: public static String encrypt(String password, String algorithm, byte[] salt) { StringBuffer buffer = new StringBuffer(); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase(algorithm)) { throw new InternalError("Not implemented"); } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append("{SSHA}"); } else { buffer.append("{SHA}"); } try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append("{SMD5}"); } else { buffer.append("{MD5}"); } try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } int outSize = size; digest.reset(); digest.update(password.getBytes()); if (salt != null && salt.length > 0) { digest.update(salt); outSize += salt.length; } byte[] out = new byte[outSize]; System.arraycopy(digest.digest(), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy(salt, 0, out, size, salt.length); } buffer.append(Base64.encode(out)); return buffer.toString(); }
00
Code Sample 1: private void parseUrl() { URLLexer lexer; URLParser parser; if (this.parent != null) { this.hops = ((HTTPFile) this.parent).hops - 1; } if (this.searchFilter.accept(this.url.getPath())) { if (!visited.contains(this.url.toExternalForm())) { if (this.hops > 0) { try { visited.add(this.url.toExternalForm()); InputStream in = this.url.openStream(); lexer = new URLLexer(this.url.openStream()); parser = new URLParser(lexer); URL[] urls = parser.htmlDocument(this.url); if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Found the following URLs in " + this.url.toExternalForm() + " : " + StringUtil.ArrayToString(urls, 10)); } for (int i = 0; i < urls.length; i++) { this.addInternal(urls[i]); } } catch (IOException e) { if (Debug.debug) { Debug.getInstance().error(e.getMessage()); } } catch (RecognitionException e) { if (Debug.debug) { Debug.getInstance().error("Problems while lexing " + this.url.toExternalForm() + " : " + e.getMessage(), e); } } catch (TokenStreamException e) { if (Debug.debug) { Debug.getInstance().error("Problems while parsing " + this.url.toExternalForm() + " : " + e.getMessage(), e); } } } } else { if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Skipping URL " + this.url.toExternalForm() + " : Maximum depth reached."); } } } else { if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Skipping URL " + this.url.toExternalForm() + " : Already parsed."); } } } Code Sample 2: public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } }
11
Code Sample 1: public void authenticate(final ConnectionHandler ch, final AuthenticationCriteria ac) throws NamingException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(this.passwordScheme); md.update(((String) ac.getCredential()).getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new NamingException(e.getMessage()); } ch.connect(this.config.getBindDn(), this.config.getBindCredential()); NamingEnumeration<SearchResult> en = null; try { en = ch.getLdapContext().search(ac.getDn(), "userPassword={0}", new Object[] { String.format("{%s}%s", this.passwordScheme, LdapUtil.base64Encode(hash)).getBytes() }, LdapConfig.getCompareSearchControls()); if (!en.hasMore()) { throw new AuthenticationException("Compare authentication failed."); } } finally { if (en != null) { en.close(); } } } Code Sample 2: public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); }
11
Code Sample 1: protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } } Code Sample 2: @Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); }
11
Code Sample 1: public static String hash(final String s) { if (s == null || s.length() == 0) return null; try { final MessageDigest hashEngine = MessageDigest.getInstance("SHA-1"); hashEngine.update(s.getBytes("iso-8859-1"), 0, s.length()); return convertToHex(hashEngine.digest()); } catch (final Exception e) { return null; } } Code Sample 2: public static byte[] encode(String origin, String algorithm) throws NoSuchAlgorithmException { String resultStr = null; resultStr = new String(origin); MessageDigest md = MessageDigest.getInstance(algorithm); md.update(resultStr.getBytes()); return md.digest(); }
00
Code Sample 1: public String decrypt(String text, String passphrase, int keylen) { RC2ParameterSpec parm = new RC2ParameterSpec(keylen); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes(getCharset())); SecretKeySpec skeySpec = new SecretKeySpec(md.digest(), "RC2"); Cipher cipher = Cipher.getInstance("RC2/ECB/NOPADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, parm); byte[] dString = Base64.decode(text); byte[] d = cipher.doFinal(dString); String clearTextNew = decodeBytesNew(d); return clearTextNew; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public static String[] check() throws Exception { if (currentVersion == null) throw new Exception(); URL url = new URL(versionURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String str = ""; BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); while (br.ready()) { str = str + br.readLine(); } br.close(); Document document = DocumentHelper.parseText(str); Node node = document.selectSingleNode("//root/version"); String latestVersion = node.valueOf("@id"); Double latest = Double.parseDouble(latestVersion); Double current = Double.parseDouble(currentVersion.substring(0, currentVersion.indexOf("-"))); if (latest > current) { String[] a = { latestVersion, node.valueOf("@url"), node.valueOf("@description") }; return a; } return null; }
11
Code Sample 1: private void chooseGame(DefaultHttpClient httpclient) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(Constants.STRATEGICDOMINATION_URL + "/gameboard.cgi?gameid=" + 1687); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("cg form get: " + response.getStatusLine()); if (entity != null) { InputStream inStream = entity.getContent(); IOUtils.copy(inStream, System.out); } System.out.println("cg set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } Code Sample 2: private void copyFile(String sourceFilename, String targetFilename) throws IOException { File source = new File(sourceFilename); File target = new File(targetFilename); InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target); 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(File file, String destDir) throws IOException { if (!isCanReadFile(file)) throw new RuntimeException("The File can't read:" + file.getPath()); if (!isCanWriteDirectory(destDir)) throw new RuntimeException("The Directory can't write:" + destDir); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(file).getChannel(); dstChannel = new FileOutputStream(destDir + "/" + file.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { throw e; } finally { if (srcChannel != null) try { srcChannel.close(); } catch (IOException e) { } if (dstChannel != null) try { dstChannel.close(); } catch (IOException e) { } } } Code Sample 2: 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, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; }
00
Code Sample 1: public void delete(String remoteFile) { String remotePath = connector.getRemoteDirectory(); remotePath += PATH_SEPARATOR + remoteFile; FTPClient ftp = new FTPClient(); try { String hostname = connector.getUrl().getHost(); ftp.connect(hostname); log.info("Connected to " + hostname); log.info(ftp.getReplyString()); boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword()); if (loggedIn) { ftp.deleteFile(remotePath); ftp.logout(); } ftp.disconnect(); } catch (SocketException e) { log.error("File chmod failed with message: " + e.getMessage()); } catch (IOException e) { log.error("File chmod failed with message: " + e.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } } Code Sample 2: private static TreeViewTreeNode newInstance(String className, String urlString) { try { URL url = new URL(urlString); InputStream is = url.openStream(); XMLDecoder xd = new XMLDecoder(is); Object userObject = xd.readObject(); xd.close(); return newInstance(className, userObject); } catch (Exception e) { Debug.println(e); throw (RuntimeException) new IllegalStateException().initCause(e); } }
00
Code Sample 1: @Override public TDSModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); TDSModel model = loadModel(url.openStream(), skin); if (baseURLWasNull) { popBaseURL(); } return (model); } Code Sample 2: private static void getPatronInfo(HttpClient client) throws Exception { HttpGet httpget = new HttpGet("http://libsys.arlingtonva.us/patroninfo~S1/1079675/items"); HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } EntityUtils.consume(entity); }
11
Code Sample 1: public static String encode(String plaintext) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not encrypt password for ISA db verification"); } } Code Sample 2: public boolean validateLogin(String username, String password) { boolean user_exists = false; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); statement = connect.prepareStatement("SELECT id from toepen.users WHERE username = ? AND password = ?"); statement.setString(1, username); statement.setString(2, password_hash); resultSet = statement.executeQuery(); while (resultSet.next()) { user_exists = true; } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_exists; } }
00
Code Sample 1: public static void putNextJarEntry(JarOutputStream modelStream, String name, File file) throws IOException { JarEntry entry = new JarEntry(name); entry.setSize(file.length()); modelStream.putNextEntry(entry); InputStream fileStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(fileStream, modelStream); fileStream.close(); } Code Sample 2: private void checkSettings() throws ConfigurationException { List serverList = getConfiguration().getServerList(); for (Object aServerList : serverList) { JiraServerDetails jiraServerDetails = (JiraServerDetails) aServerList; URL url = null; try { if (jiraServerDetails.getBaseurl() == null || "".equals(jiraServerDetails.getBaseurl())) { throw new ConfigurationException("BaseURL is empty."); } url = new URL(jiraServerDetails.getBaseurl()); String content = getURLContent(url.openConnection().getInputStream()); if (content.indexOf("Atlassian JIRA") == -1) { throw new ConfigurationException("URL (" + url.toString() + ") Doesn't put to an installation of Atlassian JIRA"); } try { jiraServerDetails.getRpcClient(true).login(); } catch (JiraException e) { throw new ConfigurationException("Jira Server ( " + url.toString() + " ) is earlier than 2.6 or has RPC disabled."); } } catch (MalformedURLException e) { throw new ConfigurationException("Malformed URL: " + url); } catch (IOException e) { throw new ConfigurationException("Unable to contact server: " + url); } try { MyIssuesFeedBuilder feed = new MyIssuesFeedBuilder(new JiraServerDetails[] { jiraServerDetails }); feed.buildFeedData(); } catch (FeedException feedException) { throw new ConfigurationException(feedException.getMessage()); } } }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); HttpClient client = new DefaultHttpClient(); HttpGet httpGetRequest = new HttpGet("http://www.google.com/"); String line = "", responseString = ""; try { HttpResponse response = client.execute(httpGetRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while ((line = br.readLine()) != null) { responseString += line; } br.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } tv.setText(responseString); setContentView(tv); } Code Sample 2: private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; }
00
Code Sample 1: private void writeCard() { try { new URL(createURLStringExistRESTGetXQuery("update value //scheda[cata = \"" + cata + "\"] with " + "\"replaced from /schede/scheda-... by jEpi-Scheda-Applet\"")).openStream().close(); String urlString = "http://" + server + "/exist/rest/db/schede/" + "scheda-" + cata + ".xml"; HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(urlString).openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("PUT"); OutputStream outputStream = httpURLConnection.getOutputStream(); uiSchedaXml.write(outputStream); outputStream.close(); httpURLConnection.getInputStream().close(); httpURLConnection.disconnect(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } Code Sample 2: public Vector<Question> reload() throws IOException { Vector<Question> questions = new Vector<Question>(); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); shortName = br.readLine(); if (shortName != null && shortName.equals("SHORTNAME")) { shortName = br.readLine(); author = br.readLine(); if (author != null && author.equals("AUTHOR")) { author = br.readLine(); description = br.readLine(); if (description != null && description.equals("DESCRIPTION")) { description = br.readLine(); try { questions = QuestionLoader.getQuestions(br); } catch (IOException ioe) { ioe.printStackTrace(); throw ioe; } finally { br.close(); is.close(); } } else { throw new IllegalArgumentException(); } } else { throw new IllegalArgumentException(); } } else { throw new IllegalArgumentException(); } return questions; }
00
Code Sample 1: private static void processFile(StreamDriver driver, String sourceName) throws Exception { String destName = sourceName + ".xml"; File dest = new File(destName); if (dest.exists()) { throw new IllegalArgumentException("File '" + destName + "' already exists!"); } FileChannel sourceChannel = new FileInputStream(sourceName).getChannel(); try { MappedByteBuffer sourceByteBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, 0, sourceChannel.size()); CharsetDecoder decoder = Charset.forName("ISO-8859-15").newDecoder(); CharBuffer sourceBuffer = decoder.decode(sourceByteBuffer); driver.generateXmlDocument(sourceBuffer, new FileOutputStream(dest)); } finally { sourceChannel.close(); } } Code Sample 2: public static int writeFile(URL url, File outFilename) { InputStream input; try { input = url.openStream(); } catch (IOException e) { e.printStackTrace(); return 0; } FileOutputStream outputStream; try { outputStream = new FileOutputStream(outFilename); } catch (FileNotFoundException e) { e.printStackTrace(); return 0; } return writeFile(input, outputStream); }
00
Code Sample 1: public static String calculateHA2(String uri) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes("GET", ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(uri, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(sourceFile); os = new FileOutputStream(destFile); IOUtils.copy(is, os); } finally { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
00
Code Sample 1: public static String read(URL url) throws Exception { String filename = Integer.toString(url.toString().hashCode()); boolean cached = false; File dir = new File(Config.CACHE_PATH); for (File file : dir.listFiles()) { if (!file.isFile()) continue; if (file.getName().equals(filename)) { filename = file.getName(); cached = true; break; } } File file = new File(Config.CACHE_PATH, filename); if (Config.USE_CACHE && cached) return read(file); System.out.println(">> CACHE HIT FAILED."); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { System.out.println(">> OPEN STREAM FAILED: " + url.toString()); return null; } String content = read(in); save(file, content); return content; } Code Sample 2: public static Vector<String> readFileFromURL(URL url) { Vector<String> text = new Vector<String>(); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { text.add(line); } in.close(); } catch (Exception e) { return null; } return text; }
00
Code Sample 1: public MytemMaster getMytemMaster(String janCode) throws GaeException { HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); BufferedReader reader = null; StringBuffer request = new StringBuffer(address); request.append("api/mytems/show?jan="); request.append(janCode); try { HttpGet httpGet = new HttpGet(request.toString()); HttpResponse httpResponse = client.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == NOT_FOUND) { return null; } if (statusCode >= 400) { throw new GaeException("Status Error = " + Integer.toString(statusCode)); } reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } return createMytemMaster(builder.toString()); } catch (ClientProtocolException e) { throw new GaeException(e); } catch (SocketTimeoutException e) { throw new GaeException(e); } catch (IOException exception) { throw new GaeException(exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public static int deleteSysPosInsert() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_SYS_POSITION_INSERT "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; }
00
Code Sample 1: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private static String calculateScenarioMD5(Scenario scenario) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); Vector<JTest> allTests = scenario.getTests(); for (JTest t : allTests) { String name = t.getTestName() + t.getTestId(); String parameters = ""; if (t instanceof RunnerTest) { parameters = ((RunnerTest) t).getPropertiesAsString(); } md.update(name.getBytes()); md.update(parameters.getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
00
Code Sample 1: private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); } 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: private HashMap<String, GCVote> getVotes(ArrayList<String> waypoints, boolean blnSleepBeforeDownload) { if (blnSleepBeforeDownload) { try { Thread.sleep(PACKET_SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } final String strWaypoints = this.join(waypoints, ","); try { String strParameters = URLEncoder.encode("waypoints", "UTF-8") + "=" + URLEncoder.encode(strWaypoints, "UTF-8"); if (this.mstrUsername.length() > 0) { strParameters += "&" + URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(this.mstrUsername, "UTF-8"); if (this.mstrPassword.length() > 0) { strParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(this.mstrPassword, "UTF-8"); } } final URL url = new URL(BASE_URL_GET_VOTE); URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(strParameters); osw.flush(); final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); saxParserFactory.setNamespaceAware(true); final SAXParser saxParser = saxParserFactory.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final GCVoteHandler gcVoteHandler = new GCVoteHandler(); xmlReader.setContentHandler(gcVoteHandler); xmlReader.parse(new InputSource(new InputStreamReader(conn.getInputStream()))); return gcVoteHandler.getVotes(); } catch (Exception e) { e.printStackTrace(); return null; } } Code Sample 2: public static String makeMD5(String pin) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pin.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { hexString.append(Integer.toHexString(0xFF & hash[i])); } return hexString.toString(); } catch (Exception e) { return null; } }
11
Code Sample 1: private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
00
Code Sample 1: @Override public IMedium createMedium(String urlString, IMetadata optionalMetadata) throws MM4UCannotCreateMediumElementsException { Debug.println("createMedium(): URL: " + urlString); IAudio tempAudio = null; try { String cachedFileUri = null; try { URL url = new URL(urlString); InputStream is = url.openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); MediaCache cache = new MediaCache(); cachedFileUri = cache.addAudio(urlString, out).getURI().substring(5); } catch (MalformedURLException e) { cachedFileUri = urlString; } TAudioFileFormat fFormat = null; try { fFormat = (TAudioFileFormat) new MpegAudioFileReader().getAudioFileFormat(new File(cachedFileUri)); } catch (Exception e) { System.err.println("getAudioFileFormat() failed: " + e); } int length = Constants.UNDEFINED_INTEGER; if (fFormat != null) { length = Math.round(Integer.valueOf(fFormat.properties().get("duration").toString()).intValue() / 1000); } String mimeType = Utilities.getMimetype(Utilities.getURISuffix(urlString)); optionalMetadata.addIfNotNull(IMedium.MEDIUM_METADATA_MIMETYPE, mimeType); if (length != Constants.UNDEFINED_INTEGER) { tempAudio = new Audio(this, length, urlString, optionalMetadata); } } catch (Exception exc) { exc.printStackTrace(); return null; } return tempAudio; } Code Sample 2: private static void downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
00
Code Sample 1: private String listaArquivo() { String arquivo = ""; String linha = ""; try { URL url = new URL(this.getCodeBase(), "./listador?dir=" + "cenarios" + "/" + user); URLConnection con = url.openConnection(); con.setUseCaches(false); InputStream in = con.getInputStream(); DataInputStream result = new DataInputStream(new BufferedInputStream(in)); while ((linha = result.readLine()) != null) { arquivo += linha + "\n"; } return arquivo; } catch (Exception e) { return null; } } Code Sample 2: public DataSet(String name, String type, URL docBase, String plotDir) { sitename = name.toUpperCase(); data = new Vector[3]; data[0] = new Vector(); data[1] = new Vector(); data[2] = new Vector(); if (type == null) return; plottype = type.toLowerCase(); String filename; filename = plotDir + sitename + "_" + plottype + ".plt.gz"; try { double total = 0; URL dataurl = new URL(docBase, filename); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String myline = readme.readLine(); if (myline == null) break; myline = myline.toLowerCase(); if (myline.startsWith("fit:")) { if (haveFit) { continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); fit = new Double[5]; String bye = (String) st.nextToken(); fit[0] = new Double((String) st.nextToken()); fit[1] = new Double((String) st.nextToken()); fit[2] = new Double((String) st.nextToken()); fit[3] = new Double((String) st.nextToken()); fit[4] = new Double((String) st.nextToken()); haveFit = true; continue; } if (myline.startsWith("decyear:")) { StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); String bye = (String) st.nextToken(); decYear = new Double((String) st.nextToken()); haveDate = true; continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); boolean ok = true; String tmp; Double[] mydbl = new Double[3]; for (int i = 0; i < 3 && ok; i++) { if (st.hasMoreTokens()) { tmp = (String) st.nextToken(); if (tmp.startsWith("X") || tmp.startsWith("x")) { ok = false; break; } else { mydbl[i] = new Double(tmp); } } else { mydbl[i] = new Double(0.0); } } if (ok) { if (mydbl[2].doubleValue() > 100) continue; total = mydbl[1].doubleValue() + total; for (int i = 0; i < 3; i++) { data[i].addElement(mydbl[i]); } } } average = total / length(); } catch (FileNotFoundException e) { System.err.println("PlotApplet: file not found: " + e); } catch (IOException e) { System.err.println("PlotApplet: error reading input file: " + e); } }
00
Code Sample 1: 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); System.out.println(cm); cm.setCookies(url.openConnection()); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: @RequestMapping("/import") public String importPicture(@ModelAttribute PictureImportCommand command) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); URL url = command.getUrl(); IOUtils.copy(url.openStream(), baos); byte[] imageData = imageFilterService.touchupImage(baos.toByteArray()); String filename = StringUtils.substringAfterLast(url.getPath(), "/"); String email = userService.getCurrentUser().getEmail(); Picture picture = new Picture(email, filename, command.getDescription(), imageData); pictureRepository.store(picture); return "redirect:/picture/gallery"; }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: private boolean createPKCReqest(String keystoreLocation, String pw) { boolean created = false; Security.addProvider(new BouncyCastleProvider()); KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when creating PKC request: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when creating PKC request: " + e.getMessage()); } return false; } PKCS10CertificationRequest request = null; PublicKey pk = cert.getPublicKey(); try { request = new PKCS10CertificationRequest("SHA1with" + pk.getAlgorithm(), new X500Principal(((X509Certificate) cert).getSubjectDN().toString()), pk, new DERSet(), (PrivateKey) ks.getKey("saws", pw.toCharArray())); PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(new FileOutputStream("sawsRequest.csr"))); pemWrt.writeObject(request); pemWrt.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error creating PKC request file: " + e.getMessage()); } return false; } return created; }
00
Code Sample 1: public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); } Code Sample 2: public final String encrypt(final String plaintext, final String salt) { if (plaintext == null) { throw new NullPointerException(); } if (salt == null) { throw new NullPointerException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update((plaintext + salt).getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } }
00
Code Sample 1: @Override public void remove(int disciplinaId) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "delete from Disciplina where id = ?"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setInt(1, disciplinaId); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de Revendedor no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } } Code Sample 2: public synchronized String decrypt(String plaintext) throws Exception { MessageDigest md = null; String strhash = new String((new BASE64Decoder()).decodeBuffer(plaintext)); System.out.println("strhash1122 " + strhash); try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } byte raw[] = md.digest(); try { md.update(new String(raw).getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } System.out.println("plain text " + strhash); String strcode = new String(raw); System.out.println("strcode.." + strcode); return strcode; }
11
Code Sample 1: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } Code Sample 2: public void verRecordatorio() { try { cantidadArchivos = obtenerCantidad() + 1; boolean existe = false; String filenametxt = ""; String filenamezip = ""; String hora = ""; String lugar = ""; String actividad = ""; String linea = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (dia == Integer.parseInt(identificarDato(datoSeleccionado))) { existe = true; hora = input.readLine(); lugar = input.readLine(); while ((linea = input.readLine()) != null) actividad += linea + "\n"; verRecordatorioInterfaz(hora, lugar, actividad); hora = ""; lugar = ""; actividad = ""; } input.close(); } if (!existe) JOptionPane.showMessageDialog(null, "No existe un recordatorio guardado\n" + "para el " + identificarDato(datoSeleccionado) + " de " + meses[mesTemporal].toLowerCase() + " del a�o " + anoTemporal, "No existe", JOptionPane.INFORMATION_MESSAGE); table.clearSelection(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); } Code Sample 2: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: 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); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: 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; }
11
Code Sample 1: private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; } Code Sample 2: public String downloadFromUrl(URL url) { BufferedReader dis; String content = ""; HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setAllowUserInteraction(false); dis = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; while ((line = dis.readLine()) != null) { content = content.concat(line); content = content.concat("\n"); } } catch (MalformedURLException ex) { System.err.println(ex + " (downloadFromUrl)"); } catch (java.io.IOException iox) { System.out.println(iox + " (downloadFromUrl)"); } catch (Exception generic) { System.out.println(generic.toString() + " (downloadFromUrl)"); } finally { } return content; }
00
Code Sample 1: @Override public void init() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Throwable e) { } try { PopupFactory.setSharedInstance(new PopupFactory()); } catch (Throwable e) { } Container c = getContentPane(); c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS)); String[] labels = getAppletInfo().split("\n"); for (int i = 0; i < labels.length; i++) { c.add(new JLabel((labels[i].length() == 0) ? " " : labels[i])); } new Worker<Drawing>() { @Override protected Drawing construct() throws IOException { Drawing result; System.out.println("getParameter.datafile:" + getParameter("datafile")); if (getParameter("data") != null) { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data"))); result = (Drawing) domi.readObject(0); } else if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); InputStream in = url.openConnection().getInputStream(); try { NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in); result = (Drawing) domi.readObject(0); } finally { in.close(); } } else { result = null; } return result; } @Override protected void done(Drawing result) { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.removeAll(); c.add(drawingPanel = new NetPanel()); if (result != null) { Drawing drawing = (Drawing) result; setDrawing(drawing); } } @Override protected void failed(Throwable value) { Container c = getContentPane(); c.setLayout(new BorderLayout()); c.removeAll(); c.add(drawingPanel = new NetPanel()); value.printStackTrace(); getDrawing().add(new TextFigure(value.toString())); value.printStackTrace(); } @Override protected void finished() { Container c = getContentPane(); initDrawing(getDrawing()); c.validate(); } }.start(); } Code Sample 2: protected void initDefaultRolesFile() { String webConfigPath = System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3"); File mappingFile = new File(webConfigPath + "roles.json"); if (!mappingFile.isAbsolute()) mappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), mappingFile.getPath()); if (mappingFile.exists()) return; log.info("Init default Role Mapping file! mappingFile:" + mappingFile); if (mappingFile.getParentFile().mkdirs()) log.info("M-WRITE dir:" + mappingFile.getParent()); FileChannel fos = null; InputStream is = null; try { URL url = getClass().getResource("/META-INF/roles-default.json"); log.info("Use default Mapping File content of url:" + url); is = url.openStream(); ReadableByteChannel inCh = Channels.newChannel(is); fos = new FileOutputStream(mappingFile).getChannel(); int pos = 0; while (is.available() > 0) pos += fos.transferFrom(inCh, pos, is.available()); } catch (Exception e) { log.error("Roles file doesn't exist and the default can't be created!", e); } finally { close(is); close(fos); } }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } } Code Sample 2: private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
00
Code Sample 1: public void saveProjectFile(File aFile) { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); File destDir = new File(theProjectsDirectory, sdf.format(Calendar.getInstance().getTime())); if (destDir.mkdirs()) { File outFile = new File(destDir, "project.xml"); try { FileChannel sourceChannel = new FileInputStream(aFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(outFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException e) { e.printStackTrace(); } finally { aFile.delete(); } } } Code Sample 2: @Test public void test00_reinitData() throws Exception { Logs.logMethodName(); init(); Db db = DbConnection.defaultCieDbRW(); try { db.begin(); PreparedStatement pst = db.prepareStatement("TRUNCATE e_module;"); pst.executeUpdate(); pst = db.prepareStatement("TRUNCATE e_application_version;"); pst.executeUpdate(); ModuleHelper.synchronizeDbWithModuleList(db); ModuleHelper.declareNewVersion(db); ModuleHelper.updateModuleVersions(db); esisId = com.entelience.directory.PeopleFactory.lookupUserName(db, "esis"); assertNotNull(esisId); guestId = com.entelience.directory.PeopleFactory.lookupUserName(db, "guest"); assertNotNull(guestId); extenId = com.entelience.directory.PeopleFactory.lookupUserName(db, "exten"); assertNotNull(extenId); db.commit(); } catch (Exception e) { db.rollback(); throw e; } }
00
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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } 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 void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } } Code Sample 2: private Bitmap fetchImage(String urlstr) throws Exception { URL url; url = new URL(urlstr); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setDoInput(true); c.setRequestProperty("User-Agent", "Agent"); c.connect(); InputStream is = c.getInputStream(); Bitmap img; img = BitmapFactory.decodeStream(is); return img; }