label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: @Override public InputStream getResourceStream(final String arg0) throws ResourceNotFoundException { try { final ServletContext context = CContext.getInstance().getContext(); final URL url = context.getResource(arg0); return url.openStream(); } catch (final Exception e) { return null; } } Code Sample 2: public static void doHttpPost(String urlName, byte[] data, String contentType, String cookieData) throws InteropException { URL url = getAccessURL(urlName); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", cookieData); connection.setRequestProperty("Content-type", contentType); connection.setRequestProperty("Content-length", "" + data.length); OutputStream stream = connection.getOutputStream(); stream.write(data); stream.flush(); stream.close(); connection.connect(); InputStream inputStream = connection.getInputStream(); inputStream.close(); } catch (IOException ex) { throw new InteropException("Error POSTing to " + urlName, ex); } }
11
Code Sample 1: public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest digest; digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(message.getBytes("iso-8859-1"), 0, message.length()); byte[] output = new byte[20]; digest.digest(output, 0, output.length); return convertToHex(output); } Code Sample 2: private void onDhReply(final SshDhReply msg) throws GeneralSecurityException, IOException { if ((this.keyPair == null) || this.connection.isServer()) throw new SshException("%s: unexpected %s", this.connection.uri, msg.getType()); final BigInteger k; { final DHPublicKeySpec remoteKeySpec = new DHPublicKeySpec(new BigInteger(msg.f), P1, G); final KeyFactory dhKeyFact = KeyFactory.getInstance("DH"); final DHPublicKey remotePubKey = (DHPublicKey) dhKeyFact.generatePublic(remoteKeySpec); final KeyAgreement dhKex = KeyAgreement.getInstance("DH"); dhKex.init(this.keyPair.getPrivate()); dhKex.doPhase(remotePubKey, true); k = new BigInteger(dhKex.generateSecret()); } final MessageDigest md = createMessageDigest(); final byte[] h; { updateByteArray(md, SshVersion.LOCAL.toString().getBytes()); updateByteArray(md, this.connection.getRemoteSshVersion().toString().getBytes()); updateByteArray(md, this.keyExchangeInitLocal.getPayload()); updateByteArray(md, this.keyExchangeInitRemote.getPayload()); updateByteArray(md, msg.hostKey); updateByteArray(md, ((DHPublicKey) this.keyPair.getPublic()).getY().toByteArray()); updateByteArray(md, msg.f); updateBigInt(md, k); h = md.digest(); } if (this.sessionId == null) this.sessionId = h; this.keyExchangeInitLocal = null; this.keyExchangeInitRemote = null; this.h = h; this.k = k; this.connection.send(new SshKeyExchangeNewKeys()); }
00
Code Sample 1: private static Document getDocument(URL url, String applicationVersion, boolean addHeader, int timeOut) throws IOException, ParserConfigurationException, SAXException { HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setConnectTimeout(1000 * timeOut); huc.setRequestMethod("GET"); if (addHeader) { huc.setRequestProperty("JavaPEG-Version", applicationVersion); } huc.connect(); int code = huc.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { throw new IOException("Invaild HTTP response: " + code); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse(huc.getInputStream()); } Code Sample 2: @Test public void GetBingSearchResult() throws UnsupportedEncodingException { String query = "Scanner Java example"; String request = "http://api.bing.net/xml.aspx?AppId=731DD1E61BE6DE4601A3008DC7A0EB379149EC29" + "&Version=2.2&Market=en-US&Query=" + URLEncoder.encode(query, "UTF-8") + "&Sources=web+spell&Web.Count=50"; try { URL url = new URL(request); System.out.println("Host : " + url.getHost()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String finalContents = ""; while ((inputLine = reader.readLine()) != null) { finalContents += "\n" + inputLine; } Document doc = Jsoup.parse(finalContents); Elements eles = doc.getElementsByTag("web:Url"); for (Element ele : eles) { System.out.println(ele.text()); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public void convert(String newDocumentName, URL url) throws IOException { documentPath = createDirectoryStructure(this.destinationPath, newDocumentName); try { Document doc = builder.build(url.openStream()); Element elementx = doc.getRootElement(); convertElement(elementx); System.out.println("\n\n"); XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat()); System.out.println("as file: " + url.getFile()); File inputFile = new File(url.getFile()); File outputFile = new File(documentPath, renameFileExtention(inputFile, "-remaining.xml")); System.out.println("outputFile: " + outputFile); outp.output(doc, new FileOutputStream(outputFile)); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static String getHash(String uri) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(uri.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); }
00
Code Sample 1: 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(); } Code Sample 2: protected InputStream openStreamInternal(String userAgent, Iterator mimeTypes, Iterator encodingTypes) throws IOException { if (stream != null) return stream; hasBeenOpened = true; URL url = null; try { url = buildURL(); } catch (MalformedURLException mue) { throw new IOException("Unable to make sense of URL for connection"); } if (url == null) return null; URLConnection urlC = url.openConnection(); if (urlC instanceof HttpURLConnection) { if (userAgent != null) urlC.setRequestProperty(HTTP_USER_AGENT_HEADER, userAgent); if (mimeTypes != null) { String acceptHeader = ""; while (mimeTypes.hasNext()) { acceptHeader += mimeTypes.next(); if (mimeTypes.hasNext()) acceptHeader += ","; } urlC.setRequestProperty(HTTP_ACCEPT_HEADER, acceptHeader); } if (encodingTypes != null) { String encodingHeader = ""; while (encodingTypes.hasNext()) { encodingHeader += encodingTypes.next(); if (encodingTypes.hasNext()) encodingHeader += ","; } urlC.setRequestProperty(HTTP_ACCEPT_ENCODING_HEADER, encodingHeader); } contentType = urlC.getContentType(); contentEncoding = urlC.getContentEncoding(); } return (stream = urlC.getInputStream()); }
00
Code Sample 1: public File copyLocalFileAsTempFileInExternallyAccessableDir(String localFileRef) throws IOException { log.debug("copyLocalFileAsTempFileInExternallyAccessableDir"); File f = this.createTempFileInExternallyAccessableDir(); FileChannel srcChannel = new FileInputStream(localFileRef).getChannel(); FileChannel dstChannel = new FileOutputStream(f).getChannel(); log.debug("before transferring via FileChannel from src-inputStream: " + localFileRef + " to dest-outputStream: " + f.getAbsolutePath()); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); log.debug("copyLocalFileAsTempFileInExternallyAccessableDir returning: " + f.getAbsolutePath()); return f; } Code Sample 2: public static XMLConfigurator loadFromDefaultSystemProperty() throws IOException { String urlStr = System.getProperty(DEFAULT_SYS_PROP_NAME); if (urlStr == null || urlStr.length() == 0) { return null; } InputStream in = null; DOMRetriever xmlDoc = null; try { URL url = new URL(urlStr); xmlDoc = new DOMRetriever(in = url.openStream()); } catch (MalformedURLException e) { throw new RuntimeException(e); } finally { if (in != null) in.close(); } return newInstance(xmlDoc); }
00
Code Sample 1: public boolean add(String url) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("POST"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.setRequestProperty(GameRecord.GAME_MESSAGE_HEADER, message); request.setRequestProperty(GameRecord.GAME_LATITUDE_HEADER, df.format(lat)); request.setRequestProperty(GameRecord.GAME_LONGITUDE_HEADER, df.format(lon)); request.setRequestProperty("Content-Length", "0"); request.connect(); if (request.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected response: " + request.getResponseCode() + " " + request.getResponseMessage()); } return true; } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
00
Code Sample 1: public void createNewFile(String filePath, InputStream in) throws IOException { FileOutputStream out = null; try { File file = newFileRef(filePath); FileHelper.createNewFile(file, true); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } Code Sample 2: private void addDocToDB(String action, DataSource database) { String typeOfDoc = findTypeOfDoc(action).trim().toLowerCase(); Connection con = null; try { con = database.getConnection(); con.setAutoCommit(false); checkDupDoc(typeOfDoc, con); String add = "insert into " + typeOfDoc + " values( ?, ?, ?, ?, ?, ?, ? )"; PreparedStatement prepStatement = con.prepareStatement(add); prepStatement.setString(1, selectedCourse.getCourseId()); prepStatement.setString(2, selectedCourse.getAdmin()); prepStatement.setTimestamp(3, getTimeStamp()); prepStatement.setString(4, getLink()); prepStatement.setString(5, homePage.getUser()); prepStatement.setString(6, getText()); prepStatement.setString(7, getTitle()); prepStatement.executeUpdate(); prepStatement.close(); con.commit(); } catch (Exception e) { sqlError = true; e.printStackTrace(); if (con != null) try { con.rollback(); } catch (Exception logOrIgnore) { } try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } finally { if (con != null) try { con.close(); } catch (Exception logOrIgnore) { } } }
11
Code Sample 1: private synchronized void persist() { Connection conn = null; try { PoolManager pm = PoolManager.getInstance(); conn = pm.getConnection(JukeXTrackStore.DB_NAME); conn.setAutoCommit(false); Statement state = conn.createStatement(); state.executeUpdate("DELETE FROM PlaylistEntry WHERE playlistid=" + this.id); if (this.size() > 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO PlaylistEntry ( playlistid , trackid , position ) VALUES "); int location = 0; Iterator i = ll.iterator(); while (i.hasNext()) { long currTrackID = ((DatabaseObject) i.next()).getId(); sql.append('(').append(this.id).append(',').append(currTrackID).append(',').append(location++).append(')'); if (i.hasNext()) sql.append(','); } state.executeUpdate(sql.toString()); } conn.commit(); conn.setAutoCommit(true); state.close(); } catch (SQLException se) { try { conn.rollback(); } catch (SQLException ignore) { } log.error("Encountered an error persisting a playlist", se); } finally { try { conn.close(); } catch (SQLException ignore) { } } } Code Sample 2: public void testPreparedStatement0009() throws Exception { Connection cx = getConnection(); dropTable("#t0009"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.commit(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); cx.commit(); cx.setAutoCommit(true); }
11
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public boolean load() { if (getFilename() != null && getFilename().length() > 0) { try { File file = new File(PreferencesManager.getDirectoryLocation("macros") + File.separator + getFilename()); URL url = file.toURL(); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); String macro_text = ""; while (line != null) { macro_text = macro_text.concat(line); line = br.readLine(); if (line != null) { macro_text = macro_text.concat(System.getProperty("line.separator")); } } code = macro_text; } catch (Exception e) { System.err.println("Exception at StoredMacro.load(): " + e.toString()); return false; } } return true; }
00
Code Sample 1: public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { throw new RuntimeException("Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("NoSuchAlgorithmException : " + e.getMessage()); } return digest; } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
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: protected String decrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PrivateKey pk = getPrivateKey(key); if (pk == null) { throw new CryptographicFailureException("PrivateKeyNotFound", String.format("Cannot find private key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes())); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(bout.toByteArray()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } }
00
Code Sample 1: public 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 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); }
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 String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
00
Code Sample 1: public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Tag"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } } Code Sample 2: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
00
Code Sample 1: public static String hash(String toEncripty) { if (toEncripty != null) { try { synchronized (toEncripty) { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncripty.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } toEncripty = hexString.toString(); } } catch (Exception e) { e.getMessage(); } } return toEncripty; } Code Sample 2: public void rename(String virtualWiki, String oldTopicName, String newTopicName) throws Exception { Connection conn = DatabaseConnection.getConnection(); try { boolean commit = false; conn.setAutoCommit(false); try { PreparedStatement pstm = conn.prepareStatement(STATEMENT_RENAME); try { pstm.setString(1, newTopicName); pstm.setString(2, oldTopicName); pstm.setString(3, virtualWiki); if (pstm.executeUpdate() == 0) throw new SQLException("Unable to rename topic " + oldTopicName + " on wiki " + virtualWiki); } finally { pstm.close(); } doUnlockTopic(conn, virtualWiki, oldTopicName); doRenameAllVersions(conn, virtualWiki, oldTopicName, newTopicName); commit = true; } finally { if (commit) conn.commit(); else conn.rollback(); } } finally { conn.close(); } }
11
Code Sample 1: private static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IOException("Destination file cannot be created: " + destFile.getPath()); } } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: protected void downgradeHistory(Collection<String> versions) { Assert.notEmpty(versions); try { Connection connection = this.database.getDefaultConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE " + this.logTableName + " SET RESULT = 'DOWNGRADED' WHERE TYPE = 'B' AND TARGET = ? AND RESULT = 'COMPLETE'"); boolean commit = false; try { for (String version : versions) { statement.setString(1, version); int modified = statement.executeUpdate(); Assert.isTrue(modified <= 1, "Expecting not more than 1 record to be updated, not " + modified); } commit = true; } finally { statement.close(); if (commit) connection.commit(); else connection.rollback(); } } catch (SQLException e) { throw new SystemException(e); } } Code Sample 2: public SCFFile(URL url) throws IOException { URLConnection connection = url.openConnection(); byte[] content = new byte[connection.getContentLength()]; DataInputStream dis = new DataInputStream(connection.getInputStream()); dis.readFully(content); dis.close(); dis = new DataInputStream(new ByteArrayInputStream(content)); header = new SCFHeader(dis); if (!header.magicNumber.equals(".scf")) throw new RuntimeException(url + " is not an SCF file"); A = new int[header.samples]; C = new int[header.samples]; G = new int[header.samples]; T = new int[header.samples]; max = Integer.MIN_VALUE; dis.reset(); dis.skipBytes(header.samplesOffset); if (header.sampleSize == 1) { if (header.version < 3.00) { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedByte(); if (A[i] > max) max = A[i]; C[i] = dis.readUnsignedByte(); if (C[i] > max) max = C[i]; G[i] = dis.readUnsignedByte(); if (G[i] > max) max = G[i]; T[i] = dis.readUnsignedByte(); if (T[i] > max) max = T[i]; } } else { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedByte(); if (A[i] > max) max = A[i]; } for (int i = 0; i < header.samples; ++i) { C[i] = dis.readUnsignedByte(); if (C[i] > max) max = C[i]; } for (int i = 0; i < header.samples; ++i) { G[i] = dis.readUnsignedByte(); if (G[i] > max) max = G[i]; } for (int i = 0; i < header.samples; ++i) { T[i] = dis.readUnsignedByte(); if (T[i] > max) max = T[i]; } } } else if (header.sampleSize == 2) { if (header.version < 3.00) { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedShort(); if (A[i] > max) max = A[i]; C[i] = dis.readUnsignedShort(); if (C[i] > max) max = C[i]; G[i] = dis.readUnsignedShort(); if (G[i] > max) max = G[i]; T[i] = dis.readUnsignedShort(); if (T[i] > max) max = T[i]; } } else { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedShort(); if (A[i] > max) max = A[i]; } for (int i = 0; i < header.samples; ++i) { C[i] = dis.readUnsignedShort(); if (C[i] > max) max = C[i]; } for (int i = 0; i < header.samples; ++i) { G[i] = dis.readUnsignedShort(); if (G[i] > max) max = G[i]; } for (int i = 0; i < header.samples; ++i) { T[i] = dis.readUnsignedShort(); if (T[i] > max) max = T[i]; } } } centers = new int[header.bases]; byte[] buf = new byte[header.bases]; dis.reset(); dis.skipBytes(header.basesOffset); if (header.version < 3.00) { for (int i = 0; i < header.bases; ++i) { centers[i] = dis.readInt(); dis.skipBytes(4); buf[i] = dis.readByte(); dis.skipBytes(3); } } else { for (int i = 0; i < header.bases; ++i) centers[i] = dis.readInt(); dis.skipBytes(4 * header.bases); dis.readFully(buf); } sequence = new String(buf); dis.close(); }
00
Code Sample 1: protected boolean checkLogin(String username, String password) { log.debug("Called checkLogin with " + username); String urlIn = GeoNetworkContext.url + "/" + GeoNetworkContext.loginService + "?username=" + username + "&password=" + password; Element results = null; String cookieValue = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); log.debug("CheckLogin to GeoNetwork returned " + Xml.getString(results)); } finally { in.close(); } Map<String, List<String>> headers = conn.getHeaderFields(); List<String> values = headers.get("Set-Cookie"); for (Iterator iter = values.iterator(); iter.hasNext(); ) { String v = (String) iter.next(); if (cookieValue == null) { cookieValue = v; } else { cookieValue = cookieValue + ";" + v; } } } catch (Exception e) { throw new RuntimeException("User login to GeoNetwork failed: ", e); } if (!results.getName().equals("ok")) return false; Session session = getConnection().getSession(); session.removeAttribute("usercookie.object"); session.setAttribute("usercookie.object", cookieValue); log.debug("Cookie set is " + cookieValue); return true; } 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: private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); } Code Sample 2: public static String getMD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: private void createScript(File scriptsLocation, String relativePath, String scriptContent) { Writer fileWriter = null; try { File scriptFile = new File(scriptsLocation.getAbsolutePath() + "/" + relativePath); scriptFile.getParentFile().mkdirs(); fileWriter = new FileWriter(scriptFile); IOUtils.copy(new StringReader(scriptContent), fileWriter); } catch (IOException e) { throw new UnitilsException(e); } finally { IOUtils.closeQuietly(fileWriter); } } Code Sample 2: private static void loadEmoticons() { emoticons = new Hashtable(); URL url = ChatPanel.class.getResource("/resources/text/emoticon.properties"); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = br.readLine()) != null) { if (line.trim().length() == 0 || line.charAt(0) == '#') continue; int i0 = line.indexOf('='); if (i0 != -1) { String key = line.substring(0, i0).trim(); String value = line.substring(i0 + 1).trim(); value = StringUtil.replaceString(value, "\\n", "\n"); URL eUrl = ChatPanel.class.getResource("/resources/emoticon/" + value); if (eUrl != null) emoticons.put(key, new ImageIcon(eUrl)); } } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { } } } }
00
Code Sample 1: public String encryptPassword(String clearPassword) throws NullPointerException { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new NullPointerException("NoSuchAlgorithmException: " + e.toString()); } sha.update(clearPassword.getBytes()); byte encryptedPassword[] = sha.digest(); sha = null; StringBuffer result = new StringBuffer(); for (int i = 0; i < encryptedPassword.length; i++) { result.append(Byte.toString(encryptedPassword[i])); } return (result.toString()); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static String Md5By32(String plainText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); 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 GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: private void copyTemplate(String resource, OutputStream outputStream) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); } Code Sample 2: private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; }
11
Code Sample 1: public static void testString(String string, String expected) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(string.getBytes(), 0, string.length()); String result = toString(md.digest()); System.out.println(expected); System.out.println(result); if (!expected.equals(result)) System.out.println("NOT EQUAL!"); } catch (Exception x) { x.printStackTrace(); } } Code Sample 2: String digest(final UserAccountEntity account) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(account.getUserId().getBytes("UTF-8")); digest.update(account.getLastLogin().toString().getBytes("UTF-8")); digest.update(account.getPerson().getGivenName().getBytes("UTF-8")); digest.update(account.getPerson().getSurname().getBytes("UTF-8")); digest.update(account.getPerson().getEmail().getBytes("UTF-8")); digest.update(m_random); return new String(Base64.altEncode(digest.digest())); } catch (final Exception e) { LOG.error("Exception", e); throw new RuntimeException(e); } }
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: @Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } }
00
Code Sample 1: private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; } Code Sample 2: public Web(String urlString) throws java.net.MalformedURLException, java.io.IOException { final java.net.URL url = new java.net.URL(urlString); final java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) throw new java.lang.IllegalArgumentException("URL protocol must be HTTP."); final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(100000); conn.setReadTimeout(100000); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-agent", "spider"); conn.connect(); responseHeader = conn.getHeaderFields(); responseCode = conn.getResponseCode(); responseURL = conn.getURL(); length = conn.getContentLength(); final String type = conn.getContentType(); if (type != null) { final String[] parts = type.split(";"); MIMEtype = parts[0].trim(); for (int i = 1; i < parts.length && charset == null; i++) { final String t = parts[i].trim(); final int index = t.toLowerCase().indexOf("charset="); if (index != -1) charset = t.substring(index + 8); } } final java.io.InputStream stream = conn.getErrorStream(); if (stream != null) { content = readStream(length, stream); } else if ((inputStream = conn.getContent()) != null && inputStream instanceof java.io.InputStream) { content = readStream(length, (java.io.InputStream) inputStream); } conn.disconnect(); }
00
Code Sample 1: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; String review = request.getParameter("review"); String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String inforId = request.getParameter("inforId"); request.setAttribute("id", inforId); String str_postFIX = ""; int i_p = 0; if (null == review) { FormFile file = vo.getFile(); if (file != null) { 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(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); String fullPath = realpath + "attach/" + strAppend + str_postFIX; 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(); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); return "editsave"; } else { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); FormFile file = vo.getFile(); FormFile file2 = vo.getFile2(); FormFile file3 = vo.getFile3(); t_infor_review newreview = new t_infor_review(); String content = request.getParameter("content"); newreview.setContent(content); if (null != inforId) newreview.setInfor_id(Integer.parseInt(inforId)); newreview.setInsert_day(new Date()); UserDetails user = LoginUtils.getLoginUser(request); newreview.setCreate_name(user.getUsercode()); if (null != file.getFileName() && !"".equals(file.getFileName())) { newreview.setAttachname1(file.getFileName()); String strAppend1 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); newreview.setAttachfullname1(realpath + "attach/" + strAppend1 + str_postFIX); saveFile(file.getInputStream(), realpath + "attach/" + strAppend1 + str_postFIX); } if (null != file2.getFileName() && !"".equals(file2.getFileName())) { newreview.setAttachname2(file2.getFileName()); String strAppend2 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file2.getFileName().lastIndexOf("."); str_postFIX = file2.getFileName().substring(i_p, file2.getFileName().length()); newreview.setAttachfullname2(realpath + "attach/" + strAppend2 + str_postFIX); saveFile(file2.getInputStream(), realpath + "attach/" + strAppend2 + str_postFIX); } if (null != file3.getFileName() && !"".equals(file3.getFileName())) { newreview.setAttachname3(file3.getFileName()); String strAppend3 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file3.getFileName().lastIndexOf("."); str_postFIX = file3.getFileName().substring(i_p, file3.getFileName().length()); newreview.setAttachfullname3(realpath + "attach/" + strAppend3 + str_postFIX); saveFile(file3.getInputStream(), realpath + "attach/" + strAppend3 + str_postFIX); } t_infor_review_EditMap reviewEdit = new t_infor_review_EditMap(); reviewEdit.add(newreview); request.setAttribute("review", "1"); return "aftersave"; } } Code Sample 2: public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
11
Code Sample 1: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } Code Sample 2: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; } Code Sample 2: public static long removePropertyInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, String propriete) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (propriete.equals(Metadata.TITLE)) { coreProperties.setTitle(""); } else if (propriete.equals(Metadata.AUTHOR)) { coreProperties.setCreator(""); } else if (propriete.equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(""); } else if (propriete.equals(Metadata.COMMENTS)) { coreProperties.setDescription(""); } else if (propriete.equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(""); } else if (propriete.equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(""); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(propriete)) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(propriete)) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { } } try { digest.update(data.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { } return encodeHex(digest.digest()); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: private void dumpFile(File repository, File copy) { try { if (copy.exists() && !copy.delete()) { throw new RuntimeException("can't delete copy: " + copy); } printFile("Real Archive File", repository); new ZipArchive(repository.getPath()); IOUtils.copyFiles(repository, copy); printFile("Copy Archive File", copy); new ZipArchive(copy.getPath()); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void markAsCachedHelper(Item item, Date from, Date to, Map<String, Boolean> properties) { if (properties.size() == 0) { return; } Connection conn = null; Iterable<Integer> props = representer.getInternalReps(properties.keySet()); Integer hostIndex = representer.lookUpInternalRep(item.getResolved().getHost()); HashMap<Integer, long[]> periods = new HashMap<Integer, long[]>(); for (Map.Entry<String, Boolean> e : properties.entrySet()) { periods.put(representer.lookUpInternalRep(e.getKey()), new long[] { from.getTime(), to.getTime(), e.getValue() ? 1 : 0 }); } try { conn = getConnection(); conn.setAutoCommit(false); conn.setSavepoint(); PreparedStatement stmt = null; try { stmt = conn.prepareStatement("SELECT MIN(starttime), MAX(endtime), MAX(hasvalues) FROM cachedperiods WHERE " + "id = ? AND host = ? AND prop = ? AND " + "starttime <= ? AND endtime >= ?"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(4, to.getTime()); stmt.setLong(5, from.getTime()); for (Map.Entry<Integer, long[]> e1 : periods.entrySet()) { stmt.setInt(3, e1.getKey()); ResultSet rs = stmt.executeQuery(); if (rs.next()) { e1.getValue()[0] = Math.min(rs.getLong(1), e1.getValue()[0]); e1.getValue()[1] = Math.max(rs.getLong(2), e1.getValue()[1]); e1.getValue()[2] = Math.max(rs.getInt(3), e1.getValue()[2]); } StorageUtils.close(rs); } StorageUtils.close(stmt); stmt = conn.prepareStatement("DELETE FROM cachedperiods WHERE " + "id = ? AND host = ? AND " + "starttime <= ? AND endtime >= ? AND " + "prop IN (" + StringUtils.join(props.iterator(), ",") + ")"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(3, to.getTime()); stmt.setLong(4, from.getTime()); stmt.executeUpdate(); StorageUtils.close(stmt); stmt = conn.prepareStatement("INSERT INTO cachedperiods (id, host, prop, starttime, endtime, hasvalues) VALUES (?, ?, ?, ?, ?, ?)"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); for (Map.Entry<Integer, long[]> e2 : periods.entrySet()) { stmt.setInt(3, e2.getKey()); stmt.setLong(4, e2.getValue()[0]); stmt.setLong(5, e2.getValue()[1]); stmt.setInt(6, (int) e2.getValue()[2]); stmt.executeUpdate(); } } finally { StorageUtils.close(stmt); } conn.commit(); } catch (SQLException ex) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Cannot update cachedperiods table.", ex); try { conn.rollback(); } catch (SQLException ex1) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Could not roll back database, please consult system administrator.", ex1); } } finally { StorageUtils.close(conn); } } Code Sample 2: private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); }
00
Code Sample 1: public static URLConnection createConnection(URL url) throws java.io.IOException { URLConnection urlConn = url.openConnection(); if (urlConn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setRequestMethod("POST"); } urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setDefaultUseCaches(false); return urlConn; } 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 void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); } Code Sample 2: public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
11
Code Sample 1: public void testCodingBeyondContentLimitFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff; and a lot more stuff"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); } Code Sample 2: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); getLog().info("Process request " + pathInfo); if (null != pathInfo) { String pathId = getPathId(pathInfo); JobResources res = ContextUtil.getJobResource(pathId); if (null != res) { RequestType requType = getRequestType(request); ResultAccess access = new ResultAccess(res); Collection<Long> uIdColl = res.getUniqIds(); boolean isFiltered = false; { List<String> postSeqIds = getSeqList(request); if (!postSeqIds.isEmpty()) { isFiltered = true; uIdColl = access.loadIds(postSeqIds); } } try { if ((requType.equals(RequestType.FASTA)) || (requType.equals(RequestType.SWISSPROT))) { OutputStreamWriter out = null; out = new OutputStreamWriter(response.getOutputStream()); for (Long uid : uIdColl) { if (requType.equals(RequestType.FASTA)) { SwissProt sw = access.getSwissprotEntry(uid); if (null != sw) { PrintFactory.instance().print(ConvertFactory.instance().SwissProt2fasta(sw), out); } else { System.err.println("Not able to read Swissprot entry " + uid + " in project " + res.getBaseDir()); } } else if (requType.equals(RequestType.SWISSPROT)) { File swissFile = res.getSwissprotFile(uid); if (swissFile.exists()) { InputStream in = null; try { in = new FileInputStream(swissFile); IOUtils.copy(in, out); } catch (IOException e) { e.printStackTrace(); System.err.println("Problems with reading file to output stream " + swissFile); } finally { IOUtils.closeQuietly(in); } } else { System.err.println("Swissprot file does not exist: " + swissFile); } } } out.flush(); } else { if (uIdColl.size() <= 2) { isFiltered = false; uIdColl = res.getUniqIds(); } Tree tree = access.getTreeByUniquId(uIdColl); if (requType.equals(RequestType.TREE)) { response.getWriter().write(tree.toNewHampshireX()); } else if (requType.equals(RequestType.PNG)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); ImageMap map = ImageFactory.instance().createProteinCard(sp, tree, true, res); response.setContentType("image/png"); response.addHeader("Content-Disposition", "filename=ProteinCards.png"); ImageFactory.instance().printPNG(map.getImage(), response.getOutputStream()); response.getOutputStream().flush(); } else if (requType.equals(RequestType.HTML)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); createHtml(res, access, tree, request, response, sp, isFiltered); } } } catch (Exception e) { e.printStackTrace(); getLog().error("Problem with Request: " + pathInfo + "; type " + requType, e); } } else { getLog().error("Resource is null: " + pathId + "; path " + pathInfo); } } else { getLog().error("PathInfo is null!!!"); } }
11
Code Sample 1: public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; }
00
Code Sample 1: public synchronized void readModels(Project p, URL url) throws IOException { _proj = p; Argo.log.info("======================================="); Argo.log.info("== READING MODEL " + url); try { XMIReader reader = new XMIReader(); InputSource source = new InputSource(url.openStream()); source.setSystemId(url.toString()); _curModel = reader.parse(source); if (reader.getErrors()) { throw new IOException("XMI file " + url.toString() + " could not be parsed."); } _UUIDRefs = new HashMap(reader.getXMIUUIDToObjectMap()); } catch (SAXException saxEx) { Exception ex = saxEx.getException(); if (ex == null) { saxEx.printStackTrace(); } else { ex.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } Argo.log.info("======================================="); try { _proj.addModel((ru.novosoft.uml.foundation.core.MNamespace) _curModel); } catch (PropertyVetoException ex) { System.err.println("An error occurred adding the model to the project!"); ex.printStackTrace(); } Collection ownedElements = _curModel.getOwnedElements(); Iterator oeIterator = ownedElements.iterator(); while (oeIterator.hasNext()) { MModelElement me = (MModelElement) oeIterator.next(); if (me instanceof MClass) { _proj.defineType((MClass) me); } else if (me instanceof MDataType) { _proj.defineType((MDataType) me); } } } Code Sample 2: private void getViolationsReportByProductOfferIdYearMonthDay() throws IOException { String xmlFile9Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonthDay.xml"; URL url9; url9 = new URL(bmReportingWSUrl); URLConnection connection9 = url9.openConnection(); HttpURLConnection httpConn9 = (HttpURLConnection) connection9; FileInputStream fin9 = new FileInputStream(xmlFile9Send); ByteArrayOutputStream bout9 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin9, bout9); fin9.close(); byte[] b9 = bout9.toByteArray(); httpConn9.setRequestProperty("Content-Length", String.valueOf(b9.length)); httpConn9.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn9.setRequestProperty("SOAPAction", soapAction); httpConn9.setRequestMethod("POST"); httpConn9.setDoOutput(true); httpConn9.setDoInput(true); OutputStream out9 = httpConn9.getOutputStream(); out9.write(b9); out9.close(); InputStreamReader isr9 = new InputStreamReader(httpConn9.getInputStream()); BufferedReader in9 = new BufferedReader(isr9); String inputLine9; StringBuffer response9 = new StringBuffer(); while ((inputLine9 = in9.readLine()) != null) { response9.append(inputLine9); } in9.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: " + "getViolationsReportByProductOfferIdYearMonthDay\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response9.toString()); }
00
Code Sample 1: public int update(BusinessObject o) throws DAOException { int update = 0; Item item = (Item) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ITEM")); pst.setString(1, item.getDescription()); pst.setDouble(2, item.getUnit_price()); pst.setInt(3, item.getQuantity()); pst.setDouble(4, item.getVat()); pst.setInt(5, item.getIdProject()); if (item.getIdBill() == 0) pst.setNull(6, java.sql.Types.INTEGER); else pst.setInt(6, item.getIdBill()); pst.setInt(7, item.getIdCurrency()); pst.setInt(8, item.getId()); System.out.println("item => " + item.getDescription() + " " + item.getUnit_price() + " " + item.getQuantity() + " " + item.getVat() + " " + item.getIdProject() + " " + item.getIdBill() + " " + item.getIdCurrency() + " " + item.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; } Code Sample 2: @MediumTest public void testUrlRewriteRules() throws Exception { ContentResolver resolver = getContext().getContentResolver(); GoogleHttpClient client = new GoogleHttpClient(resolver, "Test", false); Settings.Gservices.putString(resolver, "url:test", "http://foo.bar/ rewrite " + mServerUrl + "new/"); Settings.Gservices.putString(resolver, "digest", mServerUrl); try { HttpGet method = new HttpGet("http://foo.bar/path"); HttpResponse response = client.execute(method); String body = EntityUtils.toString(response.getEntity()); assertEquals("/new/path", body); } finally { client.close(); } }
00
Code Sample 1: public void run() { runCounter++; try { LOGGER.info("Fetching feed [" + runCounter + "] " + _feedInfo); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); disableSSLCertificateChecking(httpClient); if (_proxy != null && _feedInfo.getUseProxy()) { LOGGER.info("Configuring proxy " + _proxy); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxy); } if (_feedInfo.getUsername() != null) { Credentials credentials; if (_feedInfo.getUsername().contains("/")) { String username = _feedInfo.getUsername().substring(_feedInfo.getUsername().indexOf("/") + 1); String domain = _feedInfo.getUsername().substring(0, _feedInfo.getUsername().indexOf("/")); String workstation = InetAddress.getLocalHost().getHostName(); LOGGER.info("Configuring NT credentials : username=[" + username + "] domain=[" + domain + "] workstation=[" + workstation + "]"); credentials = new NTCredentials(username, _feedInfo.getPassword(), workstation, domain); httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } else { credentials = new UsernamePasswordCredentials(_feedInfo.getUsername(), _feedInfo.getPassword()); LOGGER.info("Configuring Basic credentials " + credentials); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } } if (_feedInfo.getCookie() != null) { BasicClientCookie cookie = new BasicClientCookie(_feedInfo.getCookie().getName(), _feedInfo.getCookie().getValue()); cookie.setVersion(0); if (_feedInfo.getCookie().getDomain() != null) cookie.setDomain(_feedInfo.getCookie().getDomain()); if (_feedInfo.getCookie().getPath() != null) cookie.setPath(_feedInfo.getCookie().getPath()); LOGGER.info("Adding cookie " + cookie); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } HttpGet httpget = new HttpGet(_feedInfo.getUrl()); HttpResponse response = httpClient.execute(httpget, localContext); LOGGER.info("Response Status : " + response.getStatusLine()); LOGGER.debug("Headers : " + Arrays.toString(response.getAllHeaders())); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { LOGGER.error("Request was unsuccessful for " + _feedInfo + " : " + response.getStatusLine()); } else { SyndFeedInput input = new SyndFeedInput(); XmlReader reader = new XmlReader(response.getEntity().getContent()); SyndFeed feed = input.build(reader); if (feed.getTitle() != null) _feedInfo.setTitle(feed.getTitle()); LOGGER.debug("Feed : " + new SyndFeedOutput().outputString(feed)); LOGGER.info("Feed [" + feed.getTitle() + "] contains " + feed.getEntries().size() + " entries"); @SuppressWarnings("unchecked") List<SyndEntry> entriesList = feed.getEntries(); Collections.sort(entriesList, new SyndEntryPublishedDateComparator()); for (SyndEntry entry : entriesList) { if (VisitedEntries.getInstance().isAlreadyVisited(entry.getUri())) { LOGGER.debug("Already received " + entry.getUri()); } else { _feedInfo.addEntry(entry); LOGGER.debug("New entry " + entry.toString()); _entryDisplay.displayEntry(feed, entry, firstRun); } } LOGGER.info("Completing entries for feed " + feed.getTitle()); if (firstRun) firstRun = false; } } catch (IllegalArgumentException e) { LOGGER.error(e.getMessage(), e); } catch (FeedException e) { LOGGER.error(e.getMessage(), e); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (KeyManagementException e) { LOGGER.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); } } Code Sample 2: public void testScenario() throws Exception { String expression = "SELECT id, name, address, phone FROM " + TABLE + " where id > 2 and id < 12 order by id"; SQLQuery query = new SQLQuery(); query.setResourceID(mResourceID); query.addExpression(expression); TupleToWebRowSetCharArrays tupleToWebRowSet = new TupleToWebRowSetCharArrays(); tupleToWebRowSet.connectDataInput(query.getDataOutput()); DeliverToFTP deliverToFTP = new DeliverToFTP(); deliverToFTP.connectDataInput(tupleToWebRowSet.getResultOutput()); deliverToFTP.addFilename(FILE); deliverToFTP.addHost(mURL); PipelineWorkflow pipeline = new PipelineWorkflow(); pipeline.add(query); pipeline.add(tupleToWebRowSet); pipeline.add(deliverToFTP); mDRER.execute(pipeline, RequestExecutionType.SYNCHRONOUS); final URL url = new URL("ftp://" + mURL + "/" + FILE); final URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); InputStream is = connection.getInputStream(); WebRowSetToResultSet converter = new WebRowSetToResultSet(new InputStreamReader(is)); converter.setResultSetType(ResultSet.TYPE_FORWARD_ONLY); ResultSet rs = converter.getResultSet(); JDBCTestHelper.validateResultSet(mConnection, expression, rs, 1); rs.close(); }
11
Code Sample 1: public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); } Code Sample 2: public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } }
11
Code Sample 1: public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: static byte[] genDigest(String pad, byte[] passwd) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM); digest.update(pad.getBytes()); digest.update(passwd); return digest.digest(); }
11
Code Sample 1: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } } Code Sample 2: public static void ExtraeArchivoJAR(String Archivo, String DirJAR, String DirDestino) { FileInputStream entrada = null; FileOutputStream salida = null; try { File f = new File(DirDestino + separador + Archivo); try { f.createNewFile(); } catch (Exception sad) { sad.printStackTrace(); } InputStream source = OP_Proced.class.getResourceAsStream(DirJAR + "/" + Archivo); BufferedInputStream in = new BufferedInputStream(source); FileOutputStream out = new FileOutputStream(f); int ch; while ((ch = in.read()) != -1) out.write(ch); in.close(); out.close(); } catch (IOException ex) { System.out.println(ex); } finally { if (entrada != null) { try { entrada.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (salida != null) { try { salida.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
00
Code Sample 1: String getOutputPage(String action, String XML, String xslFileName, InputStream pageS, HttpServletRequest request) throws NoSuchAlgorithmException, UnsupportedEncodingException, TransformerException { String sPage = null; Transformer transformer = null; String dig = null; CharArrayWriter page = new CharArrayWriter(); if (this.nCachedPages > 0) { java.security.MessageDigest mess = java.security.MessageDigest.getInstance("SHA1"); mess.update(XML.getBytes()); mess.update(Long.toString(new File(basePath + xslFileName).lastModified()).getBytes()); dig = new String(mess.digest()); synchronized (pages) { if (pages.containsKey(dig)) { sPage = pages.get(dig); } } } if (sPage == null && xslFileName.length() > 4) { try { long modifyTime = new File(basePath + xslFileName).lastModified(); String path = basePath.replaceAll("\\\\", "/") + xslFileName; path = "file:///" + path; boolean add2cache = false; if (this.nCachedTransformers > 0) { String cacheKey = action + xslFileName + modifyTime; if (this.transformers.containsKey(cacheKey)) { transformer = this.transformers.get(cacheKey); synchronized (transformer) { transformer.transform(new StreamSource(new ByteArrayInputStream(XML.getBytes("UTF-8"))), new StreamResult(page)); } } else { add2cache = true; } } if (transformer == null) { transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(path)); transformer.transform(new StreamSource(new ByteArrayInputStream(XML.getBytes("UTF-8"))), new StreamResult(page)); } sPage = page.toString(); sPage = sPage.replaceAll("&lt;", "<"); sPage = sPage.replaceAll("&gt;", ">"); sPage = replaceLinks(sPage, request); if (this.nCachedPages > 0) { synchronized (pages) { pages.put(dig, sPage); if (pages.size() > nCachedPages) { Iterator<String> i = pages.values().iterator(); i.next(); i.remove(); } } } if (add2cache) { synchronized (this.transformers) { this.transformers.put(action + xslFileName + modifyTime, transformer); if (this.transformers.size() > this.nCachedTransformers) { Iterator<Transformer> it = this.transformers.values().iterator(); it.next(); it.remove(); } } } } catch (TransformerException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "---------------------------------------------"); Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); Logger.getLogger(getClass().getName()).log(Level.SEVERE, ("XSL file: " + xslFileName)); Logger.getLogger(getClass().getName()).log(Level.SEVERE, XML); Logger.getLogger(getClass().getName()).log(Level.SEVERE, "---------------------------------------------"); throw ex; } } return sPage; } Code Sample 2: public List<String> makeQuery(String query) { List<String> result = new ArrayList<String>(); try { query = URLUTF8Encoder.encode(query); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", "http://poo.sk"); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } String response = builder.toString(); JSONObject json = new JSONObject(response); Long count = Long.decode(json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount")); LOG.info("Found " + count + " potential pages"); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); result.add(j.getString("url")); } } catch (Exception e) { LOG.error("Couldnt query Google for some reason check exception below"); e.printStackTrace(); } return result; }
11
Code Sample 1: public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); 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: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } }
11
Code Sample 1: public boolean chequearMarca(int a, int m, int d) { boolean existe = false; try { cantidadArchivos = obtenerCantidad() + 1; String filenametxt = ""; String filenamezip = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (ano == a && mes == m && dia == d) existe = true; input.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } return (existe); } Code Sample 2: public void transport(File file) throws TransportException { if (file.exists()) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { transport(file); } } else if (file.isFile()) { try { FileChannel inChannel = new FileInputStream(file).getChannel(); FileChannel outChannel = new FileOutputStream(getOption("destination")).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { log.error("File transfer failed", e); } } } }
11
Code Sample 1: private static void copyFile(String src, String dest) throws IOException { File destFile = new File(dest); if (destFile.exists()) { destFile.delete(); } FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public java.io.File gzip(java.io.File file) throws Exception { java.io.File tmp = null; InputStream is = null; OutputStream os = null; try { tmp = java.io.File.createTempFile(file.getName(), ".gz"); tmp.deleteOnExit(); is = new BufferedInputStream(new FileInputStream(file)); os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(tmp))); byte[] buf = new byte[4096]; int nread = -1; while ((nread = is.read(buf)) != -1) { os.write(buf, 0, nread); } os.flush(); } finally { os.close(); is.close(); } return tmp; }
00
Code Sample 1: public void patchFile(final File classFile) { if (!classFile.exists()) { myErrors.add(new FormErrorInfo(null, "Class to bind does not exist: " + myRootContainer.getClassToBind())); return; } FileInputStream fis; try { byte[] patchedData; fis = new FileInputStream(classFile); try { patchedData = patchClass(fis); if (patchedData == null) { return; } } finally { fis.close(); } FileOutputStream fos = new FileOutputStream(classFile); try { fos.write(patchedData); } finally { fos.close(); } } catch (IOException e) { myErrors.add(new FormErrorInfo(null, "Cannot read or write class file " + classFile.getPath() + ": " + e.toString())); } } 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: private void updateViewerContent(ScrollingGraphicalViewer viewer) { BioPAXGraph graph = (BioPAXGraph) viewer.getContents().getModel(); if (!graph.isMechanistic()) return; Map<String, Color> highlightMap = new HashMap<String, Color>(); for (Object o : graph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (node.isHighlighted()) { highlightMap.put(node.getIDHash(), node.getHighlightColor()); } } for (Object o : graph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (edge.isHighlighted()) { highlightMap.put(edge.getIDHash(), edge.getHighlightColor()); } } HighlightLayer hLayer = (HighlightLayer) ((ChsScalableRootEditPart) viewer.getRootEditPart()).getLayer(HighlightLayer.HIGHLIGHT_LAYER); hLayer.removeAll(); hLayer.highlighted.clear(); viewer.deselectAll(); graph.recordLayout(); PathwayHolder p = graph.getPathway(); if (withContent != null) { p.updateContentWith(withContent); } BioPAXGraph newGraph = main.getRootGraph().excise(p); newGraph.setAsRoot(); viewer.setContents(newGraph); boolean layedout = newGraph.fetchLayout(); if (!layedout) { new CoSELayoutAction(main).run(); } viewer.deselectAll(); GraphAnimation.run(viewer); for (Object o : newGraph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (highlightMap.containsKey(node.getIDHash())) { node.setHighlightColor(highlightMap.get(node.getIDHash())); node.setHighlight(true); } } for (Object o : newGraph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (highlightMap.containsKey(edge.getIDHash())) { edge.setHighlightColor(highlightMap.get(edge.getIDHash())); edge.setHighlight(true); } } } 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())); } } }
00
Code Sample 1: private void alterarCategoria(Categoria cat) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "UPDATE categoria SET nome_categoria = ? where id_categoria = ?"; ps = conn.prepareStatement(sql); ps.setString(1, cat.getNome()); ps.setInt(2, cat.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
00
Code Sample 1: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: @Override public boolean connect(String host, String userName, String password) throws IOException, UnknownHostException { try { if (ftpClient != null) if (ftpClient.isConnected()) ftpClient.disconnect(); ftpClient = new FTPSClient("SSL", false); boolean success = false; ftpClient.connect(host); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) success = ftpClient.login(userName, password); if (!success) ftpClient.disconnect(); return success; } catch (Exception ex) { throw new IOException(ex.getMessage()); } }
11
Code Sample 1: private void javaToHtml(File source, File destination) throws IOException { Reader reader = new FileReader(source); Writer writer = new FileWriter(destination); JavaUtils.writeJava(reader, writer); writer.flush(); writer.close(); } Code Sample 2: private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); }
11
Code Sample 1: private String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] data = md.digest(); return convertToHex(data); } catch (Exception ex) { ex.printStackTrace(); } return null; } Code Sample 2: public static boolean isMatchingAsPassword(final String password, final String amd5Password) { boolean response = false; try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); final byte[] md5Byte = algorithm.digest(); final StringBuffer buffer = new StringBuffer(); for (final byte b : md5Byte) { if ((b <= 15) && (b >= 0)) { buffer.append("0"); } buffer.append(Integer.toHexString(0xFF & b)); } response = (amd5Password != null) && amd5Password.equals(buffer.toString()); } catch (final NoSuchAlgorithmException e) { ProjektUtil.LOG.error("No digester MD5 found in classpath!", e); } return response; }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
11
Code Sample 1: public void execute() throws MojoExecutionException, MojoFailureException { try { this.getLog().info("copy source web.xml - " + this.getWebXml() + " to build dir (source web.xml required if mergewebxml execution is enabled)"); File destination = new File(this.getBuildDir(), "web.xml"); if (!destination.exists()) { destination.getParentFile().mkdirs(); destination.createNewFile(); } FileIOUtils.copyFile(this.getWebXml(), destination); for (int i = 0; i < this.getCompileTarget().length; i++) { File moduleFile = null; for (Iterator it = this.getProject().getCompileSourceRoots().iterator(); it.hasNext() && moduleFile == null; ) { File check = new File(it.next().toString() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } for (Iterator it = this.getProject().getResources().iterator(); it.hasNext(); ) { Resource r = (Resource) it.next(); File check = new File(r.getDirectory() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } ClassLoader loader = this.fixThreadClasspath(); if (moduleFile == null) { try { String classpath = "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"; InputStream is = loader.getResourceAsStream(classpath); System.out.println("Looking for classpath: " + classpath + "(" + (is != null) + ")"); if (is != null) { File temp = new File(this.getBuildDir(), this.getCompileTarget()[i].concat(".gwt.xml")); FileOutputStream fos = new FileOutputStream(temp); FileIOUtils.copyStream(is, fos); moduleFile = temp; } } catch (IOException e) { this.getLog().info(e); } } GwtWebInfProcessor processor = null; try { if (moduleFile != null) { getLog().info("Module file: " + moduleFile.getAbsolutePath()); processor = new GwtWebInfProcessor(this.getCompileTarget()[i], moduleFile, destination.getAbsolutePath(), destination.getAbsolutePath(), this.isWebXmlServletPathAsIs()); processor.process(); } else { throw new MojoExecutionException("module file null"); } } catch (ExitException e) { this.getLog().info(e.getMessage()); } } } catch (Exception e) { throw new MojoExecutionException("Unable to merge web.xml", e); } } 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"); } FileChannel input = new FileInputStream(srcFile).getChannel(); try { FileChannel output = new FileOutputStream(destFile).getChannel(); try { output.transferFrom(input, 0, input.size()); } 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()); } }
11
Code Sample 1: public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { String context = request.getContextPath(); String resource = request.getRequestURI().replace(context, ""); resource = resource.replaceAll("^/\\w*/", ""); if ((StringUtils.isEmpty(resource)) || (resource.endsWith("/"))) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } URL url = ClassLoaderUtils.getResource(resource); if (url == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if ((this.deny != null) && (this.deny.length > 0)) { for (String s : this.deny) { s = s.trim(); if (s.indexOf('*') != -1) { s = s.replaceAll("\\*", ".*"); } if (Pattern.matches(s, resource)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } } InputStream input = url.openStream(); OutputStream output = response.getOutputStream(); URLConnection connection = url.openConnection(); String contentEncoding = connection.getContentEncoding(); int contentLength = connection.getContentLength(); String contentType = connection.getContentType(); if (contentEncoding != null) { response.setCharacterEncoding(contentEncoding); } response.setContentLength(contentLength); response.setContentType(contentType); IOUtils.copy(input, output, true); }
00
Code Sample 1: private void writeStatsToDatabase(long transferJobAIPCount, long reprocessingJobAIPCount, long transferJobAIPVolume, long reprocessingJobAIPVolume, long overallBinaryAIPCount, Map<String, AIPStatistics> mimeTypeRegister) throws SQLException { int nextAIPStatsID; long nextMimetypeStatsID; Statement select = dbConnection.createStatement(); String aipStatsQuery = "select max(aip_statistics_id) from aip_statistics"; ResultSet result = select.executeQuery(aipStatsQuery); if (result.next()) { nextAIPStatsID = result.getInt(1) + 1; } else { throw new SQLException("Problem getting maximum AIP Statistics ID"); } String mimetypeStatsQuery = "select max(mimetype_aip_statistics_id) from mimetype_aip_statistics"; result = select.executeQuery(mimetypeStatsQuery); if (result.next()) { nextMimetypeStatsID = result.getLong(1) + 1; } else { throw new SQLException("Problem getting maximum MIME type AIP Statistics ID"); } String insertAIPStatsEntryQuery = "insert into aip_statistics " + "(aip_statistics_id, tj_aip_count, tj_aip_volume, rj_aip_count, rj_aip_volume, " + "collation_date, binary_aip_count) " + "values (?, ?, ?, ?, ?, ?, ?)"; PreparedStatement insert = dbConnection.prepareStatement(insertAIPStatsEntryQuery); insert.setInt(1, nextAIPStatsID); insert.setLong(2, transferJobAIPCount); insert.setLong(3, transferJobAIPVolume); insert.setLong(4, reprocessingJobAIPCount); insert.setLong(5, reprocessingJobAIPVolume); insert.setDate(6, new java.sql.Date(System.currentTimeMillis())); insert.setLong(7, overallBinaryAIPCount); int rowsAdded = insert.executeUpdate(); if (rowsAdded != 1) { dbConnection.rollback(); throw new SQLException("Could not insert row into AIP statistics table"); } String insertMimeTypeStatsQuery = "insert into mimetype_aip_statistics " + "(mimetype_aip_statistics_id, aip_statistics_id, mimetype_aip_count, mimetype_aip_volume, mimetype) " + "values (?, ?, ?, ?, ?)"; insert = dbConnection.prepareStatement(insertMimeTypeStatsQuery); insert.setInt(2, nextAIPStatsID); for (String mimeType : mimeTypeRegister.keySet()) { AIPStatistics mimeTypeStats = mimeTypeRegister.get(mimeType); insert.setLong(1, nextMimetypeStatsID); insert.setLong(3, mimeTypeStats.aipCount); insert.setLong(4, mimeTypeStats.aipVolume); insert.setString(5, mimeType); nextMimetypeStatsID++; rowsAdded = insert.executeUpdate(); if (rowsAdded != 1) { dbConnection.rollback(); throw new SQLException("Could not insert row into MIME Type AIP statistics table"); } } dbConnection.commit(); } Code Sample 2: public String getResourceAsString(String name) throws IOException { String content = null; InputStream stream = aClass.getResourceAsStream(name); if (stream != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(stream, buffer); content = buffer.toString(); } else { Assert.fail("Resource not available: " + name); } return content; }
00
Code Sample 1: private BundleURLClassPath createBundleURLClassPath(Bundle bundle, Version version, File bundleFile, File cache, boolean alreadyCached) throws Exception { String bundleClassPath = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClassPath == null) { bundleClassPath = "."; } ManifestEntry[] entries = ManifestEntry.parse(bundleClassPath); String[] classPaths = new String[0]; for (int i = 0; i < entries.length; i++) { String classPath = entries[i].getName(); if (classPath.startsWith("/")) { classPath = classPath.substring(1); } if (classPath.endsWith(".jar")) { try { File file = new File(cache, classPath); if (!alreadyCached) { file.getParentFile().mkdirs(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(classPath).toString(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } else { if (!file.exists()) { throw new IOException(new StringBuilder("classpath ").append(classPath).append(" not found").toString()); } } } catch (IOException e) { FrameworkEvent frameworkEvent = new FrameworkEvent(FrameworkEvent.INFO, bundle, e); framework.postFrameworkEvent(frameworkEvent); continue; } } classPaths = (String[]) ArrayUtil.add(classPaths, classPath); } if (!alreadyCached) { String bundleNativeCode = (String) bundle.getHeaders().get(Constants.BUNDLE_NATIVECODE); if (bundleNativeCode != null) { entries = ManifestEntry.parse(bundleNativeCode); for (int i = 0; i < entries.length; i++) { ManifestEntry entry = entries[i]; String libPath = entry.getName(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(libPath).toString(); File file = new File(cache, libPath); file.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } } } BundleURLClassPath urlClassPath = new BundleURLClassPathImpl(bundle, version, classPaths, cache); return urlClassPath; } Code Sample 2: 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); } }
11
Code Sample 1: private boolean writeResource(PluginProxy eclipseInstallPlugin, ResourceProxy translation, LocaleProxy locale) throws Exception { String translationResourceName = determineTranslatedResourceName(translation, locale); String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(Messages.getString("Characters_period"), File.separator); if (translation.getRelativePath().contains(pluginNameInDirFormat)) { return writeResourceToBundleClasspath(translation, locale); } else if (translationResourceName.contains(File.separator)) { String resourcePath = translationResourceName.substring(0, translationResourceName.lastIndexOf(File.separatorChar)); File resourcePathDirectory = new File(directory.getPath() + File.separatorChar + resourcePath); resourcePathDirectory.mkdirs(); } File fragmentResource = new File(directory.getPath() + File.separatorChar + translationResourceName); File translatedResource = new File(translation.getFileResource().getAbsolutePath()); FileChannel inputChannel = new FileInputStream(translatedResource).getChannel(); FileChannel outputChannel = new FileOutputStream(fragmentResource).getChannel(); inputChannel.transferTo(0, inputChannel.size(), outputChannel); inputChannel.close(); outputChannel.close(); return true; } Code Sample 2: @Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
11
Code Sample 1: public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); } Code Sample 2: public static void main(String[] a) throws Exception { HashMap<String, Integer> numberOfOccurencesOfThisComboe = new HashMap<String, Integer>(); HashMap<String, String> fileToCATHMapping = new HashMap<String, String>(); ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; String reducedComboForFilteringOut = allEntries[1] + allEntries[2] + allEntries[3]; fileToCATHMapping.put(fileName, reducedComboForFilteringOut); if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } for (String fileName : allFilesToBeCopied) { String reducedComboForFilteringOut = fileToCATHMapping.get(fileName); if (!numberOfOccurencesOfThisComboe.containsKey(reducedComboForFilteringOut)) { numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, 1); } else { Integer thisCounter = numberOfOccurencesOfThisComboe.get(reducedComboForFilteringOut); thisCounter = thisCounter + 1; numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, thisCounter); } } HashSet<String> isSingleElement = new HashSet<String>(); for (Entry<String, Integer> thisEntry : numberOfOccurencesOfThisComboe.entrySet()) { if (thisEntry.getValue() == 1) { System.out.println("single: " + thisEntry.getKey()); isSingleElement.add(thisEntry.getKey()); } else { System.out.println("not single: " + thisEntry.getKey()); } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { if (!isSingleElement.contains(fileToCATHMapping.get(file))) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: public void process(String number) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Constants.TRAIN_INFO_URL.value()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair(Constants.TRAIN_NUMBER_POST_PARAM_NAME.value(), number)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httpPost); InputStream is = response.getEntity().getContent(); Document doc = getDocument(is); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(Constants.XPATH_TRAIN_STOPS_INFO.value()); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; List<String> list = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { list.add(nodes.item(i).getNodeValue()); } parse(list); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } } Code Sample 2: static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); }
00
Code Sample 1: public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } } Code Sample 2: 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(); } 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()); } state = CONNECTED; logger.info("Successfully logged in"); version = determineVersion(); writer.setTargetVersion(version); logger.info("Determined Asterisk version: " + version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
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: public SWORDEntry ingestDepost(final DepositCollection pDeposit, final ServiceDocument pServiceDocument) throws SWORDException { try { ZipFileAccess tZipFile = new ZipFileAccess(super.getTempDir()); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); _datastreamList.add(tDatastream); _datastreamList.addAll(tZipFile.getFiles(tZipTempFileName)); int i = 0; boolean found = false; for (i = 0; i < _datastreamList.size(); i++) { if (_datastreamList.get(i).getId().equalsIgnoreCase("mets")) { found = true; break; } } if (found) { SAXBuilder tBuilder = new SAXBuilder(); _mets = new METSObject(tBuilder.build(((LocalDatastream) _datastreamList.get(i)).getPath())); LocalDatastream tLocalMETSDS = (LocalDatastream) _datastreamList.remove(i); new File(tLocalMETSDS.getPath()).delete(); _datastreamList.add(_mets.getMETSDs()); _datastreamList.addAll(_mets.getMetadataDatastreams()); } else { throw new SWORDException("Couldn't find a METS document in the zip file, ensure it is named mets.xml or METS.xml"); } SWORDEntry tEntry = super.ingestDepost(pDeposit, pServiceDocument); tZipFile.removeLocalFiles(); return tEntry; } catch (IOException tIOExcpt) { String tMessage = "Couldn't retrieve METS from deposit: " + tIOExcpt.toString(); LOG.error(tMessage); tIOExcpt.printStackTrace(); throw new SWORDException(tMessage, tIOExcpt); } catch (JDOMException tJDOMExcpt) { String tMessage = "Couldn't build METS from deposit: " + tJDOMExcpt.toString(); LOG.error(tMessage); tJDOMExcpt.printStackTrace(); throw new SWORDException(tMessage, tJDOMExcpt); } }
00
Code Sample 1: public static void testAutoIncrement() { final int count = 3; final Object lock = new Object(); for (int i = 0; i < count; i++) { new Thread(new Runnable() { @Override public void run() { while (true) { StringBuilder buffer = new StringBuilder(128); buffer.append("insert into DOMAIN ( ").append(LS); buffer.append(" DOMAIN_ID, TOP_DOMAIN_ID, DOMAIN_HREF, ").append(LS); buffer.append(" DOMAIN_RANK, DOMAIN_TYPE, DOMAIN_STATUS, ").append(LS); buffer.append(" DOMAIN_ICO_CREATED, DOMAIN_CDATE ").append(LS); buffer.append(") values ( ").append(LS); buffer.append(" null ,null, ?,").append(LS); buffer.append(" 1, 2, 1, ").append(LS); buffer.append(" 0, now() ").append(LS); buffer.append(") ").append(LS); String sqlInsert = buffer.toString(); boolean isAutoCommit = false; int i = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = ConnHelper.getConnection(); conn.setAutoCommit(isAutoCommit); pstmt = conn.prepareStatement(sqlInsert); for (i = 0; i < 10; i++) { String lock = "" + ((int) (Math.random() * 100000000)) % 100; pstmt.setString(1, lock); pstmt.executeUpdate(); } if (!isAutoCommit) conn.commit(); rs = pstmt.executeQuery("select max(DOMAIN_ID) from DOMAIN"); if (rs.next()) { String str = System.currentTimeMillis() + " " + rs.getLong(1); } } catch (Exception e) { try { if (!isAutoCommit) conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(System.out); } String msg = System.currentTimeMillis() + " " + Thread.currentThread().getName() + " - " + i + " " + e.getMessage() + LS; FileIO.writeToFile("D:/DEAD_LOCK.txt", msg, true, "GBK"); } finally { ConnHelper.close(conn, pstmt, rs); } } } }).start(); } } Code Sample 2: protected InputSource loadExternalSdl(String aActualLocation) throws RuntimeException { logger.debug("loadExternalSdl(String) " + aActualLocation); try { URL url = new URL(aActualLocation); return new InputSource(url.openStream()); } catch (MalformedURLException e) { logger.error(e); throw new RuntimeException(aActualLocation + AeMessages.getString("AeWsdlLocator.ERROR_1"), e); } catch (IOException e) { logger.error(e); throw new RuntimeException(AeMessages.getString("AeWsdlLocator.ERROR_2") + aActualLocation, e); } }
00
Code Sample 1: private void populateAPI(API api) { try { if (api.isPopulated()) { log.traceln("Skipping API " + api.getName() + " (already populated)"); return; } api.setPopulated(true); String sql = "update API set populated=1 where name=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, api.getName()); pstmt.executeUpdate(); pstmt.close(); storePackagesAndClasses(api); conn.commit(); } catch (SQLException ex) { log.error("Store (api: " + api.getName() + ") failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } } Code Sample 2: public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), e); } } Code Sample 2: public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
00
Code Sample 1: public static String crypt(String password, String salt) throws java.security.NoSuchAlgorithmException { int saltEnd; int len; int value; int i; MessageDigest hash1; MessageDigest hash2; byte[] digest; byte[] passwordBytes; byte[] saltBytes; StringBuffer result; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if ((saltEnd = salt.indexOf('$')) != -1) { salt = salt.substring(0, saltEnd); } if (salt.length() > 8) { salt = salt.substring(0, 8); } hash1 = MessageDigest.getInstance("MD5"); hash1.update(password.getBytes()); hash1.update(magic.getBytes()); hash1.update(salt.getBytes()); hash2 = MessageDigest.getInstance("MD5"); hash2.update(password.getBytes()); hash2.update(salt.getBytes()); hash2.update(password.getBytes()); digest = hash2.digest(); for (len = password.length(); len > 0; len -= 16) { hash1.update(digest, 0, len > 16 ? 16 : len); } passwordBytes = password.getBytes(); for (i = password.length(); i > 0; i >>= 1) { if ((i & 1) == 1) { hash1.update((byte) 0); } else { hash1.update(passwordBytes, 0, 1); } } result = new StringBuffer(magic); result.append(salt); result.append("$"); digest = hash1.digest(); saltBytes = salt.getBytes(); for (i = 0; i < 1000; i++) { hash2.reset(); if ((i & 1) == 1) { hash2.update(passwordBytes); } else { hash2.update(digest); } if (i % 3 != 0) { hash2.update(saltBytes); } if (i % 7 != 0) { hash2.update(passwordBytes); } if ((i & 1) != 0) { hash2.update(digest); } else { hash2.update(passwordBytes); } digest = hash2.digest(); } value = ((digest[0] & 0xff) << 16) | ((digest[6] & 0xff) << 8) | (digest[12] & 0xff); result.append(to64(value, 4)); value = ((digest[1] & 0xff) << 16) | ((digest[7] & 0xff) << 8) | (digest[13] & 0xff); result.append(to64(value, 4)); value = ((digest[2] & 0xff) << 16) | ((digest[8] & 0xff) << 8) | (digest[14] & 0xff); result.append(to64(value, 4)); value = ((digest[3] & 0xff) << 16) | ((digest[9] & 0xff) << 8) | (digest[15] & 0xff); result.append(to64(value, 4)); value = ((digest[4] & 0xff) << 16) | ((digest[10] & 0xff) << 8) | (digest[5] & 0xff); result.append(to64(value, 4)); value = digest[11] & 0xff; result.append(to64(value, 2)); return result.toString(); } Code Sample 2: public static void loginBayFiles() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to bayfiles.com"); HttpPost httppost = new HttpPost("http://bayfiles.com/ajax_login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("username", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("SESSID")) { sessioncookie = "SESSID=" + escookie.getValue(); System.out.println(sessioncookie); login = true; System.out.println("BayFiles.com Login success :)"); } } if (!login) { System.out.println("BayFiles.com Login failed :("); } }
11
Code Sample 1: private void _resetLanguages(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; File from = new java.io.File(filePath); from.createNewFile(); String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File to = new java.io.File(tmpFilePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { Logger.debug(this, "Property File copy Failed " + e, e); } } } Code Sample 2: private File uploadToTmp() { if (fileFileName == null) { return null; } File tmpFile = dataDir.tmpFile(shortname, fileFileName); log.debug("Uploading dwc archive file for new resource " + shortname + " to " + tmpFile.getAbsolutePath()); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); output = new FileOutputStream(tmpFile); IOUtils.copy(input, output); output.flush(); log.debug("Uploaded file " + fileFileName + " with content-type " + fileContentType); } catch (IOException e) { log.error(e); return null; } finally { if (output != null) { IOUtils.closeQuietly(output); } if (input != null) { IOUtils.closeQuietly(input); } } return tmpFile; }
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: @Override public String encodePassword(final String password, final Object salt) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(salt.toString().getBytes()); byte[] passwordHash = digest.digest(password.getBytes()); Base64 encoder = new Base64(); byte[] encoded = encoder.encode(passwordHash); return new String(encoded); } catch (Exception e) { throw new RuntimeException(e); } }
00
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: protected void doGetPost(HttpServletRequest req, HttpServletResponse resp, boolean post) throws ServletException, IOException { if (responseBufferSize > 0) resp.setBufferSize(responseBufferSize); String pathinfo = req.getPathInfo(); if (pathinfo == null) { String urlstring = req.getParameter(REMOTE_URL); if (urlstring == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.nourl")); return; } boolean allowCookieForwarding = "true".equals(req.getParameter(ALLOW_COOKIE_FORWARDING)); boolean allowFormDataForwarding = "true".equals(req.getParameter(ALLOW_FORM_DATA_FORWARDING)); String target = new JGlossURLRewriter(req.getContextPath() + req.getServletPath(), new URL(HttpUtils.getRequestURL(req).toString()), null, allowCookieForwarding, allowFormDataForwarding).rewrite(urlstring, true); resp.sendRedirect(target); return; } Set connectionAllowedProtocols; if (req.isSecure()) connectionAllowedProtocols = secureAllowedProtocols; else connectionAllowedProtocols = allowedProtocols; Object[] oa = JGlossURLRewriter.parseEncodedPath(pathinfo); if (oa == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.malformedrequest"), new Object[] { pathinfo })); return; } boolean allowCookieForwarding = ((Boolean) oa[0]).booleanValue(); boolean allowFormDataForwarding = ((Boolean) oa[1]).booleanValue(); String urlstring = (String) oa[2]; getServletContext().log("received request for " + urlstring); if (urlstring.toLowerCase().indexOf(req.getServletPath().toLowerCase()) != -1) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.addressnotallowed"), new Object[] { urlstring })); return; } if (urlstring.indexOf(':') == -1) { if (req.isSecure()) { if (secureAllowedProtocols.contains("https")) urlstring = "https://" + urlstring; } else { if (allowedProtocols.contains("http")) urlstring = "http://" + urlstring; } } URL url; try { url = new URL(urlstring); } catch (MalformedURLException ex) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.malformedurl"), new Object[] { urlstring })); return; } String protocol = url.getProtocol(); if (!connectionAllowedProtocols.contains(protocol)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.protocolnotallowed"), new Object[] { protocol })); getServletContext().log("protocol not allowed accessing " + url.toString()); return; } boolean remoteIsHttp = protocol.equals("http") || protocol.equals("https"); boolean forwardCookies = remoteIsHttp && enableCookieForwarding && allowCookieForwarding; boolean forwardFormData = remoteIsHttp && enableFormDataForwarding && allowFormDataForwarding && (enableFormDataSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https")); if (forwardFormData) { String query = req.getQueryString(); if (query != null && query.length() > 0) { if (url.getQuery() == null || url.getQuery().length() == 0) url = new URL(url.toExternalForm() + "?" + query); else url = new URL(url.toExternalForm() + "&" + query); } } JGlossURLRewriter rewriter = new JGlossURLRewriter(new URL(req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath() + req.getServletPath()).toExternalForm(), url, connectionAllowedProtocols, allowCookieForwarding, allowFormDataForwarding); URLConnection connection = url.openConnection(); if (forwardFormData && post && remoteIsHttp) { getServletContext().log("using POST"); try { ((HttpURLConnection) connection).setRequestMethod("POST"); } catch (ClassCastException ex) { getServletContext().log("failed to set method POST: " + ex.getMessage()); } connection.setDoInput(true); connection.setDoOutput(true); } String acceptEncoding = buildAcceptEncoding(req.getHeader("accept-encoding")); getServletContext().log("accept-encoding: " + acceptEncoding); if (acceptEncoding != null) connection.setRequestProperty("Accept-Encoding", acceptEncoding); forwardRequestHeaders(connection, req); if (forwardCookies && (enableCookieSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https"))) CookieTools.addRequestCookies(connection, req.getCookies(), getServletContext()); try { connection.connect(); } catch (UnknownHostException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.unknownhost"), new Object[] { url.toExternalForm(), url.getHost() })); return; } catch (IOException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.connect"), new Object[] { url.toExternalForm(), ex.getClass().getName(), ex.getMessage() })); return; } if (forwardFormData && post && remoteIsHttp) { InputStream is = req.getInputStream(); OutputStream os = connection.getOutputStream(); byte[] buf = new byte[512]; int len; while ((len = is.read(buf)) != -1) os.write(buf, 0, len); is.close(); os.close(); } forwardResponseHeaders(connection, req, resp, rewriter); if (forwardCookies && (enableCookieSecureInsecureForwarding || req.isSecure() || !url.getProtocol().equals("https"))) CookieTools.addResponseCookies(connection, resp, req.getServerName(), req.getContextPath() + req.getServletPath(), req.isSecure(), getServletContext()); if (remoteIsHttp) { try { int response = ((HttpURLConnection) connection).getResponseCode(); getServletContext().log("response code " + response); resp.setStatus(response); if (response == 304) return; } catch (ClassCastException ex) { getServletContext().log("failed to read response code: " + ex.getMessage()); } } String type = connection.getContentType(); getServletContext().log("content type " + type + " url " + connection.getURL().toString()); boolean supported = false; if (type != null) { for (int i = 0; i < rewrittenContentTypes.length; i++) if (type.startsWith(rewrittenContentTypes[i])) { supported = true; break; } } if (supported) { String encoding = connection.getContentEncoding(); supported = encoding == null || encoding.endsWith("gzip") || encoding.endsWith("deflate") || encoding.equals("identity"); } if (supported) rewrite(connection, req, resp, rewriter); else tunnel(connection, req, resp); }
00
Code Sample 1: public InputStream getEntry(String entryPath) throws IOException { if (!entries.contains(entryPath)) { return null; } JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (ze.getName().equals(entryPath)) { return jis; } } while (true); assert (false); return null; } Code Sample 2: private void serveCGI(TinyCGI script) throws IOException, TinyWebThreadException { parseHTTPHeaders(); OutputStream cgiOut = null; File tempFile = null; try { if (script == null) sendError(500, "Internal Error", "Couldn't load script."); if (script instanceof TinyCGIHighVolume) { tempFile = File.createTempFile("cgi", null); cgiOut = new FileOutputStream(tempFile); } else { cgiOut = new ByteArrayOutputStream(); } script.service(inputStream, cgiOut, env); } catch (Exception cgie) { this.exceptionEncountered = cgie; if (tempFile != null) tempFile.delete(); if (clientSocket == null) { return; } else if (cgie instanceof TinyCGIException) { TinyCGIException tce = (TinyCGIException) cgie; sendError(tce.getStatus(), tce.getTitle(), tce.getText(), tce.getOtherHeaders()); } else { StringWriter w = new StringWriter(); cgie.printStackTrace(new PrintWriter(w)); sendError(500, "CGI Error", "Error running script: " + "<PRE>" + w.toString() + "</PRE>"); } } finally { if (script != null) doneWithScript(script); } InputStream cgiResults = null; long totalSize = 0; if (tempFile == null) { byte[] results = ((ByteArrayOutputStream) cgiOut).toByteArray(); totalSize = results.length; cgiResults = new ByteArrayInputStream(results); } else { cgiOut.close(); totalSize = tempFile.length(); cgiResults = new FileInputStream(tempFile); } String contentType = null, statusString = "OK", line, header; StringBuffer otherHeaders = new StringBuffer(); StringBuffer text = new StringBuffer(); int status = 200; int headerLength = 0; while (true) { line = readLine(cgiResults, true); headerLength += line.length(); if (line.charAt(0) == '\r' || line.charAt(0) == '\n') break; header = parseHeader(line, text); if (header.toUpperCase().equals("STATUS")) { statusString = text.toString(); status = Integer.parseInt(statusString.substring(0, 3)); statusString = statusString.substring(4); } else if (header.toUpperCase().equals("CONTENT-TYPE")) contentType = text.toString(); else { if (header.toUpperCase().equals("LOCATION")) status = 302; otherHeaders.append(header).append(": ").append(text.toString()).append(CRLF); } } sendHeaders(status, statusString, contentType, totalSize - headerLength, -1, otherHeaders.toString()); byte[] buf = new byte[2048]; int bytesRead; while ((bytesRead = cgiResults.read(buf)) != -1) outputStream.write(buf, 0, bytesRead); outputStream.flush(); try { cgiResults.close(); if (tempFile != null) tempFile.delete(); } catch (IOException ioe) { } }
11
Code Sample 1: public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException { if (!generatedOutputDirectory.exists()) { generatedOutputDirectory.createFolder(); } if (outputDirectory.exists()) { outputDirectory.createFolder(); } ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/service/xdoc/resources.zip"), outputDirectory); for (Library library : libraryModels) { String libraryName = library.getName(); String libraryLocation = library.getLocation(); generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder(); try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName); FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.xml"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } for (Component component : library.getComponents()) { String componentName = component.getName(); System.out.println("Generating " + libraryName + ":" + componentName + "..."); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("libraryName", libraryName); parameters.put("componentName", componentName); String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters); Writer out = null; try { FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true)); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); Resource specificationLocation = component.getSpecificationLocation(); if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) { File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI()); FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource"); if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) { File[] files = srcResourcesDirectory.listFiles(); if (files != null) { for (File resource : files) { if (resource.isFile() && !resource.isHidden()) { FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName()); resourceFileObject.createFile(); InputStream inResource = null; OutputStream outResource = null; try { inResource = new FileInputStream(resource); outResource = resourceFileObject.getContent().getOutputStream(); IOUtils.copy(inResource, outResource); } finally { IOUtils.closeQuietly(inResource); IOUtils.closeQuietly(outResource); } } } } } } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } } { Writer out = null; try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl")); FileObject index = generatedOutputDirectory.resolveFile("index.xml"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } } 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(); }
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 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; }
00
Code Sample 1: @Override List<String> HttpGet(URL url) throws IOException { List<String> responseList = new ArrayList<String>(); Logger.getInstance().logInfo("HTTP GET: " + url, null, getGatewayId()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(20000); con.setAllowUserInteraction(false); responseList.add(con.getResponseCode() + " " + con.getResponseMessage()); InputStream inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) responseList.add(inputLine); in.close(); return responseList; } Code Sample 2: private void appendAndDelete(FileOutputStream outstream, String file) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(file); byte[] buffer = new byte[65536]; int l; while ((l = input.read(buffer)) != -1) outstream.write(buffer, 0, l); input.close(); new File(file).delete(); }
11
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuilder hexString = new StringBuilder(); 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 String encrypt(String password, Long digestSeed) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes("UTF-8")); algorithm.update(digestSeed.toString().getBytes("UTF-8")); byte[] messageDigest = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xff & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
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: 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: private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } } Code Sample 2: public void deleteInstance(int instanceId) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, instanceId) == false) throw new ObjectNotFoundException(instanceId); ObjectLinkTable objectLinkList = new ObjectLinkTable(); ObjectAttributeTable objectAttributeList = new ObjectAttributeTable(); objectLinkList.deleteObject(stmt, instanceId); objectAttributeList.deleteObject(stmt, instanceId); stmt.executeUpdate("delete from Objects where ObjectId = " + instanceId); 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); } }
00
Code Sample 1: protected byte[] computeHash() { try { final MessageDigest inputHash = MessageDigest.getInstance("SHA"); inputHash.update(bufferFileData().getBytes()); return inputHash.digest(); } catch (final NoSuchAlgorithmException nsae) { lastException = nsae; return new byte[0]; } catch (final IOException ioe) { lastException = ioe; return new byte[0]; } } Code Sample 2: public int extractDocumentsInternal(DocumentHolder holder, DocumentFactory docFactory) { FTPClient client = new FTPClient(); try { client.connect(site, port == 0 ? 21 : port); client.login(user, password); visitDirectory(client, "", path, holder, docFactory); client.disconnect(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { } return fileCount; }
00
Code Sample 1: private static InputStream download(String url) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse httpresponse = httpclient.execute(httpget); HttpEntity httpentity = httpresponse.getEntity(); if (httpentity != null) { return httpentity.getContent(); } } catch (Exception e) { Log.e("Android", e.getMessage()); } return null; } Code Sample 2: private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
11
Code Sample 1: private void generateSchema() { ConsoleOutputWindow console = DefaultXPontusWindowImpl.getInstance().getConsole(); MessagesWindowDockable mconsole = (MessagesWindowDockable) console.getDockableById(MessagesWindowDockable.DOCKABLE_ID); ByteArrayOutputStream bao = new ByteArrayOutputStream(); IDocumentContainer container = (IDocumentContainer) DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentDockable(); try { SchemaGenerationModel model = view.getModel(); boolean isValid = transformationIsValid(model); if (!isValid) { return; } DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Generating schema..."); view.setVisible(false); InputFormat inFormat = null; OutputFormat of = null; if (model.getInputType().equalsIgnoreCase("RELAX NG Grammar")) { inFormat = new SAXParseInputFormat(); } else if (model.getInputType().equalsIgnoreCase("RELAX NG Compact Grammar")) { inFormat = new CompactParseInputFormat(); } else if (model.getInputType().equalsIgnoreCase("DTD")) { inFormat = new DtdInputFormat(); } else if (model.getInputType().equalsIgnoreCase("XML")) { inFormat = new XmlInputFormat(); } if (model.getOutputType().equalsIgnoreCase("DTD")) { of = new DtdOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("Relax NG Grammar")) { of = new RngOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("XML Schema")) { of = new XsdOutputFormat(); } else if (model.getOutputType().equalsIgnoreCase("Relax NG Compact Grammar")) { of = new RncOutputFormat(); } ErrorHandlerImpl eh = new ErrorHandlerImpl(bao); SchemaCollection sc = null; if (!view.getModel().isUseExternalDocument()) { JTextComponent jtc = DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentEditor(); if (jtc == null) { XPontusComponentsUtils.showErrorMessage("No document opened!!!"); DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!"); return; } String suffixe = model.getOutputType().toLowerCase(); File tmp = File.createTempFile("schemageneratorhandler", +System.currentTimeMillis() + "." + suffixe); OutputStream m_outputStream = new FileOutputStream(tmp); CharsetDetector detector = new CharsetDetector(); detector.setText(jtc.getText().getBytes()); Writer m_writer = new OutputStreamWriter(m_outputStream, "UTF-8"); IOUtils.copy(detector.detect().getReader(), m_writer); IOUtils.closeQuietly(m_writer); try { sc = inFormat.load(UriOrFile.toUri(tmp.getAbsolutePath()), new String[0], model.getOutputType().toLowerCase(), eh); } catch (Exception ife) { ife.printStackTrace(); StrBuilder stb = new StrBuilder(); stb.append("\nError loading input document!\n"); stb.append("Maybe the input type is invalid?\n"); stb.append("Please check again the input type list or trying validating your document\n"); throw new Exception(stb.toString()); } tmp.deleteOnExit(); } else { try { sc = inFormat.load(UriOrFile.toUri(view.getModel().getInputURI()), new String[0], model.getOutputType().toLowerCase(), eh); } catch (Exception ife) { StrBuilder stb = new StrBuilder(); stb.append("\nError loading input document!\n"); stb.append("Maybe the input type is invalid?\n"); stb.append("Please check again the input type list or trying validating your document\n"); throw new Exception(stb.toString()); } } OutputDirectory od = new LocalOutputDirectory(sc.getMainUri(), new File(view.getModel().getOutputURI()), model.getOutputType().toLowerCase(), DEFAULT_OUTPUT_ENCODING, DEFAULT_LINE_LENGTH, DEFAULT_INDENT); of.output(sc, od, new String[0], model.getInputType().toLowerCase(), eh); mconsole.println("Schema generated sucessfully!"); DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Schema generated sucessfully!"); if (model.isOpenInEditor()) { XPontusComponentsUtils.showWarningMessage("The document will NOT be opened in the editor sorry for that!\n You need to open it yourself."); } } catch (Exception ex) { DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!"); StringWriter sw = new StringWriter(); PrintWriter ps = new PrintWriter(sw); ex.printStackTrace(ps); StrBuilder sb = new StrBuilder(); sb.append("Error generating schema"); sb.appendNewLine(); sb.append(new String(bao.toByteArray())); sb.appendNewLine(); if (ex instanceof SAXParseException) { SAXParseException spe = (SAXParseException) ex; sb.append("Error around line " + spe.getLineNumber()); sb.append(", column " + spe.getColumnNumber()); sb.appendNewLine(); } sb.append(sw.toString()); mconsole.println(sb.toString(), OutputDockable.RED_STYLE); logger.error(sb.toString()); try { ps.flush(); ps.close(); sw.flush(); sw.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } } finally { console.setFocus(MessagesWindowDockable.DOCKABLE_ID); Toolkit.getDefaultToolkit().beep(); } } 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 void copieFichier(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } Code Sample 2: public static String getMD5Hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); String hexChar = ""; for (int i = 0; i < hash.length; i++) { hexChar = Integer.toHexString(0xFF & hash[i]); if (hexChar.length() < 2) { hexChar = "0" + hexChar; } hexString.append(hexChar); } return hexString.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
00
Code Sample 1: public static String encrypt(String password) { String sign = password; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(sign.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } sign = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return sign; } Code Sample 2: public static Map<String, List<String>> getResponseHeader(String address) { System.out.println(address); URLConnection conn = null; Map<String, List<String>> responseHeader = null; try { URL url = new URL(address); conn = url.openConnection(); responseHeader = conn.getHeaderFields(); } catch (Exception e) { e.printStackTrace(); } return responseHeader; }
00
Code Sample 1: public void loadProfilefromConfig(String filename, P xslProfileClass, String profileTag) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { if (Val.chkStr(profileTag).equals("")) { profileTag = "Profile"; } String configuration_folder_path = this.getConfigurationFolderPath(); if (configuration_folder_path == null || configuration_folder_path.length() == 0) { Properties properties = new Properties(); final URL url = CswProfiles.class.getResource("CswCommon.properties"); properties.load(url.openStream()); configuration_folder_path = properties.getProperty("DEFAULT_CONFIGURATION_FOLDER_PATH"); } DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); ResourcePath rscPath = new ResourcePath(); InputSource configFile = rscPath.makeInputSource(configuration_folder_path + filename); if (configFile == null) { configFile = rscPath.makeInputSource("/" + configuration_folder_path + filename); } Document doc = builder.parse(configFile); NodeList profileNodes = doc.getElementsByTagName(profileTag); for (int i = 0; i < profileNodes.getLength(); i++) { Node currProfile = profileNodes.item(i); XPath xpath = XPathFactory.newInstance().newXPath(); String id = Val.chkStr(xpath.evaluate("ID", currProfile)); String name = Val.chkStr(xpath.evaluate("Name", currProfile)); String description = Val.chkStr(xpath.evaluate("Description", currProfile)); String requestXslt = Val.chkStr(xpath.evaluate("GetRecords/XSLTransformations/Request", currProfile)); String expectedGptXmlOutput = Val.chkStr(xpath.evaluate("GetRecords/XSLTransformations/Request/@expectedGptXmlOutput", currProfile)); if (expectedGptXmlOutput.equals("")) { expectedGptXmlOutput = FORMAT_SEARCH_TO_XSL.MINIMAL_LEGACY_CSWCLIENT.toString(); } String responseXslt = Val.chkStr(xpath.evaluate("GetRecords/XSLTransformations/Response", currProfile)); String requestKVPs = Val.chkStr(xpath.evaluate("GetRecordByID/RequestKVPs", currProfile)); String metadataXslt = Val.chkStr(xpath.evaluate("GetRecordByID/XSLTransformations/Response", currProfile)); boolean extentSearch = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("SupportSpatialQuery", currProfile))); boolean liveDataMaps = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("SupportContentTypeQuery", currProfile))); boolean extentDisplay = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("SupportSpatialBoundary", currProfile))); boolean harvestable = Boolean.parseBoolean(Val.chkStr(xpath.evaluate("Harvestable", currProfile))); requestXslt = configuration_folder_path + requestXslt; responseXslt = configuration_folder_path + responseXslt; metadataXslt = configuration_folder_path + metadataXslt; SearchXslProfile profile = null; try { profile = xslProfileClass.getClass().newInstance(); profile.setId(id); profile.setName(name); profile.setDescription(description); profile.setRequestxslt(requestXslt); profile.setResponsexslt(responseXslt); profile.setMetadataxslt(metadataXslt); profile.setSupportsContentTypeQuery(liveDataMaps); profile.setSupportsSpatialBoundary(extentDisplay); profile.setSupportsSpatialQuery(extentSearch); profile.setKvp(requestKVPs); profile.setHarvestable(harvestable); profile.setFormatRequestToXsl(SearchXslProfile.FORMAT_SEARCH_TO_XSL.valueOf(expectedGptXmlOutput)); profile.setFilter_extentsearch(extentSearch); profile.setFilter_livedatamap(liveDataMaps); addProfile((P) profile); } catch (InstantiationException e) { throw new IOException("Could not instantiate profile class" + e.getMessage()); } catch (IllegalAccessException e) { throw new IOException("Could not instantiate profile class" + e.getMessage()); } } } Code Sample 2: private void processar() { boolean bOK = false; String sSQL = "DELETE FROM FNSALDOLANCA WHERE CODEMP=? AND CODFILIAL=?"; try { state("Excluindo base atual de saldos..."); PreparedStatement ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("FNSALDOLANCA")); ps.executeUpdate(); ps.close(); state("Base excluida..."); bOK = true; } catch (SQLException err) { Funcoes.mensagemErro(this, "Erro ao excluir os saldos!\n" + err.getMessage(), true, con, err); err.printStackTrace(); } if (bOK) { bOK = false; sSQL = "SELECT CODPLAN,DATASUBLANCA,SUM(VLRSUBLANCA) VLRSUBLANCA FROM " + "FNSUBLANCA WHERE CODEMP=? AND CODFILIAL=? GROUP BY CODPLAN,DATASUBLANCA " + "ORDER BY CODPLAN,DATASUBLANCA"; try { state("Iniciando reconstru��o..."); PreparedStatement ps = con.prepareStatement(sSQL); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("FNLANCA")); ResultSet rs = ps.executeQuery(); String sPlanAnt = ""; double dSaldo = 0; bOK = true; int iFilialPlan = ListaCampos.getMasterFilial("FNPLANEJAMENTO"); int iFilialSaldo = ListaCampos.getMasterFilial("FNSALDOLANCA"); while (rs.next() && bOK) { if ("1010100000004".equals(rs.getString("CodPlan"))) { System.out.println("Debug"); } if (sPlanAnt.equals(rs.getString("CodPlan"))) { dSaldo += rs.getDouble("VLRSUBLANCA"); } else dSaldo = rs.getDouble("VLRSUBLANCA"); bOK = insereSaldo(iFilialSaldo, iFilialPlan, rs.getString("CodPlan"), rs.getDate("DataSubLanca"), dSaldo); sPlanAnt = rs.getString("CodPlan"); if ("1010100000004".equals(sPlanAnt)) { System.out.println("Debug"); } } ps.close(); state("Aguardando grava��o final..."); } catch (SQLException err) { bOK = false; Funcoes.mensagemErro(this, "Erro ao excluir os lan�amentos!\n" + err.getMessage(), true, con, err); err.printStackTrace(); } } try { if (bOK) { con.commit(); state("Registros processados com sucesso!"); } else { state("Registros antigos restaurados!"); con.rollback(); } } catch (SQLException err) { Funcoes.mensagemErro(this, "Erro ao relizar precedimento!\n" + err.getMessage(), true, con, err); err.printStackTrace(); } bRunProcesso = false; btProcessar.setEnabled(true); }
00
Code Sample 1: public HttpURLConnection getURLConnection() throws IOException { String url_str = getServerURL(); URL url = new URL(url_str); HttpURLConnection urlConnection; if (url_str.toLowerCase().startsWith("https")) { HttpsURLConnection urlSConnection = (HttpsURLConnection) url.openConnection(); urlSConnection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); urlConnection = urlSConnection; } else urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); if (useHTTPProxy && getProxyLogin() != null) { String authString = getProxyLogin() + ":" + getProxyPassword(); String auth = "Basic " + new sun.misc.BASE64Encoder().encode(authString.getBytes()); urlConnection.setRequestProperty("Proxy-Authorization", auth); } urlConnection.setDoOutput(true); if (useHTTPProxy) { System.getProperties().put("proxySet", "true"); System.getProperties().put("proxyHost", proxyHost); System.getProperties().put("proxyPort", String.valueOf(proxyPort)); } return urlConnection; } Code Sample 2: public JythonWrapperAction(AActionBO.ActionDTO dto, URL url) throws IOException { super(dto); InputStream in = url.openStream(); InputStreamReader rin = new InputStreamReader(in); BufferedReader reader = new BufferedReader(rin); StringBuffer s = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { s.append(str); s.append("\n"); } in.close(); script = s.toString(); }
00
Code Sample 1: public void login(LoginData loginData) throws ConnectionEstablishException, AccessDeniedException { try { int reply; this.ftpClient.connect(loginData.getFtpServer()); reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); throw (new ConnectionEstablishException("FTP server refused connection.")); } } catch (IOException e) { if (this.ftpClient.isConnected()) { try { this.ftpClient.disconnect(); } catch (IOException f) { } } e.printStackTrace(); throw (new ConnectionEstablishException("Could not connect to server.", e)); } try { if (!this.ftpClient.login(loginData.getFtpBenutzer(), loginData.getFtpPasswort())) { this.logout(); throw (new AccessDeniedException("Could not login into server.")); } } catch (IOException ioe) { ioe.printStackTrace(); throw (new AccessDeniedException("Could not login into server.", ioe)); } } Code Sample 2: public void createVendorSignature() { byte b; try { _vendorMessageDigest = MessageDigest.getInstance("MD5"); _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1"); _vendorSig.initSign((PrivateKey) _vendorPrivateKey); _vendorMessageDigest.update(getBankString().getBytes()); _vendorMessageDigestBytes = _vendorMessageDigest.digest(); _vendorSig.update(_vendorMessageDigestBytes); _vendorSignatureBytes = _vendorSig.sign(); } catch (Exception e) { } ; }
00
Code Sample 1: public static String[] getURLListFromResource(String resourceName, String regExFilter, boolean firstNoEmptyMatched) { String[] urlArray; Vector<String> urlVector = new Vector<String>(); try { ClassLoader classLoader = MqatMain.class.getClassLoader(); URLClassLoader urlClassLoader = (URLClassLoader) classLoader; Enumeration e = urlClassLoader.findResources(resourceName); for (; e.hasMoreElements(); ) { URL url = (URL) e.nextElement(); if ("file".equals(url.getProtocol())) { File file = new File(url.getPath()); File[] fileList = file.listFiles(); if (fileList != null) { for (int i = 0; i < fileList.length; i++) { String urlStr = fileList[i].toURL().toString(); if (urlStr.matches(regExFilter)) { urlVector.add(urlStr); } } } } else if ("jar".equals(url.getProtocol())) { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = jarConnection.getJarFile(); Enumeration jarEntries = jarFile.entries(); for (; jarEntries.hasMoreElements(); ) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) { String urlStr = url.toString().substring(0, url.toString().lastIndexOf('!') + 1); urlStr += "/" + jarEntry; if (urlStr.matches(regExFilter)) { urlVector.add(urlStr); } } } } if (!urlVector.isEmpty() && firstNoEmptyMatched) { break; } } } catch (Exception ex) { ExceptionHandler.handle(ex, ExceptionHandler.NO_VISUAL); } urlArray = urlVector.toArray(new String[urlVector.size()]); return urlArray; } Code Sample 2: @Override public String encryptPassword(String password) throws JetspeedSecurityException { if (securePasswords == false) { return password; } if (password == null) { return null; } try { if ("SHA-512".equals(passwordsAlgorithm)) { password = password + JetspeedResources.getString("aipo.encrypt_key"); MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); md.reset(); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < hash.length; i++) { sb.append(Integer.toHexString((hash[i] >> 4) & 0x0F)); sb.append(Integer.toHexString(hash[i] & 0x0F)); } return sb.toString(); } else { MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); byte[] digest = md.digest(password.getBytes(ALEipConstants.DEF_CONTENT_ENCODING)); ByteArrayOutputStream bas = new ByteArrayOutputStream(digest.length + digest.length / 3 + 1); OutputStream encodedStream = MimeUtility.encode(bas, "base64"); encodedStream.write(digest); encodedStream.flush(); encodedStream.close(); return bas.toString(); } } catch (Exception e) { logger.error("Unable to encrypt password." + e.getMessage(), e); return null; } }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: @Test public void testCascadeTraining() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("parity8.train"), new FileOutputStream(temp)); Fann fann = new FannShortcut(8, 1); Trainer trainer = new Trainer(fann); float desiredError = .00f; float mse = trainer.cascadeTrain(temp.getPath(), 30, 1, desiredError); assertTrue("" + mse, mse <= desiredError); }
00
Code Sample 1: public DataSet newparse() throws SnifflibDatatypeException { NumberFormat numformat = NumberFormat.getInstance(); if (this.headers.size() != this.types.size()) { throw new SnifflibDatatypeException("Different number of headers (" + this.headers.size() + ") and types(" + this.types.size() + ")."); } DataSet out = null; if (!this.dryrun) { out = new DataSet(); } BufferedReader r = null; StreamTokenizer tokenizer = null; try { if (this.isURL) { if (this.url2goto == null) { return (null); } DataInputStream in = null; try { in = new DataInputStream(this.url2goto.openStream()); System.out.println("READY TO READ FROM URL:" + url2goto); r = new BufferedReader(new InputStreamReader(in)); } catch (Exception err) { throw new RuntimeException("Problem reading from URL " + this.url2goto + ".", err); } } else { if (this.file == null) { throw new RuntimeException("Data file to be parsed can not be null."); } if (!this.file.exists()) { throw new RuntimeException("The file " + this.file + " does not exist."); } r = new BufferedReader(new FileReader(this.file)); } if (this.ignorePreHeaderLines > 0) { String strLine; int k = 0; while ((k < this.ignorePreHeaderLines) && ((strLine = r.readLine()) != null)) { k++; } } tokenizer = new StreamTokenizer(r); tokenizer.resetSyntax(); tokenizer.eolIsSignificant(true); boolean parseNumbers = false; for (int k = 0; k < this.types.size(); k++) { Class type = (Class) this.types.get(k); if (Number.class.isAssignableFrom(type)) { parseNumbers = true; break; } } if (parseNumbers) { tokenizer.parseNumbers(); } tokenizer.eolIsSignificant(true); if (this.delimiter.equals("\\t")) { tokenizer.whitespaceChars('\t', '\t'); tokenizer.quoteChar('"'); tokenizer.whitespaceChars(' ', ' '); } else if (this.delimiter.equals(",")) { tokenizer.quoteChar('"'); tokenizer.whitespaceChars(',', ','); tokenizer.whitespaceChars(' ', ' '); } else { if (this.delimiter.length() > 1) { throw new RuntimeException("Delimiter must be a single character. Multiple character delimiters are not allowed."); } if (this.delimiter.length() > 0) { tokenizer.whitespaceChars(this.delimiter.charAt(0), this.delimiter.charAt(0)); } else { tokenizer.wordChars(Character.MIN_VALUE, Character.MAX_VALUE); tokenizer.eolIsSignificant(true); tokenizer.ordinaryChar('\n'); } } boolean readingHeaders = true; boolean readingInitialValues = false; boolean readingData = false; boolean readingScientificNotation = false; if (this.headers.size() > 0) { readingHeaders = false; readingInitialValues = true; } if (this.types.size() > 0) { readingInitialValues = false; Class targetclass; for (int j = 0; j < this.types.size(); j++) { targetclass = (Class) this.types.get(j); try { this.constructors.add(targetclass.getConstructor(String.class)); } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Could not find appropriate constructor for " + targetclass + ". " + err.getMessage()); } } readingData = true; } int currentColumn = 0; int currentRow = 0; this.rowcount = 0; boolean advanceField = true; while (true) { tokenizer.nextToken(); switch(tokenizer.ttype) { case StreamTokenizer.TT_WORD: { advanceField = true; if (readingScientificNotation) { throw new RuntimeException("Problem reading scientific notation at row " + currentRow + " column " + currentColumn + "."); } if (readingHeaders) { this.headers.add(tokenizer.sval); } else { if (readingInitialValues) { this.types.add(String.class); } if (!this.dryrun) { if (out.getColumnCount() <= currentColumn) { out.addColumn((String) this.headers.get(currentColumn), (Class) this.types.get(currentColumn)); } } try { Constructor construct; if (currentColumn < this.constructors.size()) { construct = (Constructor) this.constructors.get(currentColumn); } else { Class targetclass = (Class) this.types.get(currentColumn); construct = targetclass.getConstructor(String.class); this.constructors.add(construct); } try { try { try { if (!this.dryrun) { out.setValueAt(construct.newInstance((String) tokenizer.sval), currentRow, currentColumn); } else if (this.findingTargetValue) { Object vvv = construct.newInstance((String) tokenizer.sval); this.valueQueue.push(vvv); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = vvv; r.close(); return (null); } } } catch (java.lang.reflect.InvocationTargetException err) { throw new SnifflibDatatypeException("Problem constructing 1" + err.getMessage()); } } catch (java.lang.IllegalAccessException err) { throw new SnifflibDatatypeException("Problem constructing 2" + err.getMessage()); } } catch (java.lang.InstantiationException err) { throw new SnifflibDatatypeException("Problem constructing 3" + err.getMessage()); } } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Problem constructing 4" + err.getMessage()); } } break; } case StreamTokenizer.TT_NUMBER: { advanceField = true; if (readingHeaders) { throw new SnifflibDatatypeException("Expecting string header at row=" + currentRow + ", column=" + currentColumn + "."); } else { if (readingInitialValues) { this.types.add(Double.class); } if (!this.dryrun) { if (out.getColumnCount() <= currentColumn) { out.addColumn((String) this.headers.get(currentColumn), (Class) this.types.get(currentColumn)); } } try { Constructor construct; if (currentColumn < this.constructors.size()) { construct = (Constructor) this.constructors.get(currentColumn); } else { Class targetclass = (Class) this.types.get(currentColumn); construct = targetclass.getConstructor(double.class); this.constructors.add(construct); } if (readingScientificNotation) { Double val = this.scientificNumber; if (!this.dryrun) { try { out.setValueAt(new Double(val.doubleValue() * tokenizer.nval), currentRow, currentColumn); } catch (Exception err) { throw new SnifflibDatatypeException("Problem constructing " + construct.getDeclaringClass() + "at row " + currentRow + " column " + currentColumn + ".", err); } } else if (this.findingTargetValue) { Double NVAL = new Double(tokenizer.nval); Object vvv = null; try { vvv = Double.parseDouble(val + "E" + NVAL.intValue()); } catch (Exception err) { throw new RuntimeException("Problem parsing scientific notation at row=" + currentRow + " col=" + currentColumn + ".", err); } tokenizer.nextToken(); if (tokenizer.ttype != 'e') { this.valueQueue.push(vvv); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = vvv; r.close(); return (null); } currentColumn++; } else { tokenizer.pushBack(); } } readingScientificNotation = false; } else { try { this.scientificNumber = new Double(tokenizer.nval); if (!this.dryrun) { out.setValueAt(this.scientificNumber, currentRow, currentColumn); } else if (this.findingTargetValue) { this.valueQueue.push(this.scientificNumber); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = this.scientificNumber; r.close(); return (null); } } } catch (Exception err) { throw new SnifflibDatatypeException("Problem constructing " + construct.getDeclaringClass() + "at row " + currentRow + " column " + currentColumn + ".", err); } } } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Problem constructing" + err.getMessage()); } } break; } case StreamTokenizer.TT_EOL: { if (readingHeaders) { readingHeaders = false; readingInitialValues = true; } else { if (readingInitialValues) { readingInitialValues = false; readingData = true; } } if (readingData) { if (valueQueue.getUpperIndex() < currentRow) { valueQueue.push(""); } currentRow++; } break; } case StreamTokenizer.TT_EOF: { if (readingHeaders) { throw new SnifflibDatatypeException("End of file reached while reading headers."); } if (readingInitialValues) { throw new SnifflibDatatypeException("End of file reached while reading initial values."); } if (readingData) { readingData = false; } break; } default: { if (tokenizer.ttype == '"') { advanceField = true; if (readingHeaders) { this.headers.add(tokenizer.sval); } else { if (readingInitialValues) { this.types.add(String.class); } if (!this.dryrun) { if (out.getColumnCount() <= currentColumn) { out.addColumn((String) this.headers.get(currentColumn), (Class) this.types.get(currentColumn)); } } try { Constructor construct; if (currentColumn < this.constructors.size()) { construct = (Constructor) this.constructors.get(currentColumn); } else { Class targetclass = (Class) this.types.get(currentColumn); construct = targetclass.getConstructor(String.class); this.constructors.add(construct); } try { try { try { if (!this.dryrun) { out.setValueAt(construct.newInstance((String) tokenizer.sval), currentRow, currentColumn); } else if (this.findingTargetValue) { Object vvv = construct.newInstance((String) tokenizer.sval); this.valueQueue.push(vvv); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = vvv; r.close(); return (null); } } } catch (java.lang.reflect.InvocationTargetException err) { throw new SnifflibDatatypeException("Problem constructing a " + construct, err); } } catch (java.lang.IllegalAccessException err) { throw new SnifflibDatatypeException("Problem constructing 2 ", err); } } catch (java.lang.InstantiationException err) { throw new SnifflibDatatypeException("Problem constructing 3 ", err); } } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Problem constructing 4", err); } } } else if (tokenizer.ttype == 'e') { Class targetclass = (Class) this.types.get(currentColumn); if (Number.class.isAssignableFrom(targetclass)) { currentColumn--; readingScientificNotation = true; advanceField = false; } } else { advanceField = false; } break; } } if (tokenizer.ttype == StreamTokenizer.TT_EOF) { advanceField = false; break; } if (advanceField) { currentColumn++; if (!readingHeaders) { if (currentColumn >= this.headers.size()) { currentColumn = 0; } } } } if (!readingHeaders) { this.rowcount = currentRow; } else { this.rowcount = 0; readingHeaders = false; if (this.ignorePostHeaderLines > 0) { String strLine; int k = 0; while ((k < this.ignorePostHeaderLines) && ((strLine = r.readLine()) != null)) { k++; } } } r.close(); } catch (java.io.IOException err) { throw new SnifflibDatatypeException(err.getMessage()); } if (!this.dryrun) { for (int j = 0; j < this.headers.size(); j++) { out.setColumnName(j, (String) this.headers.get(j)); } } return (out); } Code Sample 2: public void openAndClose(ZKEntry zke, LinkedList toOpen, LinkedList toRemove) throws SQLException { conn.setAutoCommit(false); try { Statement stm = conn.createStatement(); ResultSet rset = stm.executeQuery("SELECT now();"); rset.next(); Timestamp now = rset.getTimestamp("now()"); for (int i = 0; i < toRemove.size(); i++) { Workitem wi = (Workitem) toRemove.get(i); rset = stm.executeQuery("SELECT intime, part FROM stampzk WHERE stampzkid = '" + wi.getStampZkId() + "';"); rset.next(); long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); stm.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + wi.getStampZkId() + "';"); } rset = stm.executeQuery("SELECT COUNT(*) FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); rset.next(); int count = rset.getInt("COUNT(*)") + toOpen.size(); rset = stm.executeQuery("SELECT * FROM stampzk WHERE personalid='" + zke.getWorker().getPersonalId() + "' AND outtime='0';"); while (rset.next()) { long diff = now.getTime() - rset.getLong("intime"); float diffp = diff * rset.getFloat("part"); int firstId = rset.getInt("firstid"); if (firstId == 0) firstId = rset.getInt("stampzkid"); Statement ust = conn.createStatement(); ust.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + rset.getInt("stampzkid") + "';"); ust.executeUpdate("INSERT INTO stampzk SET zeitkid='" + rset.getInt("zeitkid") + "', personalid='" + zke.getWorker().getPersonalId() + "', funcsid='" + rset.getInt("funcsid") + "', part='" + (float) 1f / count + "', intime='" + now.getTime() + "', firstid='" + firstId + "';"); } for (int i = 0; i < toOpen.size(); i++) { stm.executeUpdate("INSERT INTO stampzk SET zeitkid='" + zke.getZeitKId() + "', personalid='" + zke.getWorker().getPersonalId() + "', intime='" + now.getTime() + "', funcsid='" + ((Workitem) toOpen.get(i)).getWorkType() + "', part='" + (float) 1f / count + "';"); } } catch (SQLException sqle) { conn.rollback(); conn.setAutoCommit(true); throw sqle; } conn.commit(); conn.setAutoCommit(true); }
00
Code Sample 1: public String getSHA1(String input) { byte[] output = null; try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes()); output = md.digest(); } catch (Exception e) { System.out.println("Exception: " + e); } return StringUtils.byte2hex(output); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); } Code Sample 2: private InputStream openStream(URL url, ProgressListener listener, int minProgress, int maxProgress) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.setDoOutput(false); String lengthStr = con.getHeaderField("Content-Length"); InputStream urlIn; try { urlIn = con.getInputStream(); } catch (IOException e) { throw new IOException(con.getResponseCode() + ": " + con.getResponseMessage(), e); } if (lengthStr == null || lengthStr.isEmpty()) { LogService.getRoot().warning("Server did not send content length."); return urlIn; } else { try { long length = Long.parseLong(lengthStr); return new ProgressReportingInputStream(urlIn, listener, minProgress, maxProgress, length); } catch (NumberFormatException e) { LogService.getRoot().log(Level.WARNING, "Server sent illegal content length: " + lengthStr, e); return urlIn; } } }
11
Code Sample 1: private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; } Code Sample 2: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
00
Code Sample 1: public static void main(String[] args) throws Exception { URI uri = new URI("file:/c:/foo.xyz"); System.err.println(uri); uri = new URI("bin.file:/c:/foo.xyz"); System.err.println(uri); uri = new URI("bin.http://c:/foo.xyz"); System.err.println(uri); uri = new URI("bin.http://c:/foo.xyz?x[3:5]"); System.err.println(uri); uri = new File("C:\\Documents and Settings\\jbf\\My Documents\\foo.jy").toURI(); System.err.println(uri); uri = new File("/home/jbf/my%file.txt").toURI(); System.err.println(uri); System.err.println(uri.toURL()); URL url = uri.toURL(); InputStream in = url.openStream(); int ch = in.read(); while (ch != -1) { System.err.print((char) ch); ch = in.read(); } } Code Sample 2: public void PutFile(ClientConnector cc, Map<String, String> attributes) throws Exception { String destinationNode = attributes.get("dest_name"); String destinationUser = attributes.get("dest_user"); String destinationPassword = attributes.get("dest_password"); String destinationFile = attributes.get("dest_file"); String messageID = attributes.get("messageID"); String destinationFileType = attributes.get("dest_file_type"); Integer destinationPort = 21; String destinationPortString = attributes.get("dest_port"); if ((destinationPortString != null) && (destinationPortString.equals(""))) { try { destinationPort = Integer.parseInt(destinationPortString); } catch (Exception e) { destinationPort = 21; log.debug("Destination Port \"" + destinationPortString + "\" was not valid. Using Default (21)"); } } log.info("Starting FTP push of \"" + destinationFile + "\" to \"" + destinationNode); if ((destinationUser == null) || (destinationUser.equals(""))) { List userDBVal = axt.db.GeneralDAO.getNodeValue(destinationNode, "ftpUser"); if (userDBVal.size() < 1) { destinationUser = DEFAULTUSER; } else { destinationUser = (String) userDBVal.get(0); } } if ((destinationPassword == null) || (destinationPassword.equals(""))) { List passwordDBVal = axt.db.GeneralDAO.getNodeValue(destinationNode, "ftpPassword"); if (passwordDBVal.size() < 1) { destinationPassword = DEFAULTPASSWORD; } else { destinationPassword = (String) passwordDBVal.get(0); } } log.debug("Getting Stage File ID"); String stageFile = null; try { stageFile = STAGINGDIR + "/" + axt.db.GeneralDAO.getStageFile(messageID); } catch (Exception stageException) { throw new Exception("Failed to assign a staging file \"" + stageFile + "\" - ERROR: " + stageException); } InputStream in; try { in = new FileInputStream(stageFile); } catch (FileNotFoundException fileNFException) { throw new Exception("Failed to get the staging file \"" + stageFile + "\" - ERROR: " + fileNFException); } log.debug("Sending File"); FTPClient ftp = new FTPClient(); try { log.debug("Connecting"); ftp.connect(destinationNode, destinationPort); log.debug("Checking Status"); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: " + ftp.getReplyString()); } log.debug("Logging In"); if (!ftp.login(destinationUser, destinationPassword)) { ftp.disconnect(); throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: Login Failed"); } } catch (SocketException socketException) { throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: " + socketException); } catch (IOException ioe) { throw new Exception("Failed to connect to \"" + destinationNode + "\" as user \"" + destinationUser + "\" - ERROR: " + ioe); } log.debug("Performing Site Commands"); Iterator siteIterator = GeneralDAO.getNodeValue(destinationNode, "ftpSite").iterator(); while (siteIterator.hasNext()) { String siteCommand = null; try { siteCommand = (String) siteIterator.next(); ftp.site(siteCommand); } catch (IOException e) { throw new Exception("FTP \"site\" command \"" + siteCommand + "\" failed - ERROR: " + e); } } if (destinationFileType != null) { if (destinationFileType.equals("A")) { log.debug("Set File Type to ASCII"); ftp.setFileType(FTP.ASCII_FILE_TYPE); } else if (destinationFileType.equals("B")) { log.debug("Set File Type to BINARY"); ftp.setFileType(FTP.BINARY_FILE_TYPE); } else if (destinationFileType.equals("E")) { log.debug("Set File Type to EBCDIC"); ftp.setFileType(FTP.EBCDIC_FILE_TYPE); } } log.debug("Pushing File"); OutputStream out = null; try { out = ftp.storeFileStream(destinationFile); if (out == null) { throw new Exception("Failed send the file \"" + destinationFile + "\" to \"" + destinationNode + "\" - ERROR: " + ftp.getReplyString()); } } catch (IOException ioe2) { log.error("Failed to push the file \"" + destinationFile + "\" to \"" + destinationNode + "\" - ERROR: " + ioe2); } DESCrypt decrypter = null; try { decrypter = new DESCrypt(); } catch (Exception cryptInitError) { log.error("Failed to initialize the encrypt process - ERROR: " + cryptInitError); } try { decrypter.decrypt(in, out); } catch (Exception cryptError) { log.error("Send Error" + cryptError); } log.debug("Logging Out"); try { out.close(); ftp.logout(); in.close(); } catch (IOException ioe3) { log.error("Failed close connection to \"" + destinationNode + "\" - ERROR: " + ioe3); } return; }
11
Code Sample 1: 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; } 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 void delete(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(channel.getPath(), "1", connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); String sqlStr = "delete from t_ip_channel where channel_path=?"; preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); sqlStr = "delete from t_ip_channel_order where channel_order_site = ?"; preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException ex) { connection.rollback(); log.error("ɾ��Ƶ��ʧ�ܣ�channelPath=" + channel.getPath(), ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } } Code Sample 2: public static void main(String args[]) { if (args.length < 1) { printUsage(); } URL url; BufferedReader in = null; try { url = new URL(args[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if (responseCode == 200) { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } else { System.out.println("Response code " + responseCode + " means there was an error reading url " + args[0]); } } catch (IOException e) { System.err.println("IOException attempting to read url " + args[0]); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception ignore) { } } } }
11
Code Sample 1: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } Code Sample 2: private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
00
Code Sample 1: public void update(Site site) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String exp = site.getExtendParent(); String path = site.getPath(); try { String sqlStr = "update t_ip_site set id=?,name=?,description=?,ascii_name=?,remark_number=?,increment_index=?,use_status=?,appserver_id=? where id=?"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(path, exp, connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); selfDefineAdd(selfDefinePath, site, connection, preparedStatement); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, site.getSiteID()); preparedStatement.setString(2, site.getName()); preparedStatement.setString(3, site.getDescription()); preparedStatement.setString(4, site.getAsciiName()); preparedStatement.setInt(5, site.getRemarkNumber()); preparedStatement.setString(6, site.getIncrementIndex().trim()); preparedStatement.setString(7, String.valueOf(site.getUseStatus())); preparedStatement.setString(8, String.valueOf(site.getAppserverID())); preparedStatement.setInt(9, site.getSiteID()); preparedStatement.executeUpdate(); connection.commit(); int resID = site.getSiteID() + Const.SITE_TYPE_RES; StructResource sr = new StructResource(); sr.setResourceID(Integer.toString(resID)); sr.setOperateID(Integer.toString(1)); sr.setOperateTypeID(Const.OPERATE_TYPE_ID); sr.setTypeID(Const.RES_TYPE_ID); StructAuth sa = new AuthorityManager().getExternalAuthority(sr); int authID = sa.getAuthID(); if (authID == 0) { String resName = site.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); } site.wirteFile(); } catch (SQLException ex) { connection.rollback(); log.error("����վ������ʧ��!", ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } } Code Sample 2: public boolean uploadFromServlet(InputStream is, String serverFileName, String serverPath, String serverUrl, int serverPort, String userName, String passWord) throws IOException { FTPClient ftp = new FTPClient(); FTPClientConfig conf = new FTPClientConfig(); conf.setServerLanguageCode("zh_CN"); conf.setServerTimeZoneId("Asia/Chongqing"); try { ftp.configure(conf); int reply; ftp.setDefaultPort(serverPort); ftp.connect(serverUrl); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection."); } } catch (IOException e) { disconnectFtp(ftp); } try { if (!ftp.login(userName, passWord)) { throw new IOException("Can not log in with given username and password."); } if (!ftp.changeWorkingDirectory(serverPath)) { throw new IOException("Can not change to working directory."); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.storeFile(serverFileName, is)) { throw new IOException("Can not store file to FTP server."); } is.close(); } catch (SocketException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); return false; } } } return true; }
00
Code Sample 1: private static QDataSet test3_binary() throws IOException, StreamException { URL url = TestQDataSetStreamHandler.class.getResource("test3.binary.qds"); QDataSetStreamHandler handler = new QDataSetStreamHandler(); StreamTool.readStream(Channels.newChannel(url.openStream()), handler); QDataSet qds = handler.getDataSet(); return qds; } Code Sample 2: public void importarHistoricoDeCotacoesDosPapeis(File[] pArquivosTXT, boolean pApagarDadosImportadosAnteriormente, Andamento pAndamento) throws FileNotFoundException, SQLException { if (pApagarDadosImportadosAnteriormente) { Statement stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_COTACAO_AVISTA_LOTE_PDR"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "TRUNCATE TABLE TMP_TB_COTACAO_OUTROS_MERCADOS"; stmtLimpezaInicialDestino.executeUpdate(sql); } final int TAMANHO_DO_REGISTRO = 245; long TAMANHO_DOS_METADADOS_DO_ARQUIVO = 2 * TAMANHO_DO_REGISTRO; long tamanhoDosArquivos = 0; for (File arquivoTXT : pArquivosTXT) { long tamanhoDoArquivo = arquivoTXT.length(); tamanhoDosArquivos += tamanhoDoArquivo; } int quantidadeEstimadaDeRegistros = (int) ((tamanhoDosArquivos - (pArquivosTXT.length * TAMANHO_DOS_METADADOS_DO_ARQUIVO)) / TAMANHO_DO_REGISTRO); String sqlMercadoAVistaLotePadrao = "INSERT INTO TMP_TB_COTACAO_AVISTA_LOTE_PDR(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoMercadoAVistaLotePadrao = (OraclePreparedStatement) conDestino.prepareStatement(sqlMercadoAVistaLotePadrao); stmtDestinoMercadoAVistaLotePadrao.setExecuteBatch(COMANDOS_POR_LOTE); String sqlOutrosMercados = "INSERT INTO TMP_TB_COTACAO_OUTROS_MERCADOS(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoOutrosMercados = (OraclePreparedStatement) conDestino.prepareStatement(sqlOutrosMercados); stmtDestinoOutrosMercados.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportadosDosArquivos = 0; Scanner in = null; int numeroDoRegistro = -1; try { for (File arquivoTXT : pArquivosTXT) { int quantidadeDeRegistrosImportadosDoArquivoAtual = 0; int vDATA_PREGAO; try { in = new Scanner(new FileInputStream(arquivoTXT), Constantes.CONJUNTO_DE_CARACTERES_DOS_ARQUIVOS_TEXTO_DA_BOVESPA.name()); String registro; numeroDoRegistro = 0; while (in.hasNextLine()) { ++numeroDoRegistro; registro = in.nextLine(); if (registro.length() != TAMANHO_DO_REGISTRO) throw new ProblemaNaImportacaoDeArquivo(); if (registro.startsWith("01")) { stmtDestinoMercadoAVistaLotePadrao.clearParameters(); stmtDestinoOutrosMercados.clearParameters(); vDATA_PREGAO = Integer.parseInt(registro.substring(2, 10).trim()); int vCODBDI = Integer.parseInt(registro.substring(10, 12).trim()); String vCODNEG = registro.substring(12, 24).trim(); int vTPMERC = Integer.parseInt(registro.substring(24, 27).trim()); String vNOMRES = registro.substring(27, 39).trim(); String vESPECI = registro.substring(39, 49).trim(); String vPRAZOT = registro.substring(49, 52).trim(); String vMODREF = registro.substring(52, 56).trim(); BigDecimal vPREABE = obterBigDecimal(registro.substring(56, 69).trim(), 13, 2); BigDecimal vPREMAX = obterBigDecimal(registro.substring(69, 82).trim(), 13, 2); BigDecimal vPREMIN = obterBigDecimal(registro.substring(82, 95).trim(), 13, 2); BigDecimal vPREMED = obterBigDecimal(registro.substring(95, 108).trim(), 13, 2); BigDecimal vPREULT = obterBigDecimal(registro.substring(108, 121).trim(), 13, 2); BigDecimal vPREOFC = obterBigDecimal(registro.substring(121, 134).trim(), 13, 2); BigDecimal vPREOFV = obterBigDecimal(registro.substring(134, 147).trim(), 13, 2); int vTOTNEG = Integer.parseInt(registro.substring(147, 152).trim()); BigDecimal vQUATOT = new BigDecimal(registro.substring(152, 170).trim()); BigDecimal vVOLTOT = obterBigDecimal(registro.substring(170, 188).trim(), 18, 2); BigDecimal vPREEXE = obterBigDecimal(registro.substring(188, 201).trim(), 13, 2); int vINDOPC = Integer.parseInt(registro.substring(201, 202).trim()); int vDATVEN = Integer.parseInt(registro.substring(202, 210).trim()); int vFATCOT = Integer.parseInt(registro.substring(210, 217).trim()); BigDecimal vPTOEXE = obterBigDecimal(registro.substring(217, 230).trim(), 13, 6); String vCODISI = registro.substring(230, 242).trim(); int vDISMES = Integer.parseInt(registro.substring(242, 245).trim()); boolean mercadoAVistaLotePadrao = (vTPMERC == 10 && vCODBDI == 2); OraclePreparedStatement stmtDestino; if (mercadoAVistaLotePadrao) { stmtDestino = stmtDestinoMercadoAVistaLotePadrao; } else { stmtDestino = stmtDestinoOutrosMercados; } stmtDestino.setIntAtName("DATA_PREGAO", vDATA_PREGAO); stmtDestino.setIntAtName("CODBDI", vCODBDI); stmtDestino.setStringAtName("CODNEG", vCODNEG); stmtDestino.setIntAtName("TPMERC", vTPMERC); stmtDestino.setStringAtName("NOMRES", vNOMRES); stmtDestino.setStringAtName("ESPECI", vESPECI); stmtDestino.setStringAtName("PRAZOT", vPRAZOT); stmtDestino.setStringAtName("MODREF", vMODREF); stmtDestino.setBigDecimalAtName("PREABE", vPREABE); stmtDestino.setBigDecimalAtName("PREMAX", vPREMAX); stmtDestino.setBigDecimalAtName("PREMIN", vPREMIN); stmtDestino.setBigDecimalAtName("PREMED", vPREMED); stmtDestino.setBigDecimalAtName("PREULT", vPREULT); stmtDestino.setBigDecimalAtName("PREOFC", vPREOFC); stmtDestino.setBigDecimalAtName("PREOFV", vPREOFV); stmtDestino.setIntAtName("TOTNEG", vTOTNEG); stmtDestino.setBigDecimalAtName("QUATOT", vQUATOT); stmtDestino.setBigDecimalAtName("VOLTOT", vVOLTOT); stmtDestino.setBigDecimalAtName("PREEXE", vPREEXE); stmtDestino.setIntAtName("INDOPC", vINDOPC); stmtDestino.setIntAtName("DATVEN", vDATVEN); stmtDestino.setIntAtName("FATCOT", vFATCOT); stmtDestino.setBigDecimalAtName("PTOEXE", vPTOEXE); stmtDestino.setStringAtName("CODISI", vCODISI); stmtDestino.setIntAtName("DISMES", vDISMES); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportadosDoArquivoAtual++; quantidadeDeRegistrosImportadosDosArquivos++; } else if (registro.startsWith("99")) { BigDecimal totalDeRegistros = obterBigDecimal(registro.substring(31, 42).trim(), 11, 0); assert (totalDeRegistros.intValue() - 2) == quantidadeDeRegistrosImportadosDoArquivoAtual : "Quantidade de registros divergente"; break; } double percentualCompleto = (double) quantidadeDeRegistrosImportadosDosArquivos / quantidadeEstimadaDeRegistros * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = arquivoTXT.getName(); problemaDetalhado.linhaProblematicaDoArquivo = numeroDoRegistro; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { in.close(); } } } finally { pAndamento.setPercentualCompleto(100); stmtDestinoMercadoAVistaLotePadrao.close(); stmtDestinoOutrosMercados.close(); } }
00
Code Sample 1: private void saveStateAsLast(URL url) { InputStream sourceStream = null; OutputStream destinationStream = null; File lastBundlesTxt = getLastBundleInfo(); try { try { destinationStream = new FileOutputStream(lastBundlesTxt); sourceStream = url.openStream(); SimpleConfiguratorUtils.transferStreams(sourceStream, destinationStream); } finally { if (destinationStream != null) destinationStream.close(); if (sourceStream != null) sourceStream.close(); } } catch (IOException e) { } } Code Sample 2: @Test public void testGrantLicense() throws Exception { context.turnOffAuthorisationSystem(); Item item = Item.create(context); String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); LicenseUtils.grantLicense(context, item, defaultLicense); StringWriter writer = new StringWriter(); IOUtils.copy(item.getBundles("LICENSE")[0].getBitstreams()[0].retrieve(), writer); String license = writer.toString(); assertThat("testGrantLicense 0", license, equalTo(defaultLicense)); context.restoreAuthSystemState(); }
11
Code Sample 1: private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }