label
class label
2 classes
source_code
stringlengths
398
72.9k
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: protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); }
11
Code Sample 1: public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout, Map<String, String> headers) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); if (username != null || password != null) { byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } Code Sample 2: public static void refresh() { URL[] urls = Constants.Wiki2xhtml.getUpdateURLs(); content.setLength(0); InputStream is = null; BufferedReader br = null; for (int i = 0; i < urls.length; i++) { try { is = urls[i].openStream(); br = new BufferedReader(new InputStreamReader(is)); String s; while ((s = br.readLine()) != null) { if (s.length() == 0) continue; if (s.startsWith("--")) break; content.append(s + '\n'); } is.close(); break; } catch (FileNotFoundException e) { System.err.println("File not found: " + urls[i].getHost() + urls[i].getPath()); } catch (IOException e) { System.err.println("Error: " + e.getMessage()); } } }
11
Code Sample 1: protected Configuration() { try { Enumeration<URL> resources = getClass().getClassLoader().getResources("activejdbc_models.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); LogFilter.log(logger, "Load models from: " + url.toExternalForm()); InputStream inputStream = null; try { inputStream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { String[] parts = Util.split(line, ':'); String modelName = parts[0]; String dbName = parts[1]; if (modelsMap.get(dbName) == null) { modelsMap.put(dbName, new ArrayList<String>()); } modelsMap.get(dbName).add(modelName); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) inputStream.close(); } } } catch (IOException e) { throw new InitException(e); } if (modelsMap.isEmpty()) { LogFilter.log(logger, "ActiveJDBC Warning: Cannot locate any models, assuming project without models."); return; } try { InputStream in = getClass().getResourceAsStream("/activejdbc.properties"); if (in != null) properties.load(in); } catch (Exception e) { throw new InitException(e); } String cacheManagerClass = properties.getProperty("cache.manager"); if (cacheManagerClass != null) { try { Class cmc = Class.forName(cacheManagerClass); cacheManager = (CacheManager) cmc.newInstance(); } catch (Exception e) { throw new InitException("failed to initialize a CacheManager. Please, ensure that the property " + "'cache.manager' points to correct class which extends 'activejdbc.cache.CacheManager' class and provides a default constructor.", e); } } } Code Sample 2: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; }
00
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: public void importarHistoricoDoPIB(Andamento pAndamento) throws FileNotFoundException, SQLException, Exception { pAndamento.delimitarIntervaloDeVariacao(0, 49); PIB[] valoresPendentesDoPIB = obterValoresPendentesDoPIB(pAndamento); pAndamento.delimitarIntervaloDeVariacao(50, 100); if (valoresPendentesDoPIB != null && valoresPendentesDoPIB.length > 0) { String sql = "INSERT INTO tmp_TB_PIB(ULTIMO_DIA_DO_MES, PIB_ACUM_12MESES_REAL, PIB_ACUM_12MESES_DOLAR) VALUES(:ULTIMO_DIA_DO_MES, :PIB_ACUM_12MESES_REAL, :PIB_ACUM_12MESES_DOLAR)"; OraclePreparedStatement stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosASeremImportados = valoresPendentesDoPIB.length; try { int quantidadeDeRegistrosImportados = 0; int numeroDoRegistro = 0; final BigDecimal MILHAO = new BigDecimal("1000000"); for (PIB valorPendenteDoPIB : valoresPendentesDoPIB) { ++numeroDoRegistro; stmtDestino.clearParameters(); java.sql.Date vULTIMO_DIA_DO_MES = new java.sql.Date(obterUltimoDiaDoMes(valorPendenteDoPIB.mesEAno).getTime()); BigDecimal vPIB_ACUM_12MESES_REAL = valorPendenteDoPIB.valorDoPIBEmReais.multiply(MILHAO).setScale(0, RoundingMode.DOWN); BigDecimal vPIB_ACUM_12MESES_DOLAR = valorPendenteDoPIB.valorDoPIBEmDolares.multiply(MILHAO).setScale(0, RoundingMode.DOWN); stmtDestino.setDateAtName("ULTIMO_DIA_DO_MES", vULTIMO_DIA_DO_MES); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_REAL", vPIB_ACUM_12MESES_REAL); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_DOLAR", vPIB_ACUM_12MESES_DOLAR); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosASeremImportados * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); throw ex; } finally { if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } pAndamento.setPercentualCompleto(100); }
00
Code Sample 1: public void delete(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); if (urlConnection instanceof HttpURLConnection) { final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setRequestMethod("DELETE"); int responseCode = httpURLConnection.getResponseCode(); switch(responseCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_ACCEPTED: case HttpURLConnection.HTTP_NO_CONTENT: { break; } default: { throw new IOException("DELETE failed with HTTP response code " + responseCode); } } } else { throw new IOException("Delete is not supported for " + uri); } } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } } Code Sample 2: private String digestPassword(String password) { StringBuffer hexString = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes()); byte[] messageDigest = algorithm.digest(); for (byte b : messageDigest) { hexString.append(Integer.toHexString(0xFF & b)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); }
00
Code Sample 1: public Model read(String uri, String base, String lang) { try { URL url = new URL(uri); return read(url.openStream(), base, lang); } catch (IOException e) { throw new OntologyException("I/O error while reading from uri " + uri); } } Code Sample 2: private void makeDailyBackup() throws CacheOperationException, ConfigurationException { final int MAX_DAILY_BACKUPS = 5; File cacheFolder = getBackupFolder(); cacheLog.debug("Making a daily backup of current Beehive archive..."); try { File oldestDaily = new File(DAILY_BACKUP_PREFIX + "." + MAX_DAILY_BACKUPS); if (oldestDaily.exists()) { moveToWeeklyBackup(oldestDaily); } for (int index = MAX_DAILY_BACKUPS - 1; index > 0; index--) { File daily = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + index); File target = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + (index + 1)); if (!daily.exists()) { cacheLog.debug("Daily backup file ''{0}'' was not present. Skipping...", daily.getAbsolutePath()); continue; } if (!daily.renameTo(target)) { sortBackups(); throw new CacheOperationException("There was an error moving ''{0}'' to ''{1}''.", daily.getAbsolutePath(), target.getAbsolutePath()); } else { cacheLog.debug("Moved " + daily.getAbsolutePath() + " to " + target.getAbsolutePath()); } } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied read/write access to daily backup files in ''{0}'' : {1}" + e, cacheFolder.getAbsolutePath(), e.getMessage()); } File beehiveArchive = getCachedArchive(); File tempBackupArchive = new File(cacheFolder, BEEHIVE_ARCHIVE_NAME + ".tmp"); BufferedInputStream archiveReader = null; BufferedOutputStream tempBackupWriter = null; try { archiveReader = new BufferedInputStream(new FileInputStream(beehiveArchive)); tempBackupWriter = new BufferedOutputStream(new FileOutputStream(tempBackupArchive)); int len, bytecount = 0; final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = archiveReader.read(buffer, 0, BUFFER_SIZE)) != -1) { tempBackupWriter.write(buffer, 0, len); bytecount += len; } tempBackupWriter.flush(); long originalFileSize = beehiveArchive.length(); if (originalFileSize != bytecount) { throw new CacheOperationException("Original archive size was {0} bytes but only {1} were copied.", originalFileSize, bytecount); } cacheLog.debug("Finished copying ''{0}'' to ''{1}''.", beehiveArchive.getAbsolutePath(), tempBackupArchive.getAbsolutePath()); } catch (FileNotFoundException e) { throw new CacheOperationException("Files required for copying a backup of Beehive archive could not be found, opened " + "or created : {1}", e, e.getMessage()); } catch (IOException e) { throw new CacheOperationException("Error while making a copy of the Beehive archive : {0}", e, e.getMessage()); } finally { if (archiveReader != null) { try { archiveReader.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, beehiveArchive.getAbsolutePath(), t.getMessage()); } } if (tempBackupWriter != null) { try { tempBackupWriter.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, tempBackupArchive.getAbsolutePath(), t.getMessage()); } } } validateArchive(tempBackupArchive); File newestDaily = getNewestDailyBackupFile(); try { if (!tempBackupArchive.renameTo(newestDaily)) { throw new CacheOperationException("Error moving ''{0}'' to ''{1}''.", tempBackupArchive.getAbsolutePath(), newestDaily.getAbsolutePath()); } else { cacheLog.info("Backup complete. Saved in ''{0}''", newestDaily.getAbsolutePath()); } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied write access to ''{0}'' : {1}", e, newestDaily.getAbsolutePath(), e.getMessage()); } }
00
Code Sample 1: protected static Certificate[] getCurrentCertificates() throws Exception { Certificate[] certificate = AppletLoader.class.getProtectionDomain().getCodeSource().getCertificates(); if (certificate == null) { URL location = AppletLoader.class.getProtectionDomain().getCodeSource().getLocation(); JarURLConnection jurl = (JarURLConnection) (new URL("jar:" + location.toString() + "!/org/lwjgl/util/applet/AppletLoader.class").openConnection()); jurl.setDefaultUseCaches(true); certificate = jurl.getCertificates(); } return certificate; } Code Sample 2: 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(); }
00
Code Sample 1: public void actionPerformed(ActionEvent event) { System.out.println("STARTING on" + getQueryField().getText()); try { URL url = new URL(getQueryField().getText()); getResponseField().setText("opening URL"); DataInputStream inputStream = new DataInputStream(url.openStream()); getResponseField().setText("collating response"); String line = inputStream.readLine(); String totalString = ""; while (line != null) { totalString += line + "\n"; line = inputStream.readLine(); } System.out.println("FINISHING"); getResponseField().setText(totalString); System.out.println("FINISHED"); } catch (Exception exception) { getResponseField().setText(exception.getMessage() + "\n"); } } Code Sample 2: public static void executeUpdate(Database db, String... statements) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(db); con.setAutoCommit(false); stmt = con.createStatement(); for (String statement : statements) { stmt.executeUpdate(statement); } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } throw e; } finally { closeStatement(stmt); closeConnection(con); } }
11
Code Sample 1: private boolean copyFiles(File sourceDir, File destinationDir) { boolean result = false; try { if (sourceDir != null && destinationDir != null && sourceDir.exists() && destinationDir.exists() && sourceDir.isDirectory() && destinationDir.isDirectory()) { File sourceFiles[] = sourceDir.listFiles(); if (sourceFiles != null && sourceFiles.length > 0) { File destFiles[] = destinationDir.listFiles(); if (destFiles != null && destFiles.length > 0) { for (int i = 0; i < destFiles.length; i++) { if (destFiles[i] != null) { destFiles[i].delete(); } } } for (int i = 0; i < sourceFiles.length; i++) { if (sourceFiles[i] != null && sourceFiles[i].exists() && sourceFiles[i].isFile()) { String fileName = destFiles[i].getName(); File destFile = new File(destinationDir.getAbsolutePath() + "/" + fileName); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(sourceFiles[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } } } } result = true; } catch (Exception e) { System.out.println("Exception in copyFiles Method : " + e); } return result; } Code Sample 2: protected void setTestContent(IDfDocument document, String testFileName) throws Exception { InputStream testFileIs = new BufferedInputStream(FileHelper.getFileAsStreamFromClassPath(testFileName)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(testFileIs, baos); String contentType = formatHelper.getFormatForExtension(FileHelper.getFileExtension(testFileName)); document.setContentType(contentType); document.setContent(baos); }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); }
00
Code Sample 1: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } Code Sample 2: public void loadSourceCode() { int length = MAX_SOURCE_LENGTH; try { File file = new File(filename); length = (int) file.length(); } catch (SecurityException ex) { } char[] buff = new char[length]; InputStream is; InputStreamReader isr; CodeViewer cv = new CodeViewer(); URL url; try { url = getClass().getResource(filename); is = url.openStream(); isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); sourceCode = new String("<html><pre>"); String line = reader.readLine(); while (line != null) { sourceCode += cv.syntaxHighlight(line) + " \n "; line = reader.readLine(); } sourceCode += "</pre></html>"; } catch (Exception ex) { sourceCode = getString("SourceCode.error"); } }
00
Code Sample 1: public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } } Code Sample 2: private void initSerializerFiles(String fileName, HashSet<String> fileList, HashMap<Class, Class> classMap, Class type) { try { ClassLoader classLoader = getClassLoader(); if (classLoader == null) return; Enumeration iter; iter = classLoader.getResources(fileName); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); if (fileList.contains(url.toString())) continue; fileList.add(url.toString()); InputStream is = null; try { is = url.openStream(); Properties props = new Properties(); props.load(is); for (Map.Entry entry : props.entrySet()) { String apiName = (String) entry.getKey(); String serializerName = (String) entry.getValue(); Class apiClass = null; Class serializerClass = null; try { apiClass = Class.forName(apiName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + apiName + " is not available in this context: " + getClassLoader()); continue; } try { serializerClass = Class.forName(serializerName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + serializerName + " is not available in this context: " + getClassLoader()); continue; } if (!type.isAssignableFrom(serializerClass)) throw new HessianException(url + ": " + serializerClass.getName() + " is invalid because it does not implement " + type.getName()); classMap.put(apiClass, serializerClass); } } finally { if (is != null) is.close(); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new HessianException(e); } }
00
Code Sample 1: public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); int id = getId(dn, con); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); PreparedStatement ps = con.prepareStatement("DELETE FROM users WHERE id=?"); ps.setInt(1, id); ps.executeUpdate(); ps = con.prepareStatement("DELETE FROM locationmap WHERE person=?"); ps.setInt(1, id); ps.executeUpdate(); ps.close(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); }
11
Code Sample 1: public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } Code Sample 2: public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: private void FindAvail() throws ParserConfigurationException, SQLException { Savepoint sp1; String availsql = "select xmlquery('$c/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]' "; availsql += "passing hp_administrator.availability.AVAIL as \"c\") "; availsql += " from hp_administrator.availability "; availsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "'"; System.out.println(availsql); String availxml = ""; String seatxml = ""; String navailstr = ""; String nspavailstr = ""; String currentcoachstr = ""; String srctillstr = "", srcavailstr = "", srcmaxstr = ""; Integer srctill, srcavail, srcmax; Integer navailcoach; Integer nspavailcoach, seatstart, seatcnt, alloccnt; String routesrcstr = "", routedeststr = ""; PreparedStatement pstseat; Statement stavail, stavailupd, stseatupd, stseat; ResultSet rsavail, rsseat; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document docavail, docseattmp, docseatfin, docseat; Element rootavail, rootseat; Node n; try { stavail = conn.createStatement(); sp1 = conn.setSavepoint(); rsavail = stavail.executeQuery(availsql); if (rsavail.next()) availxml = rsavail.getString(1); System.out.println(availxml); StringBuffer StringBuffer1 = new StringBuffer(availxml); ByteArrayInputStream Bis1 = new ByteArrayInputStream(StringBuffer1.toString().getBytes("UTF-16")); docavail = db.parse(Bis1); StringWriter sw; OutputFormat formatter; formatter = new OutputFormat(); formatter.setPreserveSpace(true); formatter.setEncoding("UTF-8"); formatter.setOmitXMLDeclaration(true); XMLSerializer serializer; rootavail = docavail.getDocumentElement(); NodeList coachlist = rootavail.getElementsByTagName("coach"); Element currentcoach, minseat; Element routesrc, routedest, nextstn, dest, user, agent; NodeList nl, nl1; number_of_tickets_rem = booking_details.getNoOfPersons(); int tickpos = 0; firsttime = true; boolean enterloop; for (int i = 0; i < coachlist.getLength(); i++) { currentcoach = (Element) coachlist.item(i); currentcoachstr = currentcoach.getAttribute("number"); String coachmaxstr = currentcoach.getAttribute("coachmax"); Integer coachmax = Integer.parseInt(coachmaxstr.trim()); routesrc = (Element) currentcoach.getFirstChild(); routedest = (Element) currentcoach.getLastChild(); routedest = (Element) routedest.getPreviousSibling().getPreviousSibling().getPreviousSibling(); routesrcstr = routesrc.getNodeName(); routedeststr = routedest.getNodeName(); String seatsql = "select xmlquery('$c/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]' "; seatsql += " passing hp_administrator.book_tickets.SEAT as \"c\") from hp_administrator.book_tickets "; seatsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "' "; System.out.println("route :" + sourcenws); System.out.println("route :" + destnnws); System.out.println("route src :" + routesrcstr); System.out.println("route dest :" + routedeststr); System.out.println(seatsql); stseat = conn.createStatement(); rsseat = stseat.executeQuery(seatsql); if (rsseat.next()) seatxml = rsseat.getString(1); StringBuffer StringBuffer2 = new StringBuffer(seatxml); ByteArrayInputStream Bis2 = new ByteArrayInputStream(StringBuffer2.toString().getBytes("UTF-16")); docseat = db.parse(Bis2); rootseat = docseat.getDocumentElement(); enterloop = false; if (routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 1"); navailstr = routesrc.getTextContent(); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = routesrc.getAttribute("agent"); else nspavailstr = routesrc.getAttribute("user"); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = routesrc.getAttribute(sourcenws + "TILL"); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); srcmax = Integer.parseInt(srcmaxstr.trim()); srcavailstr = routesrc.getTextContent(); srcavail = Integer.parseInt(srcavailstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - srcavail; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); seatno.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); int updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); updvar = stseatupd.executeUpdate(seatupdstr); if (updvar > 0) System.out.println("upda seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda" + sp + " success"); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + sp + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 2"); String excesssrcstr = routesrc.getTextContent(); System.out.println(excesssrcstr); Integer excesssrc = Integer.parseInt(excesssrcstr.trim()); NodeList nl2 = currentcoach.getElementsByTagName(destnnws); Element e2 = (Element) nl2.item(0); String desttillstr = e2.getAttribute(destnnws + "TILL"); System.out.println(desttillstr); Integer desttillcnt = Integer.parseInt(desttillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } System.out.println(spdesttillstr); System.out.println(spexcesssrcstr); Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); Element seat, stn; if (booking_details.getNoOfPersons() <= desttillcnt && booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; tickpos = 0; boolean initflg = true; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; seat = (Element) seat.getParentNode().getFirstChild(); } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; tickpos = 0; boolean initflg = true; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); ; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (!routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 3"); NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); System.out.println(navailstr); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = e2.getAttribute("agent"); else nspavailstr = e2.getAttribute("user"); System.out.println(nspavailstr); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = e2.getAttribute(sourcenws + "TILL"); System.out.println(srctillstr); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = e2.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - navailcoach; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println("!@#------->" + seatupdstr); stseatupd = conn.createStatement(); } } else if (!routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 4"); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); Element seat, stn; NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); Integer excesssrc = Integer.parseInt(navailstr.trim()); nl2 = currentcoach.getElementsByTagName(destnnws); e2 = (Element) nl2.item(0); navailstr = e2.getAttribute(destnnws + "TILL"); Integer desttillcnt = Integer.parseInt(navailstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); boolean initflg = true; if (booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } } availfin = true; } catch (SQLException e) { conn.rollback(); e.printStackTrace(); } catch (UnsupportedEncodingException e) { conn.rollback(); e.printStackTrace(); } catch (SAXException e) { conn.rollback(); e.printStackTrace(); } catch (IOException e) { conn.rollback(); e.printStackTrace(); } } Code Sample 2: public static List<ReactomeBean> getUrlData(URL url) throws IOException { List<ReactomeBean> beans = new ArrayList<ReactomeBean>(256); log.debug("Retreiving content for: " + url); StringBuffer content = new StringBuffer(4096); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.startsWith("#")) { continue; } StringTokenizer stringTokenizer = new StringTokenizer(str, "\t"); String InteractionAc = stringTokenizer.nextToken(); String reactomeId = stringTokenizer.nextToken(); ReactomeBean reactomeBean = new ReactomeBean(); reactomeBean.setReactomeID(reactomeId); reactomeBean.setInteractionAC(InteractionAc); beans.add(reactomeBean); } in.close(); return beans; }
00
Code Sample 1: private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } } Code Sample 2: public static boolean downloadFile(String url, String destination) { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; try { java.net.URL fileurl; try { fileurl = new java.net.URL(url); } catch (MalformedURLException e) { return false; } bi = new BufferedInputStream(fileurl.openStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int readedbyte; while ((readedbyte = bi.read()) != -1) { bo.write(readedbyte); } bo.flush(); } catch (IOException ex) { return false; } finally { try { bi.close(); bo.close(); } catch (Exception ex) { } } return true; }
00
Code Sample 1: public static String addWeibo(String weibo, File pic, String uid) throws Throwable { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("_surl", "")); qparams.add(new BasicNameValuePair("_t", "0")); qparams.add(new BasicNameValuePair("location", "home")); qparams.add(new BasicNameValuePair("module", "stissue")); if (pic != null) { String picId = upLoadImg(pic, uid); qparams.add(new BasicNameValuePair("pic_id", picId)); } qparams.add(new BasicNameValuePair("rank", "weibo")); qparams.add(new BasicNameValuePair("text", weibo)); HttpPost post = getHttpPost("http://weibo.com/aj/mblog/add?__rnd=1333611402611", uid); UrlEncodedFormEntity params = new UrlEncodedFormEntity(qparams, HTTP.UTF_8); post.setEntity(params); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity, HTTP.UTF_8); post.abort(); return content; } Code Sample 2: public Font(String path, String fontName) { this(); StringTokenizer tok = new StringTokenizer(path, ";"); NybbleInputStream str = null; while (str == null & tok.hasMoreTokens()) { try { URL url = new URL(tok.nextToken() + "/"); url = new URL(url, fontName); System.out.println(url.toString()); str = new NybbleInputStream(url.openStream()); parsePkStream(str); str.close(); name = fontName; } catch (java.io.IOException e) { } } }
11
Code Sample 1: public void testPreparedStatement0009() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.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(); } pstmt.close(); assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); con.commit(); pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); 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(); } assertEquals(count, rowsToAdd); con.commit(); pstmt.close(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, rowsToAdd); con.commit(); stmt.close(); con.setAutoCommit(true); } Code Sample 2: protected void doBackupOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "(version_no,parent_organize_type,child_organize_type) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("parent_organize_type")); ps.setString(3, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION_B INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException while committing or rollback"); } }
11
Code Sample 1: Library(MainFrame mf, boolean newLibrary, String templateName, String newFileName) throws Exception { mainFrame = mf; trackMap = new HashMap<String, LibraryTrack>(); trackVec = new Vector<LibraryTrack>(); String propFileName = null; File propFile = null; String notExist = ""; String[] options = templateDesc; boolean isCurrent = mainFrame.library != null; int ix; if (!newLibrary) { propFileName = mainFrame.name + ".jampal"; propFile = new File(propFileName); } if (isCurrent) { options = new String[templateDesc.length + 1]; options[0] = "Copy of Current Library"; for (ix = 0; ix < templateDesc.length; ix++) { options[ix + 1] = templateDesc[ix]; } } boolean copyLibrary = false; if (newLibrary) { if (templateName == null) { Object resp = JOptionPane.showInputDialog(mainFrame.frame, "Please select a template.", "Select Type of Library", JOptionPane.WARNING_MESSAGE, null, options, null); if (resp == null) return; templateName = (String) resp; } for (ix = 0; ix < options.length && !options[ix].equals(templateName); ix++) ; if (isCurrent) ix--; boolean creatingPlaylist = false; BufferedReader in; if (ix == -1) { in = new BufferedReader(new FileReader(mainFrame.name + ".jampal")); copyLibrary = true; creatingPlaylist = (mainFrame.library.attributes.libraryType == 'P'); } else { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/" + templateNames[ix]))); creatingPlaylist = ("playlist.jampal".equals(templateNames[ix])); } if (newFileName == null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Create New Library File"); String currentDirectory = null; if (mainFrame.name != null) { File nameFile = new File(mainFrame.name); currentDirectory = nameFile.getParent(); if (currentDirectory == null) currentDirectory = "."; } if (currentDirectory == null) currentDirectory = Jampal.jampalDirectory; if (currentDirectory != null) fileChooser.setCurrentDirectory(new File(currentDirectory)); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(false); Mp3FileFilter filter = new Mp3FileFilter(); filter.setExtension("jampal", "Jampal library files"); fileChooser.addChoosableFileFilter(filter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(filter); fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); int returnVal = fileChooser.showSaveDialog(mainFrame.frame); if (returnVal == fileChooser.APPROVE_OPTION) { propFile = fileChooser.getSelectedFile(); propFileName = propFile.getPath(); if (!propFileName.toLowerCase().endsWith(".jampal")) { propFileName = propFileName + ".jampal"; propFile = new File(propFileName); } } else return; } else { propFileName = newFileName; propFile = new File(propFileName); } if (propFile.exists()) { if (JOptionPane.showConfirmDialog(mainFrame.frame, "File " + propFileName + " already exists. Do you want to overwrite it ?", "Warning", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; } PrintWriter out = new PrintWriter(new FileOutputStream(propFile)); String libName = propFile.getName(); libName = libName.substring(0, libName.length() - 7); for (; ; ) { String line = in.readLine(); if (line == null) break; if (creatingPlaylist && line.startsWith("playlist=")) { line = "playlist=" + libName; } if (line.startsWith("libraryname=")) { line = "libraryname=" + libName + ".jmp"; } out.println(line); } in.close(); out.close(); if (!creatingPlaylist && !copyLibrary) { String playlistName = propFile.getParent() + File.separator + "playlist.jampal"; File playlistFile = new File(playlistName); if (!playlistFile.exists()) { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/playlist.jampal"))); out = new PrintWriter(new FileOutputStream(playlistFile)); for (; ; ) { String line = in.readLine(); if (line == null) break; out.println(line); } in.close(); out.close(); } } } if (propFileName != null) attributes = new LibraryAttributes(propFileName); insertBefore = -1; } Code Sample 2: private void publishMap(LWMap map) throws IOException { File savedMap = PublishUtil.saveMap(map); InputStream istream = new BufferedInputStream(new FileInputStream(savedMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("ConceptMap", "vue"))); int fileLength = (int) savedMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: public static Test suite() throws Exception { java.net.URL url = ClassLoader.getSystemResource("host0.jndi.properties"); java.util.Properties host0JndiProps = new java.util.Properties(); host0JndiProps.load(url.openStream()); java.util.Properties systemProps = System.getProperties(); systemProps.putAll(host0JndiProps); System.setProperties(systemProps); TestSuite suite = new TestSuite(); suite.addTest(new TestSuite(T06OTSInterpositionUnitTestCase.class)); TestSetup wrapper = new JBossTestSetup(suite) { protected void setUp() throws Exception { super.setUp(); deploy("dtmpassthrough2ots.jar"); } protected void tearDown() throws Exception { undeploy("dtmpassthrough2ots.jar"); super.tearDown(); } }; return wrapper; }
00
Code Sample 1: public static void copyFile(String sourceName, String destName) throws IOException { FileChannel sourceChannel = null; FileChannel destChannel = null; try { sourceChannel = new FileInputStream(sourceName).getChannel(); destChannel = new FileOutputStream(destName).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException exception) { throw exception; } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException ex) { } } if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { } } } } Code Sample 2: public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
11
Code Sample 1: @Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } } 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: private static String genRandomGUID(boolean secure) { String valueBeforeMD5 = ""; String valueAfterMD5 = ""; MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); return valueBeforeMD5; } 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(); String strTemp = ""; for (int i = 0; i < array.length; i++) { strTemp = (Integer.toHexString(array[i] & 0XFF)); if (strTemp.length() == 1) { valueAfterMD5 = valueAfterMD5 + "0" + strTemp; } else { valueAfterMD5 = valueAfterMD5 + strTemp; } } return valueAfterMD5.toUpperCase(); } Code Sample 2: private String hashString(String key) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); byte[] hash = digest.digest(); BigInteger bi = new BigInteger(1, hash); return String.format("%0" + (hash.length << 1) + "X", bi) + KERNEL_VERSION; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "" + key.hashCode(); } }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: private Document getDocument(URL url) throws SAXException, IOException { InputStream is; try { is = url.openStream(); } catch (IOException io) { System.out.println("parameter error : The specified reading data is mistaken."); System.out.println(" Request URL is " + sourceUri); throw new IOException("\t" + io.toString()); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.println("error : The error of DocumentBuilder instance generation"); throw new RuntimeException(pce.toString()); } Document doc; try { doc = builder.parse(is); } catch (Exception e) { System.out.println("error : parse of reading data went wrong."); System.out.println(" Request URL is " + sourceUri); throw new RuntimeException(e.toString()); } return doc; } Code Sample 2: public boolean doUpload(int count) { String objFileName = Long.toString(new java.util.Date().getTime()) + Integer.toString(count); try { this.objectFileName[count] = objFileName + "_bak." + this.sourceFileExt[count]; File objFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); if (objFile.exists()) { this.doUpload(count); } else { objFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(objFile); BufferedOutputStream bos = new BufferedOutputStream(fos); int readLength = 0; int offset = 0; String str = ""; long readSize = 0L; while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) { str = new String(this.b, 0, readLength); if (str.indexOf("Content-Type:") != -1) { break; } } this.inStream.readLine(this.b, 0, this.b.length); while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) { str = new String(this.b, 0, readLength); if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45 && this.b[3] == 45 && this.b[4] == 45) { break; } bos.write(this.b, 0, readLength); readSize += readLength; if (readSize > this.size) { this.fileMessage[count] = "�ϴ��ļ������ļ���С�������ƣ�"; this.ok = false; break; } } if (this.ok) { bos.flush(); bos.close(); int fileLength = (int) (objFile.length()); byte[] bb = new byte[fileLength - 2]; FileInputStream fis = new FileInputStream(objFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(bb, 0, (fileLength - 2)); fis.close(); bis.close(); this.objectFileName[count] = objFileName + "." + this.sourceFileExt[count]; File ok_file = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); ok_file.createNewFile(); BufferedOutputStream bos_ok = new BufferedOutputStream(new FileOutputStream(ok_file)); bos_ok.write(bb); bos_ok.close(); objFile.delete(); this.fileMessage[count] = "OK"; return true; } else { bos.flush(); bos.close(); File delFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); delFile.delete(); this.objectFileName[count] = "none"; return false; } } catch (Exception e) { this.objectFileName[count] = "none"; this.fileMessage[count] = e.toString(); return false; } }
00
Code Sample 1: public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { noSuchAlgorithmException.printStackTrace(); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException unsupportedEncodingException) { unsupportedEncodingException.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
11
Code Sample 1: private void transformFile(File input, File output, Cipher cipher, boolean compress, String progressMessage) throws IOException { FileInputStream fileInputStream = new FileInputStream(input); InputStream inputStream; if (progressMessage != null) { inputStream = new ProgressMonitorInputStream(null, progressMessage, fileInputStream); } else { inputStream = fileInputStream; } FilterInputStream is = new BufferedInputStream(inputStream); FilterOutputStream os = new BufferedOutputStream(new FileOutputStream(output)); FilterInputStream fis; FilterOutputStream fos; if (compress) { fis = is; fos = new GZIPOutputStream(new CipherOutputStream(os, cipher)); } else { fis = new GZIPInputStream(new CipherInputStream(is, cipher)); fos = os; } byte[] buffer = new byte[cipher.getBlockSize() * blocksInBuffer]; int readLength = fis.read(buffer); while (readLength != -1) { fos.write(buffer, 0, readLength); readLength = fis.read(buffer); } if (compress) { GZIPOutputStream gos = (GZIPOutputStream) fos; gos.finish(); } fos.close(); fis.close(); } Code Sample 2: public void run() { try { textUpdater.start(); int cnt; byte[] buf = new byte[4096]; File file = null; ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(filename))); ZipEntry ze = zis.getNextEntry(); FileOutputStream fos; while (ze != null) { if (ze.isDirectory()) { file = new File(ze.getName()); if (!file.exists()) { textUpdater.appendText("Creating directory: " + ze.getName() + "\n"); file.mkdirs(); } } else { textUpdater.appendText("Extracting file: " + ze.getName() + "\n"); fos = new FileOutputStream(dstdir + File.separator + ze.getName()); while ((cnt = zis.read(buf, 0, buf.length)) != -1) fos.write(buf, 0, cnt); fos.close(); } zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); if (complete != null) textUpdater.appendText(complete + "\n"); } catch (Exception e) { e.printStackTrace(); } textUpdater.setFinished(true); }
00
Code Sample 1: public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
11
Code Sample 1: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; } Code Sample 2: public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } Code Sample 2: static String hash(String text) { try { StringBuffer plugins = new StringBuffer(); for (PlayPlugin plugin : Play.plugins) { plugins.append(plugin.getClass().getName()); } MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update((Play.version + plugins.toString() + text).getBytes("utf-8")); byte[] digest = messageDigest.digest(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { int value = digest[i]; if (value < 0) { value += 256; } builder.append(Integer.toHexString(value)); } return builder.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } Code Sample 2: public void copyNIO(File in, File out) throws IOException { FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { inStream = new FileInputStream(in); outStream = new FileOutputStream(out); sourceChannel = inStream.getChannel(); destinationChannel = outStream.getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } }
00
Code Sample 1: public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } } Code Sample 2: public byte[] download(URL url, OutputStream out) throws IOException { boolean returnByByteArray = (out == null); ByteArrayOutputStream helper = null; if (returnByByteArray) { helper = new ByteArrayOutputStream(); } String s = url.toExternalForm(); URLConnection conn = url.openConnection(); String name = Launcher.getFileName(s); InputStream in = conn.getInputStream(); total = url.openConnection().getContentLength(); setStatusText(String.format("Downloading %s (%.2fMB)...", name, ((float) total / 1024 / 1024))); long justNow = System.currentTimeMillis(); int numRead = -1; byte[] buffer = new byte[2048]; while ((numRead = in.read(buffer)) != -1) { size += numRead; if (returnByByteArray) { helper.write(buffer, 0, numRead); } else { out.write(buffer, 0, numRead); } long now = System.currentTimeMillis(); if ((now - justNow) > 250) { setProgress((int) (((float) size / (float) total) * 100)); justNow = now; } } hideProgress(); if (returnByByteArray) { return helper.toByteArray(); } else { return null; } }
11
Code Sample 1: public void testRoundTrip_1(String resource) throws Exception { long start1 = System.currentTimeMillis(); File originalFile = File.createTempFile("RoundTripTest", "testRoundTrip_1"); FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(getClass().getResourceAsStream(resource), fos); fos.close(); long start2 = System.currentTimeMillis(); IsoFile isoFile = new IsoFile(new FileInputStream(originalFile).getChannel()); long start3 = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(baos); long start4 = System.currentTimeMillis(); Walk.through(isoFile); long start5 = System.currentTimeMillis(); isoFile.getBox(wbc); wbc.close(); long start6 = System.currentTimeMillis(); System.err.println("Preparing tmp copy took: " + (start2 - start1) + "ms"); System.err.println("Parsing took : " + (start3 - start2) + "ms"); System.err.println("Writing took : " + (start6 - start3) + "ms"); System.err.println("Walking took : " + (start5 - start4) + "ms"); byte[] a = IOUtils.toByteArray(getClass().getResourceAsStream(resource)); byte[] b = baos.toByteArray(); Assert.assertArrayEquals(a, b); } Code Sample 2: public static void copyZip() { InputStream is; OutputStream os; String javacZip = ""; try { if ("windows".equalsIgnoreCase(Compilador.getSo())) { javacZip = "javacWin.zip"; is = UnZip.class.getResourceAsStream("javacWin.zip"); } else if ("linux".equalsIgnoreCase(Compilador.getSo())) { javacZip = "javacLinux.zip"; is = UnZip.class.getResourceAsStream("javacLinux.zip"); } is = UnZip.class.getResourceAsStream(javacZip); File tempZip = File.createTempFile("tempJavacJTraductor", ".zip"); tempZip.mkdir(); tempZip.deleteOnExit(); os = FileUtils.openOutputStream(tempZip); IOUtils.copy(is, os); is.close(); os.close(); extractZip(tempZip.getPath()); } catch (Exception ex) { JOptionPane.showMessageDialog(PseutemView.mainPanel, "Error al copiar los archivos temporales necesarios para ejecutar el programa:\n\n" + ex, "Error copiando.", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public String getUser() { try { HttpGet get = new HttpGet("http://twemoi.status.net/api/account/verify_credentials.xml"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); return ""; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); String salida = sBuf.toString(); String user_name = salida.split("</screen_name>")[0].split("<screen_name>")[1]; return user_name; } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (IOException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } return null; }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } } Code Sample 2: private Tuple execute(final HttpMethodBase method, int numTries) throws IOException { final Timer timer = Metric.newTimer("RestClientImpl.execute"); try { final int sc = httpClient.executeMethod(method); if (sc < OK_MIN || sc > OK_MAX) { throw new RestException("Unexpected status code: " + sc + ": " + method.getStatusText() + " -- " + method, sc); } final InputStream in = method.getResponseBodyAsStream(); try { final StringWriter writer = new StringWriter(2048); IOUtils.copy(in, writer, method.getResponseCharSet()); return new Tuple(sc, writer.toString()); } finally { in.close(); } } catch (NullPointerException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (SocketException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (IOException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw e; } finally { method.releaseConnection(); timer.stop(); } }
00
Code Sample 1: private boolean undefSeqLen = true; private boolean undefItemLen = true; private boolean fmi = true; /** Creates a new instance of Acr2Dcm */ public Acr2Dcm() { } public void setStudyUID(String uid) { this.studyUID = uid; } public void setSeriesUID(String uid) { this.seriesUID = uid; } public void setInstUID(String uid) { this.instUID = uid; } public void setClassUID(String uid) { this.classUID = uid; } public void setSkipGroupLen(boolean skipGroupLen) { Code Sample 2: private boolean exportPKC(String keystoreLocation, String pw) { boolean created = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when exporting PKC: " + e.getMessage()); } return false; } try { StringBuffer sb = new StringBuffer("-----BEGIN CERTIFICATE-----\n"); sb.append(new String(Base64.encode(cert.getEncoded()))); sb.append("\n-----END CERTIFICATE-----\n"); OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream("sawsSigningPKC.crt")); wr.write(new String(sb)); wr.flush(); wr.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error exporting PKC file: " + e.getMessage()); } return false; } return created; }
11
Code Sample 1: public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private List parseUrlGetUids(String url) throws FetchError { List hids = new ArrayList(); try { InputStream is = (new URL(url)).openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String inputLine = ""; Pattern pattern = Pattern.compile("\\<input\\s+type=hidden\\s+name=hid\\s+value=(\\d+)\\s?\\>", Pattern.CASE_INSENSITIVE); while ((inputLine = in.readLine()) != null) { Matcher matcher = pattern.matcher(inputLine); if (matcher.find()) { String id = matcher.group(1); if (!hids.contains(id)) { hids.add(id); } } } } catch (Exception e) { System.out.println(e); throw new FetchError(e); } return hids; } Code Sample 2: public void testBasic() { CameraInfo ci = C328rCameraInfo.getInstance(); assertNotNull(ci); assertNotNull(ci.getCapabilities()); assertFalse(ci.getCapabilities().isEmpty()); System.out.println(ci.getUrl()); URL url = ci.getUrl(); try { URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public String getWeather(String cityName, String fileAddr) { try { URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather=" + cityName); InputStream inputstream = url.openStream(); String s, str; BufferedReader in = new BufferedReader(new InputStreamReader(inputstream)); StringBuffer stringbuffer = new StringBuffer(); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileAddr), "utf-8")); while ((s = in.readLine()) != null) { stringbuffer.append(s); } str = new String(stringbuffer); out.write(str); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } File file = new File(fileAddr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String str = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); NodeList nodelist1 = (NodeList) doc.getElementsByTagName("forecast_conditions"); NodeList nodelist2 = nodelist1.item(0).getChildNodes(); str = nodelist2.item(4).getAttributes().item(0).getNodeValue() + ",temperature:" + nodelist2.item(1).getAttributes().item(0).getNodeValue() + "℃-" + nodelist2.item(2).getAttributes().item(0).getNodeValue() + "℃"; } catch (Exception e) { e.printStackTrace(); } return str; } Code Sample 2: private ArrayList<String> getYearsAndMonths() { String info = ""; ArrayList<String> items = new ArrayList<String>(); try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf("/"); if (pos != -1) { token = token.substring(1, pos); if (Patterns.hasFormatYYYYdotMM(token)) { items.add(token); } } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return items; }
00
Code Sample 1: public void myCheckCredHandler(View v) { Log.d("login_section", "entered handler"); EditText Username = (EditText) findViewById(R.id.Username); EditText Password = (EditText) findViewById(R.id.user_pass); String username_S = Username.getText().toString(); String pass_S = Password.getText().toString(); TextView ltv = (TextView) findViewById(R.id.LoginPagetv); HttpClient httpclient = createHttpClient(); HttpPost httppost = new HttpPost(authenticationURL); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("login", username_S)); nameValuePairs.add(new BasicNameValuePair("password", pass_S)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); Log.d("login_section", responseBody); JSONObject jsonObject = new JSONObject(responseBody); if (status == this.statusOK && jsonObject.getBoolean("logged_in")) { ltv.setText("You have been logged in. :D"); etracks.setLogged(true); etracks.setUserToken(jsonObject.getString("user_token")); Intent it = new Intent(Intent.ACTION_VIEW); it.setClassName(this, etracks.class.getName()); this.finish(); startActivity(it); } else if (status == this.statusUnprocessable && !jsonObject.getBoolean("logged_in")) { if (!jsonObject.isNull("errors")) ltv.setText(jsonObject.getString("errors")); else ltv.setText("login unsuccessful"); } else Log.d("login_section", "what just happened?"); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (JSONException e) { e.printStackTrace(); } } Code Sample 2: JSONResponse execute() throws ServerException, RtmApiException, IOException { HttpClient httpclient = new DefaultHttpClient(); URI uri; try { uri = new URI(this.request.getUrl()); HttpPost httppost = new HttpPost(uri); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(is))); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } return new JSONResponse(sb.toString()); } finally { is.close(); } } catch (URISyntaxException e) { throw new RtmApiException(e.getMessage()); } catch (ClientProtocolException e) { throw new RtmApiException(e.getMessage()); } }
00
Code Sample 1: public String sendXml(URL url, String xmlMessage, boolean isResponseExpected) throws IOException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (xmlMessage == null) { throw new IllegalArgumentException("xmlMessage == null"); } LOGGER.finer("url = " + url); LOGGER.finer("xmlMessage = :" + xmlMessage + ":"); LOGGER.finer("isResponseExpected = " + isResponseExpected); String answer = null; try { URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Content-type", "text/xml"); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); Writer writer = null; try { writer = new OutputStreamWriter(urlConnection.getOutputStream()); writer.write(xmlMessage); writer.flush(); } finally { if (writer != null) { writer.close(); } } LOGGER.finer("message written"); StringBuilder sb = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); if (isResponseExpected) { String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine).append("\n"); } answer = sb.toString(); LOGGER.finer("response read"); } } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "No response", e); } finally { if (in != null) { in.close(); } } } catch (ConnectException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } LOGGER.finer("answer = :" + answer + ":"); return answer; } Code Sample 2: private void zip(FileHolder fileHolder, int zipCompressionLevel) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File zipDestFile = new File(fileHolder.destFiles[0]); try { ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile)); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); ZipEntry entry = new ZipEntry(selectedFile.getName()); outStream.setLevel(zipCompressionLevel); outStream.putNextEntry(entry); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.closeEntry(); this.inStream.close(); } outStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error zipping: " + zipDestFile); logger.logError(errEntry); } return; }
00
Code Sample 1: public void removeForwardAddress(final List<NewUser> forwardAddresses) { try { final List<Integer> usersToRemoveFromCache = new ArrayList<Integer>(); connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("userForwardAddresses.delete")); Iterator<NewUser> iter = forwardAddresses.iterator(); Iterator<Integer> iter2; NewUser newUser; while (iter.hasNext()) { newUser = iter.next(); iter2 = newUser.forwardAddressIds.iterator(); while (iter2.hasNext()) { psImpl.setInt(1, iter2.next()); psImpl.executeUpdate(); } usersToRemoveFromCache.add(newUser.userId); } } }); connection.commit(); cmDB.removeUsers(usersToRemoveFromCache); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void main(String[] args) { String WTKdir = null; String sourceFile = null; String instrFile = null; String outFile = null; String jadFile = null; Manifest mnf; if (args.length == 0) { usage(); return; } int i = 0; while (i < args.length && args[i].startsWith("-")) { if (("-WTK".equals(args[i])) && (i < args.length - 1)) { i++; WTKdir = args[i]; } else if (("-source".equals(args[i])) && (i < args.length - 1)) { i++; sourceFile = args[i]; } else if (("-instr".equals(args[i])) && (i < args.length - 1)) { i++; instrFile = args[i]; } else if (("-o".equals(args[i])) && (i < args.length - 1)) { i++; outFile = args[i]; } else if (("-jad".equals(args[i])) && (i < args.length - 1)) { i++; jadFile = args[i]; } else { System.out.println("Error: Unrecognized option: " + args[i]); System.exit(0); } i++; } if (WTKdir == null || sourceFile == null || instrFile == null) { System.out.println("Error: Missing parameter!!!"); usage(); return; } if (outFile == null) outFile = sourceFile; FileInputStream fisJar; try { fisJar = new FileInputStream(sourceFile); } catch (FileNotFoundException e1) { System.out.println("Cannot find source jar file: " + sourceFile); e1.printStackTrace(); return; } FileOutputStream fosJar; File aux = null; try { aux = File.createTempFile("predef", "aux"); fosJar = new FileOutputStream(aux); } catch (IOException e1) { System.out.println("Cannot find temporary jar file: " + aux); e1.printStackTrace(); return; } JarFile instrJar = null; Enumeration en = null; File tempDir = null; try { instrJar = new JarFile(instrFile); en = instrJar.entries(); tempDir = File.createTempFile("jbtp", ""); tempDir.delete(); System.out.println("Create directory: " + tempDir.mkdirs()); tempDir.deleteOnExit(); } catch (IOException e) { System.out.println("Cannot open instrumented file: " + instrFile); e.printStackTrace(); return; } String[] wtklib = new java.io.File(WTKdir + File.separator + "lib").list(new OnlyJar()); String preverifyCmd = WTKdir + File.separator + "bin" + File.separator + "preverify -classpath " + WTKdir + File.separator + "lib" + File.separator + CLDC_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + MIDP_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + WMA_JAR + File.pathSeparator + instrFile; for (int k = 0; k < wtklib.length; k++) { preverifyCmd += File.pathSeparator + WTKdir + File.separator + "lib" + wtklib[k]; } preverifyCmd += " " + "-d " + tempDir.getAbsolutePath() + " "; while (en.hasMoreElements()) { JarEntry je = (JarEntry) en.nextElement(); String jeName = je.getName(); if (jeName.endsWith(".class")) jeName = jeName.substring(0, jeName.length() - 6); preverifyCmd += jeName + " "; } try { Process p = Runtime.getRuntime().exec(preverifyCmd); if (p.waitFor() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Error calling the preverify command."); while (in.ready()) { System.out.print("" + in.readLine()); } System.out.println(); in.close(); return; } } catch (Exception e) { System.out.println("Cannot execute preverify command"); e.printStackTrace(); return; } File[] listOfFiles = computeFiles(tempDir); System.out.println("-------------------------------\n" + "Files to insert: "); String[] strFiles = new String[listOfFiles.length]; int l = tempDir.toString().length() + 1; for (int j = 0; j < listOfFiles.length; j++) { strFiles[j] = listOfFiles[j].toString().substring(l); strFiles[j] = strFiles[j].replace(File.separatorChar, '/'); System.out.println(strFiles[j]); } System.out.println("-------------------------------"); try { JarInputStream jis = new JarInputStream(fisJar); mnf = jis.getManifest(); JarOutputStream jos = new JarOutputStream(fosJar, mnf); nextJar: for (JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry()) { String s = je.getName(); for (int k = 0; k < strFiles.length; k++) { if (strFiles[k].equals(s)) continue nextJar; } jos.putNextEntry(je); byte[] b = new byte[512]; for (int k = jis.read(b, 0, 512); k >= 0; k = jis.read(b, 0, 512)) { jos.write(b, 0, k); } } jis.close(); for (int j = 0; j < strFiles.length; j++) { FileInputStream fis = new FileInputStream(listOfFiles[j]); JarEntry je = new JarEntry(strFiles[j]); jos.putNextEntry(je); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); jos.write(b, 0, k); } fis.close(); } jos.close(); fisJar.close(); fosJar.close(); } catch (IOException e) { System.out.println("Cannot read/write jar file."); e.printStackTrace(); return; } try { FileOutputStream fos = new FileOutputStream(outFile); FileInputStream fis = new FileInputStream(aux); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); fos.write(b, 0, k); } fis.close(); fos.close(); } catch (IOException e) { System.out.println("Cannot write output jar file: " + outFile); e.printStackTrace(); } Iterator it; Attributes atr; atr = mnf.getMainAttributes(); it = atr.keySet().iterator(); if (jadFile != null) { FileOutputStream fos; try { File outJarFile = new File(outFile); fos = new FileOutputStream(jadFile); PrintStream psjad = new PrintStream(fos); while (it.hasNext()) { Object ats = it.next(); psjad.println(ats + ": " + atr.get(ats)); } psjad.println("MIDlet-Jar-URL: " + outFile); psjad.println("MIDlet-Jar-Size: " + outJarFile.length()); fos.close(); } catch (IOException eio) { System.out.println("Cannot create jad file."); eio.printStackTrace(); } } }
00
Code Sample 1: private void LoadLoginInfo() { m_PwdList.removeAllElements(); String szTemp = null; int iIndex = 0; int iSize = m_UsrList.size(); for (int i = 0; i < iSize; i++) m_PwdList.add(""); try { if ((m_UsrList.size() > 0) && m_bSavePwd) { char[] MD5PWD = new char[80]; java.util.Arrays.fill(MD5PWD, (char) 0); java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-1"); String szPath = System.getProperty("user.home"); szPath += System.getProperty("file.separator") + "MochaJournal" + System.getProperty("file.separator") + "user.dat"; java.io.File file = new java.io.File(szPath); if (file.exists()) { java.io.FileInputStream br = new java.io.FileInputStream(file); byte[] szEncryptPwd = null; int iLine = 0; while (br.available() > 0) { md.reset(); md.update(((String) m_UsrList.get(iLine)).getBytes()); byte[] DESUSR = md.digest(); byte alpha = 0; for (int i2 = 0; i2 < DESUSR.length; i2++) alpha += DESUSR[i2]; iSize = br.read(); if (iSize > 0) { szEncryptPwd = new byte[iSize]; br.read(szEncryptPwd); char[] cPwd = new char[iSize]; for (int i = 0; i < iSize; i++) { int iChar = (int) szEncryptPwd[i] - (int) alpha; if (iChar < 0) iChar += 256; cPwd[i] = (char) iChar; } m_PwdList.setElementAt(new String(cPwd), iLine); } iLine++; } } } } catch (java.security.NoSuchAlgorithmException e) { System.err.println(e); } catch (java.io.IOException e3) { System.err.println(e3); } } Code Sample 2: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
11
Code Sample 1: public static String executePost(String urlStr, Map paramsMap) throws IOException { StringBuffer result = new StringBuffer(); HttpURLConnection connection = null; URL url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); Iterator paramKeys = paramsMap.keySet().iterator(); while (paramKeys.hasNext()) { String paramName = (String) paramKeys.next(); out.print(paramName + "=" + paramsMap.get(paramName)); if (paramKeys.hasNext()) { out.print('&'); } } out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); String msg = result.toString(); return stripOuterElement(msg); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static void run(File targetFolder, URL url) throws UpdateException { try { run(targetFolder, new ZipInputStream(url.openStream())); } catch (Exception e) { if (e instanceof UpdateException) throw (UpdateException) e; else throw new UpdateException(e); } } Code Sample 2: @RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET) public void getImage(@PathVariable String fileName, HttpServletRequest req, HttpServletResponse res) throws Exception { File file = new File(STORAGE_PATH + fileName + ".jpg"); res.setHeader("Cache-Control", "no-store"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); res.setContentType("image/jpg"); ServletOutputStream ostream = res.getOutputStream(); IOUtils.copy(new FileInputStream(file), ostream); ostream.flush(); ostream.close(); }
00
Code Sample 1: @Override public void vote(String urlString, Map<String, String> headData, Map<String, String> paramData) { HttpURLConnection httpConn = null; try { URL url = new URL(urlString); httpConn = (HttpURLConnection) url.openConnection(); String cookies = getCookies(httpConn); System.out.println(cookies); BufferedReader post = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GB2312")); String text = null; while ((text = post.readLine()) != null) { System.out.println(text); } } catch (MalformedURLException e) { e.printStackTrace(); throw new VoteBeanException("网址不正确", e); } catch (IOException e) { e.printStackTrace(); throw new VoteBeanException("不能打开网址", e); } } Code Sample 2: public void getFile(String url, String filepath) throws BggException { System.out.println(url); int retry = retryCount + 1; lastURL = url; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; BufferedInputStream bis = null; OutputStream osw = null; try { con = (HttpURLConnection) new URL(url).openConnection(); con.setDoInput(true); setHeaders(con); con.setRequestMethod("GET"); responseCode = con.getResponseCode(); bis = new BufferedInputStream(con.getInputStream()); int data; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filepath)); while ((data = bis.read()) != -1) bos.write(data); bos.flush(); bos.close(); break; } finally { try { bis.close(); } catch (Exception ignore) { } try { osw.close(); } catch (Exception ignore) { } try { con.disconnect(); } catch (Exception ignore) { } } } catch (IOException ioe) { if (responseCode == UNAUTHORIZED || responseCode == FORBIDDEN) { throw new BggException(ioe.getMessage(), responseCode); } if (retriedCount == retryCount) { throw new BggException(ioe.getMessage(), responseCode); } } try { Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { } } }
11
Code Sample 1: private File getTempFile(DigitalObject object, String pid) throws Exception { File directory = new File(tmpDir, object.getId()); File target = new File(directory, pid); if (!target.exists()) { target.getParentFile().mkdirs(); target.createNewFile(); } Payload payload = object.getPayload(pid); InputStream in = payload.open(); FileOutputStream out = null; try { out = new FileOutputStream(target); IOUtils.copyLarge(in, out); } catch (Exception ex) { close(out); target.delete(); payload.close(); throw ex; } close(out); payload.close(); return target; } Code Sample 2: public ODFSignatureService(TimeStampServiceValidator timeStampServiceValidator, RevocationDataService revocationDataService, SignatureFacet signatureFacet, InputStream documentInputStream, OutputStream documentOutputStream, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo digestAlgo) throws Exception { super(digestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".odf"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
11
Code Sample 1: public Object mapRow(ResultSet rs, int i) throws SQLException { Blob blob = rs.getBlob(1); if (rs.wasNull()) return null; try { InputStream inputStream = blob.getBinaryStream(); if (length > 0) IOUtils.copy(inputStream, outputStream, offset, length); else IOUtils.copy(inputStream, outputStream); inputStream.close(); } catch (IOException e) { } return null; } Code Sample 2: private static boolean genMovieRatingFile(String completePath, String masterFile, String CustLocationsFileName, String MovieRatingFileName) { try { File inFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC1 = new FileInputStream(inFile1).getChannel(); int fileSize1 = (int) inC1.size(); int totalNoDataRows = fileSize1 / 7; ByteBuffer mappedBuffer = inC1.map(FileChannel.MapMode.READ_ONLY, 0, fileSize1); System.out.println("Loaded master binary file"); File inFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel inC2 = new FileInputStream(inFile2).getChannel(); int fileSize2 = (int) inC2.size(); System.out.println(fileSize2); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieRatingFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); for (int i = 0; i < 1; i++) { ByteBuffer locBuffer = inC2.map(FileChannel.MapMode.READ_ONLY, i * fileSize2, fileSize2); System.out.println("Loaded cust location file chunk: " + i); while (locBuffer.hasRemaining()) { int locationToRead = locBuffer.getInt(); mappedBuffer.position((locationToRead - 1) * 7); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); ByteBuffer outBuf = ByteBuffer.allocate(3); outBuf.putShort(movieName); outBuf.put(rating); outBuf.flip(); outC.write(outBuf); } } mappedBuffer.clear(); inC1.close(); inC2.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
11
Code Sample 1: @SuppressWarnings("deprecation") public static final ReturnCode runCommand(IOBundle io, String[] args) { if ((args.length < 3) || (args.length > 4)) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 3) && (!args[1].equals("show"))) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 4) && (!(args[2].equals("training") || args[2].equals("log") || args[2].equals("configuration")))) return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Access denied to directory: " + args[2]); if (args[1].equals("open")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); io.println(fileName); io.println(file.length() + " bytes"); while (dis.available() != 0) { io.println(dis.readLine()); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_NOT_FOUND, "File " + fileName + " doesn't exist"); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error reading File " + fileName); } } else if (args[1].equals("save")) { final String fileName = args[2] + "/" + args[3]; String line; try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); line = io.readLine(); int count = Integer.parseInt(line.trim()); while (count > 0) { out.write(io.read()); count = count - 1; } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error writing File " + fileName); } } else if (args[1].equals("delete")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); if (!file.exists()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such file or directory: " + fileName); if (!file.canWrite()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "File is write-protected: " + fileName); if (file.isDirectory()) { String[] files = file.list(); if (files.length > 0) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Directory is not empty: " + fileName); } if (!file.delete()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Deletion failed: " + fileName); } else if (args[1].equals("show")) { File directory = new File(args[2]); String[] files; if ((!directory.isDirectory()) || (!directory.exists())) { return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such directory: " + directory); } int count = 0; files = directory.list(); io.println("Files in directory \"" + directory + "\":"); for (int i = 0; i < files.length; i++) { directory = new File(files[i]); if (!directory.isDirectory()) { count++; io.println(" " + files[i]); } } io.println("Total " + count + " files"); } else return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Unrecognized command"); return ReturnCode.makeReturnCode(ReturnCode.RET_OK); } Code Sample 2: private Tuple execute(final HttpMethodBase method, int numTries) throws IOException { final Timer timer = Metric.newTimer("RestClientImpl.execute"); try { final int sc = httpClient.executeMethod(method); if (sc < OK_MIN || sc > OK_MAX) { throw new RestException("Unexpected status code: " + sc + ": " + method.getStatusText() + " -- " + method, sc); } final InputStream in = method.getResponseBodyAsStream(); try { final StringWriter writer = new StringWriter(2048); IOUtils.copy(in, writer, method.getResponseCharSet()); return new Tuple(sc, writer.toString()); } finally { in.close(); } } catch (NullPointerException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (SocketException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw new IOException("Failed to connet to " + url + " [" + method + "]", e); } catch (IOException e) { if (numTries < 3) { try { Thread.sleep(200); } catch (InterruptedException ie) { Thread.interrupted(); } return execute(method, numTries + 1); } throw e; } finally { method.releaseConnection(); timer.stop(); } }
00
Code Sample 1: public void setNewPassword(String password) { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); final String encrypted = "{MD5}" + new String(Base64Encoder.encode(digest.digest())); setUserPassword(encrypted.getBytes()); this.newPassword = password; firePropertyChange("newPassword", "", password); firePropertyChange("password", new byte[0], getUserPassword()); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't encrypt user's password", e); } } Code Sample 2: public void init() { this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); try { if (memeId < 0) { } else { conurl = new URL(ServerURL + "?meme_id=" + memeId); java.io.InputStream xmlstr = conurl.openStream(); this.removeAllWorkSheets(); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT); this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE); this.setDupeStringMode(WorkBookHandle.SHAREDUPES); ExtenXLS.parseNBind(this, xmlstr); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); } } catch (Exception ex) { throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR); } }
00
Code Sample 1: public void testReleaseOnIOException() throws Exception { localServer.register("/dropdead", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { BasicHttpEntity entity = new BasicHttpEntity() { @Override public void writeTo(final OutputStream outstream) throws IOException { byte[] tmp = new byte[5]; outstream.write(tmp); outstream.flush(); DefaultHttpServerConnection conn = (DefaultHttpServerConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION); try { conn.sendResponseHeader(response); } catch (HttpException ignore) { } } }; entity.setChunked(true); response.setEntity(entity); } }); HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/dropdead"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); try { EntityUtils.toByteArray(e); fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException expected) { } assertEquals(0, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); } Code Sample 2: private InputStream getInputStream() throws URISyntaxException, MalformedURLException, IOException { InputStream inStream = null; try { URL url = new URI(wsdlFile).toURL(); URLConnection connection = url.openConnection(); connection.connect(); inStream = connection.getInputStream(); } catch (IllegalArgumentException ex) { inStream = new FileInputStream(wsdlFile); } return inStream; }
11
Code Sample 1: public void setPassword(String plaintext) throws java.security.NoSuchAlgorithmException { StringBuffer encrypted = new StringBuffer(); java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(plaintext.getBytes()); byte[] digestArray = digest.digest(); for (int i = 0; i < digestArray.length; i++) { encrypted.append(byte2hex(digestArray[i])); } setEncryptedPassword(encrypted.toString()); } Code Sample 2: public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); }
11
Code Sample 1: public static int gzipFile(File file_input, String file_output) { File gzip_output = new File(file_output); GZIPOutputStream gzip_out_stream; try { FileOutputStream out = new FileOutputStream(gzip_output); gzip_out_stream = new GZIPOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) gzip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_GZIP_FAIL; } try { gzip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public static void main(String[] args) throws IOException { File fileIn = new File("D:\\zz_c\\study2\\src\\study\\io\\A.java"); InputStream fin = new FileInputStream(fileIn); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(); pout.connect(pin); IoRead i = new IoRead(); i.setIn(pin); File fileOU1 = new File("D:\\zz_c\\study2\\src\\study\\io\\A1.java"); File fileOU2 = new File("D:\\zz_c\\study2\\src\\study\\io\\A2.java"); File fileOU3 = new File("D:\\zz_c\\study2\\src\\study\\io\\A3.java"); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU1))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU2))); i.addOut(new BufferedOutputStream(new FileOutputStream(fileOU3))); PipedInputStream pin2 = new PipedInputStream(); PipedOutputStream pout2 = new PipedOutputStream(); i.addOut(pout2); pout2.connect(pin2); i.start(); int read; try { read = fin.read(); while (read != -1) { pout.write(read); read = fin.read(); } fin.close(); pout.close(); } catch (IOException e) { e.printStackTrace(); } int c = pin2.read(); while (c != -1) { System.out.print((char) c); c = pin2.read(); } pin2.close(); } Code Sample 2: @Override public ImageData getImageData(URL url) { InputStream in = null; try { URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", "Tahiti/Alpha5x"); conn.setRequestProperty("agent-system", "aglets"); conn.setAllowUserInteraction(true); conn.connect(); in = conn.getInputStream(); String type = conn.getContentType(); int len = conn.getContentLength(); if (len < 0) { len = in.available(); } byte[] b = new byte[len]; int off = 0; int n = 0; while (n < len) { int count = in.read(b, off + n, len - n); if (count < 0) { throw new java.io.EOFException(); } n += count; } in.close(); return new AgletImageData(url, b, type); } catch (Exception ex) { ex.printStackTrace(); return null; } }
11
Code Sample 1: private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); } Code Sample 2: public void notifyTerminated(Writer r) { all_writers.remove(r); if (all_writers.isEmpty()) { all_terminated = true; Iterator iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); do { try { fc.stream.flush(); fc.stream.close(); } catch (IOException e) { } fc = fc.next; } while (fc != null); } iterator = open_files.iterator(); boolean all_ok = true; while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); logger.logComment("File chunk <" + fc.name + "> " + fc.start_byte + " " + fc.position + " " + fc.actual_file); boolean ok = true; while (fc.next != null) { ok = ok && (fc.start_byte + fc.actual_file.length()) == fc.next.start_byte; fc = fc.next; } if (ok) { logger.logComment("Received file <" + fc.name + "> is contiguous (and hopefully complete)"); } else { logger.logError("Received file <" + fc.name + "> is NOT contiguous"); all_ok = false; } } if (all_ok) { byte[] buffer = new byte[16384]; iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); try { if (fc.next != null) { FileOutputStream fos = new FileOutputStream(fc.actual_file, true); fc = fc.next; while (fc != null) { FileInputStream fis = new FileInputStream(fc.actual_file); int actually_read = fis.read(buffer); while (actually_read != -1) { fos.write(buffer, 0, actually_read); actually_read = fis.read(buffer); } fc.actual_file.delete(); fc = fc.next; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } fte.allWritersTerminated(); fte = null; } }
00
Code Sample 1: public void render(final HttpServletRequest request, final HttpServletResponse response, final byte[] bytes, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } response.setContentLength(bytes.length); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); } Code Sample 2: public void removeUser(final User user) throws IOException { try { Connection conn = null; boolean autoCommit = false; try { conn = pool.getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); final PreparedStatement removeUser = conn.prepareStatement("delete from users where userId = ?"); removeUser.setString(1, user.getUserId()); removeUser.executeUpdate(); final PreparedStatement deleteRoles = conn.prepareStatement("delete from userRoles where userId=?"); deleteRoles.setString(1, user.getUserId()); deleteRoles.executeUpdate(); conn.commit(); } catch (Throwable t) { if (conn != null) conn.rollback(); throw new SQLException(t.toString()); } finally { if (conn != null) { conn.setAutoCommit(autoCommit); conn.close(); } } } catch (final SQLException sqle) { log.log(Level.SEVERE, sqle.toString(), sqle); throw new IOException(sqle.toString()); } }
00
Code Sample 1: private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); try { data = Data.valueOf(md.digest()); response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); ID = response.getWord(); registerSettings(); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } } Code Sample 2: void bsort(int a[], int lo, int hi) throws Exception { for (int j = hi; j > lo; j--) { for (int i = lo; i < j; i++) { if (a[i] > a[i + 1]) { int T = a[i]; a[i] = a[i + 1]; a[i + 1] = T; pause(); } } } }
11
Code Sample 1: public void testReadNormal() throws Exception { archiveFileManager.executeWith(new TemporaryFileExecutor() { public void execute(File temporaryFile) throws Exception { ZipArchive archive = new ZipArchive(temporaryFile.getPath()); InputStream input = archive.getInputFrom(ARCHIVE_FILE_1); if (input != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, output); assertEquals(ARCHIVE_FILE_1 + " contents not correct", ARCHIVE_FILE_1_CONTENT, output.toString()); } else { fail("cannot open " + ARCHIVE_FILE_1); } } }); } Code Sample 2: public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) System.out.write(x); } if (args.length == 1) print("Checksum: " + csumi.getChecksum().getValue()); bis.close(); ZipFile zf = new ZipFile("test.zip"); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry) e.nextElement(); print("File: " + ze2); } }
00
Code Sample 1: private static void tryToMerge(String url) { if ("none".equalsIgnoreCase(url)) return; Properties nullProps = new Properties(); FileProperties propsIn = new FileProperties(nullProps, nullProps); try { propsIn.load(new URL(url).openStream()); } catch (Exception e) { } if (propsIn.isEmpty()) return; for (Iterator i = propsIn.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry) i.next(); String propKey = ((String) e.getKey()).trim(); if (!propKey.startsWith(MERGE_PROP_PREFIX)) continue; String settingName = propKey.substring(MERGE_PROP_PREFIX.length()); if (getVal(settingName) == null) { String settingVal = ((String) e.getValue()).trim(); set(settingName, settingVal); } } } Code Sample 2: public static void copyFile(File oldPathFile, File newPathFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(oldPathFile)); out = new BufferedOutputStream(new FileOutputStream(newPathFile)); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (in.read(buffer) > 0) out.write(buffer); } finally { if (null != in) in.close(); if (null != out) out.close(); } }
00
Code Sample 1: public void convert(CSVReader reader, Writer writer, int nbTotalRows) throws IOException, InterruptedException { Validate.notNull(reader, "CSVReader"); Validate.notNull(writer, "Writer"); Writer bufferedWriter = new BufferedWriter(writer); File fileForColsDef = createTempFileForCss(); BufferedWriter colsDefWriter = new BufferedWriter(new FileWriter(fileForColsDef)); File fileForTable = createTempFileForTable(); BufferedWriter tableWriter = new BufferedWriter(new FileWriter(fileForTable)); try { int currentRow = 0; String[] nextLine = reader.readNext(); if (nextLine != null) { int[] colsCharCount = new int[nextLine.length]; writeTableRowHeader(tableWriter, nextLine); while ((nextLine = reader.readNext()) != null) { currentRow++; if (progress != null) { float percent = ((float) currentRow / (float) nbTotalRows) * 100f; progress.updateProgress(ConvertionStepEnum.PROCESSING_ROWS, percent); } writeTableRow(tableWriter, nextLine, colsCharCount); } writeTableStart(colsDefWriter, colsCharCount); writeColsDefinitions(colsDefWriter, colsCharCount); } writeConverterInfos(bufferedWriter); writeTableEnd(tableWriter); flushAndClose(tableWriter); flushAndClose(colsDefWriter); BufferedReader colsDefReader = new BufferedReader(new FileReader(fileForColsDef)); BufferedReader tableReader = new BufferedReader(new FileReader(fileForTable)); mergeFiles(bufferedWriter, colsDefReader, tableReader); } finally { closeQuietly(tableWriter); closeQuietly(colsDefWriter); fileForTable.delete(); fileForColsDef.delete(); } } 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(); }
11
Code Sample 1: @SuppressWarnings("unchecked") public ArrayList<GmailContact> getAllContacts() throws GmailException { String query = properties.getString("export_page"); query = query.replace("[RANDOM_INT]", "" + random.nextInt()); int statusCode = -1; GetMethod get = new GetMethod(query); if (log.isInfoEnabled()) log.info("getting all contacts ..."); try { statusCode = client.executeMethod(get); if (statusCode != 200) throw new GmailException("In contacts export page: Status code expected: 200 -> Status code returned: " + statusCode); } catch (HttpException e) { throw new GmailException("HttpException in contacts export page:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in contacts export page:" + e.getMessage()); } finally { get.releaseConnection(); } if (log.isTraceEnabled()) log.trace("accessing contacts export page successful..."); String query_post = properties.getString("outlook_export_page"); PostMethod post = new PostMethod(query_post); post.addRequestHeader("Accept-Encoding", "gzip,deflate"); post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.8"); NameValuePair[] data = { new NameValuePair("at", getCookie("GMAIL_AT")), new NameValuePair("ecf", "o"), new NameValuePair("ac", "Export Contacts") }; post.setRequestBody(data); if (log.isTraceEnabled()) log.trace("getting contacts csv file..."); try { statusCode = client.executeMethod(post); if (statusCode != 200) throw new GmailException("In csv file post: Status code expected: 200 -> Status code returned: " + statusCode); if (log.isTraceEnabled()) log.trace("Gmail: csv charset: " + post.getResponseCharSet()); GMAIL_OUTPUT_CHARSET = post.getResponseCharSet(); InputStreamReader isr = new InputStreamReader(new GZIPInputStream(post.getResponseBodyAsStream()), post.getResponseCharSet()); CSVReader reader = new CSVReader(isr); List csvEntries = reader.readAll(); reader.close(); ArrayList<GmailContact> contacts = new ArrayList<GmailContact>(); MessageDigest m = MessageDigest.getInstance("MD5"); if (log.isTraceEnabled()) log.trace("creating Gmail contacts..."); for (int i = 1; i < csvEntries.size(); i++) { GmailContact contact = new GmailContact(); String[] value = (String[]) csvEntries.get(i); for (int j = 0; j < value.length; j++) { switch(j) { case 0: contact.setName(value[j]); break; case 1: contact.setEmail(value[j]); if (contact.getName() == null) contact.setIdName(value[j]); else contact.setIdName(contact.getName() + value[j]); break; case 2: contact.setNotes(value[j]); break; case 3: contact.setEmail2(value[j]); break; case 4: contact.setEmail3(value[j]); break; case 5: contact.setMobilePhone(value[j]); break; case 6: contact.setPager(value[j]); break; case 7: contact.setCompany(value[j]); break; case 8: contact.setJobTitle(value[j]); break; case 9: contact.setHomePhone(value[j]); break; case 10: contact.setHomePhone2(value[j]); break; case 11: contact.setHomeFax(value[j]); break; case 12: contact.setHomeAddress(value[j]); break; case 13: contact.setBusinessPhone(value[j]); break; case 14: contact.setBusinessPhone2(value[j]); break; case 15: contact.setBusinessFax(value[j]); break; case 16: contact.setBusinessAddress(value[j]); break; case 17: contact.setOtherPhone(value[j]); break; case 18: contact.setOtherFax(value[j]); break; case 19: contact.setOtherAddress(value[j]); break; } } m.update(contact.toString().getBytes()); if (log.isTraceEnabled()) log.trace("setting Md5 Hash..."); contact.setMd5Hash(new BigInteger(m.digest()).toString()); contacts.add(contact); } if (log.isTraceEnabled()) log.trace("Mapping contacts uid..."); Collections.sort(contacts); ArrayList<GmailContact> idList = getAllContactsID(); for (int i = 0; i < idList.size(); i++) { contacts.get(i).setId(idList.get(i).getId()); } if (log.isInfoEnabled()) log.info("getting all contacts info successful..."); return contacts; } catch (HttpException e) { throw new GmailException("HttpException in csv file post:" + e.getMessage()); } catch (IOException e) { throw new GmailException("IOException in csv file post:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new GmailException("No such md5 algorithm " + e.getMessage()); } finally { post.releaseConnection(); } } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: public static InputStream getData(DataTransferDescriptor desc, GlobusCredential creds) throws Exception { URL url = new URL(desc.getUrl()); if (url.getProtocol().equals("http")) { URLConnection conn = url.openConnection(); conn.connect(); return conn.getInputStream(); } else if (url.getProtocol().equals("https")) { if (creds != null) { GlobusGSSCredentialImpl cred = new GlobusGSSCredentialImpl(creds, GSSCredential.INITIATE_AND_ACCEPT); GSIHttpURLConnection connection = new GSIHttpURLConnection(url); connection.setGSSMode(GSIConstants.MODE_SSL); connection.setCredentials(cred); return connection.getInputStream(); } else { throw new Exception("To use the https protocol to retrieve data from the Transfer Service you must have credentials"); } } throw new Exception("Protocol " + url.getProtocol() + " not supported."); } Code Sample 2: private String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: private void Connect() throws NpsException { try { client = new FTPClient(); client.connect(host.hostname, host.remoteport); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); client = null; nps.util.DefaultLog.error_noexception("FTP Server:" + host.hostname + "refused connection."); return; } client.login(host.uname, host.upasswd); client.enterLocalPassiveMode(); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.changeWorkingDirectory(host.remotedir); } catch (Exception e) { nps.util.DefaultLog.error(e); } } Code Sample 2: private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; }
11
Code Sample 1: @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); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { if (in.getCanonicalPath().equals(out.getCanonicalPath())) { return; } 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 void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: static void invalidSlave(String msg, Socket sock) throws IOException { BufferedReader _sinp = null; PrintWriter _sout = null; try { _sout = new PrintWriter(sock.getOutputStream(), true); _sinp = new BufferedReader(new InputStreamReader(sock.getInputStream())); _sout.println(msg); logger.info("NEW< " + msg); String txt = AsyncSlaveListener.readLine(_sinp, 30); String sname = ""; String spass = ""; String shash = ""; try { String[] items = txt.split(" "); sname = items[1].trim(); spass = items[2].trim(); shash = items[3].trim(); } catch (Exception e) { throw new IOException("Slave Inititalization Faailed"); } String pass = sname + spass + _pass; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(pass.getBytes()); String hash = AsyncSlaveListener.hash2hex(md5.digest()).toLowerCase(); if (!hash.equals(shash)) { throw new IOException("Slave Inititalization Faailed"); } } catch (Exception e) { } throw new IOException("Slave Inititalization Faailed"); } 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: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } }
00
Code Sample 1: public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); System.out.println("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { System.out.println("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); return UTType.Item; } if (contentType != null) { System.out.println("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; System.out.println("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; } Code Sample 2: @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; boolean checkPassword1 = false; boolean checkPassword2 = false; sql = "select password from Usuarios where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { Tree tree1 = CreateTree(password, 0); Tree tree2 = CreateTree(password, 1); tree1.enumerateTree(tree1.root); tree2.enumerateTree(tree2.root); for (int i = 0; i < tree1.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree1.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword1 = true; break; } else checkPassword1 = false; } for (int i = 0; i < tree2.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree2.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword2 = true; break; } else checkPassword2 = false; } if (checkPassword1 == true || checkPassword2 == true) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); setTries(0); setVisible(false); Error.log(3003, "Senha pessoal verificada positivamente."); Error.log(3002, "Autentica��o etapa 2 encerrada."); PasswordTableWindow ptw = new PasswordTableWindow(login); ptw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); Error.log(3004, "Senha pessoal verificada negativamente."); int tries = getTries(); if (tries == 0) { Error.log(3005, "Primeiro erro da senha pessoal contabilizado."); } else if (tries == 1) { Error.log(3006, "Segundo erro da senha pessoal contabilizado."); } else if (tries == 2) { Error.log(3007, "Terceiro erro da senha pessoal contabilizado."); Error.log(3008, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 2."); Error.log(3002, "Autentica��o etapa 2 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } if (e.getSource() == btnClear) { passwordField.setText(""); } }
00
Code Sample 1: public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); } Code Sample 2: @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ImagesService imgService = ImagesServiceFactory.getImagesService(); InputStream stream = request.getInputStream(); ArrayList<Byte> bytes = new ArrayList<Byte>(); int b = 0; while ((b = stream.read()) != -1) { bytes.add((byte) b); } byte img[] = new byte[bytes.size()]; for (int i = 0; i < bytes.size(); i++) { img[i] = bytes.get(i); } BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); String urlBlobstore = blobstoreService.createUploadUrl("/blobstore-servlet?action=upload"); URL url = new URL("http://localhost:8888" + urlBlobstore); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=29772313"); OutputStream out = connection.getOutputStream(); out.write(img); out.flush(); out.close(); System.out.println(connection.getResponseCode()); System.out.println(connection.getResponseMessage()); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String responseText = ""; String line; while ((line = rd.readLine()) != null) { responseText += line; } out.close(); rd.close(); response.sendRedirect("/blobstore-servlet?action=getPhoto&" + responseText); }
00
Code Sample 1: private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } Code Sample 2: public String encripta(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } }
00
Code Sample 1: private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); } Code Sample 2: public static String md5hash(String text) { java.security.MessageDigest md; try { md = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.update(text.getBytes()); byte[] md5bytes = md.digest(); return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes)); }
11
Code Sample 1: private static String calculateMD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(s.getBytes()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { throw new UndeclaredThrowableException(e); } } Code Sample 2: public void visit(AuthenticationMD5Password message) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(((String) properties.get("password") + (String) properties.get("user")).getBytes("iso8859-1")); String newValue = toHexString(md5.digest()) + new String(message.getSalt(), "iso8859-1"); md5.reset(); md5.update(newValue.getBytes("iso8859-1")); newValue = toHexString(md5.digest()); PasswordMessage mes = new PasswordMessage("md5" + newValue); byte[] data = encoder.encode(mes); out.write(data); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static String EncryptString(String method, String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); if (method.equals("SHA1") || method.equals("MD5")) { try { md = MessageDigest.getInstance(method); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); return null; } } else { return null; } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { String tmp = Integer.toHexString(0xff & byteHash[i]); if (tmp.length() < 2) tmp = "0" + tmp; resultString.append(tmp); } return (resultString.toString()); } Code Sample 2: 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); } }
11
Code Sample 1: public boolean backupFile(File oldFile, File newFile) { boolean isBkupFileOK = false; FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(oldFile).getChannel(); targetChannel = new FileOutputStream(newFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((newFile != null) && (newFile.exists()) && (newFile.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; } Code Sample 2: public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&amp;") != -1) { String syn1 = syn.substring(0, syn.indexOf("&amp;")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } }
00
Code Sample 1: @Override public InputStream openStream(long off, long len) throws IOException { URLConnection con = url.openConnection(); if (!(con instanceof HttpURLConnection)) { return null; } long t0 = System.currentTimeMillis(); HttpURLConnection urlcon = (HttpURLConnection) con; urlcon.setRequestProperty("Connection", "Keep-Alive"); String rangeS = ""; if (off > 0) rangeS += "bytes=" + off + "-"; if (len > 0 && off + len < length) rangeS += (len - 1); if (rangeS.length() > 0) { urlcon.setRequestProperty("Range", rangeS); } urlcon.setRequestProperty("Content-Type", "application/octet-stream"); InputStream in = urlcon.getInputStream(); rangeS = urlcon.getHeaderField("Content-Range"); long responseOff = 0; long responseEnd = -1; if (rangeS != null) { int start = rangeS.indexOf(' ') + 1; int end = rangeS.indexOf('-', start); String offS = rangeS.substring(start, end).trim(); responseOff = Long.parseLong(offS); start = end + 1; end = rangeS.indexOf('/', start); String lenS = rangeS.substring(start, end).trim(); responseEnd = 1 + Long.parseLong(lenS); } while (responseOff < off && responseOff <= responseEnd) { long s = in.skip(off - responseOff); if (s <= 0) { break; } responseOff += s; } length = urlcon.getHeaderFieldInt("Content-Length", -1); long respTime = System.currentTimeMillis() - t0; if (responseTime < 0) { responseTime = respTime; } else { responseTime = Math.round(0.5 * responseTime + 0.5 * respTime); } return in; } Code Sample 2: void loadPlaylist() { if (running_as_applet) { String s = null; for (int i = 0; i < 10; i++) { s = getParameter("jorbis.player.play." + i); if (s == null) break; playlist.addElement(s); } } if (playlistfile == null) { return; } try { InputStream is = null; try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), playlistfile); else url = new URL(playlistfile); URLConnection urlc = url.openConnection(); is = urlc.getInputStream(); } catch (Exception ee) { } if (is == null && !running_as_applet) { try { is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + playlistfile); } catch (Exception ee) { } } if (is == null) return; while (true) { String line = readline(is); if (line == null) break; byte[] foo = line.getBytes(); for (int i = 0; i < foo.length; i++) { if (foo[i] == 0x0d) { line = new String(foo, 0, i); break; } } playlist.addElement(line); } } catch (Exception e) { System.out.println(e); } }
11
Code Sample 1: public static void _save(PortletRequest req, PortletResponse res, PortletConfig config, ActionForm form) throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); 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 (NonWritableChannelException we) { } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "Property File save Failed " + e, e); } SessionMessages.add(req, "message", "message.usermanager.display.save"); } Code Sample 2: private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } }
00
Code Sample 1: public static void main(String arg[]) { try { URL url = new URL(tempurl); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); connect.setDoInput(true); connect.setDoOutput(true); BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream(), "gb2312")); String line = null; StringBuffer content = new StringBuffer(); while ((line = in.readLine()) != null) { content.append(line); } in.close(); url = null; String msg = content.toString(); Matcher m = p.matcher(msg); while (m.find()) { System.out.println(m.group(1) + "---" + m.group(2) + "---" + m.group(3) + "---" + m.group(4) + "---" + m.group(5) + "---"); } } catch (Exception e) { System.out.println("Error:"); System.out.println(e.getStackTrace()); } } Code Sample 2: public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuilder hashStringBuf = new StringBuilder("{SHA}"); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { log.error("Error getting password hash - " + nsae.getMessage()); return null; } }
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: private void putFile(String location, String file) throws Exception { System.out.println("Put file to " + location); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true); RDFFormat dataFormat = RDFFormat.forFileName(file, RDFFormat.RDFXML); conn.setRequestProperty("Content-Type", dataFormat.getDefaultMIMEType()); InputStream dataStream = ProtocolTest.class.getResourceAsStream(file); try { OutputStream connOut = conn.getOutputStream(); try { IOUtil.transfer(dataStream, connOut); } finally { connOut.close(); } } finally { dataStream.close(); } conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_NO_CONTENT) { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); } }
11
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: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String requestURI = req.getRequestURI(); logger.info("The requested URI: {}", requestURI); String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH); int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER); String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter; String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null; if (arxivId == null) { logger.error("The request with an empty arxiv id parameter"); return; } String filePath = segmentId == null ? format("/opt/mocassin/aux-pdf/%s" + StringUtil.arxivid2filename(arxivId, "pdf")) : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf"); if (!new File(filePath).exists()) { filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf")); } try { FileInputStream fileInputStream = new FileInputStream(filePath); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(fileInputStream, byteArrayOutputStream); resp.setContentType("application/pdf"); resp.setHeader("Content-disposition", String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf"))); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.close(); } catch (FileNotFoundException e) { logger.error("Error while downloading: PDF file= '{}' not found", filePath); } catch (IOException e) { logger.error("Error while downloading the PDF file", e); } }
00
Code Sample 1: public InputStream getResourceAsStream(String name) { if (debug >= 2) log("getResourceAsStream(" + name + ")"); InputStream stream = null; stream = findLoadedResource(name); if (stream != null) { if (debug >= 2) log(" --> Returning stream from cache"); return (stream); } if (delegate) { if (debug >= 3) log(" Delegating to parent classloader"); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { if (debug >= 2) log(" --> Returning stream from parent"); return (stream); } } if (debug >= 3) log(" Searching local repositories"); URL url = findResource(name); if (url != null) { if (debug >= 2) log(" --> Returning stream from local"); try { return (url.openStream()); } catch (IOException e) { log("url.openStream(" + url.toString() + ")", e); return (null); } } if (!delegate) { if (debug >= 3) log(" Delegating to parent classloader"); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { if (debug >= 2) log(" --> Returning stream from parent"); return (stream); } } if (debug >= 2) log(" --> Resource not found, returning null"); return (null); } Code Sample 2: public int delete(BusinessObject o) throws DAOException { int delete = 0; Project project = (Project) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_PROJECT")); pst.setInt(1, project.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 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 delete; }
00
Code Sample 1: public static int best(int r, int n, int s) { if ((n <= 0) || (r < 0) || (r > n) || (s < 0)) return 0; int[] rolls = new int[n]; for (int i = 0; i < n; i++) rolls[i] = d(s); boolean found; do { found = false; for (int x = 0; x < n - 1; x++) { if (rolls[x] < rolls[x + 1]) { int t = rolls[x]; rolls[x] = rolls[x + 1]; rolls[x + 1] = t; found = true; } } } while (found); int sum = 0; for (int i = 0; i < r; i++) sum += rolls[i]; return sum; } Code Sample 2: public static void TestDBStore() throws PDException, Exception { StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB"); System.out.println("Driver[" + StDB.getDriver() + "] Tabla [" + StDB.getTable() + "]"); StDB.Connect(); FileInputStream in = new FileInputStream("/tmp/readme.htm"); StDB.Insert("12345678-1", "1.0", in); int TAMBUFF = 1024 * 64; byte Buffer[] = new byte[TAMBUFF]; InputStream Bytes; Bytes = StDB.Retrieve("12345678-1", "1.0"); FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm"); int readed = Bytes.read(Buffer); while (readed != -1) { fo.write(Buffer, 0, readed); readed = Bytes.read(Buffer); } Bytes.close(); fo.close(); StDB.Delete("12345678-1", "1.0"); StDB.Disconnect(); }
11
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
00
Code Sample 1: public void genCreateSchema(DiagramModel diagramModel, String source) { try { con.setAutoCommit(false); stmt = con.createStatement(); Collection boxes = diagramModel.getBoxes(); BoxModel box; ItemModel item; String sqlQuery; int counter = 0; for (Iterator x = boxes.iterator(); x.hasNext(); ) { box = (BoxModel) x.next(); if (!box.isAbstractDef()) { sqlQuery = sqlCreateTableBegin(box); Collection items = box.getItems(); for (Iterator y = items.iterator(); y.hasNext(); ) { item = (ItemModel) y.next(); sqlQuery = sqlQuery + sqlColumn(item); } sqlQuery = sqlQuery + sqlForeignKeyColumns(box); sqlQuery = sqlQuery + sqlPrimaryKey(box); sqlQuery = sqlQuery + sqlUniqueKey(box); sqlQuery = sqlQuery + sqlCreateTableEnd(box, source); System.out.println(sqlQuery); try { stmt.executeUpdate(sqlQuery); counter++; } catch (SQLException e) { String tableName = box.getName(); System.out.println("// Problem while creating table " + tableName + " : " + e.getMessage()); String msg = Para.getPara().getText("tableNotCreated") + " -- " + tableName; this.informUser(msg); } } } this.genCreateForeignKeys(diagramModel); con.commit(); if (counter > 0) { String msg = Para.getPara().getText("schemaCreated") + " -- " + counter + " " + Para.getPara().getText("tables"); this.informUser(msg); } else { this.informUser(Para.getPara().getText("schemaNotCreated")); } } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the JDBC schema generation! "); try { con.rollback(); this.informUser(Para.getPara().getText("schemaNotCreated")); } catch (SQLException e1) { System.out.println(e1.getMessage() + " // Problem with the connection rollback! "); } } finally { try { con.setAutoCommit(true); stmt.close(); } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the statement closing! "); } } } Code Sample 2: public static URL getIconURLForUser(String id) { try { URL url = new URL("http://profiles.yahoo.com/" + id); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String input = null; while ((input = r.readLine()) != null) { if (input.indexOf("<a href=\"") < 0) continue; if (input.indexOf("<img src=\"") < 0) continue; if (input.indexOf("<a href=\"") > input.indexOf("<img src=\"")) continue; String href = input.substring(input.indexOf("<a href=\"") + 9); String src = input.substring(input.indexOf("<img src=\"") + 10); if (href.indexOf("\"") < 0) continue; if (src.indexOf("\"") < 0) continue; href = href.substring(0, href.indexOf("\"")); src = src.substring(0, src.indexOf("\"")); if (href.equals(src)) { return new URL(href); } } } catch (IOException e) { } URL toReturn = null; try { toReturn = new URL("http://us.i1.yimg.com/us.yimg.com/i/ppl/no_photo.gif"); } catch (MalformedURLException e) { Debug.assrt(false); } return toReturn; }
00
Code Sample 1: public void testTransactions0010() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0010 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(); } assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i + ((j - 1) * rowsToAdd)); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) { i -= rowsToAdd; } assertEquals(rs.getString(1).trim().length(), i); } assertEquals(count, (2 * rowsToAdd)); stmt.close(); pstmt.close(); con.setAutoCommit(true); } Code Sample 2: private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public void reload() throws SAXException, IOException { if (url != null) { java.io.InputStream is = url.openStream(); configDoc = builder.parse(is); is.close(); System.out.println("XML config file read correctly from " + url); } else { configDoc = builder.parse(configFile); System.out.println("XML config file read correctly from " + configFile); } } Code Sample 2: public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException { URI uri = request.getURI(); String original = uri.toString(); UrlRules rules = UrlRules.getRules(mResolver); UrlRules.Rule rule = rules.matchRule(original); String rewritten = rule.apply(original); if (rewritten == null) { Log.w(TAG, "Blocked by " + rule.mName + ": " + original); throw new BlockedRequestException(rule); } else if (rewritten == original) { return executeWithoutRewriting(request, context); } try { uri = new URI(rewritten); } catch (URISyntaxException e) { throw new RuntimeException("Bad URL from rule: " + rule.mName, e); } RequestWrapper wrapper = wrapRequest(request); wrapper.setURI(uri); request = wrapper; if (LOCAL_LOGV) Log.v(TAG, "Rule " + rule.mName + ": " + original + " -> " + rewritten); return executeWithoutRewriting(request, context); }
00
Code Sample 1: public void saveSharedFiles(List<FrostSharedFileItem> sfFiles) throws SQLException { Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); Statement s = conn.createStatement(); s.executeUpdate("DELETE FROM SHAREDFILES"); s.close(); s = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO SHAREDFILES (" + "path,size,fnkey,sha,owner,comment,rating,keywords," + "lastuploaded,uploadcount,reflastsent,requestlastreceived,requestsreceivedcount,lastmodified) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (Iterator<FrostSharedFileItem> i = sfFiles.iterator(); i.hasNext(); ) { FrostSharedFileItem sfItem = i.next(); int ix = 1; ps.setString(ix++, sfItem.getFile().getPath()); ps.setLong(ix++, sfItem.getFileSize()); ps.setString(ix++, sfItem.getChkKey()); ps.setString(ix++, sfItem.getSha()); ps.setString(ix++, sfItem.getOwner()); ps.setString(ix++, sfItem.getComment()); ps.setInt(ix++, sfItem.getRating()); ps.setString(ix++, sfItem.getKeywords()); ps.setLong(ix++, sfItem.getLastUploaded()); ps.setInt(ix++, sfItem.getUploadCount()); ps.setLong(ix++, sfItem.getRefLastSent()); ps.setLong(ix++, sfItem.getRequestLastReceived()); ps.setInt(ix++, sfItem.getRequestsReceived()); ps.setLong(ix++, sfItem.getLastModified()); ps.executeUpdate(); } ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (Throwable t) { logger.log(Level.SEVERE, "Exception during save", t); try { conn.rollback(); } catch (Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); } try { conn.setAutoCommit(true); } catch (Throwable t1) { } } finally { AppLayerDatabase.getInstance().givePooledConnection(conn); } } Code Sample 2: public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: protected void setupService(MessageContext msgContext) throws Exception { String realpath = msgContext.getStrProp(Constants.MC_REALPATH); String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION); if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION; if ((realpath != null) && (realpath.endsWith(extension))) { String jwsFile = realpath; String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH); File f2 = new File(jwsFile); if (!f2.exists()) { throw new FileNotFoundException(rel); } if (rel.charAt(0) == '/') { rel = rel.substring(1); } int lastSlash = rel.lastIndexOf('/'); String dir = null; if (lastSlash > 0) { dir = rel.substring(0, lastSlash); } String file = rel.substring(lastSlash + 1); String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR); if (outdir == null) outdir = "."; if (dir != null) { outdir = outdir + File.separator + dir; } File outDirectory = new File(outdir); if (!outDirectory.exists()) { outDirectory.mkdirs(); } if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile); String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "java"; String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "class"; if (log.isDebugEnabled()) { log.debug("jFile: " + jFile); log.debug("cFile: " + cFile); log.debug("outdir: " + outdir); } File f1 = new File(cFile); String clsName = null; if (clsName == null) clsName = f2.getName(); if (clsName != null && clsName.charAt(0) == '/') clsName = clsName.substring(1); clsName = clsName.substring(0, clsName.length() - extension.length()); clsName = clsName.replace('/', '.'); if (log.isDebugEnabled()) log.debug("ClsName: " + clsName); if (!f1.exists() || f2.lastModified() > f1.lastModified()) { log.debug(Messages.getMessage("compiling00", jwsFile)); log.debug(Messages.getMessage("copy00", jwsFile, jFile)); FileReader fr = new FileReader(jwsFile); FileWriter fw = new FileWriter(jFile); char[] buf = new char[4096]; int rc; while ((rc = fr.read(buf, 0, 4095)) >= 0) fw.write(buf, 0, rc); fw.close(); fr.close(); log.debug("javac " + jFile); Compiler compiler = CompilerFactory.getCompiler(); compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext)); compiler.setDestination(outdir); compiler.addFile(jFile); boolean result = compiler.compile(); (new File(jFile)).delete(); if (!result) { (new File(cFile)).delete(); Document doc = XMLUtils.newDocument(); Element root = doc.createElementNS("", "Errors"); StringBuffer message = new StringBuffer("Error compiling "); message.append(jFile); message.append(":\n"); List errors = compiler.getErrors(); int count = errors.size(); for (int i = 0; i < count; i++) { CompilerError error = (CompilerError) errors.get(i); if (i > 0) message.append("\n"); message.append("Line "); message.append(error.getStartLine()); message.append(", column "); message.append(error.getStartColumn()); message.append(": "); message.append(error.getMessage()); } root.appendChild(doc.createTextNode(message.toString())); throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root }); } ClassUtils.removeClassLoader(clsName); soapServices.remove(clsName); } ClassLoader cl = ClassUtils.getClassLoader(clsName); if (cl == null) { cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile); } msgContext.setClassLoader(cl); SOAPService rpc = (SOAPService) soapServices.get(clsName); if (rpc == null) { rpc = new SOAPService(new RPCProvider()); rpc.setName(clsName); rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName); rpc.setEngine(msgContext.getAxisEngine()); String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS); if (allowed == null) allowed = "*"; rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed); String scope = (String) getOption(RPCProvider.OPTION_SCOPE); if (scope == null) scope = Scope.DEFAULT.getName(); rpc.setOption(RPCProvider.OPTION_SCOPE, scope); rpc.getInitializedServiceDesc(msgContext); soapServices.put(clsName, rpc); } rpc.setEngine(msgContext.getAxisEngine()); rpc.init(); msgContext.setService(rpc); } if (log.isDebugEnabled()) { log.debug("Exit: JWSHandler::invoke"); } } Code Sample 2: public static byte[] loadFile(File file) throws IOException { BufferedInputStream in = null; ByteArrayOutputStream sink = null; try { in = new BufferedInputStream(new FileInputStream(file)); sink = new ByteArrayOutputStream(); IOUtils.copy(in, sink); return sink.toByteArray(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(sink); } }
00
Code Sample 1: public String uploadVideo(String ticketId, String filePath) { TreeMap<String, String> uploadParams = new TreeMap<String, String>(); String url = "http://www.vimeo.com/services/upload/"; uploadParams.put("api_key", apiKey); uploadParams.put("auth_token", this.TEMP_AUTH_TOKEN); uploadParams.put("ticket_id", ticketId); uploadParams.put("format", "json"); String signature = this.generateAppSignature(uploadParams); uploadParams.put("api_sig", signature); ClientHttpRequest request = null; try { request = new ClientHttpRequest(new URL(url).openConnection()); } catch (IOException e) { e.printStackTrace(); } for (Entry<String, String> param : uploadParams.entrySet()) { try { request.setParameter(param.getKey(), param.getValue()); } catch (IOException e) { e.printStackTrace(); } } InputStream videoInput = null; try { videoInput = new FileInputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } try { request.setParameter("video", filePath, videoInput); } catch (IOException e) { e.printStackTrace(); } InputStream response = null; try { response = request.post(); } catch (IOException e) { e.printStackTrace(); } try { InputStreamReader inR = new InputStreamReader(response); BufferedReader buf = new BufferedReader(inR); String line; try { while ((line = buf.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return "hey"; } Code Sample 2: private void generateDocFile(String srcFileName, String s, String destFileName) { try { ZipFile docxFile = new ZipFile(new File(srcFileName)); ZipEntry documentXML = docxFile.getEntry("word/document.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream documentXMLIS1 = docxFile.getInputStream(documentXML); Document doc = dbf.newDocumentBuilder().parse(documentXMLIS1); Transformer t = TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(baos)); ZipOutputStream docxOutFile = new ZipOutputStream(new FileOutputStream(destFileName)); Enumeration<ZipEntry> entriesIter = (Enumeration<ZipEntry>) docxFile.entries(); while (entriesIter.hasMoreElements()) { ZipEntry entry = entriesIter.nextElement(); if (entry.getName().equals("word/document.xml")) { docxOutFile.putNextEntry(new ZipEntry(entry.getName())); byte[] datas = s.getBytes("UTF-8"); docxOutFile.write(datas, 0, datas.length); docxOutFile.closeEntry(); } else if (entry.getName().equals("word/media/image1.png")) { InputStream incoming = new FileInputStream("c:/aaa.jpg"); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } else { InputStream incoming = docxFile.getInputStream(entry); byte[] data = new byte[incoming.available()]; int readCount = incoming.read(data, 0, data.length); docxOutFile.putNextEntry(new ZipEntry(entry.getName())); docxOutFile.write(data, 0, readCount); docxOutFile.closeEntry(); } } docxOutFile.close(); } catch (Exception e) { } }
00
Code Sample 1: private String writeInputStreamToString(InputStream stream) { StringWriter stringWriter = new StringWriter(); try { IOUtils.copy(stream, stringWriter); } catch (IOException e) { e.printStackTrace(); } String namespaces = stringWriter.toString().trim(); return namespaces; } Code Sample 2: protected void initializeGraphicalViewer() { getGraphicalViewer().setContents(loadModel()); getGraphicalViewer().addDropTargetListener(createTransferDropTargetListener()); getGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection().isEmpty()) { return; } loadProperties(((StructuredSelection) event.getSelection()).getFirstElement()); } }); }
00
Code Sample 1: public List<BadassEntry> parse() { mBadassEntries = new ArrayList<BadassEntry>(); try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains(START_PARSE)) flag1 = true; if (flag1 && line.contains(STOP_PARSE)) break; if (flag1) { if (line.contains(ENTRY_HINT)) { parseBadass(line); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mBadassEntries; } Code Sample 2: public static void main(String[] args) { FTPClient f = new FTPClient(); String host = "ftpdatos.aemet.es"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); final String datestamp = sdf.format(new Date()); System.out.println(datestamp); String pathname = "datos_observacion/observaciones_diezminutales/" + datestamp + "_diezminutales/"; try { InetAddress server = InetAddress.getByName(host); f.connect(server); String username = "anonymous"; String password = "a@b.c"; f.login(username, password); FTPFile[] files = f.listFiles(pathname, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { return file.getName().startsWith(datestamp); } }); FTPFile file = files[files.length - 2]; f.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); boolean download = false; String remote = pathname + "/" + file.getName(); if (download) { File out = new File("/home/randres/Desktop/" + file.getName()); FileOutputStream fout = new FileOutputStream(out); System.out.println(f.retrieveFile(remote, fout)); fout.flush(); fout.close(); } else { GZIPInputStream gzipin = new GZIPInputStream(f.retrieveFileStream(remote)); LineNumberReader lreader = new LineNumberReader(new InputStreamReader(gzipin, "Cp1250")); String line = null; while ((line = lreader.readLine()) != null) { Aeminuto.processLine(line); } lreader.close(); } f.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private void documentFileChooserActionPerformed(java.awt.event.ActionEvent evt) { if (evt.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { File selectedFile = documentFileChooser.getSelectedFile(); File collectionCopyFile; String newDocumentName = selectedFile.getName(); Document newDocument = new Document(newDocumentName); if (activeCollection.containsDocument(newDocument)) { int matchingFilenameDistinguisher = 1; StringBuilder distinguisherReplacer = new StringBuilder(); newDocumentName = newDocumentName.concat("(" + matchingFilenameDistinguisher + ")"); newDocument.setDocumentName(newDocumentName); while (activeCollection.containsDocument(newDocument)) { matchingFilenameDistinguisher++; newDocumentName = distinguisherReplacer.replace(newDocumentName.length() - 2, newDocumentName.length() - 1, new Integer(matchingFilenameDistinguisher).toString()).toString(); newDocument.setDocumentName(newDocumentName); } } Scanner tokenizer = null; FileChannel fileSource = null; FileChannel collectionDestination = null; HashMap<String, Integer> termHashMap = new HashMap<String, Integer>(); Index collectionIndex = activeCollection.getIndex(); int documentTermMaxFrequency = 0; int currentTermFrequency; try { tokenizer = new Scanner(new BufferedReader(new FileReader(selectedFile))); tokenizer.useDelimiter(Pattern.compile("\\p{Space}|\\p{Punct}|\\p{Cntrl}")); String nextToken; while (tokenizer.hasNext()) { nextToken = tokenizer.next().toLowerCase(); if (!nextToken.isEmpty()) if (termHashMap.containsKey(nextToken)) termHashMap.put(nextToken, termHashMap.get(nextToken) + 1); else termHashMap.put(nextToken, 1); } Term newTerm; for (String term : termHashMap.keySet()) { newTerm = new Term(term); if (!collectionIndex.termExists(newTerm)) collectionIndex.addTerm(newTerm); currentTermFrequency = termHashMap.get(term); if (currentTermFrequency > documentTermMaxFrequency) documentTermMaxFrequency = currentTermFrequency; collectionIndex.addOccurence(newTerm, newDocument, currentTermFrequency); } activeCollection.addDocument(newDocument); String userHome = System.getProperty("user.home"); String fileSeparator = System.getProperty("file.separator"); collectionCopyFile = new File(userHome + fileSeparator + "Infrared" + fileSeparator + activeCollection.getDocumentCollectionName() + fileSeparator + newDocumentName); collectionCopyFile.createNewFile(); fileSource = new FileInputStream(selectedFile).getChannel(); collectionDestination = new FileOutputStream(collectionCopyFile).getChannel(); collectionDestination.transferFrom(fileSource, 0, fileSource.size()); } catch (FileNotFoundException e) { System.err.println(e.getMessage() + " This error should never occur! The file was just selected!"); return; } catch (IOException e) { JOptionPane.showMessageDialog(this, "An I/O error occured during file transfer!", "File transfer I/O error", JOptionPane.WARNING_MESSAGE); return; } finally { try { if (tokenizer != null) tokenizer.close(); if (fileSource != null) fileSource.close(); if (collectionDestination != null) collectionDestination.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (evt.getActionCommand().equalsIgnoreCase(JFileChooser.CANCEL_SELECTION)) processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } Code Sample 2: public void addAuthors() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or author selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or author selected."); int i, j; Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); String pStr = ""; PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','member added','" + dt + "',2,'add member'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { if (!uids[j].equals(userId)) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw new Exception(e.getMessage() + "\n" + pStr + "\npnum=" + pnum + "\n" + pids[0] + "\nunum=" + unum + "\n" + uids[1] + uids[0]); } }
11
Code Sample 1: public static void copy(File source, File dest) throws Exception { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int i; String dicomURL = request.getParameter("datasetURL"); String contentType = request.getParameter("contentType"); String studyUID = request.getParameter("studyUID"); String seriesUID = request.getParameter("seriesUID"); String objectUID = request.getParameter("objectUID"); dicomURL += "&contentType=" + contentType + "&studyUID=" + studyUID + "&seriesUID=" + seriesUID + "&objectUID=" + objectUID + "&transferSyntax=1.2.840.10008.1.2.1"; dicomURL = dicomURL.replace("+", "%2B"); InputStream is = null; DataInputStream dis = null; try { URL url = new URL(dicomURL); is = url.openStream(); dis = new DataInputStream(is); for (i = 0; i < dicomData.length; i++) dicomData[i] = dis.readUnsignedByte(); String windowCenter = getElementValue("00281050"); String windowWidth = getElementValue("00281051"); request.getSession(true).setAttribute(WINDOW_CENTER_PARAM, windowCenter == null ? null : windowCenter.trim()); request.getSession(true).setAttribute(WINDOW_WIDTH_PARAM, windowWidth == null ? null : windowWidth.trim()); dis.skipBytes(50000000); is.close(); dis.close(); out.println("Success"); out.close(); } catch (Exception e) { log.error("Unable to read and send the DICOM dataset page", e); } }
11
Code Sample 1: public static String calculateSHA1(String data, String key) throws NoSuchAlgorithmException, UnsupportedEncodingException { data += key; MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(data.getBytes("iso-8859-1"), 0, data.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static String hash(final String s) { if (s == null || s.length() == 0) return null; try { final MessageDigest hashEngine = MessageDigest.getInstance("SHA-1"); hashEngine.update(s.getBytes("iso-8859-1"), 0, s.length()); return convertToHex(hashEngine.digest()); } catch (final Exception e) { return null; } }
11
Code Sample 1: public static void main(String[] args) throws IOException, WrongFormatException, URISyntaxException { System.out.println(new URI("google.com.ua.css").toString()); Scanner scc = new Scanner(System.in); System.err.print(scc.nextLine().substring(1)); ServerSocket s = new ServerSocket(5354); while (true) { Socket client = s.accept(); InputStream iStream = client.getInputStream(); BufferedReader bf = new BufferedReader(new InputStreamReader(iStream)); String line = ""; while (!(line = bf.readLine()).equals("")) { System.out.println(line); } System.out.println("end of request"); new PrintWriter(client.getOutputStream()).println("hi"); bf.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!"); }
11
Code Sample 1: public boolean doUpload(int count) { String objFileName = Long.toString(new java.util.Date().getTime()) + Integer.toString(count); try { this.objectFileName[count] = objFileName + "_bak." + this.sourceFileExt[count]; File objFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); if (objFile.exists()) { this.doUpload(count); } else { objFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(objFile); BufferedOutputStream bos = new BufferedOutputStream(fos); int readLength = 0; int offset = 0; String str = ""; long readSize = 0L; while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) { str = new String(this.b, 0, readLength); if (str.indexOf("Content-Type:") != -1) { break; } } this.inStream.readLine(this.b, 0, this.b.length); while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) { str = new String(this.b, 0, readLength); if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45 && this.b[3] == 45 && this.b[4] == 45) { break; } bos.write(this.b, 0, readLength); readSize += readLength; if (readSize > this.size) { this.fileMessage[count] = "�ϴ��ļ������ļ���С�������ƣ�"; this.ok = false; break; } } if (this.ok) { bos.flush(); bos.close(); int fileLength = (int) (objFile.length()); byte[] bb = new byte[fileLength - 2]; FileInputStream fis = new FileInputStream(objFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(bb, 0, (fileLength - 2)); fis.close(); bis.close(); this.objectFileName[count] = objFileName + "." + this.sourceFileExt[count]; File ok_file = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); ok_file.createNewFile(); BufferedOutputStream bos_ok = new BufferedOutputStream(new FileOutputStream(ok_file)); bos_ok.write(bb); bos_ok.close(); objFile.delete(); this.fileMessage[count] = "OK"; return true; } else { bos.flush(); bos.close(); File delFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); delFile.delete(); this.objectFileName[count] = "none"; return false; } } catch (Exception e) { this.objectFileName[count] = "none"; this.fileMessage[count] = e.toString(); return false; } } Code Sample 2: public static boolean copyFile(String src, String dst) { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(new File(src)).getChannel(); outChannel = new FileOutputStream(new File(dst)).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (FileNotFoundException e) { e.printStackTrace(); MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst); return false; } catch (IOException e) { MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst); return false; } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } catch (IOException e) { MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst); return false; } } return true; }
00
Code Sample 1: private String sendImpl(String from, String destNumber, String text) throws IOException { final QueryStringBuilder query = new QueryStringBuilder(); query.append("user", username); query.append("password", password); query.append("api_id", apiId); query.append("to", destNumber); if (from != null) { query.append("from", from); } query.append("text", text); final URL url = new URL(CLICKATELL_GATEWAY_URL + "sendmsg" + query.toString()); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); final BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); try { return br.readLine(); } finally { br.close(); } } Code Sample 2: public void download(String contentUuid, File path) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream output = new FileOutputStream(path); IoUtils.copyBytes(inputStream, output); IoUtils.close(inputStream); IoUtils.close(output); } catch (IOException ioex) { throw new WebServiceClientException("Could not download or saving content to path [" + path.getAbsolutePath() + "]", ioex); } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } }