label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| Code Sample 1:
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Code Sample 2:
public byte[] getEncoded(X509Certificate checkCert, X509Certificate rootCert, String url) { try { if (checkCert == null || rootCert == null) return null; if (url == null) { url = PdfPKCS7.getOCSPURL(checkCert); } if (url == null) return null; OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber()); byte[] array = request.getEncoded(); URL urlt = new URL(url); HttpURLConnection con = (HttpURLConnection) urlt.openConnection(); con.setRequestProperty("Content-Type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.write(array); dataOut.flush(); dataOut.close(); if (con.getResponseCode() / 100 != 2) { throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } InputStream in = (InputStream) con.getContent(); OCSPResp ocspResponse = new OCSPResp(RandomAccessFileOrArray.InputStreamToArray(in)); if (ocspResponse.getStatus() != 0) throw new IOException(MessageLocalization.getComposedMessage("invalid.status.1", ocspResponse.getStatus())); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse != null) { SingleResp[] responses = basicResponse.getResponses(); if (responses.length == 1) { SingleResp resp = responses[0]; Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { return basicResponse.getEncoded(); } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.revoked")); } else { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.unknown")); } } } } catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error("OcspClientBouncyCastle", ex); } return null; } |
11
| Code Sample 1:
public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } }
Code Sample 2:
public String encripta(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } } |
00
| Code Sample 1:
static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; }
Code Sample 2:
public boolean downloadNextTLE() { boolean success = true; if (!downloadINI) { errorText = "startTLEDownload() must be ran before downloadNextTLE() can begin"; return false; } if (!this.hasMoreToDownload()) { errorText = "There are no more TLEs to download"; return false; } int i = currentTLEindex; try { URL url = new URL(rootWeb + fileNames[i]); URLConnection c = url.openConnection(); InputStreamReader isr = new InputStreamReader(c.getInputStream()); BufferedReader br = new BufferedReader(isr); File outFile = new File(localPath + fileNames[i]); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); String currentLine = ""; while ((currentLine = br.readLine()) != null) { writer.write(currentLine); writer.newLine(); } br.close(); writer.close(); } catch (Exception e) { System.out.println("Error Reading/Writing TLE - " + fileNames[i] + "\n" + e.toString()); success = false; errorText = e.toString(); return false; } currentTLEindex++; return success; } |
00
| Code Sample 1:
public static String generateStringSHA256(String content) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ScannerChecksum.class.getName()).log(Level.SEVERE, null, ex); } md.update(content.getBytes()); byte byteData[] = md.digest(); @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
Code Sample 2:
public static void main(String[] args) throws IOException { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); loginLocalhostr(); initialize(); HttpOptions httpoptions = new HttpOptions(localhostrurl); HttpResponse myresponse = httpclient.execute(httpoptions); HttpEntity myresEntity = myresponse.getEntity(); System.out.println(EntityUtils.toString(myresEntity)); fileUpload(); } |
00
| Code Sample 1:
private void loadRDFURL(URL url) throws RDFParseException, RepositoryException { URI urlContext = valueFactory.createURI(url.toString()); try { URLConnection urlConn = url.openConnection(); urlConn.setRequestProperty("Accept", "application/rdf+xml"); InputStream is = urlConn.getInputStream(); repoConn.add(is, url.toString(), RDFFormat.RDFXML, urlContext); is.close(); repoConn.commit(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static Chunk updateLastSend(Chunk c) throws Exception { DBConnectionManager dbm = null; Connection conn = null; PreparedStatement stmt = null; Chunk ret = null; String SQL = "UPDATE CHUNK SET SENT=? WHERE FILEHASH=? AND STARTOFF=? AND LENGTH=?"; log.debug("update chunk last sent for chunk " + c.getHash() + " startoff " + c.getStartOffset()); try { dbm = DBConnectionManager.getInstance(); conn = dbm.getConnection("satmule"); stmt = conn.prepareStatement(SQL); stmt.setDate(1, new java.sql.Date(c.getLastSend().getTime())); stmt.setString(2, c.getHash()); stmt.setLong(3, c.getStartOffset()); stmt.setLong(4, c.getSize()); stmt.executeUpdate(); conn.commit(); stmt.close(); dbm.freeConnection("satmule", conn); } catch (Exception e) { log.error("Error while updating chunk " + c.getHash() + "offset:" + c.getStartOffset() + "SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (conn == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { conn.rollback(); excep = new Exception("SQL Error : " + SQL + " error: " + e); dbm.freeConnection("satmule", conn); } throw excep; } return ret; } |
11
| Code Sample 1:
private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } }
Code Sample 2:
protected static byte[] hashPassword(byte[] saltBytes, String plaintextPassword) throws AssertionError { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw (AssertionError) new AssertionError("No MD5 message digest supported.").initCause(ex); } digest.update(saltBytes); try { digest.update(plaintextPassword.getBytes("utf-8")); } catch (UnsupportedEncodingException ex) { throw (AssertionError) new AssertionError("No UTF-8 encoding supported.").initCause(ex); } byte[] passwordBytes = digest.digest(); return passwordBytes; } |
11
| Code Sample 1:
public void testCommitRollback() throws Exception { Statement stmt = con.createStatement(); assertNotNull(stmt); assertTrue(con.getAutoCommit()); stmt.execute("CREATE TABLE #TESTCOMMIT (id int primary key)"); con.setAutoCommit(false); assertFalse(con.getAutoCommit()); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (1)")); con.commit(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (2)")); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (3)")); con.rollback(); assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (4)")); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM #TESTCOMMIT"); rs.next(); assertEquals("commit", 2, rs.getInt(1)); stmt.close(); }
Code Sample 2:
@Override protected String doIt() throws Exception { PreparedStatement insertStmt = null; try { insertStmt = DB.prepareStatement("INSERT INTO AD_Sequence_No(AD_SEQUENCE_ID, CALENDARYEAR, " + "AD_CLIENT_ID, AD_ORG_ID, ISACTIVE, CREATED, CREATEDBY, " + "UPDATED, UPDATEDBY, CURRENTNEXT) " + "(SELECT AD_Sequence_ID, '" + year + "', " + "AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, " + "Updated, UpdatedBy, StartNo " + "FROM AD_Sequence a " + "WHERE StartNewYear = 'Y' AND NOT EXISTS ( " + "SELECT AD_Sequence_ID " + "FROM AD_Sequence_No b " + "WHERE a.AD_Sequence_ID = b.AD_Sequence_ID " + "AND CalendarYear = ?)) ", get_TrxName()); insertStmt.setString(1, year); insertStmt.executeUpdate(); commit(); } catch (Exception ex) { rollback(); throw ex; } finally { DB.close(insertStmt); } return "Sequence No updated successfully"; } |
11
| Code Sample 1:
public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); }
Code Sample 2:
public static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } } |
00
| Code Sample 1:
public static String EncryptString(String method, String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); if (method.equals("SHA1") || method.equals("MD5")) { try { md = MessageDigest.getInstance(method); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); return null; } } else { return null; } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { String tmp = Integer.toHexString(0xff & byteHash[i]); if (tmp.length() < 2) tmp = "0" + tmp; resultString.append(tmp); } return (resultString.toString()); }
Code Sample 2:
public boolean optimize(int coreId) { try { URL url = new URL(solrUrl + "/core" + coreId + "/update"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("Content-type", "text/xml"); conn.setRequestProperty("charset", "utf-8"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); System.out.println("******************optimizing"); wr.write("<optimize/>"); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } |
00
| Code Sample 1:
private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; }
Code Sample 2:
public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } } |
11
| Code Sample 1:
public void xtest12() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf"); InputStream page1 = manager.cut(pdf, 36, 36); OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
Code Sample 2:
private void makeDailyBackup() throws CacheOperationException, ConfigurationException { final int MAX_DAILY_BACKUPS = 5; File cacheFolder = getBackupFolder(); cacheLog.debug("Making a daily backup of current Beehive archive..."); try { File oldestDaily = new File(DAILY_BACKUP_PREFIX + "." + MAX_DAILY_BACKUPS); if (oldestDaily.exists()) { moveToWeeklyBackup(oldestDaily); } for (int index = MAX_DAILY_BACKUPS - 1; index > 0; index--) { File daily = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + index); File target = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + (index + 1)); if (!daily.exists()) { cacheLog.debug("Daily backup file ''{0}'' was not present. Skipping...", daily.getAbsolutePath()); continue; } if (!daily.renameTo(target)) { sortBackups(); throw new CacheOperationException("There was an error moving ''{0}'' to ''{1}''.", daily.getAbsolutePath(), target.getAbsolutePath()); } else { cacheLog.debug("Moved " + daily.getAbsolutePath() + " to " + target.getAbsolutePath()); } } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied read/write access to daily backup files in ''{0}'' : {1}" + e, cacheFolder.getAbsolutePath(), e.getMessage()); } File beehiveArchive = getCachedArchive(); File tempBackupArchive = new File(cacheFolder, BEEHIVE_ARCHIVE_NAME + ".tmp"); BufferedInputStream archiveReader = null; BufferedOutputStream tempBackupWriter = null; try { archiveReader = new BufferedInputStream(new FileInputStream(beehiveArchive)); tempBackupWriter = new BufferedOutputStream(new FileOutputStream(tempBackupArchive)); int len, bytecount = 0; final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = archiveReader.read(buffer, 0, BUFFER_SIZE)) != -1) { tempBackupWriter.write(buffer, 0, len); bytecount += len; } tempBackupWriter.flush(); long originalFileSize = beehiveArchive.length(); if (originalFileSize != bytecount) { throw new CacheOperationException("Original archive size was {0} bytes but only {1} were copied.", originalFileSize, bytecount); } cacheLog.debug("Finished copying ''{0}'' to ''{1}''.", beehiveArchive.getAbsolutePath(), tempBackupArchive.getAbsolutePath()); } catch (FileNotFoundException e) { throw new CacheOperationException("Files required for copying a backup of Beehive archive could not be found, opened " + "or created : {1}", e, e.getMessage()); } catch (IOException e) { throw new CacheOperationException("Error while making a copy of the Beehive archive : {0}", e, e.getMessage()); } finally { if (archiveReader != null) { try { archiveReader.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, beehiveArchive.getAbsolutePath(), t.getMessage()); } } if (tempBackupWriter != null) { try { tempBackupWriter.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, tempBackupArchive.getAbsolutePath(), t.getMessage()); } } } validateArchive(tempBackupArchive); File newestDaily = getNewestDailyBackupFile(); try { if (!tempBackupArchive.renameTo(newestDaily)) { throw new CacheOperationException("Error moving ''{0}'' to ''{1}''.", tempBackupArchive.getAbsolutePath(), newestDaily.getAbsolutePath()); } else { cacheLog.info("Backup complete. Saved in ''{0}''", newestDaily.getAbsolutePath()); } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied write access to ''{0}'' : {1}", e, newestDaily.getAbsolutePath(), e.getMessage()); } } |
00
| Code Sample 1:
public static void main(String arg[]) { try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } }
Code Sample 2:
public void contextInitialized(ServletContextEvent event) { try { String osName = System.getProperty("os.name"); if (osName != null && osName.toLowerCase().contains("windows")) { URL url = new URL("http://localhost/"); URLConnection urlConn = url.openConnection(); urlConn.setDefaultUseCaches(false); } } catch (Throwable t) { } } |
00
| Code Sample 1:
public void exe2(String[] args) { Connection con = null; Connection con2 = null; Statement stmt = null; PreparedStatement pstmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = getConnection("mis030dv"); con2 = getConnection("mis030db"); con2.setAutoCommit(false); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM MIS.MAP_PUR0101 WHERE NOT EXISTS (SELECT 1 FROM MIS.RSCMGOOD@MIS030DB@DEVU01 WHERE GOODCD = PUM_CODE OR GOODCD = NEW_PUM_CODE)"); pstmt = con2.prepareStatement("INSERT INTO MIS.RSCMGOOD ( GOODCD,GOODFLAG,GOODNM,GOODHNGNM,GOODENGNM,GOODSPEC,GOODMODEL,ASETFLAG,LRGCD,MDLCD,SMLCD,EDICD,PRODCMPYCD,CMT,FSTRGSTRID,FSTRGSTDT,LASTUPDTRID,LASTUPDTDT,APPINSTDATA,MNGTFLAG) " + "VALUES ( ?,SUBSTR(?,1,1),?,?,?,?,NULL,'1',substr(?,2,2),substr(?,4,3),NULL,NULL,NULL,'OCS �����빰ǰ','MISASIS',TO_DATE('20111231','YYYYMMDD'),'MISASIS',TO_DATE('20111231','YYYYMMDD'),NULL,'N')"); int count = 0; String goodcd = null; String goodnm = null; while (rs.next()) { count++; goodcd = rs.getString("PUM_CODE").toUpperCase(); goodnm = rs.getString("PUM_HNAME"); StringUtils.trimWhitespace(goodnm); if (goodnm == null || goodnm.equals("")) goodnm = "-"; pstmt.setString(1, goodcd); pstmt.setString(2, goodcd); pstmt.setString(3, goodnm); pstmt.setString(4, goodnm); pstmt.setString(5, rs.getString("PUM_ENAME")); pstmt.setString(6, rs.getString("KYUKYEOK")); pstmt.setString(7, goodcd); pstmt.setString(8, goodcd); pstmt.executeUpdate(); if (count % 100 == 0) System.out.println("Copy Row : " + count); } System.out.println("Commit Copy Rows : " + count); con2.commit(); } catch (Exception e) { try { con2.rollback(); } catch (Exception ee) { ee.printStackTrace(); } e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); if (con2 != null) con2.close(); } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
public String crypt(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; } |
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:
public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } |
00
| Code Sample 1:
public void imagesParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("img"); } else { nl = doc_[currentquestion].getElementsByTagName("img"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("src"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).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(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static String filtraDoc(HttpServletRequest request, String resource, Repository rep, String template) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = null; int sec = 0; try { URL url = rep.getResource(request, resource); if (url == null) { return "Documento " + rep.dir + "/" + resource + " no encontrado"; } br = new BufferedReader(new InputStreamReader(url.openStream(), rep.encoding)); String line = br.readLine(); while (line != null) { int pos = line.indexOf("KAttach("); if (pos > -1) { sb.append(attach(request, ++sec, line, pos, template)); } else { line = line.replaceAll("%20", "-"); sb.append(new String(line.getBytes(rep.encoding), Config.getMng().getEncoding())).append("\n"); } line = br.readLine(); } } finally { if (br != null) br.close(); } return sb.toString(); } |
00
| Code Sample 1:
protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
Code Sample 2:
public InputSource resolveEntity(String publicId, String systemId) { String resolved = null; if (systemId != null) { try { resolved = catalog.resolveSystem(systemId); } catch (MalformedURLException me) { debug(1, "Malformed URL exception trying to resolve", publicId); resolved = null; } catch (IOException ie) { debug(1, "I/O exception trying to resolve", publicId); resolved = null; } } if (resolved == null) { if (publicId != null) { try { resolved = catalog.resolvePublic(publicId, systemId); } catch (MalformedURLException me) { debug(1, "Malformed URL exception trying to resolve", publicId); } catch (IOException ie) { debug(1, "I/O exception trying to resolve", publicId); } } if (resolved != null) { debug(2, "Resolved", publicId, resolved); } } else { debug(2, "Resolved", systemId, resolved); } if (resolved == null && retryBadSystemIds && publicId != null && systemId != null) { URL systemURL = null; try { systemURL = new URL(systemId); } catch (MalformedURLException e) { try { systemURL = new URL("file:///" + systemId); } catch (MalformedURLException e2) { systemURL = null; } } if (systemURL != null) { try { InputStream iStream = systemURL.openStream(); InputSource iSource = new InputSource(systemId); iSource.setPublicId(publicId); iSource.setByteStream(iStream); return iSource; } catch (Exception e) { } } debug(2, "Failed to open", systemId); debug(2, "\tAttempting catalog lookup without system identifier."); return resolveEntity(publicId, null); } if (resolved != null) { try { InputSource iSource = new InputSource(resolved); iSource.setPublicId(publicId); URL url = new URL(resolved); InputStream iStream = url.openStream(); iSource.setByteStream(iStream); return iSource; } catch (Exception e) { debug(1, "Failed to create InputSource", resolved); return null; } } return null; } |
11
| Code Sample 1:
public void shouldAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); }
Code Sample 2:
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); } |
11
| Code Sample 1:
protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); }
Code Sample 2:
@Test public void config() throws IOException { Reader reader = new FileReader(new File("src/test/resources/test.yml")); Writer writer = new FileWriter(new File("src/site/apt/config.apt")); writer.write("------\n"); writer.write(FileUtils.readFully(reader)); writer.flush(); writer.close(); } |
11
| Code Sample 1:
@Override public boolean putUserDescription(String openID, String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { int modified = 0; PreparedStatement updSt = getConnection().prepareStatement(UPDATE_USER_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); updSt.setString(3, openID); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Query: \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Query: \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; }
Code Sample 2:
private void salvarArtista(Artista artista) throws Exception { System.out.println("GerenteMySQL.salvarArtista()" + artista.toString2()); Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into artista VALUES (?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, artista.getNumeroInscricao()); ps.setString(2, artista.getNome()); ps.setBoolean(3, artista.isSexo()); ps.setString(4, artista.getEmail()); ps.setString(5, artista.getObs()); ps.setString(6, artista.getTelefone()); ps.setNull(7, Types.INTEGER); ps.executeUpdate(); salvarEndereco(conn, ps, artista); sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); for (Obra obra : artista.getListaObras()) { salvarObra(conn, ps, obra, artista.getNumeroInscricao()); } conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } |
11
| Code Sample 1:
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(); } }
Code Sample 2:
public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
00
| Code Sample 1:
public URLConnection makeURLcon() { URI uri; URL url; try { uri = new URI(this.URLString); url = uri.toURL(); this.urlcon = (HttpURLConnection) url.openConnection(); } catch (final URISyntaxException e) { e.printStackTrace(); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } return this.urlcon; }
Code Sample 2:
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } |
11
| 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 void exe2(String[] args) { Connection con = null; Connection con2 = null; Statement stmt = null; PreparedStatement pstmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = getConnection("mis030dv"); con2 = getConnection("mis030db"); con2.setAutoCommit(false); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM MIS.MAP_PUR0101 WHERE NOT EXISTS (SELECT 1 FROM MIS.RSCMGOOD@MIS030DB@DEVU01 WHERE GOODCD = PUM_CODE OR GOODCD = NEW_PUM_CODE)"); pstmt = con2.prepareStatement("INSERT INTO MIS.RSCMGOOD ( GOODCD,GOODFLAG,GOODNM,GOODHNGNM,GOODENGNM,GOODSPEC,GOODMODEL,ASETFLAG,LRGCD,MDLCD,SMLCD,EDICD,PRODCMPYCD,CMT,FSTRGSTRID,FSTRGSTDT,LASTUPDTRID,LASTUPDTDT,APPINSTDATA,MNGTFLAG) " + "VALUES ( ?,SUBSTR(?,1,1),?,?,?,?,NULL,'1',substr(?,2,2),substr(?,4,3),NULL,NULL,NULL,'OCS �����빰ǰ','MISASIS',TO_DATE('20111231','YYYYMMDD'),'MISASIS',TO_DATE('20111231','YYYYMMDD'),NULL,'N')"); int count = 0; String goodcd = null; String goodnm = null; while (rs.next()) { count++; goodcd = rs.getString("PUM_CODE").toUpperCase(); goodnm = rs.getString("PUM_HNAME"); StringUtils.trimWhitespace(goodnm); if (goodnm == null || goodnm.equals("")) goodnm = "-"; pstmt.setString(1, goodcd); pstmt.setString(2, goodcd); pstmt.setString(3, goodnm); pstmt.setString(4, goodnm); pstmt.setString(5, rs.getString("PUM_ENAME")); pstmt.setString(6, rs.getString("KYUKYEOK")); pstmt.setString(7, goodcd); pstmt.setString(8, goodcd); pstmt.executeUpdate(); if (count % 100 == 0) System.out.println("Copy Row : " + count); } System.out.println("Commit Copy Rows : " + count); con2.commit(); } catch (Exception e) { try { con2.rollback(); } catch (Exception ee) { ee.printStackTrace(); } e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); if (con2 != null) con2.close(); } catch (Exception e) { e.printStackTrace(); } } } |
11
| Code Sample 1:
public void downloadTranslationsAndReload() { File languages = new File(this.translationsFile); try { URL languageURL = new URL(languageServer); InputStream is = languageURL.openStream(); OutputStream os = new FileOutputStream(languages); byte[] read = new byte[512000]; int bytesRead = 0; do { bytesRead = is.read(read); if (bytesRead > 0) { os.write(read, 0, bytesRead); } } while (bytesRead > 0); is.close(); os.close(); this.loadTranslations(); } catch (Exception e) { System.err.println("Remote languages file not found!"); if (languages.exists()) { try { XMLDecoder loader = new XMLDecoder(new FileInputStream(languages)); this.languages = (Hashtable) loader.readObject(); loader.close(); } catch (Exception ex) { ex.printStackTrace(); this.languages.put(naiveLanguage, new Hashtable()); } } else this.languages.put(naiveLanguage, new Hashtable()); } }
Code Sample 2:
public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } |
00
| Code Sample 1:
public static String[] viewFilesToImport(HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER") + ""; String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN") + ""; String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD") + ""; String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH"); String[] dirList = null; if (importFTPServer.equals("") || importFTPLogin.equals("") || importFTPPassword.equals("")) { return dirList; } boolean loggedIn = false; try { int reply; ftp.connect(importFTPServer); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport connecting: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.logout(); ftp.disconnect(); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport ERROR: FTP server refused connection."); } else { loggedIn = ftp.login(importFTPLogin, importFTPPassword); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport Logging in: " + importFTPLogin + " " + importFTPPassword); } if (loggedIn) { try { ftp.changeWorkingDirectory(importFTPFilePath); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport changing dir: " + importFTPFilePath); if (!FTPReply.isPositiveCompletion(reply)) { CofaxToolsUtil.log("ERROR: cannot change directory"); } FTPFile[] remoteFileList = ftp.listFiles(); ArrayList tmpArray = new ArrayList(); for (int i = 0; i < remoteFileList.length; i++) { FTPFile testFile = remoteFileList[i]; if (testFile.getType() == FTP.ASCII_FILE_TYPE) { tmpArray.add(testFile.getName()); } } dirList = (String[]) tmpArray.toArray(new String[0]); ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport cannot read directory: " + importFTPFilePath); } } } catch (IOException e) { CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport could not connect to server: " + e); } return (dirList); }
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 List<AnalyzerResult> analyze(LWComponent c, boolean tryFallback) { List<AnalyzerResult> results = new ArrayList<AnalyzerResult>(); try { URL url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + c.getLabel()); if (flow != null) { url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + getSpecFromComponent(c)); } System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); XMLDecoder decoder = new XMLDecoder(url.openStream()); Map map = (Map) decoder.readObject(); for (Object key : map.keySet()) { results.add(new AnalyzerResult(key.toString(), map.get(key).toString())); } } catch (Exception ex) { ex.printStackTrace(); VueUtil.alert("Can't Execute Flow on the node " + c.getLabel(), "Can't Execute Seasr flow"); } return results; }
Code Sample 2:
public static BufferedReader openForReading(String name, URI base, ClassLoader classLoader) throws IOException { if ((name == null) || name.trim().equals("")) { return null; } if (name.trim().equals("System.in")) { if (STD_IN == null) { STD_IN = new BufferedReader(new InputStreamReader(System.in)); } return STD_IN; } URL url = nameToURL(name, base, classLoader); if (url == null) { throw new IOException("Could not convert \"" + name + "\" with base \"" + base + "\" to a URL."); } InputStreamReader inputStreamReader = null; try { inputStreamReader = new InputStreamReader(url.openStream()); } catch (IOException ex) { try { URL possibleJarURL = ClassUtilities.jarURLEntryResource(url.toString()); if (possibleJarURL != null) { inputStreamReader = new InputStreamReader(possibleJarURL.openStream()); } return new BufferedReader(inputStreamReader); } catch (Exception ex2) { try { if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException ex3) { } IOException ioException = new IOException("Failed to open \"" + url + "\"."); ioException.initCause(ex); throw ioException; } } return new BufferedReader(inputStreamReader); } |
00
| Code Sample 1:
protected void givenGroupRepository(String repoId, String providerId, Repository... memberRepos) throws AuthenticationException, UnsupportedEncodingException, IOException, ClientProtocolException { HttpResponse response = executeDeleteWithResponse(format("/repo_groups/%s", repoId)); consume(response.getEntity()); final StringEntity content = new StringEntity(format("{data:{id: '%s', name: '%s', provider: '%s', exposed: true, repositories: [%s]}}", repoId, repoId, providerId, render(memberRepos))); response = executePost("/repo_groups", content, new BasicHeader("Content-Type", "application/json")); consume(response.getEntity()); assertThat(response.getStatusLine().getStatusCode(), is(201)); }
Code Sample 2:
public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; } |
11
| Code Sample 1:
public static String convertStringToMD5(String toEnc) { try { MessageDigest mdEnc = MessageDigest.getInstance("MD5"); mdEnc.update(toEnc.getBytes(), 0, toEnc.length()); return new BigInteger(1, mdEnc.digest()).toString(16); } catch (Exception e) { return null; } }
Code Sample 2:
private final String createMD5(String pwd) throws Exception { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(pwd.getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } return app.toString(); } |
00
| Code Sample 1:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
Code Sample 2:
private BibtexDatabase importSpiresEntries(String key, OutputPrinter frame) { String url = constructUrl(key); try { HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Jabref"); InputStream inputStream = conn.getInputStream(); SPIRESBibtexFilterReader reader = new SPIRESBibtexFilterReader(new InputStreamReader(inputStream)); ParserResult pr = BibtexParser.parse(reader); return pr.getDatabase(); } catch (IOException e) { frame.showMessage(Globals.lang("An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (RuntimeException e) { frame.showMessage(Globals.lang("An Error occurred while fetching from SPIRES source (%0):", new String[] { url }) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } return null; } |
11
| Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static boolean saveMap(LWMap map, boolean saveAs, boolean export) { Log.info("saveMap: " + map); GUI.activateWaitCursor(); if (map == null) return false; File file = map.getFile(); int response = -1; if (map.getSaveFileModelVersion() == 0) { final Object[] defaultOrderButtons = { VueResources.getString("saveaction.saveacopy"), VueResources.getString("saveaction.save") }; Object[] messageObject = { map.getLabel() }; response = VueUtil.option(VUE.getDialogParent(), VueResources.getFormatMessage(messageObject, "dialog.saveaction.message"), VueResources.getFormatMessage(messageObject, "dialog.saveaction.title"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, defaultOrderButtons, VueResources.getString("saveaction.saveacopy")); } if (response == 0) { saveAs = true; } if ((saveAs || file == null) && !export) { file = ActionUtil.selectFile("Save Map", null); } else if (export) { file = ActionUtil.selectFile("Export Map", "export"); } if (file == null) { try { return false; } finally { GUI.clearWaitCursor(); } } try { Log.info("saveMap: target[" + file + "]"); final String name = file.getName().toLowerCase(); if (name.endsWith(".rli.xml")) { new IMSResourceList().convert(map, file); } else if (name.endsWith(".xml") || name.endsWith(".vue")) { ActionUtil.marshallMap(file, map); } else if (name.endsWith(".jpeg") || name.endsWith(".jpg")) ImageConversion.createActiveMapJpeg(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".png")) ImageConversion.createActiveMapPng(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".svg")) SVGConversion.createSVG(file); else if (name.endsWith(".pdf")) { PresentationNotes.createMapAsPDF(file); } else if (name.endsWith(".zip")) { Vector resourceVector = new Vector(); Iterator i = map.getAllDescendents(LWComponent.ChildKind.PROPER).iterator(); while (i.hasNext()) { LWComponent component = (LWComponent) i.next(); System.out.println("Component:" + component + " has resource:" + component.hasResource()); if (component.hasResource() && (component.getResource() instanceof URLResource)) { URLResource resource = (URLResource) component.getResource(); try { if (resource.isLocalFile()) { String spec = resource.getSpec(); System.out.println(resource.getSpec()); Vector row = new Vector(); row.add(new Boolean(true)); row.add(resource); row.add(new Long(file.length())); row.add("Ready"); resourceVector.add(row); } } catch (Exception ex) { System.out.println("Publisher.setLocalResourceVector: Resource " + resource.getSpec() + ex); ex.printStackTrace(); } } } File savedCMap = PublishUtil.createZip(map, resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; try { while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); } catch (Exception e) { e.printStackTrace(); } finally { istream.close(); ostream.close(); } } else if (name.endsWith(".html")) { HtmlOutputDialog hod = new HtmlOutputDialog(); hod.setVisible(true); if (hod.getReturnVal() > 0) new ImageMap().createImageMap(file, hod.getScale(), hod.getFormat()); } else if (name.endsWith(".rdf")) { edu.tufts.vue.rdf.RDFIndex index = new edu.tufts.vue.rdf.RDFIndex(); String selectionType = VueResources.getString("rdf.export.selection"); if (selectionType.equals("ALL")) { Iterator<LWMap> maps = VUE.getLeftTabbedPane().getAllMaps(); while (maps.hasNext()) { index.index(maps.next()); } } else if (selectionType.equals("ACTIVE")) { index.index(VUE.getActiveMap()); } else { index.index(VUE.getActiveMap()); } FileWriter writer = new FileWriter(file); index.write(writer); writer.close(); } else if (name.endsWith(VueUtil.VueArchiveExtension)) { Archive.writeArchive(map, file); } else { Log.warn("Unknown save type for filename extension: " + name); return false; } Log.debug("Save completed for " + file); if (!VUE.isApplet()) { VueFrame frame = (VueFrame) VUE.getMainWindow(); String title = VUE.getName() + ": " + name; frame.setTitle(title); } if (name.endsWith(".vue")) { RecentlyOpenedFilesManager rofm = RecentlyOpenedFilesManager.getInstance(); rofm.updateRecentlyOpenedFiles(file.getAbsolutePath()); } return true; } catch (Throwable t) { Log.error("Exception attempting to save file " + file + ": " + t); Throwable e = t; if (t.getCause() != null) e = t.getCause(); if (e instanceof java.io.FileNotFoundException) { Log.error("Save Failed: " + e); } else { Log.error("Save failed for \"" + file + "\"; ", e); } if (e != t) Log.error("Exception attempting to save file " + file + ": " + e); VueUtil.alert(String.format(Locale.getDefault(), VueResources.getString("saveaction.savemap.error") + "\"%s\";\n" + VueResources.getString("saveaction.targetfiel") + "\n\n" + VueResources.getString("saveaction.problem"), map.getLabel(), file, Util.formatLines(e.toString(), 80)), "Problem Saving Map"); } finally { GUI.invokeAfterAWT(new Runnable() { public void run() { GUI.clearWaitCursor(); } }); } return false; } |
00
| Code Sample 1:
public List<Class<?>> getImplementingClasses(Class<?> ancestor, boolean searchAllClasspath) throws MutableClassLoaderException { List<Class<?>> classes = new LinkedList<Class<?>>(); for (URL url : (searchAllClasspath ? getURLs() : getAddedURLs())) { Log.verbose("Checking classpath item " + url); if (!url.getPath().toLowerCase().endsWith("/")) { try { JarInputStream jis = new JarInputStream(url.openStream()); JarEntry je; while ((je = jis.getNextJarEntry()) != null) { Log.verbose("Checking resource " + je.getName()); try { if (je.getName().endsWith(".class")) { Class<?> c = this.loadClass(je.getName().replaceAll("/", ".").replaceAll(".class$", "")); if (!Modifier.isAbstract(c.getModifiers()) && !Modifier.isInterface(c.getModifiers()) && ancestor.isAssignableFrom(c)) { Log.verbose("Found class " + c.getCanonicalName() + " which implements class " + ancestor.getCanonicalName()); classes.add(c); } } } catch (Error e) { } catch (RuntimeException re) { } catch (Exception e) { } } } catch (Exception e) { Log.error(e); } } else if (url.getPath().endsWith("/")) { File root = new File(url.getPath()); for (File file : FileFunctions.getFileTree(root)) { try { if (file.getName().toLowerCase().endsWith(".class")) { Class<?> c = this.loadClass(file.getAbsolutePath().replaceAll("^" + root.getAbsolutePath() + "/", "").replaceAll("/", ".").replaceAll(".class$", "")); if (!Modifier.isAbstract(c.getModifiers()) && !Modifier.isInterface(c.getModifiers()) && ancestor.isAssignableFrom(c)) { Log.verbose("Found class " + c.getCanonicalName() + " which implements class " + ancestor.getCanonicalName()); classes.add(c); } } } catch (Exception e) { Log.error(e); } } } } return classes; }
Code Sample 2:
public void upload() throws UnknownHostException, SocketException, FTPConnectionClosedException, LoginFailedException, DirectoryChangeFailedException, CopyStreamException, RefusedConnectionException, IOException { final int NUM_XML_FILES = 2; final String META_XML_SUFFIX = "_meta.xml"; final String FILES_XML_SUFFIX = "_files.xml"; final String username = getUsername(); final String password = getPassword(); if (getFtpServer() == null) { throw new IllegalStateException("ftp server not set"); } if (getFtpPath() == null) { throw new IllegalStateException("ftp path not set"); } if (username == null) { throw new IllegalStateException("username not set"); } if (password == null) { throw new IllegalStateException("password not set"); } final String metaXmlString = serializeDocument(getMetaDocument()); final String filesXmlString = serializeDocument(getFilesDocument()); final byte[] metaXmlBytes = metaXmlString.getBytes(); final byte[] filesXmlBytes = filesXmlString.getBytes(); final int metaXmlLength = metaXmlBytes.length; final int filesXmlLength = filesXmlBytes.length; final Collection files = getFiles(); final int totalFiles = NUM_XML_FILES + files.size(); final String[] fileNames = new String[totalFiles]; final long[] fileSizes = new long[totalFiles]; final String metaXmlName = getIdentifier() + META_XML_SUFFIX; fileNames[0] = metaXmlName; fileSizes[0] = metaXmlLength; final String filesXmlName = getIdentifier() + FILES_XML_SUFFIX; fileNames[1] = filesXmlName; fileSizes[1] = filesXmlLength; int j = 2; for (Iterator i = files.iterator(); i.hasNext(); ) { final ArchiveFile f = (ArchiveFile) i.next(); fileNames[j] = f.getRemoteFileName(); fileSizes[j] = f.getFileSize(); j++; } for (int i = 0; i < fileSizes.length; i++) { _fileNames2Progress.put(fileNames[i], new UploadFileProgress(fileSizes[i])); _totalUploadSize += fileSizes[i]; } FTPClient ftp = new FTPClient(); try { if (isCancelled()) { return; } ftp.enterLocalPassiveMode(); if (isCancelled()) { return; } ftp.connect(getFtpServer()); final int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new RefusedConnectionException(getFtpServer() + "refused FTP connection"); } if (isCancelled()) { return; } if (!ftp.login(username, password)) { throw new LoginFailedException(); } try { if (!ftp.changeWorkingDirectory(getFtpPath())) { if (!isFtpDirPreMade() && !ftp.makeDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } if (isCancelled()) { return; } if (!ftp.changeWorkingDirectory(getFtpPath())) { throw new DirectoryChangeFailedException(); } } if (isCancelled()) { return; } connected(); uploadFile(metaXmlName, new ByteArrayInputStream(metaXmlBytes), ftp); uploadFile(filesXmlName, new ByteArrayInputStream(filesXmlBytes), ftp); if (isCancelled()) { return; } ftp.setFileType(FTP.BINARY_FILE_TYPE); for (final Iterator i = files.iterator(); i.hasNext(); ) { final ArchiveFile f = (ArchiveFile) i.next(); uploadFile(f.getRemoteFileName(), new FileInputStream(f.getIOFile()), ftp); } } catch (InterruptedIOException ioe) { return; } finally { ftp.logout(); } } finally { try { ftp.disconnect(); } catch (IOException e) { } } if (isCancelled()) { return; } checkinStarted(); if (isCancelled()) { return; } checkin(); if (isCancelled()) { return; } checkinCompleted(); } |
11
| Code Sample 1:
private void copyFile(String file) { FileChannel inChannel = null; FileChannel outChannel = null; try { Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss "); File in = new File(file); String[] name = file.split("\\\\"); File out = new File(".\\xml_archiv\\" + df.format(dt) + name[name.length - 1]); inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { System.err.println("Copy error!"); System.err.println("Error: " + e.getMessage()); } finally { if (inChannel != null) { try { inChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } if (outChannel != null) { try { outChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } } }
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:
public static byte[] computeMD5(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(s.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }
Code Sample 2:
private void _scanForMetaData(URL _url) throws java.io.IOException { if (DEBUG.Enabled) System.out.println(this + " _scanForMetaData: xml props " + mXMLpropertyList); if (DEBUG.Enabled) System.out.println("*** Opening connection to " + _url); markAccessAttempt(); Properties metaData = scrapeHTMLmetaData(_url.openConnection(), 2048); if (DEBUG.Enabled) System.out.println("*** Got meta-data " + metaData); markAccessSuccess(); String title = metaData.getProperty("title"); if (title != null && title.length() > 0) { setProperty("title", title); title = title.replace('\n', ' ').trim(); setTitle(title); } try { setByteSize(Integer.parseInt((String) getProperty("contentLength"))); } catch (Exception e) { } } |
00
| Code Sample 1:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
Code Sample 2:
public void copyURLToFile(TmpFile p_TmpFile) { byte[] l_Buffer; URLConnection l_Connection = null; DataInputStream l_IN = null; DataOutputStream l_Out = null; FileOutputStream l_FileOutStream = null; try { System.gc(); if (error.compareTo(noError) == 0) { l_Connection = urlHome.openConnection(); l_FileOutStream = new FileOutputStream(p_TmpFile.getAbsolutePath()); l_Out = new DataOutputStream(l_FileOutStream); l_IN = new DataInputStream(l_Connection.getInputStream()); l_Buffer = new byte[8192]; int bytes = 0; while ((bytes = l_IN.read(l_Buffer)) > 0) { l_Out.write(l_Buffer, 0, bytes); } } } catch (MalformedURLException mue) { error = "MalformedURLException in connecting url was " + mue.getMessage(); } catch (IOException io) { error = "IOException in connecting url was " + io.getMessage(); } catch (Exception e) { error = "Exception in connecting url was " + e.getMessage(); } finally { try { l_IN.close(); l_Out.flush(); l_FileOutStream.flush(); l_FileOutStream.close(); l_Out.close(); } catch (Exception e) { error = "Exception in connecting url was " + e.getMessage(); } } } |
00
| Code Sample 1:
private boolean copyFile(BackupItem item) { try { FileChannel src = new FileInputStream(item.getDrive() + ":" + item.getPath()).getChannel(); createFolderStructure(this.task.getDestinationPath() + "\\" + item.getDrive() + item.getPath()); FileChannel dest = new FileOutputStream(this.task.getDestinationPath() + "\\" + item.getDrive() + item.getPath()).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); Logging.logMessage("file " + item.getDrive() + ":" + item.getPath() + " was backuped"); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
Code Sample 2:
private void getPicture(String urlPath, String picId) throws Exception { URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(10000); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); byte[] data = readStream(inputStream); File file = new File(picDirectory + picId); FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(data); outputStream.close(); } conn.disconnect(); } |
11
| Code Sample 1:
public void init(File file) { InputStream is = null; ByteArrayOutputStream os = null; try { is = new FileInputStream(file); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); } catch (Throwable e) { throw new VisualizerEngineException("Unexcpected exception while reading MDF file", e); } if (simulationEngine != null) simulationEngine.stopSimulation(); simulationEngine = new TrafficAsynchSimulationEngine(); simulationEngine.init(MDFReader.read(os.toByteArray())); simulationEngineThread = null; }
Code Sample 2:
public void includeJs(Group group, Writer out, PageContext pageContext) throws IOException { includeResource(pageContext, out, RetentionHelper.buildRootRetentionFilePath(group, ".js"), JS_BEGIN_TAG, JS_END_TAG); ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".js"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); fileStream.close(); } } |
00
| Code Sample 1:
private Collection<URL> doSearch(final URL url) throws IOException { final Collection<URL> result = new ArrayList<URL>(); final InputStream is = url.openStream(); final ReadHTML parse = new ReadHTML(is); final StringBuilder buffer = new StringBuilder(); boolean capture = false; int ch; while ((ch = parse.read()) != -1) { if (ch == 0) { final Tag tag = parse.getTag(); if (tag.getName().equalsIgnoreCase("url")) { buffer.setLength(0); capture = true; } else if (tag.getName().equalsIgnoreCase("/url")) { result.add(new URL(buffer.toString())); buffer.setLength(0); capture = false; } } else { if (capture) { buffer.append((char) ch); } } } return result; }
Code Sample 2:
public static String getDigest(String input) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(input.getBytes()); byte[] outDigest = md5.digest(); StringBuffer outBuf = new StringBuffer(33); for (int i = 0; i < outDigest.length; i++) { byte b = outDigest[i]; int hi = (b >> 4) & 0x0f; outBuf.append(MD5Digest.hexTab[hi]); int lo = b & 0x0f; outBuf.append(MD5Digest.hexTab[lo]); } return outBuf.toString(); } |
00
| Code Sample 1:
public String getProxy(String userName, String password) throws Exception { URL url = new URL(httpURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream()); outputToServlet.writeObject(userName); outputToServlet.writeObject(password); outputToServlet.flush(); outputToServlet.close(); ObjectInputStream inputFromServlet = new ObjectInputStream(conn.getInputStream()); return inputFromServlet.readObject() + ""; }
Code Sample 2:
public final void run() { active = true; String s = findcachedir(); uid = getuid(s); try { File file = new File(s + "main_file_cache.dat"); if (file.exists() && file.length() > 0x3200000L) file.delete(); cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw"); for (int j = 0; j < 5; j++) cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw"); } catch (Exception exception) { exception.printStackTrace(); } for (int i = threadliveid; threadliveid == i; ) { if (socketreq != 0) { try { socket = new Socket(socketip, socketreq); } catch (Exception _ex) { socket = null; } socketreq = 0; } else if (threadreq != null) { Thread thread = new Thread(threadreq); thread.setDaemon(true); thread.start(); thread.setPriority(threadreqpri); threadreq = null; } else if (dnsreq != null) { try { dns = InetAddress.getByName(dnsreq).getHostName(); } catch (Exception _ex) { dns = "unknown"; } dnsreq = null; } else if (savereq != null) { if (savebuf != null) try { FileOutputStream fileoutputstream = new FileOutputStream(s + savereq); fileoutputstream.write(savebuf, 0, savelen); fileoutputstream.close(); } catch (Exception _ex) { } if (waveplay) { wave = s + savereq; waveplay = false; } if (midiplay) { midi = s + savereq; midiplay = false; } savereq = null; } else if (urlreq != null) { try { urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream()); } catch (Exception _ex) { urlstream = null; } urlreq = null; } try { Thread.sleep(50L); } catch (Exception _ex) { } } } |
00
| Code Sample 1:
public Collection<Regula> citesteReguli() throws IOException { URL url = new URL(urlulSpreLocatiaCurenta, fisier); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); Collection<Regula> rezultat = new ArrayList<Regula>(); String line = ""; while (!"".equals(line = reader.readLine())) { Regula r = parseazaRegula(line); if (r != null) rezultat.add(r); } return rezultat; }
Code Sample 2:
@Override public void dispatchContent(InputStream is) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Sending content message over JMS"); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); this.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { BytesMessage message = session.createBytesMessage(); message.writeBytes(bos.toByteArray()); return message; } }); } |
11
| Code Sample 1:
public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); } |
11
| Code Sample 1:
private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
private void zip(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } }
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(); } } |
11
| Code Sample 1:
public static void copyFile(File source, File target) throws Exception { if (source.isDirectory()) { if (!target.isDirectory()) { target.mkdirs(); } String[] children = source.list(); for (int i = 0; i < children.length; i++) { copyFile(new File(source, children[i]), new File(target, children[i])); } } else { FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(target).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { errorLog("{Malgn.copyFile} " + e.getMessage()); throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } }
Code Sample 2:
public IOCacheArray(final File file, int capacity, final IIOCacheArrayObjectMaker iomaker, int chunkSize, String name) { super(capacity, null, chunkSize, name); generator = new ICacheArrayObjectMaker() { FileOutputStream outStream; FileInputStream inStream; FileChannel outChannel; FileChannel inChannel; boolean inited = false; private synchronized void init() { if (!inited) { try { outStream = new FileOutputStream(file); inStream = new FileInputStream(file); outChannel = outStream.getChannel(); inChannel = inStream.getChannel(); } catch (FileNotFoundException foe) { Logging.errorln("IOCacheArray constuctor error: Could not open file " + file + ". Exception " + foe); Logging.errorln("outStream " + outStream + " inStream " + inStream + " outchan " + outChannel + " inchannel " + inChannel); } } inited = true; } public Object make(int itemIndex, int baseIndex, Object[] data) { init(); return iomaker.read(inChannel, itemIndex, baseIndex, data); } public boolean flush(int baseIndex, Object[] data) { init(); return iomaker.write(outChannel, baseIndex, data); } public CacheArrayBlockSummary summarize(int baseIndex, Object[] data) { init(); return iomaker.summarize(baseIndex, data); } }; } |
00
| Code Sample 1:
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(); } }
Code Sample 2:
private byte[] getResponseFromHttp(byte[] ocspPackage, URL url) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); try { con.setRequestMethod(OCSPLoginModule.POST); } catch (ProtocolException e) { throw new IOException(e.getMessage(), e); } con.setRequestProperty(OCSPLoginModule.CONTENT_TYPE, OCSPLoginModule.APPLICATION_OCSP_REQUEST); OutputStream os = null; try { os = con.getOutputStream(); os.write(ocspPackage); } catch (IOException e) { logger.error(e.getMessage()); throw e; } finally { os.close(); } InputStream in = null; byte[] respBytes = null; ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); } finally { in.close(); con.disconnect(); } respBytes = baos.toByteArray(); return respBytes; } |
00
| Code Sample 1:
private boolean saveNodeData(NodeInfo info) { boolean rCode = false; String query = mServer + "save.php" + ("?id=" + info.getId()); try { URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String contentType = info.getMIMEType().toString(); byte[] body = info.getData(); conn.setAllowUserInteraction(false); conn.setRequestMethod("PUT"); if (contentType.equals("")) { contentType = "application/octet-stream"; } System.out.println("contentType: " + contentType); conn.setRequestProperty("Content-Type", contentType); setCredentials(conn); conn.setDoOutput(true); conn.getOutputStream().write(body); rCode = saveNode(info, conn); } catch (Exception ex) { System.out.println("Exception: " + ex.toString()); } return rCode; }
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; } |
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 int executeUpdateJT(String sql, Object[][] paramsList) { Connection connection = null; connection = this.getConnection(); try { connection.setAutoCommit(false); } catch (SQLException e1) { e1.printStackTrace(); } PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < paramsList.length; i++) { if (connection != null && !connection.isClosed()) { InputStream is = null; if (paramsList[i].length > 0) { for (int j = 0; j < paramsList[i].length; j++) { Object obj = paramsList[i][j]; if (obj.getClass().equals(Class.forName("java.io.File"))) { File file = (File) obj; is = new FileInputStream(file); preparedStatement.setBinaryStream(j + 1, is, (int) file.length()); } else if (obj.getClass().equals(Class.forName("java.util.Date"))) { java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); preparedStatement.setString(j + 1, sdf.format((Date) obj)); } else { preparedStatement.setObject(j + 1, obj); } } } preparedStatement.executeUpdate(); if (is != null) { is.close(); } ; } } } catch (Exception e) { System.out.println("发生错误,数据回滚!"); e.printStackTrace(); try { connection.rollback(); return 0; } catch (SQLException e1) { e1.printStackTrace(); } } try { connection.commit(); return 1; } catch (SQLException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { log.error("未能正确关闭数据库连接!", e); System.out.println("未能正确关闭数据库连接!"); e.printStackTrace(); } } return -1; } |
11
| Code Sample 1:
public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; }
Code Sample 2:
private static void copyFile(File src, File dst) throws IOException { FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } |
11
| Code Sample 1:
private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } }
Code Sample 2:
@Override public User login(String username, String password) { User user = null; try { user = (User) em.createQuery("Select o from User o where o.username = :username").setParameter("username", username).getSingleResult(); } catch (NoResultException e) { throw new NestedException(e.getMessage(), e); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(password.getBytes("UTF-8")); byte[] hash = digest.digest(); BigInteger bigInt = new BigInteger(1, hash); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } if (hashtext.equals(user.getPassword())) return user; } catch (Exception e) { throw new NestedException(e.getMessage(), e); } return null; } |
11
| Code Sample 1:
public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } }
Code Sample 2:
public void run() { FileInputStream src; FileOutputStream dest; try { src = new FileInputStream(srcName); dest = new FileOutputStream(destName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileChannel srcC = src.getChannel(); FileChannel destC = dest.getChannel(); ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE); try { int i; System.out.println(srcC.size()); while ((i = srcC.read(buf)) > 0) { System.out.println(buf.getChar(2)); buf.flip(); destC.write(buf); buf.compact(); } destC.close(); dest.close(); } catch (IOException e1) { e1.printStackTrace(); return; } } |
11
| Code Sample 1:
public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
Code Sample 2:
public static void copy(File from, File to) { if (from.getAbsolutePath().equals(to.getAbsolutePath())) { return; } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(from); os = new FileOutputStream(to); int read = -1; byte[] buffer = new byte[10000]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } catch (Exception e) { throw new RuntimeException(); } finally { try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } } |
00
| Code Sample 1:
public void download() throws IOException { new File(file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))).mkdirs(); URLConnection urlConnection = url.openConnection(); size = urlConnection.getContentLength(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; fetchedSize = 0; date = urlConnection.getLastModified(); while (!failed && (numRead = inputStream.read(buffer)) != -1) { if (failed) { throw new IOException("Download manually stopped"); } bufferedOutputStream.write(buffer, 0, numRead); fetchedSize += numRead; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadProgress(this); } } } inputStream.close(); bufferedOutputStream.close(); if (file.toString().endsWith(".gz") || file.toString().endsWith(".gzip")) { for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingProgress(this); } } try { GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(file)); String fileName = file.toString().substring(0, file.toString().lastIndexOf(".")); OutputStream outputStream = new FileOutputStream(fileName); byte[] unpackBuffer = new byte[1024]; int length; while ((length = gzipInputStream.read(unpackBuffer)) > 0) { outputStream.write(unpackBuffer, 0, length); } gzipInputStream.close(); outputStream.close(); file.delete(); file = new File(fileName); file.setLastModified(date); failed = false; finished = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingFinished(this); } } for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } catch (IOException ioException) { file.delete(); failed = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).exceptionWasThrown(this, ioException); } } } try { Runtime.getRuntime().exec("chmod 777 " + file.getCanonicalPath()); } catch (Exception exception) { } } else { failed = false; finished = true; file.setLastModified(date); for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } }
Code Sample 2:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } |
11
| Code Sample 1:
private String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
Code Sample 2:
public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; } |
00
| Code Sample 1:
@SuppressWarnings("deprecation") private void loadClassFilesFromJar() { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement(); File jarFile = packageFragmentRoot.getResource().getLocation().toFile(); try { URL url = jarFile.toURL(); URLConnection u = url.openConnection(); ZipInputStream inputStream = new ZipInputStream(u.getInputStream()); ZipEntry entry = inputStream.getNextEntry(); while (null != entry) { if (entry.getName().endsWith(".class")) { ClassParser parser = new ClassParser(inputStream, entry.getName()); Repository.addClass(parser.parse()); } entry = inputStream.getNextEntry(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public String calcMD5(String sequence) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(sequence.toString().toUpperCase().getBytes()); BigInteger md5hash = new BigInteger(1, md5.digest()); String sequence_md5 = md5hash.toString(16); while (sequence_md5.length() < 32) { sequence_md5 = "0" + sequence_md5; } return sequence_md5; } |
00
| Code Sample 1:
public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
Code Sample 2:
private ResponseStatus performHandshake(String url) throws IOException { HttpURLConnection connection = Caller.getInstance().openConnection(url); InputStream is = connection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); int statusCode = ResponseStatus.codeForStatus(status); ResponseStatus responseStatus; if (statusCode == ResponseStatus.OK) { this.sessionId = r.readLine(); this.nowPlayingUrl = r.readLine(); this.submissionUrl = r.readLine(); responseStatus = new ResponseStatus(statusCode); } else if (statusCode == ResponseStatus.FAILED) { responseStatus = new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1)); } else { return new ResponseStatus(statusCode); } r.close(); return responseStatus; } |
00
| Code Sample 1:
protected String getCache() throws IOException { if (cache == null) { URL url = ((URI) hasContent()).toURL(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) ; in.close(); cache = inputLine; } return cache; }
Code Sample 2:
public synchronized FTPClient getFTPClient(String User, String Password) throws IOException { if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - start"); } while ((counter >= maxClients)) { try { wait(); } catch (InterruptedException e) { logger.error("getFTPClient(String, String)", e); e.printStackTrace(); } } FTPClient result = null; String key = User.concat(Password); logger.debug("versuche vorhandenen FTPClient aus Liste zu lesen"); if (Clients != null) { if (Clients.containsKey(key)) { LinkedList ClientList = (LinkedList) Clients.get(key); if (!ClientList.isEmpty()) do { result = (FTPClient) ClientList.getLast(); logger.debug("-- hole einen Client aus der Liste: " + result.toString()); ClientList.removeLast(); if (!result.isConnected()) { logger.debug("---- nicht mehr verbunden."); result = null; } else { try { result.changeWorkingDirectory("/"); } catch (IOException e) { logger.debug("---- schmei�t Exception bei Zugriff."); result = null; } } } while (result == null && !ClientList.isEmpty()); if (ClientList.isEmpty()) { Clients.remove(key); } } else { } } else logger.debug("-- keine Liste vorhanden."); if (result == null) { logger.debug("Kein FTPCLient verf�gbar, erstelle einen neuen."); result = new FTPClient(); logger.debug("-- Versuche Connect"); result.connect(Host); logger.debug("-- Versuche Login"); result.login(User, Password); result.setFileType(FTPClient.BINARY_FILE_TYPE); if (counter == maxClients - 1) { RemoveBufferedClient(); } } logger.debug("OK: neuer FTPClient ist " + result.toString()); ; counter++; if (logger.isDebugEnabled()) { logger.debug("getFTPClient(String, String) - end"); } return result; } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static boolean copyFile(String src, String dst) { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(new File(src)).getChannel(); outChannel = new FileOutputStream(new File(dst)).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (FileNotFoundException e) { e.printStackTrace(); MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst); return false; } catch (IOException e) { MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst); return false; } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } catch (IOException e) { MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst); return false; } } return true; } |
00
| Code Sample 1:
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(); } }
Code Sample 2:
@Override protected HttpResponse<HttpURLConnection> execute(HttpRequest<HttpURLConnection> con) throws HttpRequestException { HttpURLConnection unwrap = con.unwrap(); try { unwrap.connect(); } catch (IOException e) { throw new HttpRequestException(e); } return new UrlHttpResponse(unwrap); } |
11
| Code Sample 1:
private void retrieveData() { StringBuffer obsBuf = new StringBuffer(); try { URL url = new URL(getProperty("sourceURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String lineIn = null; while ((lineIn = in.readLine()) != null) { if (GlobalProps.DEBUG) { logger.log(Level.FINE, "WebSource retrieveData: " + lineIn); } obsBuf.append(lineIn); } String fmt = getProperty("dataFormat"); if (GlobalProps.DEBUG) { logger.log(Level.FINE, "Raw: " + obsBuf.toString()); } if ("NWS XML".equals(fmt)) { obs = new NWSXmlObservation(obsBuf.toString()); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't connect to: " + getProperty("sourceURL")); if (GlobalProps.DEBUG) { e.printStackTrace(); } } }
Code Sample 2:
private void createPolicy(String policyName) throws SPLException { URL url = getClass().getResource(policyName + ".spl"); StringBuffer contents = new StringBuffer(); try { BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } input.close(); System.out.println(policyName); System.out.println(contents.toString()); boolean createReturn = jspl.createPolicy(policyName, contents.toString()); System.out.println("Policy Created : " + policyName + " - " + createReturn); System.out.println(""); } catch (IOException ex) { ex.printStackTrace(); } } |
11
| Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
private void saveFile(InputStream in, String fullPath) { try { File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(in, out); out.close(); } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public void loadLicenceText() { try { URL url = this.getClass().getResource("/licences/" + this.files[this.licence_text_id]); InputStreamReader ins = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(ins); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } this.licence_text = sb.toString(); } catch (Exception ex) { System.out.println("LicenceInfo::error reading. Ex: " + ex); ex.printStackTrace(); } }
Code Sample 2:
private String[] read(String path) throws Exception { final String[] names = { "index.txt", "", "index.html", "index.htm" }; String[] list = null; for (int i = 0; i < names.length; i++) { URL url = new URL(path + names[i]); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer sb = new StringBuffer(); String s = null; while ((s = in.readLine()) != null) { s = s.trim(); if (s.length() > 0) { sb.append(s + "\n"); } } in.close(); if (sb.indexOf("<") != -1 && sb.indexOf(">") != -1) { List links = LinkExtractor.scan(url, sb.toString()); HashSet set = new HashSet(); int prefixLen = path.length(); for (Iterator it = links.iterator(); it.hasNext(); ) { String link = it.next().toString(); if (!link.startsWith(path)) { continue; } link = link.substring(prefixLen); int idx = link.indexOf("/"); int idxq = link.indexOf("?"); if (idx > 0 && (idxq == -1 || idx < idxq)) { set.add(link.substring(0, idx + 1)); } else { set.add(link); } } list = (String[]) set.toArray(new String[0]); } else { list = sb.toString().split("\n"); } return list; } catch (FileNotFoundException e) { e.printStackTrace(); continue; } } return new String[0]; } |
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 saveZipComponents(ZipComponents zipComponents, File zipFile) throws FileNotFoundException, IOException, Exception { ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile)); for (ZipComponent comp : zipComponents.getComponents()) { ZipEntry newEntry = new ZipEntry(comp.getName()); zipOutStream.putNextEntry(newEntry); if (comp.isDirectory()) { } else { if (comp.getName().endsWith("document.xml") || comp.getName().endsWith("document.xml.rels")) { } InputStream inputStream = comp.getInputStream(); IOUtils.copy(inputStream, zipOutStream); inputStream.close(); } } zipOutStream.close(); } |
00
| Code Sample 1:
protected void shutdown(final boolean unexpected) { ControlerState oldState = this.state; this.state = ControlerState.Shutdown; if (oldState == ControlerState.Running) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } this.controlerListenerManager.fireControlerShutdownEvent(unexpected); if (this.dumpDataAtEnd) { Knowledges kk; if (this.config.scenario().isUseKnowledges()) { kk = (this.getScenario()).getKnowledges(); } else { kk = this.getScenario().retrieveNotEnabledKnowledges(); } new PopulationWriter(this.population, this.network, kk).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); ActivityFacilities facilities = this.getFacilities(); if (facilities != null) { new FacilitiesWriter((ActivityFacilitiesImpl) facilities).write(this.controlerIO.getOutputFilename("output_facilities.xml.gz")); } if (((NetworkFactoryImpl) this.network.getFactory()).isTimeVariant()) { new NetworkChangeEventsWriter().write(this.controlerIO.getOutputFilename("output_change_events.xml.gz"), ((NetworkImpl) this.network).getNetworkChangeEvents()); } if (this.config.scenario().isUseHouseholds()) { new HouseholdsWriterV10(this.scenarioData.getHouseholds()).writeFile(this.controlerIO.getOutputFilename(FILENAME_HOUSEHOLDS)); } if (this.config.scenario().isUseLanes()) { new LaneDefinitionsWriter20(this.scenarioData.getScenarioElement(LaneDefinitions20.class)).write(this.controlerIO.getOutputFilename(FILENAME_LANES)); } if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); } }
Code Sample 2:
@SuppressWarnings("unchecked") protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost) throws ServletException, IOException { HttpClient httpclient = WebReader.getHttpClient(); try { StringBuffer sb = new StringBuffer(); sb.append(targetServer); sb.append(req.getRequestURI()); if (req.getQueryString() != null) { sb.append("?" + req.getQueryString()); } HttpRequestBase targetRequest = null; if (isPost) { HttpPost post = new HttpPost(sb.toString()); Enumeration<String> paramNames = req.getParameterNames(); String paramName = null; List<NameValuePair> params = new ArrayList<NameValuePair>(); while (paramNames.hasMoreElements()) { paramName = paramNames.nextElement(); params.add(new BasicNameValuePair(paramName, req.getParameterValues(paramName)[0])); } post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); targetRequest = post; } else { System.out.println("GET"); HttpGet get = new HttpGet(sb.toString()); targetRequest = get; } HttpResponse targetResponse = httpclient.execute(targetRequest); HttpEntity entity = targetResponse.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); String line = reader.readLine(); while (line != null) { writer.write(line + "\n"); line = reader.readLine(); } reader.close(); writer.close(); } finally { WebReader.returnHttpClient(httpclient); } } |
11
| Code Sample 1:
public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } |
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:
public void deleteGroupInstruction(int id, int rank) throws FidoDatabaseException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from InstructionGroups " + "where InstructionId = " + id + " and Rank = " + rank; stmt.executeUpdate(sql); bumpAllRowsUp(stmt, id, rank); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } |
11
| Code Sample 1:
void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } }
Code Sample 2:
private static void doCopyFile(FileInputStream in, FileOutputStream out) { FileChannel inChannel = null, outChannel = null; try { inChannel = in.getChannel(); outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw ManagedIOException.manage(e); } finally { if (inChannel != null) { close(inChannel); } if (outChannel != null) { close(outChannel); } } } |
00
| Code Sample 1:
public static boolean isAnimated(Icon icon) { if (icon instanceof ImageIcon) { Image image = ((ImageIcon) icon).getImage(); if (image != null) { Object comment = image.getProperty("comment", null); if (String.valueOf(comment).startsWith("GifBuilder")) return true; if (decoded.containsKey(image)) { return Boolean.TRUE.equals(decoded.get(image)); } InputStream is = null; try { URL url = new URL(icon.toString()); is = url.openConnection().getInputStream(); } catch (Exception e) { e.printStackTrace(); } if (is == null) { try { ImageProducer p = image.getSource(); if (p instanceof InputStreamImageSource) { Method m = InputStreamImageSource.class.getDeclaredMethod("getDecoder", null); m.setAccessible(true); ImageDecoder d = (ImageDecoder) m.invoke(p, null); if (d instanceof GifImageDecoder) { GifImageDecoder gd = (GifImageDecoder) d; Field input = ImageDecoder.class.getDeclaredField("input"); input.setAccessible(true); is = (InputStream) input.get(gd); } } } catch (Exception e) { e.printStackTrace(); } } if (is != null) { GifDecoder decoder = new GifDecoder(); decoder.read(is); boolean animated = decoder.getFrameCount() > 1; decoded.put(image, Boolean.valueOf(animated)); return animated; } } return false; } return icon instanceof AnimatedIcon; }
Code Sample 2:
public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } |
00
| Code Sample 1:
public void testStorageByteArray() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { OutputStream output = r.getOutputStream(); output.write("This is an example".getBytes("UTF-8")); output.write(" and another one.".getBytes("UTF-8")); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and even more."); assertEquals("This is an example and another one. and another line and write some more and even more.", r.getText()); } assertFalse(r.hasEnded()); r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
Code Sample 2:
public static String analyze(List<String> stackLines) { final MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } final Iterator<String> iterator = stackLines.iterator(); if (!iterator.hasNext()) { return null; } try { final String messageLine = iterator.next(); final String exceptionClass = getExceptionClass(messageLine); messageDigest.update(exceptionClass.getBytes("UTF-8")); analyze(exceptionClass, iterator, messageDigest); final byte[] bytes = messageDigest.digest(); final BigInteger bigInt = new BigInteger(1, bytes); final String ret = bigInt.toString(36); return ret; } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } } |
00
| Code Sample 1:
private void announce(String trackerURL, byte[] hash, byte[] peerId, int port) { try { String strUrl = trackerURL + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&peer_id=" + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&port=" + port + "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1"; URL url = new URL(strUrl); URLConnection con = url.openConnection(); con.connect(); con.getContent(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void beforeMethod(TestBase testBase) throws IOException { TFileFactory fileFactory = new TFileFactory(new InMemoryFileSystem()); ftpServer.cleanFileSystem(fileFactory); TDirectory rootDir = fileFactory.dir("/"); testBase.inject(rootDir); FTPClient ftpClient = new FTPClient(); ftpClient.connect("localhost", 8021); ftpClient.login("anonymous", "[email protected]"); testBase.inject(ftpClient); } |
11
| Code Sample 1:
public void insertQuotation(final String sText, final Source aSource) throws ConfigHandlerError, com.sun.star.uno.Exception { final XTextDocument xTextDocument = (XTextDocument) this.docController.getXInterface(XTextDocument.class, this.docController.getXFrame().getController().getModel()); final XMultiServiceFactory xMultiServiceFactory = (XMultiServiceFactory) this.docController.getXInterface(XMultiServiceFactory.class, xTextDocument); final XText xText = xTextDocument.getText(); final XTextViewCursor xTextViewCursor = ((XTextViewCursorSupplier) this.docController.getXInterface(XTextViewCursorSupplier.class, this.docController.getXFrame().getController())).getViewCursor(); final XTextRange xTextRange = xTextViewCursor.getStart(); if (aSource.getSourceType() == SourceType.QUOTE || aSource.getSourceType() == SourceType.WEBQUOTE || aSource.getSourceType() == SourceType.WEBQUOTE) { final XPropertySet xQuoteProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xTextViewCursor); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String("Quotations")); } xQuoteProps.setPropertyValue("CharStyleName", new String("Citation")); final Object aBookmark = xMultiServiceFactory.createInstance("com.sun.star.text.Bookmark"); this.sourceUtils.setNameToObject(aBookmark, this.docController.getLanguageController().__("Quote: ") + aSource.getShortinfo()); final XTextContent xTextContent = (XTextContent) this.docController.getXInterface(XTextContent.class, aBookmark); xText.insertTextContent(xTextRange, xTextContent, false); this.sourceUtils.insertBibliographyEntry(xMultiServiceFactory, xTextRange, aSource, sText); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String(this.docController.getLanguageController().__("Default"))); } xQuoteProps.setPropertyValue("CharStyleName", new String(this.docController.getLanguageController().__("Default"))); } else if (aSource.getSourceType() == SourceType.IMAGE || aSource.getSourceType() == SourceType.TABLE) { xText.insertControlCharacter(xTextRange, ControlCharacter.PARAGRAPH_BREAK, false); final XTextFrame xFrame = this.sourceUtils.getTextFrame(aSource.getShortinfo(), xMultiServiceFactory); xText.insertTextContent(xTextRange, xFrame, false); final XText xFrameText = xFrame.getText(); final XTextCursor xFrameCursor = xFrameText.createTextCursor(); final Size aNewSize = new Size(); XPropertySet xBaseFrameProps = null; final Size aPageTextAreaSize = this.sourceUtils.getPageTextAreaSize(xTextDocument, xTextViewCursor); if (aSource.getSourceType() == SourceType.IMAGE) { try { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption illustration: ") + aSource.getShortinfo()); final XNameContainer xBitmapContainer = (XNameContainer) this.docController.getXInterface(XNameContainer.class, xMultiServiceFactory.createInstance("com.sun.star.drawing.BitmapTable")); final XTextContent xImage = (XTextContent) this.docController.getXInterface(XTextContent.class, xMultiServiceFactory.createInstance("com.sun.star.text.TextGraphicObject")); this.sourceUtils.setNameToObject(xImage, this.docController.getLanguageController().__("Illustration: ") + aSource.getShortinfo()); final String graphicURL = this.docController.getPathUtils().getFileURLFromSystemPath(((Image) aSource).getFile().getPath(), ((Image) aSource).getFile().getPath()); xBaseFrameProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xImage); xBaseFrameProps.setPropertyValue("AnchorType", com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH); xBaseFrameProps.setPropertyValue("GraphicURL", graphicURL); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(graphicURL.getBytes(), 0, graphicURL.length()); final String internalName = new BigInteger(1, md.digest()).toString(16); xBitmapContainer.insertByName(internalName, graphicURL); final String internalURL = (String) (xBitmapContainer.getByName(internalName)); xBaseFrameProps.setPropertyValue("GraphicURL", internalURL); float imageRatio = (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height / (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width; final Size aUsedAreaSize = new Size(this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width * 26, this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height * 26); if (aUsedAreaSize.Width >= aPageTextAreaSize.Width) { aNewSize.Width = aPageTextAreaSize.Width; aNewSize.Height = (int) (aPageTextAreaSize.Width * imageRatio); } else { aNewSize.Width = aUsedAreaSize.Width; aNewSize.Height = aUsedAreaSize.Height; } xFrameText.insertTextContent(xFrameCursor, xImage, false); xBitmapContainer.removeByName(internalName); } catch (final NoSuchAlgorithmException e) { new ASTError(e).severe(); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Illustration"), xMultiServiceFactory); } else if (aSource.getSourceType() == SourceType.TABLE) { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption table: ") + aSource.getShortinfo()); xBaseFrameProps = this.sourceUtils.createTextEmbeddedObjectCalc(xMultiServiceFactory); this.sourceUtils.setNameToObject(xBaseFrameProps, this.docController.getLanguageController().__("Table: ") + aSource.getShortinfo()); xFrameText.insertTextContent(xFrameCursor, (XTextContent) this.docController.getXInterface(XTextContent.class, xBaseFrameProps), false); final XEmbeddedObjectSupplier2 xEmbeddedObjectSupplier = (XEmbeddedObjectSupplier2) this.docController.getXInterface(XEmbeddedObjectSupplier2.class, xBaseFrameProps); final XEmbeddedObject xEmbeddedObject = xEmbeddedObjectSupplier.getExtendedControlOverEmbeddedObject(); long nAspect = xEmbeddedObjectSupplier.getAspect(); final Size aVisualAreaSize = xEmbeddedObject.getVisualAreaSize(nAspect); final XComponent xComponent = xEmbeddedObjectSupplier.getEmbeddedObject(); XSpreadsheets xSpreadsheets = ((XSpreadsheetDocument) this.docController.getXInterface(XSpreadsheetDocument.class, xComponent)).getSheets(); final XIndexAccess xIndexAccess = (XIndexAccess) this.docController.getXInterface(XIndexAccess.class, xSpreadsheets); final XSpreadsheet xSpreadsheet = (XSpreadsheet) this.docController.getXInterface(XSpreadsheet.class, xIndexAccess.getByIndex(0)); final XSheetLinkable xSheetLinkable = (XSheetLinkable) this.docController.getXInterface(XSheetLinkable.class, xSpreadsheet); xSheetLinkable.link(this.docController.getPathUtils().getFileURLFromSystemPath(((Table) aSource).getFile().getPath(), ((Table) aSource).getFile().getPath()), "", "", "", com.sun.star.sheet.SheetLinkMode.NORMAL); final CellRangeAddress aUsedArea = this.sourceUtils.getUsedArea(xSpreadsheet); final Size aUsedAreaSize = this.sourceUtils.calcCellRangeSize(xSpreadsheets, aUsedArea); if ((aUsedAreaSize.Width != aVisualAreaSize.Width) || (aUsedAreaSize.Height != aVisualAreaSize.Height)) { aNewSize.Height = (aUsedAreaSize.Height > aPageTextAreaSize.Height) ? aPageTextAreaSize.Height : aUsedAreaSize.Height; aNewSize.Width = (aUsedAreaSize.Width > aPageTextAreaSize.Width) ? aPageTextAreaSize.Width : aUsedAreaSize.Width; xEmbeddedObject.setVisualAreaSize(nAspect, aNewSize); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Table"), xMultiServiceFactory); } xBaseFrameProps.setPropertyValue("Width", aNewSize.Width); xBaseFrameProps.setPropertyValue("Height", aNewSize.Height); final XShape xShape = (XShape) this.docController.getXInterface(XShape.class, xFrame); xShape.setSize(aNewSize); } final XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier) this.docController.getXInterface(XTextFieldsSupplier.class, xMultiServiceFactory); final XRefreshable xRefreshable = (XRefreshable) this.docController.getXInterface(XRefreshable.class, xTextFieldsSupplier.getTextFields()); xRefreshable.refresh(); }
Code Sample 2:
public boolean authenticate(String userName, String loginPassword) { if (!systemConfigManager.getBool("ldap", "authEnable")) { return false; } String ldapName = userName; AkteraUser user = userDAO.findUserByName(userName); if (user != null && StringTools.isNotTrimEmpty(user.getLdapName())) { ldapName = user.getLdapName(); } String server = systemConfigManager.getString("ldap", "authHost"); if (StringTools.isTrimEmpty(server)) { return false; } int port = NumberTools.toInt(systemConfigManager.get("ldap", "authPort"), 389); String type = StringTools.trim(systemConfigManager.getString("ldap", "authType")); String baseDn = StringTools.trim(systemConfigManager.getString("ldap", "authBaseDn")); String userDn = StringTools.trim(systemConfigManager.getString("ldap", "authUserDn")); String password = StringTools.trim(systemConfigManager.getString("ldap", "authPassword")); String query = StringTools.trim(systemConfigManager.getString("ldap", "authQuery")); String bindDn = StringTools.trim(systemConfigManager.getString("ldap", "authBindDn")); String passwordAttributeName = StringTools.trim(systemConfigManager.getString("ldap", "authPasswordAttributeName")); Map<String, Object> params = new HashMap<String, Object>(); params.put("userName", userName); params.put("ldapName", ldapName); params.put("loginName", StringTools.isTrimEmpty(ldapName) ? userName : ldapName); query = StringTools.replaceTemplate(query, params); bindDn = StringTools.replaceTemplate(bindDn, params); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port + "/" + baseDn); env.put(Context.SECURITY_AUTHENTICATION, "simple"); if ("ldapAuthBind".equals(type)) { env.put(Context.SECURITY_PRINCIPAL, bindDn); env.put(Context.SECURITY_CREDENTIALS, loginPassword); try { DirContext ctx = new InitialDirContext(env); try { ctx.close(); } catch (Exception ignored) { } return true; } catch (Exception ignored) { return false; } } if (StringTools.isTrimEmpty(userDn) || StringTools.isTrimEmpty(password)) { return false; } env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = null; NamingEnumeration<SearchResult> results = null; try { ctx = new InitialDirContext(env); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", query, controls); if (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); if (attributes.get(passwordAttributeName) == null) { return false; } String pass = new String((byte[]) attributes.get(passwordAttributeName).get()); if (pass.startsWith("{SHA}") || pass.startsWith("{MD5}")) { String method = pass.substring(1, pass.indexOf('}')); MessageDigest digest = MessageDigest.getInstance(method); digest.update(loginPassword.getBytes(), 0, loginPassword.length()); if (pass.equals("{" + method + "}" + Base64.encode(digest.digest()))) { return true; } } else { if (pass.equals(loginPassword)) { return true; } } } } catch (Exception x) { } finally { if (results != null) { try { results.close(); } catch (Exception e) { } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { } } } return false; } |
11
| Code Sample 1:
private static String encryptSHA1URL(String x) throws Exception { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); String passwd = ""; passwd = URLEncoder.encode(new String(d.digest()), "ISO-8859-1"); return passwd; }
Code Sample 2:
public void createMd5Hash() { try { String vcardObject = new ContactToVcard(TimeZone.getTimeZone("UTC"), "UTF-8").convert(this); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(vcardObject.getBytes()); this.md5Hash = new BigInteger(m.digest()).toString(); if (log.isTraceEnabled()) { log.trace("Hash is:" + this.md5Hash); } } catch (ConverterException ex) { log.error("Error creating hash:" + ex.getMessage()); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { log.error("Error creating hash:" + noSuchAlgorithmException.getMessage()); } } |
11
| Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } }
Code Sample 2:
public void actionPerformed(ActionEvent e) { int returnVal = chooser.showSaveDialog(jd); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String fileName = file.getPath(); String ext = StringUtil.getLowerExtension(fileName); if (!"png".equals(ext)) { fileName += ".png"; file = new File(fileName); } boolean doIt = true; if (file.exists()) { int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist")); if (i != JOptionPane.YES_OPTION) doIt = false; } else if (!file.getParentFile().exists()) { doIt = file.getParentFile().mkdirs(); } if (doIt) { FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(imageURL.getPath()).getChannel(); dest = new FileOutputStream(fileName).getChannel(); src.transferTo(0, src.size(), dest); } catch (FileNotFoundException e1) { warn(jd, getMessage("err_no_source_file")); } catch (IOException e2) { warn(jd, getMessage("err_output_target")); } finally { try { if (src != null) src.close(); } catch (IOException e1) { } try { if (dest != null) dest.close(); } catch (IOException e1) { } src = null; dest = null; } } } } |
00
| Code Sample 1:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String servletPath = req.getServletPath(); String requestURI = req.getRequestURI(); String resource = requestURI.substring(requestURI.indexOf(servletPath) + servletPath.length()); URL url = ClassResource.get(resourceDirectory + resource); try { File file = null; JarEntry jarEntry = null; JarFile jarFile = null; if (!url.toExternalForm().startsWith("jar:")) { file = new File(url.toURI()); } else { jarFile = ((JarURLConnection) url.openConnection()).getJarFile(); String[] jarURL = url.toExternalForm().split("!"); jarEntry = jarFile.getJarEntry(jarURL[1].substring(1)); } if (file != null && file.isDirectory()) { PrintWriter writer = resp.getWriter(); resp.setContentType("text/html"); DevelUtils.writePageBegin(writer); DevelUtils.writeTitleAndHeaderEnd(writer, "Makumba resources"); if (SourceViewServlet.redirected(req, resp, servletPath)) { return; } String relativeDirectory = file.getName(); if (file.getAbsolutePath().indexOf(resourceDirectory) != -1) { relativeDirectory = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf(resourceDirectory)); } SourceViewServlet.printDirlistingHeader(writer, file.getCanonicalPath(), relativeDirectory); if (!(relativeDirectory.equals(resourceDirectory))) { writer.println("<b><a href=\"../\">../</a></b> (up one level)"); } SourceViewServlet.processDirectory(writer, file, null); String[] list = file.list(); Arrays.sort(list); for (int i = 0; i < list.length; i++) { String s = list[i]; File f = new File(file.getAbsolutePath() + File.separator + s); if (f.isFile()) { writer.println("<b><a href=\"" + s + "\">" + s + "</a></b>"); } } writer.println("</pre>"); DevelUtils.writePageEnd(writer); resp.setHeader("Last-Modified", dfLastModified.format(new Date())); return; } else if (jarEntry != null && jarEntry.isDirectory()) { Enumeration<JarEntry> entries = jarFile.entries(); ArrayList<String> files = new ArrayList<String>(); ArrayList<String> directories = new ArrayList<String>(); PrintWriter writer = resp.getWriter(); resp.setContentType("text/html"); DevelUtils.writePageBegin(writer); DevelUtils.writeTitleAndHeaderEnd(writer, "Makumba resources"); if (SourceViewServlet.redirected(req, resp, servletPath)) { return; } String relativeDirectory = jarEntry.getName(); SourceViewServlet.printDirlistingHeader(writer, url.toExternalForm(), relativeDirectory); if (!relativeDirectory.equals(resourceDirectory) && !relativeDirectory.equals(resourceDirectory + "/")) { writer.println("<b><a href=\"../\">../</a></b> (up one level)"); } while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); if (entry.getName().startsWith(relativeDirectory)) { String s = entry.getName().substring(relativeDirectory.length()); while (s.length() > 0 && s.startsWith("/")) { s = s.substring(1); } if (s.indexOf("/") == -1) { if (s.length() > 0) { files.add(s); } } else if (s.indexOf("/") == s.lastIndexOf("/") && s.endsWith("/")) { if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); } if (s.length() > 0) { directories.add(s); } } } } for (String string : directories) { writer.println("<b><a href=\"" + string + "/\">" + string + "/</a></b>"); } for (String string : files) { writer.println("<b><a href=\"" + string + "\">" + string + "</a></b>"); } writer.println("</pre>"); DevelUtils.writePageEnd(writer); resp.setHeader("Last-Modified", dfLastModified.format(new Date())); return; } else { final Date lastModified; if (url.toExternalForm().startsWith("jar:")) { JarFile jf = ((JarURLConnection) url.openConnection()).getJarFile(); String[] jarURL = url.toExternalForm().split("!"); lastModified = new Date(jf.getJarEntry(jarURL[1].substring(1)).getTime()); } else { lastModified = new Date(new File(url.toURI()).lastModified()); } resp.setHeader("Last-Modified", dfLastModified.format(lastModified)); resp.setContentType(getContentType(url)); Object cachedResource = NamedResources.getStaticCache(makumbaResources).getResource(resource); ServletOutputStream outputStream = resp.getOutputStream(); if (isBinary(url)) { for (int i = 0; i < ((byte[]) cachedResource).length; i++) { outputStream.write(((byte[]) cachedResource)[i]); } } else { outputStream.print(cachedResource.toString()); } } } catch (URISyntaxException e) { e.printStackTrace(); } }
Code Sample 2:
public void serveResource(HTTPResource resource, HttpServletRequest request, HttpServletResponse response) throws IOException { JavaScriptResource jsr = (JavaScriptResource) resource; response.setContentType("text/javascript"); if (jsr.getScriptText() != null) { PrintWriter pw = response.getWriter(); pw.println(jsr.getScriptText()); } else if (jsr.getResourceName() != null) { URL url = ClassLoaderUtil.getResource(jsr.getResourceName()); IOUtil.copyData(response.getOutputStream(), url.openStream()); } else { throw new IOException("No Javascript to Serve"); } } |
00
| Code Sample 1:
public static void main(String[] arg) throws IOException { XmlPullParserFactory PULL_PARSER_FACTORY; try { PULL_PARSER_FACTORY = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); PULL_PARSER_FACTORY.setNamespaceAware(true); DasParser dp = new DasParser(PULL_PARSER_FACTORY); URL url = new URL("http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/features?segment=P05067"); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String aLine, xml = ""; while ((aLine = br.readLine()) != null) { xml += aLine; } WritebackDocument wbd = dp.parse(xml); System.out.println("FIN" + wbd); } catch (XmlPullParserException xppe) { throw new IllegalStateException("Fatal Exception thrown at initialisation. Cannot initialise the PullParserFactory required to allow generation of the DAS XML.", xppe); } }
Code Sample 2:
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.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } |
00
| Code Sample 1:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
Code Sample 2:
public static String calculateHash(String data, String algorithm) { if (data == null) { return null; } algorithm = (algorithm == null ? INTERNAL : algorithm.toUpperCase()); if (algorithm.equals(PLAIN)) { return data; } if (algorithm.startsWith("{RSA}")) { return encode(data, algorithm.substring(5), "RSA"); } try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data.getBytes("UTF-8")); return getHashString(md.digest()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { logger.error(nsae.getMessage()); return null; } } |
11
| Code Sample 1:
private String getCoded(String pass) { String passSecret = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(pass.getBytes("UTF8")); byte s[] = m.digest(); for (int i = 0; i < s.length; i++) { passSecret += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return passSecret; }
Code Sample 2:
public static String generateDigest(String password, String saltHex, String alg) { try { MessageDigest sha = MessageDigest.getInstance(alg); byte[] salt = new byte[0]; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (alg.startsWith("SHA")) { label = (salt.length <= 0) ? "{SHA}" : "{SSHA}"; } else if (alg.startsWith("MD5")) { label = (salt.length <= 0) ? "{MD5}" : "{SMD5}"; } sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray()); return digest.toString(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } } |
11
| Code Sample 1:
static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } }
Code Sample 2:
public boolean restore() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/Android/bluebox.bak"; String backupDBPath = "/data/android.bluebox/databases/bluebox.db"; File currentDB = new File(sd, currentDBPath); File backupDB = new File(data, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } |
00
| Code Sample 1:
private boolean sendMsg(TACMessage msg) { try { String msgStr = msg.getMessageString(); URLConnection conn = url.openConnection(); conn.setRequestProperty("Content-Length", "" + msgStr.length()); conn.setDoOutput(true); OutputStream output = conn.getOutputStream(); output.write(msgStr.getBytes()); output.flush(); InputStream input = conn.getInputStream(); int len = conn.getContentLength(); int totalRead = 0; int read; byte[] content = new byte[len]; while ((len > totalRead) && (read = input.read(content, totalRead, len - totalRead)) > 0) { totalRead += read; } output.close(); input.close(); if (len < totalRead) { log.severe("truncated message response for " + msg.getType()); return false; } else { msgStr = new String(content); msg.setReceivedMessage(msgStr); msg.deliverMessage(); } return true; } catch (Exception e) { log.log(Level.SEVERE, "could not send message", e); return false; } }
Code Sample 2:
public void testHttpsConnection() { try { URL url = new URL("https://addons.mozilla.org/zh-CN/firefox/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.getOutputStream().write("hello".getBytes()); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName); Iterator<LDAPModification> it = mods.iterator(); String sql = "UPDATE " + this.tableName + " SET "; while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() != LDAPModification.REPLACE) { throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, ""); } sql += ldap2db.get(mod.getAttribute().getName()) + "=? "; } sql += " WHERE " + this.rdnField + "=?"; PreparedStatement ps = con.prepareStatement(sql); it = mods.iterator(); int i = 1; while (it.hasNext()) { LDAPModification mod = it.next(); ps.setString(i, mod.getAttribute().getStringValue()); i++; } String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); ps.setString(i, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
Code Sample 2:
public URLConnection makeURLConnection(String server) throws IOException { if (server == null) { connection = null; } else { URL url = new URL("http://" + server + "/Bob/QueryXindice"); connection = url.openConnection(); connection.setDoOutput(true); } return connection; } |
00
| Code Sample 1:
public String encrypt(String password) { if (password.length() == 40) { return password; } if (salt != null) { password = password + salt; } MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e.getMessage(), e); } messageDigest.reset(); messageDigest.update(password.getBytes()); final byte[] bytes = messageDigest.digest(); String encrypted = new BigInteger(1, bytes).toString(16); if (encrypted.length() < 40) { final StringBuilder builder = new StringBuilder(encrypted); while (builder.length() < 40) { builder.insert(0, '0'); } encrypted = builder.toString(); } return encrypted; }
Code Sample 2:
public void testStorageString() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", r.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); try { r.getOutputStream(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } try { r.getWriter(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); } |
11
| Code Sample 1:
private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; }
Code Sample 2:
public void run() { try { File outDir = new File(outDirTextField.getText()); if (!outDir.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen directory does not exist!", "Directory Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.isDirectory()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen file is not a directory!", "Not a Directory Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.canWrite()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Cannot write to the chosen directory!", "Directory Not Writeable Error", JOptionPane.ERROR_MESSAGE); } }); return; } File archiveDir = new File("foo.bar").getAbsoluteFile().getParentFile(); URL baseUrl = UnpackWizard.class.getClassLoader().getResource(UnpackWizard.class.getName().replaceAll("\\.", "/") + ".class"); if (baseUrl.getProtocol().equals("jar")) { String jarPath = baseUrl.getPath(); jarPath = jarPath.substring(0, jarPath.indexOf('!')); if (jarPath.startsWith("file:")) { try { archiveDir = new File(new URI(jarPath)).getAbsoluteFile().getParentFile(); } catch (URISyntaxException e1) { e1.printStackTrace(System.err); } } } SortedMap<Integer, String> inputFileNames = new TreeMap<Integer, String>(); for (Entry<Object, Object> anEntry : indexProperties.entrySet()) { String key = anEntry.getKey().toString(); if (key.startsWith("archive file ")) { inputFileNames.put(Integer.parseInt(key.substring("archive file ".length())), anEntry.getValue().toString()); } } byte[] buff = new byte[64 * 1024]; try { long bytesToWrite = 0; long bytesReported = 0; long bytesWritten = 0; for (String aFileName : inputFileNames.values()) { File aFile = new File(archiveDir, aFileName); if (aFile.exists()) { if (aFile.isFile()) { bytesToWrite += aFile.length(); } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" is not a standard file!", "Non Standard File Error", JOptionPane.ERROR_MESSAGE); } }); return; } } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" does not exist!", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } } MultiFileInputStream mfis = new MultiFileInputStream(archiveDir, inputFileNames.values().toArray(new String[inputFileNames.size()])); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(mfis)); TarArchiveEntry tarEntry = tis.getNextTarEntry(); while (tarEntry != null) { File outFile = new File(outDir.getAbsolutePath() + "/" + tarEntry.getName()); if (outFile.exists()) { final File wrongFile = outFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Was about to write out file \"" + wrongFile.getAbsolutePath() + "\" but it already " + "exists.\nPlease [re]move existing files out of the way " + "and try again.", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (tarEntry.isDirectory()) { outFile.getAbsoluteFile().mkdirs(); } else { outFile.getAbsoluteFile().getParentFile().mkdirs(); OutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); int len = tis.read(buff, 0, buff.length); while (len != -1) { os.write(buff, 0, len); bytesWritten += len; if (bytesWritten - bytesReported > (10 * 1024 * 1024)) { bytesReported = bytesWritten; final int progress = (int) (bytesReported * 100 / bytesToWrite); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(progress); } }); } len = tis.read(buff, 0, buff.length); } os.close(); } tarEntry = tis.getNextTarEntry(); } long expectedCrc = 0; try { expectedCrc = Long.parseLong(indexProperties.getProperty("CRC32", "0")); } catch (NumberFormatException e) { System.err.println("Error while obtaining the expected CRC"); e.printStackTrace(System.err); } if (mfis.getCRC() == expectedCrc) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Extraction completed successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE); } }); return; } else { System.err.println("CRC Error: was expecting " + expectedCrc + " but got " + mfis.getCRC()); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "CRC Error: the data extracted does not have the expected CRC!\n" + "You should probably delete the extracted files, as they are " + "likely to be invalid.", "CRC Error", JOptionPane.ERROR_MESSAGE); } }); return; } } catch (final IOException e) { e.printStackTrace(System.err); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Input/Output Error: " + e.getLocalizedMessage(), "Input/Output Error", JOptionPane.ERROR_MESSAGE); } }); return; } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); setEnabled(true); } }); } } |
11
| Code Sample 1:
@TestTargets({ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies that the ObjectInputStream constructor calls checkPermission on security manager.", method = "ObjectInputStream", args = { InputStream.class }) }) public void test_ObjectInputStream2() throws IOException { class TestSecurityManager extends SecurityManager { boolean called; Permission permission; void reset() { called = false; permission = null; } @Override public void checkPermission(Permission permission) { if (permission instanceof SerializablePermission) { called = true; this.permission = permission; } } } class TestObjectInputStream extends ObjectInputStream { TestObjectInputStream(InputStream s) throws StreamCorruptedException, IOException { super(s); } } class TestObjectInputStream_readFields extends ObjectInputStream { TestObjectInputStream_readFields(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public GetField readFields() throws IOException, ClassNotFoundException, NotActiveException { return super.readFields(); } } class TestObjectInputStream_readUnshared extends ObjectInputStream { TestObjectInputStream_readUnshared(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public Object readUnshared() throws IOException, ClassNotFoundException { return super.readUnshared(); } } long id = new java.util.Date().getTime(); String filename = "SecurityPermissionsTest_" + id; File f = File.createTempFile(filename, null); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(new Node()); oos.flush(); oos.close(); f.deleteOnExit(); TestSecurityManager s = new TestSecurityManager(); System.setSecurityManager(s); s.reset(); new ObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream_readFields(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readFields", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); s.reset(); new TestObjectInputStream_readUnshared(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readUnshared", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); }
Code Sample 2:
public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } } |
00
| Code Sample 1:
public Leilao insertLeilao(Leilao leilao) throws SQLException { Connection conn = null; String insert = "insert into Leilao (idleilao, atividade_idatividade, datainicio, datafim) " + "values " + "(nextval('seq_leilao'), " + leilao.getAtividade().getIdAtividade() + ", '" + leilao.getDataInicio() + "', '" + leilao.getDataFim() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_leilao"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { leilao.setIdLeilao(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
Code Sample 2:
private InputStream loadSource(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); } |
00
| Code Sample 1:
public void end() throws Exception { handle.waitFor(); Calendar endTime = Calendar.getInstance(); File resultsDir = new File(runDir, "results"); if (!resultsDir.isDirectory()) throw new Exception("The results directory not found!"); String resHtml = null; String resTxt = null; String[] resultFiles = resultsDir.list(); for (String resultFile : resultFiles) { if (resultFile.indexOf("html") >= 0) resHtml = resultFile; else if (resultFile.indexOf("txt") >= 0) resTxt = resultFile; } if (resHtml == null) throw new IOException("SPECweb2005 output (html) file not found"); if (resTxt == null) throw new IOException("SPECweb2005 output (txt) file not found"); File resultHtml = new File(resultsDir, resHtml); copyFile(resultHtml.getAbsolutePath(), runDir + "SPECWeb-result.html", false); BufferedReader reader = new BufferedReader(new FileReader(new File(resultsDir, resTxt))); logger.fine("Text file: " + resultsDir + resTxt); Writer writer = new FileWriter(runDir + "summary.xml"); SummaryParser parser = new SummaryParser(getRunId(), startTime, endTime, logger); parser.convert(reader, writer); writer.close(); reader.close(); }
Code Sample 2:
public void cleanup(long timeout) throws PersisterException { long threshold = System.currentTimeMillis() - timeout; Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("delete from " + _table_name + " where " + _ts_col + " < ?"); ps.setLong(1, threshold); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to cleanup timed out objects: ", th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } } |
11
| Code Sample 1:
public synchronized void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CacheEntry entry = null; Tenant tenant = null; if (!tenantInfo.getTenants().isEmpty()) { tenant = tenantInfo.getMatchingTenant(request); if (tenant == null) { tenant = tenantInfo.getTenants().get(0); } entry = tenantToCacheEntry.get(tenant.getName()); } else { entry = cacheEntry; } if (entry == null) { File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); tempDir = new File(tempDir, "pustefix-sitemap-cache"); if (!tempDir.exists()) { tempDir.mkdirs(); } entry = new CacheEntry(); entry.file = new File(tempDir, "sitemap" + (tenant == null ? "" : "-" + tenant.getName()) + ".xml"); try { String host = AbstractPustefixRequestHandler.getServerName(request); Document doc = getSearchEngineSitemap(tenant, host); Transformer trf = TransformerFactory.newInstance().newTransformer(); trf.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream out = new FileOutputStream(entry.file); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException x) { throw new RuntimeException("Can't create message digest", x); } DigestOutputStream digestOutput = new DigestOutputStream(out, digest); trf.transform(new DOMSource(doc), new StreamResult(digestOutput)); digestOutput.close(); byte[] digestBytes = digest.digest(); entry.etag = MD5Utils.byteToHex(digestBytes); } catch (Exception x) { throw new ServletException("Error creating sitemap", x); } } String reqETag = request.getHeader("If-None-Match"); if (reqETag != null) { if (entry.etag.equals(reqETag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } long reqMod = request.getDateHeader("If-Modified-Since"); if (reqMod != -1) { if (entry.file.lastModified() < reqMod + 1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } response.setContentType("application/xml"); response.setContentLength((int) entry.file.length()); response.setDateHeader("Last-Modified", entry.file.lastModified()); response.setHeader("ETag", entry.etag); OutputStream out = new BufferedOutputStream(response.getOutputStream()); InputStream in = new FileInputStream(entry.file); int bytes_read; byte[] buffer = new byte[8]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.flush(); in.close(); out.close(); }
Code Sample 2:
public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); } |
11
| Code Sample 1:
public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; }
Code Sample 2:
public static void copy(final String source, final String dest) { final File s = new File(source); final File w = new File(dest); try { final FileInputStream in = new FileInputStream(s); final FileOutputStream out = new FileOutputStream(w); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } } |
00
| Code Sample 1:
public String getCipherString(String source) throws CadenaNoCifradaException { String encryptedSource = null; MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(source.getBytes(encoding), 0, source.length()); sha1hash = md.digest(); encryptedSource = convertToHex(sha1hash); } catch (Exception e) { throw new CadenaNoCifradaException(e); } return encryptedSource; }
Code Sample 2:
private Scanner getUrlScanner(String strUrl) { URL urlParticipants = null; Scanner scannerParticipants; try { urlParticipants = new URL(strUrl); URLConnection connParticipants; if (StringUtils.isBlank(this.configProxyIp)) { connParticipants = urlParticipants.openConnection(); } else { SocketAddress address = new InetSocketAddress(this.configProxyIp, this.configProxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connParticipants = urlParticipants.openConnection(proxy); } InputStream streamParticipant = connParticipants.getInputStream(); String charSet = StringUtils.substringAfterLast(connParticipants.getContentType(), "charset="); scannerParticipants = new Scanner(streamParticipant, charSet); } catch (MalformedURLException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "MalformedURLException"), new Object[] { urlParticipants.toString() })); } catch (IOException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "IOException"), new Object[] { urlParticipants.toString() })); } return scannerParticipants; } |
00
| Code Sample 1:
private void handleServerIntroduction(DataPacket serverPacket) { DataPacketIterator iter = serverPacket.getDataPacketIterator(); String version = iter.nextString(); int serverReportedUDPPort = iter.nextUByte2(); _authKey = iter.nextUByte4(); _introKey = iter.nextUByte4(); _clientKey = makeClientKey(_authKey, _introKey); String passwordKey = iter.nextString(); _logger.log(Level.INFO, "Connection to version " + version + " with udp port " + serverReportedUDPPort); DataPacket packet = null; if (initUDPSocketAndStartPacketReader(_tcpSocket.getInetAddress(), serverReportedUDPPort)) { ParameterBuilder builder = new ParameterBuilder(); builder.appendUByte2(_udpSocket.getLocalPort()); builder.appendString(_user); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ignore) { } md5.update(_serverKey.getBytes()); md5.update(passwordKey.getBytes()); md5.update(_password.getBytes()); for (byte b : md5.digest()) { builder.appendByte(b); } packet = new DataPacketImpl(ClientCommandConstants.INTRODUCTION, builder.toParameter()); } else { packet = new DataPacketImpl(ClientCommandConstants.TCP_ONLY); } sendTCPPacket(packet); }
Code Sample 2:
protected Boolean lancerincident(long idbloc, String Etatbloc, java.util.GregorianCalendar datebloc, long idServeur, String niveau, String message) { String codeerr; Boolean retour = false; Boolean SauvegardeEtatAutocommit; int etat; acgtools_core.AcgIO.SortieLog(new Date() + " - Appel de la fonction Lancer incident"); Statement statement = null; ResultSet resultat = null; String RequeteSQL = ""; acgtools_core.AcgIO.SortieLog(new Date() + " - nouvel incident pour le bloc : " + acgtools_core.AcgIO.RetourneDate(datebloc)); try { this.con = db.OpenConnection(); SauvegardeEtatAutocommit = this.con.getAutoCommit(); this.con.setAutoCommit(false); if (idbloc == 0) { idbloc = this.CreationBloc(idServeur); if (idbloc == 0) { retour = false; acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la création du bloc"); this.con.rollback(); this.con.close(); return false; } } acgtools_core.AcgIO.SortieLog(new Date() + " - bloc : " + idbloc); etat = this.ChargerEtatServeur(idbloc, datebloc); if (etat != 2) { statement = con.createStatement(); acgtools_core.AcgIO.SortieLog(new Date() + " - Etat chargé"); RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job ='" + idbloc + "' " + "AND incref_err_numer NOT IN " + "(SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_err_etat='c') " + "AND incref_err_numer NOT IN " + "(SELECT incenc_err_numer FROM tbl_incident_encours " + "WHERE incenc_err_etat='c') ;"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (!resultat.next()) { resultat.close(); RequeteSQL = "INSERT INTO tbl_incident_ref " + "(incref_cde_job,incref_err_date,incref_err_etat,incref_niv_crimd,incref_err_msg,incref_err_srvnm)" + "VALUES ('" + idbloc + "','" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','" + Etatbloc + "','" + niveau + "','" + message + "','" + idServeur + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job = '" + idbloc + "' " + "AND incref_err_srvnm = '" + idServeur + "' " + "AND incref_err_date = '" + acgtools_core.AcgIO.RetourneDate(datebloc) + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (resultat.next()) { codeerr = resultat.getString("incref_err_numer"); resultat.close(); RequeteSQL = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + message + "','" + niveau + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); acgtools_core.AcgIO.SortieLog(new Date() + " - Incident inséré dans la base de données"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, acgtools_core.AcgIO.RetourneDate(datebloc), message); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'historique"); this.CreerHistorique(codeerr); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(true); retour = true; } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Problème d'insertion du nouvel incident dans la base"); retour = false; } } else { codeerr = resultat.getString("incref_err_numer"); acgtools_core.AcgIO.SortieLog(new Date() + " - Numéro de l'erreur trouvé. Numéro =" + codeerr); RequeteSQL = "SELECT incenc_err_etat FROM tbl_incident_encours " + "WHERE incenc_err_numer='" + codeerr + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); resultat = statement.executeQuery(RequeteSQL); if (!resultat.next()) { resultat.close(); acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident."); String RequeteSQLInsert = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + "Incident non cloturé - " + message + "','" + niveau + "');"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQLInsert); statement.execute(RequeteSQLInsert); resultat = statement.executeQuery(RequeteSQL); } else { resultat = statement.executeQuery(RequeteSQL); acgtools_core.AcgIO.SortieLog(new Date() + " - Incident correctement positionné dans encours"); } if (resultat.next()) { switch(Etatbloc.charAt(0)) { case 'c': { acgtools_core.AcgIO.SortieLog(new Date() + " - Cloture de l'incident."); RequeteSQL = "UPDATE tbl_incident_ref SET incref_err_etat='c'" + "WHERE incref_err_numer='" + codeerr + "';"; acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL); statement.executeUpdate(RequeteSQL); this.UpdateEnCours(codeerr, "c", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } case 'm': { this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto"); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } default: { this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, ""); acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire"); this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc)); acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj"); this.CreerMaj(false); retour = true; break; } } } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident."); retour = false; } } } else { acgtools_core.AcgIO.SortieLog(new Date() + " - Systeme en maintenance, pas de remontée d'incidents."); retour = false; } } catch (ClassNotFoundException ex) { acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications."); con.rollback(); acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la connexion."); acgtools_core.AcgIO.SortieLog(ex.getMessage()); retour = false; } catch (SQLException ex) { acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications."); con.rollback(); acgtools_core.AcgIO.SortieLog(ex.getMessage()); acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la requète SQL :"); acgtools_core.AcgIO.SortieLog(RequeteSQL); retour = false; } finally { try { if (statement != null) { statement.close(); } if (retour) { con.commit(); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : succès"); } else { con.rollback(); acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : echec"); } if (con != null) { con.close(); } } catch (Exception e) { acgtools_core.AcgIO.SortieLog(new Date() + "Problème lors de la fermeture de la connection à la base de données"); } return retour; } } |
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:
static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } } |
00
| Code Sample 1:
public void echo(HttpRequest request, HttpResponse response) throws IOException { InputStream in = request.getInputStream(); if ("gzip".equals(request.getField("Content-Encoding"))) { in = new GZIPInputStream(in); } IOUtils.copy(in, response.getOutputStream()); }
Code Sample 2:
void download() throws DownloaderException { final HttpClient client = new DefaultHttpClient(); try { final FileOutputStream fos = this.activity.openFileOutput(APK_FILENAME, Context.MODE_WORLD_READABLE); final HttpResponse response = client.execute(new HttpGet(URL)); downloadFile(response, fos); fos.close(); } catch (ClientProtocolException e) { throw new DownloaderException(e); } catch (IOException e) { throw new DownloaderException(e); } } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void writeBack(File destinationFile, boolean makeCopy) throws IOException { if (makeCopy) { FileChannel sourceChannel = new java.io.FileInputStream(getFile()).getChannel(); FileChannel destinationChannel = new java.io.FileOutputStream(destinationFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } else { getFile().renameTo(destinationFile); } if (getExifTime() != null && getOriginalTime() != null && !getExifTime().equals(getOriginalTime())) { String adjustArgument = "-ts" + m_dfJhead.format(getExifTime()); ProcessBuilder pb = new ProcessBuilder(m_tm.getJheadCommand(), adjustArgument, destinationFile.getAbsolutePath()); pb.directory(destinationFile.getParentFile()); System.out.println(pb.command().get(0) + " " + pb.command().get(1) + " " + pb.command().get(2)); final Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } } |
11
| Code Sample 1:
private String fetchContent() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { buf.append(str); } return buf.toString(); }
Code Sample 2:
public static String read(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringWriter res = new StringWriter(); PrintWriter writer = new PrintWriter(new BufferedWriter(res)); String line; while ((line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); return res.toString(); } |
11
| Code Sample 1:
public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); }
Code Sample 2:
private static byte[] Md5f(String plainText) { byte[] ab = new byte[16]; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); ab = b; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ab; } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
private boolean copyFile(File inFile, File outFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(inFile)); writer = new BufferedWriter(new FileWriter(outFile)); while (reader.ready()) { writer.write(reader.read()); } writer.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); return false; } } if (writer != null) { try { writer.close(); } catch (IOException ex) { return false; } } } return true; }
Code Sample 2:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } |
11
| Code Sample 1:
private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } }
Code Sample 2:
public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); in.seek(0); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } |
00
| Code Sample 1:
protected Document fetchResource(String method, String parameter, Locale locale, final FloodLimit limit) throws IOException, SAXException { return getDocument(new CachedPage(getResourceLocation(method, parameter, locale)) { @Override protected Reader openConnection(URL url) throws IOException { try { if (limit != null) { limit.acquirePermit(); } return super.openConnection(url); } catch (InterruptedException e) { throw new IOException(e); } } ; }.get()); }
Code Sample 2:
public Dbf(URL url) throws java.io.IOException, DbfFileException { if (DEBUG) System.out.println("---->uk.ac.leeds.ccg.dbffile.Dbf constructed. Will identify itself as " + DBC); URLConnection uc = url.openConnection(); InputStream in = uc.getInputStream(); EndianDataInputStream sfile = new EndianDataInputStream(in); init(sfile); } |
00
| Code Sample 1:
public static void init() { if (init_) return; init_ = true; URLStreamHandler h = new URLStreamHandler() { protected URLConnection openConnection(URL _url) throws IOException { return new Connection(_url); } }; FuLib.setUrlHandler("data", h); }
Code Sample 2:
@Test public void testClient() throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpHost proxy = new HttpHost("127.0.0.1", 1280, "http"); HttpGet httpget = new HttpGet("http://a.b.c.d/pdn/"); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = response.getEntity().getContent(); readInputStream(is); System.out.println("----------------------------------------"); httpget.abort(); httpclient.getConnectionManager().shutdown(); } |
00
| Code Sample 1:
public RobotList<Location> sort_incr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value > enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; }
Code Sample 2:
private void downloadDirectory() throws SocketException, IOException { FTPClient client = new FTPClient(); client.connect(source.getHost()); client.login(username, password); FTPFile[] files = client.listFiles(source.getPath()); for (FTPFile file : files) { if (!file.isDirectory()) { long file_size = file.getSize() / 1024; Calendar cal = file.getTimestamp(); URL source_file = new File(source + file.getName()).toURI().toURL(); DownloadQueue.add(new Download(projectName, parser.getParserID(), source_file, file_size, cal, target + file.getName())); } } } |
11
| Code Sample 1:
protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); }
Code Sample 2:
private void channelCopy(File source, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } } |
00
| Code Sample 1:
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
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 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(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.