label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); }
|
00
|
Code Sample 1:
private void processOrder() { double neg = 0d; if (intMode == MODE_CHECKOUT) { if (round2Places(mBuf.getBufferTotal()) >= round2Places(order.getOrderTotal())) { double cash, credit, allowedCredit = 0d; allowedCredit = getStudentCredit(); if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { try { neg = Double.parseDouble(settings.get(DBSettings.MAIN_MAXNEGBALANCE)); } catch (NumberFormatException ex) { System.err.println("NumberFormatException::Potential problem with setting MAIN_MAXNEGBALANCE"); System.err.println(" * Note: If you enable negative balances, please don't leave this"); System.err.println(" blank. At least set it to 0. For right now we are setting "); System.err.println(" the max negative balance to $0.00"); System.err.println(""); System.err.println("Exception Message:" + ex.getMessage()); } if (neg < 0) neg *= -1; allowedCredit += neg; } if (round2Places(mBuf.getCredit()) <= round2Places(allowedCredit)) { if (round2Places(mBuf.getCredit()) > round2Places(getStudentCredit()) && !student.isStudentSet()) { gui.setStatus("Can't allow negative balance on an anonymous student!", true); } else { if (round2Places(mBuf.getCredit()) > round2Places(order.getOrderTotal())) { credit = round2Places(order.getOrderTotal()); } else { credit = round2Places(mBuf.getCredit()); } if ((mBuf.getCash() + credit) >= order.getOrderTotal()) { cash = round2Places(order.getOrderTotal() - credit); double change = round2Places(mBuf.getCash() - cash); if (round2Places(cash + credit) == round2Places(order.getOrderTotal())) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = dbMan.getPOSConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String host = getHostName(); String stuId = student.getStudentNumber(); String building = settings.get(DBSettings.MAIN_BUILDING); String cashier = dbMan.getPOSUser(); String strSql = "insert into " + strPOSPrefix + "trans_master ( tm_studentid, tm_total, tm_cashtotal, tm_credittotal, tm_building, tm_register, tm_cashier, tm_datetime, tm_change ) values( '" + stuId + "', '" + round2Places(order.getOrderTotal()) + "', '" + round2Places(cash) + "', '" + round2Places(credit) + "', '" + building + "', '" + host + "', '" + cashier + "', NOW(), '" + round2Places(change) + "')"; int intSqlReturnVal = -1; int masterID = -1; try { intSqlReturnVal = stmt.executeUpdate(strSql, Statement.RETURN_GENERATED_KEYS); ResultSet keys = stmt.getGeneratedKeys(); keys.next(); masterID = keys.getInt(1); keys.close(); stmt.close(); } catch (Exception exRetKeys) { System.err.println(exRetKeys.getMessage() + " (but pscafepos is attempting a work around)"); intSqlReturnVal = stmt.executeUpdate(strSql); masterID = dbMan.getLastInsertIDWorkAround(stmt, strPOSPrefix + "trans_master_tm_id_seq"); if (masterID == -1) System.err.println("It looks like the work around failed, please submit a bug report!"); else System.err.println("work around was successful!"); } if (intSqlReturnVal == 1) { if (masterID >= 0) { OrderItem[] itms = order.getOrderItems(); if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { if (itms[i] != null) { stmt = conn.createStatement(); int itemid = itms[i].getDBID(); double itemprice = round2Places(itms[i].getEffectivePrice()); int f, r, a; String strItemName, strItemBuilding, strItemCat; f = 0; r = 0; a = 0; if (itms[i].isSoldAsFree()) { f = 1; } if (itms[i].isSoldAsReduced()) { r = 1; } if (itms[i].isTypeA()) { a = 1; } strItemName = itms[i].getName(); strItemBuilding = (String) itms[i].getBuilding(); strItemCat = itms[i].getCategory(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "trans_item ( ti_itemid, ti_tmid, ti_pricesold, ti_registerid, ti_cashier, ti_studentid, ti_isfree, ti_isreduced, ti_datetime, ti_istypea, ti_itemname, ti_itembuilding, ti_itemcat ) values('" + itemid + "', '" + masterID + "', '" + round2Places(itemprice) + "', '" + host + "', '" + cashier + "', '" + stuId + "', '" + f + "', '" + r + "', NOW(), '" + a + "', '" + strItemName + "', '" + strItemBuilding + "', '" + strItemCat + "')") != 1) { gui.setCriticalMessage("Item insert failed"); conn.rollback(); } stmt.close(); stmt = conn.createStatement(); String sqlInv = "SELECT inv_id from " + strPOSPrefix + "inventory where inv_menuid = " + itemid + ""; if (stmt.execute(sqlInv)) { ResultSet rsInv = stmt.getResultSet(); int delId = -1; if (rsInv.next()) { delId = rsInv.getInt("inv_id"); } if (delId != -1) { stmt.executeUpdate("delete from " + strPOSPrefix + "inventory where inv_id = " + delId); } stmt.close(); } } else { gui.setCriticalMessage("Null Item"); conn.rollback(); } } boolean blOk = true; if (round2Places(credit) > 0d) { if (round2Places(allowedCredit) >= round2Places(credit)) { if (hasStudentCredit()) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "studentcredit set credit_amount = credit_amount - " + round2Places(credit) + " where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "studentcredit set credit_lastused = NOW() where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to update student credit account."); blOk = false; } } else { gui.setCriticalMessage("Unable to update student credit account."); blOk = false; } } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit (credit_amount,credit_active,credit_studentid,credit_lastused) values('" + round2Places((-1) * credit) + "','1','" + stuId + "', NOW())") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to create new student credit account."); blOk = false; } } } else { gui.setCriticalMessage("Student doesn't have enought credit."); blOk = false; } } if (blOk) { if (blDepositCredit && change > 0d) { try { if (doStudentCreditUpdate(change, stuId)) { change = 0d; } else blOk = false; } catch (Exception cExp) { blOk = false; } } } if (blOk) { boolean blHBOK = true; if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { stmt = conn.createStatement(); if (stmt.execute("select count(*) from " + strPOSPrefix + "hotbar where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'")) { rs = stmt.getResultSet(); rs.next(); int num = rs.getInt(1); stmt.close(); if (num == 1) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "hotbar set hb_count = hb_count + 1 where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'") != 1) blHBOK = false; } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "hotbar ( hb_itemid, hb_building, hb_register, hb_cashier, hb_count ) values( '" + itms[i].getDBID() + "', '" + building + "', '" + host + "', '" + cashier + "', '1' )") != 1) blHBOK = false; } stmt.close(); } } } else blHBOK = false; if (blHBOK) { conn.commit(); gui.setStatus("Order Complete."); gui.disableUI(); summary = new PSOrderSummary(gui); if (cashDrawer != null) cashDrawer.openDrawer(); else summary.setPOSEventListener(this); summary.display(money.format(order.getOrderTotal()), money.format(mBuf.getCash()), money.format(credit), money.format(change), money.format(getStudentCredit())); } else { conn.rollback(); gui.setStatus("Failure during Hotbar update. Transaction has been rolled back.", true); } } else { conn.rollback(); } } else { gui.setCriticalMessage("Unable to fetch items."); conn.rollback(); } } else { gui.setCriticalMessage("Unable to retrieve autoid"); conn.rollback(); } } else { gui.setCriticalMessage("Error During Writting of Transaction Master Record."); conn.rollback(); } } catch (SQLException sqlEx) { System.err.println("SQLException: " + sqlEx.getMessage()); System.err.println("SQLState: " + sqlEx.getSQLState()); System.err.println("VendorError: " + sqlEx.getErrorCode()); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { stmt = null; } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); } } } } } } else { gui.setStatus("Credit total + Cash total is less then the order total! ", true); } } } else { if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { gui.setStatus("Sorry, maximum negative balance is " + money.format(neg) + "!", true); } else gui.setStatus("Student does not have enough credit to process this order.", true); } } else { gui.setStatus("Buffer total is less then the order total.", true); } } }
Code Sample 2:
protected Resolver queryResolver(String resolver, String command, String arg1, String arg2) { InputStream iStream = null; String RFC2483 = resolver + "?command=" + command + "&format=tr9401&uri=" + arg1 + "&uri2=" + arg2; String line = null; try { URL url = new URL(RFC2483); URLConnection urlCon = url.openConnection(); urlCon.setUseCaches(false); Resolver r = (Resolver) newCatalog(); String cType = urlCon.getContentType(); if (cType.indexOf(";") > 0) { cType = cType.substring(0, cType.indexOf(";")); } r.parseCatalog(cType, urlCon.getInputStream()); return r; } catch (CatalogException cex) { if (cex.getExceptionType() == CatalogException.UNPARSEABLE) { catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483); } else if (cex.getExceptionType() == CatalogException.UNKNOWN_FORMAT) { catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483); } return null; } catch (MalformedURLException mue) { catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483); return null; } catch (IOException ie) { catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483); return null; } }
|
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:
private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; }
|
11
|
Code Sample 1:
public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; }
Code Sample 2:
public void migrate(InputMetadata meta, InputStream input, OutputCreator outputCreator) throws IOException, ResourceMigrationException { RestartInputStream restartInput = new RestartInputStream(input); Match match = resourceIdentifier.identifyResource(meta, restartInput); restartInput.restart(); if (match != null) { reporter.reportNotification(notificationFactory.createLocalizedNotification(NotificationType.INFO, "migration-resource-migrating", new Object[] { meta.getURI(), match.getTypeName(), match.getVersionName() })); processMigrationSteps(match, restartInput, outputCreator); } else { reporter.reportNotification(notificationFactory.createLocalizedNotification(NotificationType.INFO, "migration-resource-copying", new Object[] { meta.getURI() })); IOUtils.copyAndClose(restartInput, outputCreator.createOutputStream()); } }
|
00
|
Code Sample 1:
static ConversionMap create(String file) { ConversionMap out = new ConversionMap(); URL url = ConversionMap.class.getResource(file); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { if (line.length() > 0) { String[] arr = line.split("\t"); try { double value = Double.parseDouble(arr[1]); out.put(translate(lowercase(arr[0].getBytes())), value); out.defaultValue += value; out.length = arr[0].length(); } catch (NumberFormatException e) { throw new RuntimeException("Something is wrong with in conversion file: " + e); } } line = in.readLine(); } in.close(); out.defaultValue /= Math.pow(4, out.length); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Their was an error while reading the conversion map: " + e); } return out; }
Code Sample 2:
public static int[] sortAscending(double input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] > input[j + 1]) { double mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
|
11
|
Code Sample 1:
private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
Code Sample 2:
public static int save(File inputFile, File outputFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFile); outputFile.getParentFile().mkdirs(); out = new FileOutputStream(outputFile); } catch (Exception e) { e.getMessage(); } try { return IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { if (out != null) { out.close(); } } catch (IOException ioe) { ioe.getMessage(); } try { if (in != null) { in.close(); } } catch (IOException ioe) { ioe.getMessage(); } } }
|
11
|
Code Sample 1:
@Test public void testLargePut() throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream(_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream(_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte[] buffer = new byte[CommonParameters.BLOCK_SIZE]; while ((readLen = is.read(buffer, 0, size)) != -1) { ostream.write(buffer, 0, readLen); writeLen += readLen; } ostream.close(); CCNStats stats = _putHandle.getNetworkManager().getStats(); Assert.assertEquals(0, stats.getCounter("DeliverInterestFailed")); }
Code Sample 2:
public byte process(ProcessorContext<PublishRequest> context) throws InterruptedException, ProcessorException { logger.info("MapTileChacheTask:process"); PublishRequest req = context.getItem().getEntity(); if (StringUtils.isEmpty(req.getBackMap())) return TaskState.STATE_TILE_CACHED; final PublicMapPost post; final GenericDAO<PublicMapPost> postDao = DAOFactory.createDAO(PublicMapPost.class); try { ReadOnlyTransaction.beginTransaction(); } catch (DatabaseException e) { logger.error("error", e); throw new ProcessorException(e); } int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); post = postDao.findUniqueByCriteria(Expression.eq("guid", req.getPostGuid())); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(post.getSWLat(), post.getSWLon()), new LatLngPoint(post.getNELat(), post.getNELon())); 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); } } try { for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) throw new IllegalAccessException("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); } else throw new IllegalStateException("opened stream is null"); } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 100 == 0) { logger.info(numCachedTiles + " tiles cached"); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } } catch (ProcessorException e) { logger.error("map tile caching has failed: ", e); throw e; } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw new ProcessorException(e); } finally { ReadOnlyTransaction.closeTransaction(); logger.info(numCachedTiles + " tiles cached"); } return TaskState.STATE_TILE_CACHED; }
|
00
|
Code Sample 1:
public Source get_source(String pageURL, Boolean checkInBase) { URL url; URLConnection conn; Reader inReader; Source source = null; String LastModified = ""; Boolean updateData = false; try { url = new URL(pageURL); conn = url.openConnection(); conn.setRequestProperty("Accept-Charset", "windows-1251"); if (checkInBase) { for (int i = 0; ; i++) { String name = conn.getHeaderFieldKey(i); String value = conn.getHeaderField(i); if (name == null && value == null) { break; } if ("Last-Modified".equals(name)) { LastModified = value; } } Ini.rs = Ini.stmt.executeQuery("select count(1) as qwe from " + " PUBLIC.PAGES " + "where url = '" + pageURL + "';"); Ini.rs.next(); if (Ini.rs.getInt("qwe") == 0) { Ini.stmt.executeUpdate("insert into PUBLIC.PAGES(url, lastUpdateDate) " + " values('" + pageURL + "', " + "'" + LastModified + "'" + ");"); } else { Ini.rs = Ini.stmt.executeQuery("select lastUpdateDate from " + " PUBLIC.PAGES " + "where url = '" + pageURL + "';"); Ini.rs.next(); if (!Ini.rs.getString("lastUpdateDate").equals(LastModified)) { updateData = true; } else { return null; } } } inReader = new InputStreamReader(conn.getInputStream(), "windows-1251"); source = new Source(inReader); source.setLogger(null); source.fullSequentialParse(); if (updateData) { Ini.stmt.executeUpdate("delete from PUBLIC.LINKDATA " + "where id in (" + "select id from PUBLIC.PAGES " + "where url = '" + pageURL + "'" + ")"); Ini.stmt.executeUpdate("delete from PUBLIC.PAGES " + "where url = '" + pageURL + "';"); Ini.stmt.executeUpdate("insert into PUBLIC.PAGES " + " values('" + pageURL + "', " + "'" + LastModified + "'" + ");"); } } catch (Exception ex) { Ini.logger.fatal("Error: ", ex); } return source; }
Code Sample 2:
public static byte[] loadURLToBuffer(URL url, int maxLength) throws IOException { byte[] buf = new byte[maxLength]; byte[] data = null; int iCount = 0; BufferedInputStream in = new BufferedInputStream(url.openStream(), 20480); iCount = in.read(buf, 0, buf.length); if (iCount != -1) { data = new byte[iCount]; System.arraycopy(buf, 0, data, 0, iCount); } in.close(); return data; }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { log.debug("Copy from {} to {}", source.getAbsoluteFile(), dest.getAbsoluteFile()); FileInputStream fi = new FileInputStream(source); FileChannel fic = fi.getChannel(); MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length()); fic.close(); fi.close(); fi = null; if (!dest.exists()) { String destPath = dest.getPath(); log.debug("Destination path: {}", destPath); String destDir = destPath.substring(0, destPath.lastIndexOf(File.separatorChar)); log.debug("Destination dir: {}", destDir); File dir = new File(destDir); if (!dir.exists()) { if (dir.mkdirs()) { log.debug("Directory created"); } else { log.warn("Directory not created"); } } dir = null; } FileOutputStream fo = new FileOutputStream(dest); FileChannel foc = fo.getChannel(); foc.write(mbuf); foc.close(); fo.close(); fo = null; mbuf.clear(); mbuf = null; }
Code Sample 2:
void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public static InputStream getResourceRelativeAsStream(final String name, final Class context) { final URL url = getResourceRelative(name, context); if (url == null) { return null; } try { return url.openStream(); } catch (IOException e) { return null; } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); }
Code Sample 2:
public void copyHashAllFilesToDirectory(String baseDirStr, Hashtable newNamesTable, String destDirStr) throws Exception { if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(baseDirStr); if (null == newNamesTable) { newNamesTable = new Hashtable(); } BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if ((baseDir.exists()) && (baseDir.isDirectory())) { if (!newNamesTable.isEmpty()) { Enumeration enumFiles = newNamesTable.keys(); while (enumFiles.hasMoreElements()) { String newName = (String) enumFiles.nextElement(); String oldPathName = (String) newNamesTable.get(newName); if ((newName != null) && (!"".equals(newName)) && (oldPathName != null) && (!"".equals(oldPathName))) { String newPathFileName = destDirStr + sep + newName; String oldPathFileName = baseDirStr + sep + oldPathName; if (oldPathName.startsWith(sep)) { oldPathFileName = baseDirStr + oldPathName; } File f = new File(oldPathFileName); if ((f.exists()) && (f.isFile())) { in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { } } } } else { } } else { throw new Exception("Base (baseDirStr) dir not exist !"); } }
|
11
|
Code Sample 1:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
Code Sample 2:
public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while downloading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { } }
|
00
|
Code Sample 1:
public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); 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().substring(8, 24); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } }
Code Sample 2:
private static void testIfNoneMatch() throws Exception { String eTag = c.getHeaderField("ETag"); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); do { read = in.read(buffer); if (read > 0) md5.update(buffer, 0, read); } while (read < 0); byte[] digest = md5.digest(); String hexDigest = getHexString(digest); if (hexDigest.equals(eTag)) System.out.print("eTag content : md5 hex string"); String quotedHexDigest = "\"" + hexDigest + "\""; if (quotedHexDigest.equals(eTag)) System.out.print("eTag content : quoted md5 hex string"); HttpURLConnection c2 = (HttpURLConnection) url.openConnection(); c2.addRequestProperty("If-None-Match", eTag); c2.connect(); int code = c2.getResponseCode(); System.out.print("If-None-Match response: "); boolean supported = (code == 304); System.out.println(b2s(supported) + " - " + code + " (" + c2.getResponseMessage() + ")"); }
|
00
|
Code Sample 1:
public static String md5(String text) { String hashed = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes(), 0, text.length()); hashed = new BigInteger(1, digest.digest()).toString(16); } catch (Exception e) { Log.e(ctGlobal.tag, "ctCommon.md5: " + e.toString()); } return hashed; }
Code Sample 2:
public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } }
Code Sample 2:
private int renumberOrderBy(long tableID) throws SnapInException { int count = 0; Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = getDataSource().getConnection(); con.setAutoCommit(false); stmt = con.createStatement(); StringBuffer query = new StringBuffer(); query.append("SELECT ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" FROM ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_TABLEID).append(" = ").append(tableID).append(" ORDER BY ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY); Vector rowIDVector = new Vector(); rs = stmt.executeQuery(query.toString()); while (rs.next()) { count++; rowIDVector.add(rs.getLong(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID) + ""); } StringBuffer updateString = new StringBuffer(); updateString.append("UPDATE ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" SET ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY).append(" = ? WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" = ?"); PreparedStatement pstmt = con.prepareStatement(updateString.toString()); int orderByValue = ORDERBY_BY_DELTA_VALUE; Enumeration en = rowIDVector.elements(); while (en.hasMoreElements()) { pstmt.setInt(1, orderByValue); pstmt.setString(2, en.nextElement().toString()); orderByValue += ORDERBY_BY_DELTA_VALUE; pstmt.executeUpdate(); } con.setAutoCommit(true); if (pstmt != null) { pstmt.close(); } } catch (java.sql.SQLException e) { if (con == null) { logger.error("java.sql.SQLException", e); } else { try { logger.error("Transaction is being rolled back."); con.rollback(); con.setAutoCommit(true); } catch (java.sql.SQLException e2) { logger.error("java.sql.SQLException", e2); } } } catch (Exception e) { logger.error("Error occured during RenumberOrderBy", e); } finally { getDataSourceHelper().releaseResources(con, stmt, rs); } return count; }
|
00
|
Code Sample 1:
public static Image getImage(String urlChartString) throws IOException, JGoogleChartException { Image image = null; HttpURLConnection urlConn = null; URL url = new URL(urlChartString); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod("GET"); urlConn.setAllowUserInteraction(false); urlConn.setRequestProperty("HTTP-Version", "HTTP/1.1"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); int responseCode = urlConn.getResponseCode(); if (responseCode != 200) { throw new JGoogleChartException(JGoogleChartException.MSG_HTTP_ERROR_CODE + responseCode + " (" + urlConn.getResponseMessage()); } InputStream istream = urlConn.getInputStream(); image = ImageIO.read(istream); return image; }
Code Sample 2:
public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException { final Properties properties = new Properties(); properties.put("archetypeGroupId", "org.nexopenframework.plugins"); properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule"); final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion(); properties.put("archetypeVersion", version); properties.put("artifactId", moduleExtension.getArtifact()); properties.put("groupId", moduleExtension.getGroup()); properties.put("version", moduleExtension.getVersion()); final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact()); final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); final File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (final IOException e) { } } String goalName = "archetype:create"; boolean offline = false; try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin"); final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]); offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline"); } catch (final ClassNotFoundException e) { Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e); } catch (final NoSuchMethodException e) { Logger.logException("No method getDefault", e); } catch (final Throwable e) { Logger.logException(e); } if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } if (!offline) { final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore(); final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES); final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR); final StringBuffer sbRepos = new StringBuffer(); for (int k = 0; k < repos.length; k++) { sbRepos.append(repos[k]); if (k != repos.length - 1) { sbRepos.append(","); } } properties.put("remoteRepositories", sbRepos.toString()); } workingCopy.setAttribute(ATTR_GOALS, goalName); workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location)); FileUtils.deleteDirectory(new File(location + "/src")); FileUtils.forceDelete(new File(location, "pom.xml")); project.refreshLocal(IResource.DEPTH_INFINITE, null); } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } }
|
11
|
Code Sample 1:
private void createSaveServiceProps() throws MojoExecutionException { saveServiceProps = new File(workDir, "saveservice.properties"); try { FileWriter out = new FileWriter(saveServiceProps); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("saveservice.properties"), out); out.flush(); out.close(); System.setProperty("saveservice_properties", File.separator + "target" + File.separator + "jmeter" + File.separator + "saveservice.properties"); } catch (IOException e) { throw new MojoExecutionException("Could not create temporary saveservice.properties", e); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public static Set<Municipality> getMunicipios(String pURL) { Set<Municipality> result = new HashSet<Municipality>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniMun = "<muni>"; String finMun = "</muni>"; String iniNomMun = "<nm>"; String finNomMun = "</nm>"; String iniCarto = "<carto>"; String iniCodDelMEH = "<cd>"; String finCodDelMEH = "</cd>"; String iniCodMunMEH = "<cmc>"; String finCodMunMEH = "</cmc>"; String iniCodProvINE = "<cp>"; String finCodProvINE = "</cp>"; String iniCodMunINE = "<cm>"; String finCodMunINE = "</cm>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Municipality municipio; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniMun)) { municipio = new Municipality(); municipio.setCodemunicipalityine(0); municipio.setCodemunicipalitydgc(0); while ((str = br.readLine()) != null && !str.contains(finMun)) { if (str.contains(iniNomMun)) { ini = str.indexOf(iniNomMun) + iniNomMun.length(); fin = str.indexOf(finNomMun); municipio.setMuniName(str.substring(ini, fin).trim()); } if (str.contains(iniCarto)) { if (str.contains("URBANA")) municipio.setIsurban(true); if (str.contains("RUSTICA")) municipio.setIsrustic(true); } if (str.contains(iniCodDelMEH)) { ini = str.indexOf(iniCodDelMEH) + iniCodDelMEH.length(); fin = str.indexOf(finCodDelMEH); municipio.setCodemunicipalitydgc(municipio.getCodemunicipalitydgc() + Integer.parseInt(str.substring(ini, fin)) * 1000); } if (str.contains(iniCodMunMEH)) { ini = str.indexOf(iniCodMunMEH) + iniCodMunMEH.length(); fin = str.indexOf(finCodMunMEH); municipio.setCodemunicipalitydgc(municipio.getCodemunicipalitydgc() + Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniCodProvINE)) { ini = str.indexOf(iniCodProvINE) + iniCodProvINE.length(); fin = str.indexOf(finCodProvINE); municipio.setCodemunicipalityine(municipio.getCodemunicipalityine() + Integer.parseInt(str.substring(ini, fin)) * 1000); } if (str.contains(iniCodMunINE)) { ini = str.indexOf(iniCodMunINE) + iniCodMunINE.length(); fin = str.indexOf(finCodMunINE); municipio.setCodemunicipalityine(municipio.getCodemunicipalityine() + Integer.parseInt(str.substring(ini, fin))); } municipio.setDescription(); } result.add(municipio); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
Code Sample 2:
public void copyFile(String source, String destination, String description, boolean recursive) throws Exception { File sourceFile = new File(source); File destinationFile = new File(destination); if (!sourceFile.exists()) { throw new Exception("source file (" + source + ") does not exist!"); } if (!sourceFile.isFile()) { throw new Exception("source file (" + source + ") is not a file!"); } if (!sourceFile.canRead()) { throw new Exception("source file (" + source + ") is not readable!"); } if (destinationFile.exists()) { m_out.print(" - " + destination + " exists, removing... "); if (destinationFile.delete()) { m_out.println("REMOVED"); } else { m_out.println("FAILED"); throw new Exception("unable to delete existing file: " + sourceFile); } } m_out.print(" - copying " + source + " to " + destination + "... "); if (!destinationFile.getParentFile().exists()) { if (!destinationFile.getParentFile().mkdirs()) { throw new Exception("unable to create directory: " + destinationFile.getParent()); } } if (!destinationFile.createNewFile()) { throw new Exception("unable to create file: " + destinationFile); } FileChannel from = null; FileChannel to = null; try { from = new FileInputStream(sourceFile).getChannel(); to = new FileOutputStream(destinationFile).getChannel(); to.transferFrom(from, 0, from.size()); } catch (FileNotFoundException e) { throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e); } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } m_out.println("DONE"); }
|
00
|
Code Sample 1:
private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(Global.getProxy()); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=" + XmlRpcMessages.getString("XmlRpcClient.Encoding")); if (requestProperties != null) { for (Iterator propertyNames = requestProperties.keySet().iterator(); propertyNames.hasNext(); ) { String propertyName = (String) propertyNames.next(); connection.setRequestProperty(propertyName, (String) requestProperties.get(propertyName)); } } }
Code Sample 2:
private static TreeViewTreeNode newInstance(String className, String urlString) { try { URL url = new URL(urlString); InputStream is = url.openStream(); XMLDecoder xd = new XMLDecoder(is); Object userObject = xd.readObject(); xd.close(); return newInstance(className, userObject); } catch (Exception e) { Debug.println(e); throw (RuntimeException) new IllegalStateException().initCause(e); } }
|
00
|
Code Sample 1:
public static void main(String[] args) { paraProc(args); CanonicalGFF cgff = new CanonicalGFF(gffFilename); CanonicalGFF geneModel = new CanonicalGFF(modelFilename); CanonicalGFF transcriptGff = new CanonicalGFF(transcriptFilename); TreeMap ksTable1 = getKsTable(ksTable1Filename); TreeMap ksTable2 = getKsTable(ksTable2Filename); Map intronReadCntMap = new TreeMap(); Map intronSplicingPosMap = new TreeMap(); try { BufferedReader fr = new BufferedReader(new FileReader(inFilename)); while (fr.ready()) { String line = fr.readLine(); if (line.startsWith("#")) continue; String tokens[] = line.split("\t"); String chr = tokens[0]; int start = Integer.parseInt(tokens[1]); int stop = Integer.parseInt(tokens[2]); GenomeInterval intron = new GenomeInterval(chr, start, stop); int readCnt = Integer.parseInt(tokens[3]); intronReadCntMap.put(intron, readCnt); String splicingMapStr = tokens[4]; Map splicingMap = getSplicingMap(splicingMapStr); intronSplicingPosMap.put(intron, splicingMap); } fr.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } double[] hdCDF = getHdCdf(readLength, minimumOverlap); try { FileWriter fw = new FileWriter(outFilename); for (Iterator intronIterator = intronReadCntMap.keySet().iterator(); intronIterator.hasNext(); ) { GenomeInterval intron = (GenomeInterval) intronIterator.next(); int readCnt = ((Integer) intronReadCntMap.get(intron)).intValue(); TreeMap splicingMap = (TreeMap) intronSplicingPosMap.get(intron); Object ksInfoArray[] = distributionAccepter((TreeMap) splicingMap.clone(), readCnt, hdCDF, ksTable1, ksTable2); boolean ksAccepted = (Boolean) ksInfoArray[0]; double testK = (Double) ksInfoArray[1]; double standardK1 = (Double) ksInfoArray[2]; double standardK2 = (Double) ksInfoArray[3]; int positionCnt = splicingMap.size(); Object modelInfoArray[] = getModelAgreedSiteCnt(intron, cgff, geneModel, transcriptGff); int modelAgreedSiteCnt = (Integer) modelInfoArray[0]; int maxAgreedTransSiteCnt = (Integer) modelInfoArray[1]; boolean containedBySomeGene = (Boolean) modelInfoArray[2]; int numIntersectingGenes = (Integer) modelInfoArray[3]; int distance = intron.getStop() - intron.getStart(); fw.write(intron.getChr() + ":" + intron.getStart() + ".." + intron.getStop() + "\t" + distance + "\t" + readCnt + "\t" + splicingMap + "\t" + probabilityEvaluation(readLength, distance, readCnt, splicingMap, positionCnt) + "\t" + ksAccepted + "\t" + testK + "\t" + standardK1 + "\t" + standardK2 + "\t" + positionCnt + "\t" + modelAgreedSiteCnt + "\t" + maxAgreedTransSiteCnt + "\t" + containedBySomeGene + "\t" + numIntersectingGenes + "\n"); } fw.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } }
Code Sample 2:
public String buscaCDE() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDE")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDE: " + miLinea); return miLinea; }
|
11
|
Code Sample 1:
private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
Code Sample 2:
public static void translateTableMetaData(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table", nsDefinition); String filename = baseDir + "table.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + ".xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + ".json", baseDir + tableName + ".xsl"); }
|
00
|
Code Sample 1:
private void processAlignmentsFromAlignmentSource(String name, Alignment reference, String alignmentSource) throws AlignmentParserException, IllegalArgumentException, KADMOSCMDException, IOException { if (alignmentSource == null) throw new IllegalArgumentException("alignmentSource is null"); URL url; String st; BufferedReader reader; Alignment alignment; try { try { alignment = parseAlignment(alignmentSource); addAlignmentWrapper(new AlignmentWrapper(name, reference, alignmentSource, alignment)); } catch (AlignmentParserException e1) { url = new URL(alignmentSource); reader = new BufferedReader(new InputStreamReader(url.openStream())); st = ""; while (((st = reader.readLine()) != null)) { alignment = parseAlignment(st); addAlignmentWrapper(new AlignmentWrapper(name, reference, alignmentSource, alignment)); } } } catch (Exception e1) { File itemFile = new File(alignmentSource); if (itemFile.exists()) { if (itemFile.isDirectory() && !itemFile.isHidden()) { File[] files = itemFile.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile() && !files[i].isHidden()) { processAlignmentsFromAlignmentSource(name, reference, files[i].getPath()); } else if (files[i].isDirectory() && !files[i].isHidden() && deepScan) { processAlignmentsFromAlignmentSource(name, reference, files[i].getPath()); } } } else if (itemFile.isFile() && !itemFile.isHidden()) { try { alignment = parseAlignment(alignmentSource); addAlignmentWrapper(new AlignmentWrapper(name, reference, alignmentSource, alignment)); } catch (Exception e2) { reader = new BufferedReader(new FileReader(alignmentSource)); st = ""; while (((st = reader.readLine()) != null)) { alignment = parseAlignment(st); addAlignmentWrapper(new AlignmentWrapper(name, reference, st, alignment)); } } } else { throw new FileNotFoundException("File " + alignmentSource + " is neither directory nor file, or it is hidden."); } } else { throw new FileNotFoundException("File " + alignmentSource + " does not exists."); } } }
Code Sample 2:
public static void copy(File in, File out) throws IOException { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
|
11
|
Code Sample 1:
private void copyFile(String sourceFilename, String destDirname) throws BuildException { log("Copying file " + sourceFilename + " to " + destDirname); File destFile = getDestFile(sourceFilename, destDirname); InputStream inStream = null; OutputStream outStream = null; try { inStream = new BufferedInputStream(new FileInputStream(sourceFilename)); outStream = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] buffer = new byte[1024]; int n = 0; while ((n = inStream.read(buffer)) != -1) outStream.write(buffer, 0, n); } catch (Exception e) { throw new BuildException("Failed to copy file \"" + sourceFilename + "\" to directory \"" + destDirname + "\""); } finally { try { if (inStream != null) inStream.close(); } catch (IOException e) { } try { if (outStream != null) outStream.close(); } catch (IOException e) { } } }
Code Sample 2:
@SuppressWarnings("unchecked") public static void unzip(String input, String output) { try { if (!output.endsWith("/")) output = output + "/"; ZipFile zip = new ZipFile(input); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { FileUtils.forceMkdir(new File(output + entry.getName())); } else { FileOutputStream out = new FileOutputStream(output + entry.getName()); IOUtils.copy(zip.getInputStream(entry), out); IOUtils.closeQuietly(out); } } } catch (Exception e) { log.error("�����ҵ��ļ�:" + output, e); throw new RuntimeException("�����ҵ��ļ�:" + output, e); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException(); String inFileName = args[0]; String outFileName = args[1]; File fInput = new File(inFileName); Scanner in = null; try { in = new Scanner(fInput); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(outFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } while (in.hasNextLine()) { out.println(in.nextLine()); } in.close(); out.close(); }
Code Sample 2:
public static boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; }
|
00
|
Code Sample 1:
@Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("sort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("sort :: INPATH not given."); return 3; } final String wrkDir = args.get(0), out = (String) parser.getOptionValue(outputFileOpt); final List<String> strInputs = args.subList(1, args.size()); final List<Path> inputs = new ArrayList<Path>(strInputs.size()); for (final String in : strInputs) inputs.add(new Path(in)); final boolean verbose = parser.getBoolean(verboseOpt); final String intermediateOutName = out == null ? inputs.get(0).getName() : out; final Configuration conf = getConf(); conf.setStrings(INPUT_PATHS_PROP, strInputs.toArray(new String[0])); conf.set(SortOutputFormat.OUTPUT_NAME_PROP, intermediateOutName); final Path wrkDirPath = new Path(wrkDir); final Timer t = new Timer(); try { for (final Path in : inputs) Utils.configureSampling(in, conf); @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = new Job(conf); job.setJarByClass(Sort.class); job.setMapperClass(Mapper.class); job.setReducerClass(SortReducer.class); job.setMapOutputKeyClass(LongWritable.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(SAMRecordWritable.class); job.setInputFormatClass(BAMInputFormat.class); job.setOutputFormatClass(SortOutputFormat.class); for (final Path in : inputs) FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, wrkDirPath); job.setPartitionerClass(TotalOrderPartitioner.class); System.out.println("sort :: Sampling..."); t.start(); InputSampler.<LongWritable, SAMRecordWritable>writePartitionFile(job, new InputSampler.IntervalSampler<LongWritable, SAMRecordWritable>(0.01, 100)); System.out.printf("sort :: Sampling complete in %d.%03d s.\n", t.stopS(), t.fms()); job.submit(); System.out.println("sort :: Waiting for job completion..."); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("sort :: Job failed."); return 4; } System.out.printf("sort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("sort :: Merging output..."); t.start(); final Path outPath = new Path(out); final FileSystem srcFS = wrkDirPath.getFileSystem(conf); FileSystem dstFS = outPath.getFileSystem(conf); if (dstFS instanceof LocalFileSystem && dstFS instanceof ChecksumFileSystem) dstFS = ((LocalFileSystem) dstFS).getRaw(); final BAMFileWriter w = new BAMFileWriter(dstFS.create(outPath), new File("")); w.setSortOrder(SAMFileHeader.SortOrder.coordinate, true); w.setHeader(getHeaderMerger(conf).getMergedHeader()); w.close(); final OutputStream outs = dstFS.append(outPath); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, conf.get(SortOutputFormat.OUTPUT_NAME_PROP) + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("sort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("sort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Output merging failed: %s\n", e); return 5; } return 0; }
Code Sample 2:
private InputStream getInputStream(URI uri) throws IOException { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Loading ACL : " + uri.toString()); } URL url = uri.toURL(); URLConnection connection = url.openConnection(); connection.setDoInput(true); return connection.getInputStream(); }
|
11
|
Code Sample 1:
public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } }
Code Sample 2:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
|
11
|
Code Sample 1:
public int addRecipe(Recipe recipe) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; ResultSet rs = null; int retVal = -1; try { conn = getConnection(); pst1 = conn.prepareStatement("INSERT INTO recipes (name, instructions, category_id) VALUES (?, ?, ?)"); pst1.setString(1, recipe.getName()); pst1.setString(2, recipe.getInstructions()); pst1.setInt(3, recipe.getCategoryId()); if (pst1.executeUpdate() > 0) { pst2 = conn.prepareStatement("SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? AND category_id = ?"); pst2.setString(1, recipe.getName()); pst2.setString(2, recipe.getInstructions()); pst2.setInt(3, recipe.getCategoryId()); rs = pst2.executeQuery(); conn.commit(); if (rs.next()) { int id = rs.getInt(1); addIngredients(recipe, id); MainFrame.recipePanel.update(); retVal = id; } else { retVal = -1; } } else { retVal = -1; } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add recipe, the exception was " + e.getMessage()); } finally { try { if (rs != null) rs.close(); rs = null; if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (SQLException sqle) { MainFrame.appendStatusText("Can't close database connection."); } } return retVal; }
Code Sample 2:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ACCOUNT")); pst.setInt(1, acc.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 String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
Code Sample 2:
public static void main(String[] args) { Stopwatch.start(""); HtmlParser parser = new HtmlParser(); try { Stopwatch.printTimeReset("", "> ParserDelegator"); ParserDelegator del = new ParserDelegator(); Stopwatch.printTimeReset("", "> url"); URL url = new URL(args[0]); Stopwatch.printTimeReset("", "> openStrem"); InputStream is = url.openStream(); Stopwatch.printTimeReset("", "< parse"); del.parse(new InputStreamReader(is), parser, true); Stopwatch.printTimeReset("", "< parse"); } catch (Throwable t) { t.printStackTrace(); } Stopwatch.printTimeReset("", "> traversal"); TreeTraversal.traverse(parser.startTag, "eachChild", new Function() { String lastPath = null; public void apply(Object obj) { if (obj instanceof String) { System.out.print(lastPath + ":"); System.out.println(obj); return; } Tag t = (Tag) obj; lastPath = Utils.tagPath(t); System.out.println(lastPath); } }); Stopwatch.printTimeReset("", "< traversal"); }
|
00
|
Code Sample 1:
public XMLResourceBundle() throws MissingResourceException { String systemId = getShortName() + ".xml"; URL url; if ((url = getClass().getResource(systemId)) != null) { InputStream is = null; try { is = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); xmlReader.setContentHandler(new MessageContentHandler()); xmlReader.parse(new InputSource(is)); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } catch (SAXException se) { System.err.println(se.getMessage()); se.printStackTrace(); } catch (ParserConfigurationException pce) { System.err.println(pce.getMessage()); pce.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } } } else { throw new MissingResourceException("Resource file '" + systemId + "' could not be found.", systemId, null); } }
Code Sample 2:
protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
|
00
|
Code Sample 1:
public void deleteType(String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delType = "delete from type where TYPE_ID='" + id + "'"; con.setAutoCommit(false); prepStmt = con.prepareStatement("delete from correlation where TYPE_ID='" + id + "' OR CORRELATEDTYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from composition where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from distribution where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from typename where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from typereference where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement("delete from plot where TYPE_ID='" + id + "'"); prepStmt.executeUpdate(); prepStmt = con.prepareStatement(delType); prepStmt.executeUpdate(); con.commit(); prepStmt.close(); con.close(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } }
Code Sample 2:
public static synchronized String getPageContent(String pageUrl) { URL url = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String line = null; StringBuilder page = null; if (pageUrl == null || pageUrl.trim().length() == 0) { return null; } else { try { url = new URL(pageUrl); inputStreamReader = new InputStreamReader(url.openStream()); bufferedReader = new BufferedReader(inputStreamReader); page = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } } } if (page == null) { return null; } else { return page.toString(); } }
|
00
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); }
|
11
|
Code Sample 1:
public String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
static boolean generateKey() throws NoSuchAlgorithmException { java.util.Random rand = new Random(reg_name.hashCode() + System.currentTimeMillis()); DecimalFormat vf = new DecimalFormat("000"); ccKey = keyProduct + FIELD_SEPERATOR + keyType + FIELD_SEPERATOR + keyQuantity + FIELD_SEPERATOR + vf.format(lowMajorVersion) + FIELD_SEPERATOR + vf.format(lowMinorVersion) + FIELD_SEPERATOR + vf.format(highMajorVersion) + FIELD_SEPERATOR + vf.format(highMinorVersion) + FIELD_SEPERATOR + reg_name + FIELD_SEPERATOR + Integer.toHexString(rand.nextInt()).toUpperCase(); byte[] md5; MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(ccKey.getBytes()); md.update(FIELD_SEPERATOR.getBytes()); md.update(zuonicsPassword.getBytes()); md5 = md.digest(); userKey = ccKey + FIELD_SEPERATOR; for (int i = 0; i < md5.length; i++) userKey += Integer.toHexString(md5[i]).toUpperCase(); return true; }
|
11
|
Code Sample 1:
public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } }
|
00
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=15"; st.executeUpdate(sql); sql = "select money from user where id=13"; rs = st.executeQuery(sql); float money = 0.0f; while (rs.next()) { money = rs.getFloat("money"); } if (money > 1000) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=13"; st.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } }
|
00
|
Code Sample 1:
public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
Code Sample 2:
public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { final ServletOutputStream outputStream = res.getOutputStream(); if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; if (ByteArrayInputStream.class.isAssignableFrom(r.getClass())) res.addHeader("Content-Length", Integer.toString(in.available())); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } outputStream.flush(); } }
|
00
|
Code Sample 1:
public Set<Plugin<?>> loadPluginImplementationMetaData() throws PluginRegistryException { try { final Enumeration<URL> urls = JavaSystemHelper.getResources(pluginImplementationMetaInfPath); pluginImplsSet.clear(); if (urls != null) { while (urls.hasMoreElements()) { final URL url = urls.nextElement(); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.found", "classes", url.getPath())); InputStream resourceInput = null; Reader reader = null; BufferedReader buffReader = null; String line; try { resourceInput = url.openStream(); reader = new InputStreamReader(resourceInput); buffReader = new BufferedReader(reader); line = buffReader.readLine(); while (line != null) { try { pluginImplsSet.add(inspectPluginImpl(Class.forName(line.trim()))); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.processing", "class", line)); line = buffReader.readLine(); } catch (final ClassNotFoundException cnfe) { throw new PluginRegistryException("plugin.error.load.classnotfound", cnfe, pluginImplementationMetaInfPath, line); } catch (final LinkageError ncfe) { if (LOGGER.isDebugEnabled()) { echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.linkageError", "class", line, ncfe.getMessage())); } line = buffReader.readLine(); } } } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, url.getFile(), ioe.getMessage()); } finally { if (buffReader != null) { buffReader.close(); } if (reader != null) { reader.close(); } if (resourceInput != null) { resourceInput.close(); } } } } return Collections.unmodifiableSet(pluginImplsSet); } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, pluginImplementationMetaInfPath, ioe.getMessage()); } }
Code Sample 2:
@Override public ISource writeTo(ISource output) throws ResourceException { try { Document doc = getParent().getDocument(); Nodes places = doc.query(getPosition().getXpath()); if (places.size() == 0) { places = doc.query("//html"); } if (places.size() > 0 && places.get(0) instanceof Element) { Element target = (Element) places.get(0); List<URL> urls = getResourceURLs(); if (getType() == EType.TEXT) { Element tag = getHeaderTag(); ByteArrayOutputStream out = new ByteArrayOutputStream(); UtilIO.writeAllTo(urls, out); String content = out.toString(); out.close(); tag.appendChild(content); if (getPosition().getPlace() == EPlace.START) { target.insertChild(tag, 0); } else { target.appendChild(tag); } } else { for (URL url : urls) { String file = url.toString(); String name = file.substring(file.lastIndexOf("/") + 1) + "_res_" + (serialNumber++); Element tag = getHeaderTag(output, name); File resFile = getFile(output, name); if (!resFile.getParentFile().exists()) { if (!resFile.getParentFile().mkdirs()) { throw new ResourceException("Could not create resource directory '" + resFile.getParent() + "'."); } } UtilIO.writeToClose(url.openStream(), new FileOutputStream(resFile)); if (getPosition().getPlace() == EPlace.START) { target.insertChild(tag, 0); } else { target.appendChild(tag); } } } } else { throw new ResourceException("Head element not found."); } } catch (IOException e) { throw new ResourceException(e); } catch (SourceException e) { throw new ResourceException(e); } return output; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws MalformedURLException, IOException { InputStream in = null; try { in = new URL("hdfs://localhost:8020/user/leeing/maxtemp/sample.txt").openStream(); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); System.out.println("\nend."); } }
Code Sample 2:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
00
|
Code Sample 1:
public ArrayList<Tweet> getTimeLine() { try { HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~/network/updates?scope=self"); 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: No ha sido posible recoger el timeline de Linkedin"); return null; } 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(); SAXParserFactory spf = SAXParserFactory.newInstance(); StringReader XMLout = new StringReader(sBuf.toString()); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xmlParserLinkedin gwh = new xmlParserLinkedin(); xr.setContentHandler(gwh); xr.parse(new InputSource(XMLout)); return gwh.getParsedData(); } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (IOException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (ParserConfigurationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (SAXException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } return null; }
Code Sample 2:
public void processSaveCompany(Company companyBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_COMPANY " + "SET " + " full_name = ?, " + " short_name = ?, " + " address = ?, " + " telefon_buh = ?, " + " telefon_chief = ?, " + " chief = ?, " + " buh = ?, " + " fax = ?, " + " email = ?, " + " icq = ?, " + " short_client_info = ?, " + " url = ?, " + " short_info = ? " + "WHERE ID_FIRM = ? and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, companyBean.getName()); ps.setString(num++, companyBean.getShortName()); ps.setString(num++, companyBean.getAddress()); ps.setString(num++, ""); ps.setString(num++, ""); ps.setString(num++, companyBean.getCeo()); ps.setString(num++, companyBean.getCfo()); ps.setString(num++, ""); ps.setString(num++, ""); RsetTools.setLong(ps, num++, null); ps.setString(num++, ""); ps.setString(num++, companyBean.getWebsite()); ps.setString(num++, companyBean.getInfo()); RsetTools.setLong(ps, num++, companyBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
11
|
Code Sample 1:
public static void copyFromHDFSMerge(String hdfsDir, String local) throws IOException { rmr(local); File f = new File(local); f.getAbsoluteFile().getParentFile().mkdirs(); HDFSDirInputStream inp = new HDFSDirInputStream(hdfsDir); FileOutputStream oup = new FileOutputStream(local); IOUtils.copyBytes(inp, oup, 65 * 1024 * 1024, true); }
Code Sample 2:
public void actionPerformed(ActionEvent ev) { if (fileChooser == null) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)"); fileFilter.addExtension("jar"); fileFilter.addExtension("zip"); fileChooser.setFileFilter(fileFilter); } if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) { String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); JarFile jar = null; try { jar = new JarFile(fileChooser.getSelectedFile()); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } urls[0] = fileChooser.getSelectedFile().toURL(); } catch (IOException e) { Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e); return; } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { String entryName = (String) it.next(); try { devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class)); } catch (IOException e) { Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e); return; } } for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) en.nextElement(); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), fileChooser.getSelectedFile().getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(fileChooser.getSelectedFile(), deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } lsDevicesModel.addElement(entry); Config.addDeviceEntry(entry); } lsDevices.setSelectedValue(entry, true); } catch (IOException e) { Message.error("Error adding device profile, " + Message.getCauseMessage(e), e); return; } } }
|
00
|
Code Sample 1:
protected int insertRecord(PutMetadataRequest request, PutMetadataInfo info) throws ImsServiceException, SQLException { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; ResultSet rs = null; int nRows = 0; String sXml = info.getXml(); String sUuid = info.getUuid(); String sName = info.getName(); String sThumbnailBinary = info.getThumbnailBinary(); String sTable = this.getResourceTableName(); String sDataTable = this.getResourceDataTableName(); long id = doesRecordExist(sTable, sUuid); try { ManagedConnection mc = returnConnection(); con = mc.getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); if (id < 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO ").append(sTable); sql.append(" ("); sql.append("DOCUUID,"); sql.append("TITLE,"); sql.append("OWNER"); sql.append(")"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; st.setString(n++, sUuid); st.setString(n++, sName); st.setInt(n++, this.publisher.getLocalID()); nRows = st.executeUpdate(); closeStatement(st); if (nRows > 0) { if (getIsDbCaseSensitive(this.getRequestContext())) { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE UPPER(docuuid)=?"); } else { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE docuuid=?"); } st.setString(1, sUuid.toUpperCase()); rs = st.executeQuery(); rs.next(); id = rs.getLong(1); closeStatement(st); request.setActionStatus(ImsRequest.ACTION_STATUS_OK); sql = new StringBuffer(); sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID,ID,XML)"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setLong(2, id); st.setString(3, sXml); st.executeUpdate(); } } else { this.authorize(request, sUuid); StringBuffer sql = new StringBuffer(); sql.append("UPDATE ").append(sTable); sql.append(" SET "); if (!request.getLockTitle()) { sql.append("TITLE=?, "); } sql.append("OWNER=?, "); sql.append("UPDATEDATE=?"); sql.append(" WHERE DOCUUID=?"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; if (!request.getLockTitle()) { st.setString(n++, sName); } st.setInt(n++, this.publisher.getLocalID()); st.setTimestamp(n++, new Timestamp(System.currentTimeMillis())); st.setString(n++, sUuid); nRows = st.executeUpdate(); if (nRows > 0) { request.setActionStatus(ImsRequest.ACTION_STATUS_REPLACED); } closeStatement(st); sql = new StringBuffer(); if (doesRecordExist(sDataTable, sUuid) >= 0) { sql.append("UPDATE ").append(sDataTable); sql.append(" SET DOCUUID=?, XML=?, THUMBNAIL=?"); sql.append(" WHERE ID=?"); } else { sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID, XML,THUMBNAIL,ID)"); sql.append(" VALUES(?,?,?,?)"); } logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setString(2, sXml); st.setBytes(3, null); st.setLong(4, id); st.executeUpdate(); } con.commit(); } catch (ImsServiceException ex) { if (con != null) { con.rollback(); } throw ex; } catch (SQLException ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeResultSet(rs); closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } if ((sThumbnailBinary != null) && (sThumbnailBinary.length() > 0)) { this.updateThumbnail(sThumbnailBinary, sUuid); } return nRows; }
Code Sample 2:
public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
|
11
|
Code Sample 1:
public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { setHeader(resp); try { logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes"); File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif"); if (!tempFile.exists()) { logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities"); try { OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); fos.close(); } catch (ImogSerializationException mse) { logger.error(mse.getMessage(), mse); } } InputStream fis = new FileInputStream(tempFile); fis.skip(command.getLen()); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); fis.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } }
Code Sample 2:
private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
|
11
|
Code Sample 1:
public void render(final HttpServletRequest request, final HttpServletResponse response, InputStream inputStream, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } IOUtils.copy(inputStream, response.getOutputStream()); }
Code Sample 2:
public File takeFile(File f, String prefix, String suffix) throws IOException { File nf = createNewFile(prefix, suffix); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); FileOutputStream fos = new FileOutputStream(nf); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); f.delete(); return nf; }
|
11
|
Code Sample 1:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, String myImagesBehaviour) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(directoryPath + "images.xml"); SAXBuilder builder = new SAXBuilder(false); try { Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); int i = 0; TIGDataBase.activateTransactions(); while (j.hasNext() && !stop && !cancel) { current = i; i++; Element image = (Element) j.next(); String name = image.getAttributeValue("name"); List categories = image.getChildren("category"); Iterator k = categories.iterator(); if (exists(list, name)) { String pathSrc = directoryPath.concat(name); String pathDst = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase() + File.separator; String folder = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase(); if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.REPLACE_IMAGES"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); TIGDataBase.deleteAsociatedOfImage(idImage); } pathDst = pathDst.concat(name); } if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.ADD_IMAGES"))) { Vector aux = new Vector(); aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); int fileCount = 0; if (aux.size() != 0) { while (aux.size() != 0) { fileCount++; aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.')) + "_" + fileCount); } pathDst = pathDst + name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); name = name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); } else { pathDst = pathDst.concat(name); } } String pathThumbnail = (pathDst.substring(0, pathDst.lastIndexOf("."))).concat("_th.jpg"); File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertImageDB(name.substring(0, name.lastIndexOf('.')), name); int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); while (k.hasNext()) { Element category = (Element) k.next(); int idCategory = TIGDataBase.insertConceptDB(category.getValue()); TIGDataBase.insertAsociatedDB(idCategory, idImage); } } else { errorImages = errorImages + System.getProperty("line.separator") + name; } } TIGDataBase.executeQueries(); current = lengthOfTask; } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
|
00
|
Code Sample 1:
public Stopper(String stopWordsFile) { try { BufferedReader br = null; FileReader fr = null; if (stopWordsFile.startsWith("http")) { URL url = new URL(stopWordsFile); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { fr = new FileReader(new File(stopWordsFile)); br = new BufferedReader(fr); } String line = null; while ((line = br.readLine()) != null) { line = line.trim(); stopWords.put(line, ""); } fr.close(); } catch (Exception e) { System.out.println("Stopwords not Found"); return; } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public static String getMD5HashFromString(String message) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(message.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
Code Sample 2:
public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
|
11
|
Code Sample 1:
public static void main(String args[]) throws Exception { File file = new File("D:/work/love.txt"); @SuppressWarnings("unused") ZipFile zipFile = new ZipFile("D:/work/test1.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:/work/test1.zip")); zos.setEncoding("GBK"); ZipEntry entry = null; if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); int readLen = 0; byte[] buf = new byte[2048]; if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 2048)) != -1) { zos.write(buf, 0, readLen); } in.close(); } zos.close(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { HttpGet get = new HttpGet("https://localhost/docs/index.html"); DefaultHttpClient client = new DefaultHttpClient(); ServerConfig config = new ServerConfig(new Properties()); config.setParam("https.keyStoreFile", "test.keystore"); config.setParam("https.keyPassword", "nopassword"); config.setParam("https.keyStoreType", "JKS"); config.setParam("https.protocol", "SSLv3"); SSLContextCreator ssl = new SSLContextCreator(config); SSLContext ctx = ssl.getSSLContext(); SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); Scheme sch = new Scheme("https", 443, socketFactory); client.getConnectionManager().getSchemeRegistry().register(sch); HttpResponse response = client.execute(get); System.out.println(response.getStatusLine().getStatusCode()); }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public String encryptLdapPassword(String algorithm) { String sEncrypted = _password; if ((_password != null) && (_password.length() > 0)) { algorithm = Val.chkStr(algorithm); boolean bMD5 = algorithm.equalsIgnoreCase("MD5"); boolean bSHA = algorithm.equalsIgnoreCase("SHA") || algorithm.equalsIgnoreCase("SHA1") || algorithm.equalsIgnoreCase("SHA-1"); if (bSHA || bMD5) { String sAlgorithm = "MD5"; if (bSHA) { sAlgorithm = "SHA"; } try { MessageDigest md = MessageDigest.getInstance(sAlgorithm); md.update(getPassword().getBytes("UTF-8")); sEncrypted = "{" + sAlgorithm + "}" + (new BASE64Encoder()).encode(md.digest()); } catch (NoSuchAlgorithmException e) { sEncrypted = null; e.printStackTrace(System.err); } catch (UnsupportedEncodingException e) { sEncrypted = null; e.printStackTrace(System.err); } } } return sEncrypted; }
Code Sample 2:
public static String getMD5(String _pwd) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(_pwd.getBytes()); return toHexadecimal(new String(md.digest()).getBytes()); } catch (NoSuchAlgorithmException x) { x.printStackTrace(); return ""; } }
|
00
|
Code Sample 1:
private void validate(String id, WriteToWebServerFile writeFile, char[][] charData) throws Exception { for (int i = 0; i < charData.length; i++) { assertTrue("There is a URL for input " + i, writeFile.hasNextURL()); URL url = writeFile.nextURL(); String path = url.getPath(); assertTrue("URL " + url + " contains request resource ID", path.indexOf(id) != -1); URLConnection connection = url.openConnection(); Reader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); int value; int index = 0; while (((value = reader.read()) != -1) && (index < charData[i].length)) { assertEquals("Character data " + i + " : " + index, (int) charData[i][index], value); index++; } } }
Code Sample 2:
public boolean validatePassword(UserType nameMatch, String password) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(nameMatch.getSalt().getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); return encodedString.equals(nameMatch.getPassword()); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); logger.fatal("Shutting down..."); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); assert false : "This should never happen"; return false; } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(ex.getMessage()); logger.fatal(errorMessage); GlobalUITools.displayFatalExceptionMessage(null, "Could not use algorithm " + HASH_ALGORITHM, ex, true); assert false : "This could should never be reached"; return false; } }
|
00
|
Code Sample 1:
private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); }
Code Sample 2:
public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); LOG.info("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { LOG.info("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); String urlString = url.getPath(); LOG.info("OKIOSIDManagedObject.contentType(): urlString = " + urlString + "\n"); if (urlString != null) { uti = UTType.preferredIdentifierForTag(UTType.FilenameExtensionTagClass, (NSPathUtilities.pathExtension(urlString)).toLowerCase(), null); } if (uti == null) { uti = UTType.Item; } return uti; } if (contentType != null) { LOG.info("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; LOG.info("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; }
|
11
|
Code Sample 1:
@Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; }
Code Sample 2:
public static void copyFile(File in, File out) throws Exception { Permissions before = getFilePermissons(in); FileChannel inFile = new FileInputStream(in).getChannel(); FileChannel outFile = new FileOutputStream(out).getChannel(); inFile.transferTo(0, inFile.size(), outFile); inFile.close(); outFile.close(); setFilePermissions(out, before); }
|
00
|
Code Sample 1:
public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public void connectUrl(String url) throws MalformedURLException, IOException { URLConnection connection = new URL(url).openConnection(); connection.connect(); connection.getInputStream().close(); connection.getOutputStream().close(); }
|
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 List<T_new> executeGet(HttpTransport transport, String targetUrl) throws HttpResponseException, IOException { HttpRequest req = transport.buildGetRequest(); req.setUrl(targetUrl); NotifyFeed feed = req.execute().parseAs(NotifyFeed.class); if (feed.entry == null) { return Collections.emptyList(); } List<T_new> results = new ArrayList<T_new>(); for (NotifyEntry e : feed.entry) { StringBuilder buffer = new StringBuilder(); if (e.id != null) { buffer.append(e.id); } buffer.append("@"); if (e.updated != null) { buffer.append(e.updated.toStringRfc3339().substring(0, 19) + "Z"); } Key key = Datastore.createKey(T_new.class, buffer.toString()); T_new news = new T_new(); news.setTitle(e.title); if (e.content != null) { news.setNewText(e.content.substring(0, Math.min(e.content.length(), 500))); } if (e.status != null && e.content == null) { news.setNewText(e.status); } if (e.updated != null) { news.setCreatedAt(new Date(e.updated.value)); } news.setContentUrl(e.getAlternate()); if (e.author != null) { news.setAuthor(e.author.name); } news.setKey(key); results.add(news); } return results; }
|
11
|
Code Sample 1:
public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } }
Code Sample 2:
public static void request() { try { URL url = new URL("http://www.nseindia.com/marketinfo/companyinfo/companysearch.jsp?cons=ghcl§ion=7"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
@Override public String baiDuHotNews() { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://news.baidu.com/z/wise_topic_processor/wise_hotwords_list.php?bd_page_type=1&tn=wapnews_hotwords_list&type=1&index=1&pfr=3-11-bdindex-top-3--"); String hostNews = ""; try { HttpResponse response = client.execute(httpGet); HttpEntity httpEntity = response.getEntity(); BufferedReader buffer = new BufferedReader(new InputStreamReader(httpEntity.getContent())); String line = ""; boolean todayNewsExist = false, firstNewExist = false; int newsCount = -1; while ((line = buffer.readLine()) != null) { if (todayNewsExist || line.contains("<div class=\"news_title\">")) todayNewsExist = true; else continue; if (firstNewExist || line.contains("<div class=\"list-item\">")) { firstNewExist = true; newsCount++; } else continue; if (todayNewsExist && firstNewExist && (newsCount == 1)) { Pattern hrefPattern = Pattern.compile("<a.*>(.+?)</a>.*"); Matcher matcher = hrefPattern.matcher(line); if (matcher.find()) { hostNews = matcher.group(1); break; } else newsCount--; } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return hostNews; }
Code Sample 2:
public static byte[] sendSmsRequest(String url, String param) { byte[] bytes = null; try { URL httpurl = new URL(url); HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection(); httpConn.setRequestProperty("Accept-Language", "zh-CN"); httpConn.setDoOutput(true); httpConn.setDoInput(true); PrintWriter out = new PrintWriter(httpConn.getOutputStream()); out.print(param); out.flush(); out.close(); InputStream ism = httpConn.getInputStream(); bytes = new byte[httpConn.getContentLength()]; ism.read(bytes); ism.close(); MsgPrint.showByteArray("result", bytes); } catch (Exception e) { return new byte[] { 0, 0, 0, 0 }; } return bytes; }
|
11
|
Code Sample 1:
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
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); } }
|
11
|
Code Sample 1:
public static void main(String args[]) { InputStream input = System.in; OutputStream output = System.out; if (args.length > 0) { try { input = new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[0]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[0]); System.exit(-1); } } if (args.length > 1) { try { output = new FileOutputStream(args[1]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[1]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[1]); System.exit(-1); } } byte buffer[] = new byte[512]; int len; try { while ((len = input.read(buffer)) > 0) output.write(buffer, 0, len); } catch (IOException e) { System.err.println("Error copying file"); } finally { input.close(); output.close(); } }
Code Sample 2:
protected byte[] readGZippedBytes(TupleInput in) { final boolean is_compressed = in.readBoolean(); byte array[] = readBytes(in); if (array == null) return null; if (!is_compressed) { return array; } try { ByteArrayInputStream bais = new ByteArrayInputStream(array); GZIPInputStream gzin = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); IOUtils.copyTo(gzin, baos); gzin.close(); bais.close(); return baos.toByteArray(); } catch (IOException err) { throw new RuntimeException(err); } }
|
00
|
Code Sample 1:
public String generateDigest(String password, String saltHex, String algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsIgnoreCase("crypt")) { return "{CRYPT}" + UnixCrypt.crypt(password); } else if (algorithm.equalsIgnoreCase("sha")) { algorithm = "SHA-1"; } else if (algorithm.equalsIgnoreCase("md5")) { algorithm = "MD5"; } MessageDigest msgDigest = MessageDigest.getInstance(algorithm); byte[] salt = {}; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (algorithm.startsWith("SHA")) { label = (salt.length > 0) ? "{SSHA}" : "{SHA}"; } else if (algorithm.startsWith("MD5")) { label = (salt.length > 0) ? "{SMD5}" : "{MD5}"; } msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt))); return digest.toString(); }
Code Sample 2:
public TestReport runImpl() throws Exception { String parser = XMLResourceDescriptor.getXMLParserClassName(); DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parser); File f = (new File(testFileName)); URL url = f.toURL(); Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream()); Element e = doc.getElementById(targetId); if (e == null) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_GET_ELEMENT_BY_ID_FAILED); report.addDescriptionEntry(ENTRY_KEY_ID, targetId); report.setPassed(false); return report; } Document otherDocument = df.createDocument(null, rootTag, url.toString(), url.openStream()); DocumentFragment docFrag = otherDocument.createDocumentFragment(); try { docFrag.appendChild(doc.getDocumentElement()); } catch (DOMException ex) { return reportSuccess(); } DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_EXCEPTION_NOT_THROWN); report.setPassed(false); return report; }
|
11
|
Code Sample 1:
private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } }
Code Sample 2:
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
|
00
|
Code Sample 1:
public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
Code Sample 2:
public static void main(String[] args) throws IOException, ClassNotFoundException { URL urlServlet = null; try { urlServlet = new URL("http://wofproj.appspot.com/test"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection con = null; try { con = urlServlet.openConnection(); } catch (IOException e) { e.printStackTrace(); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-java-serialized-object"); OutputStream outstream = con.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outstream); oos.writeObject("tom"); oos.flush(); oos.close(); InputStream instr = con.getInputStream(); ObjectInputStream inputFromServlet = new ObjectInputStream(instr); Object retval = inputFromServlet.readObject(); inputFromServlet.close(); instr.close(); System.out.println(retval.getClass().toString()); }
|
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 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:
public DialogueSymbole(final JFrame jframe, final Element el, final String srcAttr) { super(jframe, JaxeResourceBundle.getRB().getString("symbole.Insertion"), true); this.jframe = jframe; this.el = el; final String nomf = el.getAttribute(srcAttr); boolean applet = false; try { final File dossierSymboles = new File("symboles"); if (!dossierSymboles.exists()) { JOptionPane.showMessageDialog(jframe, JaxeResourceBundle.getRB().getString("erreur.SymbolesNonTrouve"), JaxeResourceBundle.getRB().getString("erreur.Erreur"), JOptionPane.ERROR_MESSAGE); return; } liste = chercherImages(dossierSymboles); } catch (AccessControlException ex) { applet = true; try { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(urlListe.openStream())); final ArrayList<File> listeImages = new ArrayList<File>(); String ligne = null; while ((ligne = in.readLine()) != null) { if (!"".equals(ligne.trim())) listeImages.add(new File("symboles/" + ligne.trim())); } liste = listeImages.toArray(new File[listeImages.size()]); } catch (IOException ex2) { LOG.error(ex2); } } final JPanel cpane = new JPanel(new BorderLayout()); setContentPane(cpane); final GridLayout grille = new GridLayout((int) Math.ceil(liste.length / 13.0), 13, 10, 10); final JPanel spane = new JPanel(grille); cpane.add(spane, BorderLayout.CENTER); ichoix = 0; final MyMouseListener ecouteur = new MyMouseListener(); labels = new JLabel[liste.length]; for (int i = 0; i < liste.length; i++) { if (nomf != null && !"".equals(nomf) && nomf.equals(liste[i].getPath())) ichoix = i; URL urlIcone; try { if (applet) { final URL urlListe = DialogueSymbole.class.getClassLoader().getResource("symboles/liste.txt"); final String baseURL = urlListe.toString().substring(0, urlListe.toString().indexOf("symboles/liste.txt")); urlIcone = new URL(baseURL + liste[i].getPath()); } else urlIcone = liste[i].toURL(); } catch (MalformedURLException ex) { LOG.error(ex); break; } final Icon ic = new ImageIcon(urlIcone); final JLabel label = new JLabel(ic); label.addMouseListener(ecouteur); labels[i] = label; spane.add(label); } final JPanel bpane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); final JButton boutonAnnuler = new JButton(JaxeResourceBundle.getRB().getString("bouton.Annuler")); boutonAnnuler.addActionListener(this); boutonAnnuler.setActionCommand("Annuler"); bpane.add(boutonAnnuler); final JButton boutonOK = new JButton(JaxeResourceBundle.getRB().getString("bouton.OK")); boutonOK.addActionListener(this); boutonOK.setActionCommand("OK"); bpane.add(boutonOK); cpane.add(bpane, BorderLayout.SOUTH); getRootPane().setDefaultButton(boutonOK); choix(ichoix); pack(); if (jframe != null) { final Rectangle r = jframe.getBounds(); setLocation(r.x + r.width / 4, r.y + r.height / 4); } else { final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - getSize().width) / 3, (screen.height - getSize().height) / 3); } }
Code Sample 2:
public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } }
|
11
|
Code Sample 1:
public static String md5hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("MD5"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
Code Sample 2:
public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
|
11
|
Code Sample 1:
public Object execute(ExecutionEvent event) throws ExecutionException { try { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); QuizTreeView view = (QuizTreeView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.rcpquizengine.views.quizzes"); Folder rootFolder = view.getRootFolder(); if (!rootFolder.isEncrypted()) { PasswordDialog dialog = new PasswordDialog(shell); if (dialog.open() == Window.OK) { String password = dialog.getPassword(); if (!password.equals("")) { String md5 = ""; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); md5 = new BigInteger(md.digest()).toString(); rootFolder.setMd5Digest(md5); rootFolder.setEncrypted(true); MessageDialog.openInformation(shell, "Quiz bank locked", "The current quiz bank has been locked"); password = ""; md5 = ""; } } } else { MessageDialog.openError(shell, "Error locking quiz bank", "Quiz bank already locked"); } } catch (PartInitException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
00
|
Code Sample 1:
public void executeUpdate(Native nativeResource) throws Exception { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; try { HrRecord hr = getRepository(); ManagedConnection mc = returnConnection(); con = mc.getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); String sql = ""; boolean isUpdate = false; String sUuid = ""; boolean finableBeforeUpdate = false; if (UuidUtil.isUuid(hr.getUuid())) { sUuid = hr.getUuid(); finableBeforeUpdate = queryFindable(con); sql = createUpdateSQL(); st = con.prepareStatement(sql); isUpdate = true; } else { sUuid = UuidUtil.makeUuid(true); finableBeforeUpdate = hr.getFindable(); sql = createInsertSQL(); st = con.prepareStatement(sql); } if (hr.getOwnerId() < 0) { hr.setOwnerId(getOwner().getLocalID()); } int n = 1; st.setInt(n++, hr.getOwnerId()); st.setTimestamp(n++, makeTimestamp(hr.getInputDate())); st.setTimestamp(n++, makeTimestamp(hr.getUpdateDate())); st.setString(n++, hr.getName()); st.setString(n++, hr.getHostUrl()); st.setString(n++, hr.getHarvestFrequency().toString()); st.setString(n++, Boolean.toString(hr.getSendNotification())); st.setString(n++, hr.getProtocol().getKind().toLowerCase()); st.setString(n++, ProtocolSerializer.toXmlString(hr.getProtocol())); st.setString(n++, PublicationMethod.registration.name()); if (!isUpdate) { if (getRequestContext().getApplicationConfiguration().getHarvesterConfiguration().getResourceAutoApprove()) { st.setString(n++, ApprovalStatus.approved.name()); } else { st.setString(n++, ApprovalStatus.posted.name()); } } st.setString(n++, Boolean.toString(hr.getSearchable())); st.setString(n++, Boolean.toString(hr.getSynchronizable())); st.setString(n++, sUuid); logExpression(sql); int nRowCount = st.executeUpdate(); getActionResult().setNumberOfRecordsModified(nRowCount); if (!isUpdate && nRowCount == 1) { closeStatement(st); st = con.prepareStatement("SELECT ID FROM " + getHarvestingTableName() + " WHERE UPPER(DOCUUID)=?"); st.setString(1, sUuid.toUpperCase()); ResultSet genKeys = st.executeQuery(); genKeys.next(); int nLocalId = genKeys.getInt(1); hr.setLocalId(nLocalId); hr.setUuid(sUuid); closeResultSet(genKeys); } con.commit(); if (nativeResource != null || (isUpdate && finableBeforeUpdate != hr.getFindable())) { try { if (nativeResource == null && isUpdate) { nativeResource = queryNative(con); } if (nativeResource != null) { String content = nativeResource.getContent(); String sourceUri = nativeResource.getSourceUri().asString(); Publisher publisher = createPublisherOfRepository(); PublicationRequest publicationRequest = createPublicationRequest(publisher, content, sourceUri); publicationRequest.publish(); } } catch (Exception ex) { LOGGER.log(Level.INFO, "Unable to create resource definition.", ex); } } Harvester harvestEngine = getRequestContext().getApplicationContext().getHarvestingEngine(); if (_repository.getIsHarvestDue()) { harvestEngine.submit(getRequestContext(), _repository, null, _repository.getLastSyncDate()); } harvestEngine.reselect(); } catch (Exception ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } }
Code Sample 2:
public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); }
|
00
|
Code Sample 1:
public String selectFROM() throws Exception { BufferedReader in = null; String data = null; try { HttpClient httpclient = new DefaultHttpClient(); URI uri = new URI("http://**.**.**.**/OctopusManager/index2.php"); HttpGet request = new HttpGet(); request.setURI(uri); HttpResponse httpresponse = httpclient.execute(request); HttpEntity httpentity = httpresponse.getEntity(); in = new BufferedReader(new InputStreamReader(httpentity.getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } }
Code Sample 2:
public static void fileTrans(String filePath, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } File file = new File(filePath); try { FileInputStream fis = new FileInputStream(file); Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream)); byte[] buffer = new byte[2048]; int num = fis.read(buffer); while (num != -1) { dataOutputStream.write(buffer, 0, num); dataOutputStream.flush(); num = fis.read(buffer); } fis.close(); dataOutputStream.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void createTableIfNotExisting(Connection conn) throws SQLException { String sql = "select * from " + tableName; PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.executeQuery(); } catch (SQLException sqle) { ps.close(); sql = "create table " + tableName + " ( tableName varchar(255) not null primary key, " + " lastId numeric(18) not null)"; ps = conn.prepareStatement(sql); ps.executeUpdate(); } finally { ps.close(); try { if (!conn.getAutoCommit()) conn.commit(); } catch (Exception e) { conn.rollback(); } } }
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); } }
|
00
|
Code Sample 1:
protected static String readAFewChars(URL url) throws IOException { StringBuffer buf = new StringBuffer(10); Reader reader = new InputStreamReader(url.openStream()); for (int i = 0; i < 10; i++) { int c = reader.read(); if (c == -1) { break; } buf.append((char) c); } reader.close(); return buf.toString(); }
Code Sample 2:
private byte[] digestPassword(byte[] salt, String password) throws AuthenticationException { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); return md.digest(); } catch (Exception e) { throw new AuthenticationException(MESSAGE_CONFIGURATION_ERROR_KEY, e); } }
|
11
|
Code Sample 1:
public void writeTo(File f) throws IOException { if (state != STATE_OK) throw new IllegalStateException("Upload failed"); if (tempLocation == null) throw new IllegalStateException("File already saved"); if (f.isDirectory()) f = new File(f, filename); FileInputStream fis = new FileInputStream(tempLocation); FileOutputStream fos = new FileOutputStream(f); byte[] buf = new byte[BUFFER_SIZE]; try { int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } finally { deleteTemporaryFile(); fis.close(); fos.close(); } }
Code Sample 2:
public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
|
00
|
Code Sample 1:
public int[] sort() { int i, tmp; int[] newIndex = new int[nrows]; for (i = 0; i < nrows; i++) { newIndex[i] = i; } boolean change = true; if (this.ascending) { if (data[0][column] instanceof Comparable) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if (((Comparable) data[newIndex[i]][column]).compareTo((Comparable) data[newIndex[i + 1]][column]) > 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } return newIndex; } if (data[0][column] instanceof String || data[0][column] instanceof ClassLabel) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if ((data[newIndex[i]][column].toString()).compareTo(data[newIndex[i + 1]][column].toString()) > 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } } return newIndex; } if (!this.ascending) { if (data[0][column] instanceof Comparable) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if (((Comparable) data[newIndex[i]][column]).compareTo((Comparable) data[newIndex[i + 1]][column]) < 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } return newIndex; } if (data[0][column] instanceof String || data[0][column] instanceof ClassLabel) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if ((data[newIndex[i]][column].toString()).compareTo(data[newIndex[i + 1]][column].toString()) < 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } } return newIndex; } else return newIndex; }
Code Sample 2:
private Document getOpenLinkResponse(String queryDoc) throws IOException, UnvalidResponseException { URL url = new URL(WS_URI); URLConnection conn = url.openConnection(); logger.debug(".conn open"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(queryDoc); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); logger.debug(".resp obtained"); StringBuffer responseBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(NEWLINE); } wr.close(); rd.close(); logger.debug(".done"); try { return documentParser.parse(responseBuffer.toString()); } catch (SAXException e) { throw new UnvalidResponseException("Response is not a valid XML file", e); } }
|
00
|
Code Sample 1:
public static String getWhatsNew(String ver) { URL url = null; try { url = new URL("http://googlemeupdate.bravehost.com/History.htm"); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream html = null; try { html = url.openStream(); int c = 0; String Buffer = ""; String Code = ""; while (c != -1) { try { c = html.read(); } catch (IOException ex) { } Buffer = Buffer + (char) c; } Buffer = Buffer.substring(Buffer.lastIndexOf(ver) + ver.length() + 2, Buffer.indexOf("end::")).replaceAll("||", ""); return "<html>" + Buffer.substring(Buffer.indexOf("Google.mE Version: ")); } catch (IOException ex) { ex.printStackTrace(); return ""; } }
Code Sample 2:
public boolean authenticate(String plaintext) throws NoSuchAlgorithmException { String[] passwordParts = this.password.split("\\$"); md = MessageDigest.getInstance("SHA-1"); md.update(passwordParts[1].getBytes()); isAuthenticated = toHex(md.digest(plaintext.getBytes())).equalsIgnoreCase(passwordParts[2]); return isAuthenticated; }
|
00
|
Code Sample 1:
public static String getImportFileBody(String fileName, HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); String fileTransferFolder = CofaxToolsServlet.fileTransferFolder; String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER"); String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN"); String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD"); String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH"); String body = (""); try { int reply; ftp.connect(importFTPServer); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody connecting to server " + importFTPServer); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP getImportFileBody ERROR: FTP server refused connection."); } else { ftp.login(importFTPLogin, importFTPPassword); } try { boolean change = ftp.changeWorkingDirectory(importFTPFilePath); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody changing to directory: " + importFTPFilePath); CofaxToolsUtil.log("Results: " + change); OutputStream output; output = new FileOutputStream(fileTransferFolder + fileName); boolean retrieve = ftp.retrieveFile(fileName, output); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody retrieving file: " + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + change); output.close(); body = CofaxToolsUtil.readFile(fileTransferFolder + fileName, true); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody deleting remote file: " + importFTPFilePath + fileName); boolean delete = ftp.deleteFile(importFTPFilePath + fileName); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + delete); CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody disconnecting from server:" + importFTPServer); ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: cannot write file: " + fileName); } } catch (IOException e) { return ("CofaxToolsFTP getImportFileBody ERROR: could not connect to server: " + e); } return (body); }
Code Sample 2:
private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } }
|
11
|
Code Sample 1:
public void applyTo(File source, File target) throws IOException { boolean failed = true; FileInputStream fin = new FileInputStream(source); try { FileChannel in = fin.getChannel(); FileOutputStream fos = new FileOutputStream(target); try { FileChannel out = fos.getChannel(); long pos = 0L; for (Replacement replacement : replacements) { in.transferTo(pos, replacement.pos - pos, out); if (replacement.val != null) out.write(ByteBuffer.wrap(replacement.val)); pos = replacement.pos + replacement.len; } in.transferTo(pos, source.length() - pos, out); failed = false; } finally { fos.close(); if (failed == true) target.delete(); } } finally { fin.close(); } }
Code Sample 2:
public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
11
|
Code Sample 1:
protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
Code Sample 2:
public List<String> generate(String geronimoVersion, String geronimoHome, String instanceNumber) { geronimoRepository = geronimoHome + "/repository"; Debug.logInfo("The WASCE or Geronimo Repository is " + geronimoRepository, module); Classpath classPath = new Classpath(System.getProperty("java.class.path")); List<File> elements = classPath.getElements(); List<String> jar_version = new ArrayList<String>(); String jarPath = null; String jarName = null; String newJarName = null; String jarNameSimple = null; String jarVersion = "1.0"; int lastDash = -1; for (File f : elements) { if (f.exists()) { if (f.isFile()) { jarPath = f.getAbsolutePath(); jarName = f.getName(); String jarNameWithoutExt = (String) jarName.subSequence(0, jarName.length() - 4); lastDash = jarNameWithoutExt.lastIndexOf("-"); if (lastDash > -1) { jarVersion = jarNameWithoutExt.substring(lastDash + 1, jarNameWithoutExt.length()); jarNameSimple = jarNameWithoutExt.substring(0, lastDash); boolean alreadyVersioned = 0 < StringUtil.removeRegex(jarVersion, "[^.0123456789]").length(); if (!alreadyVersioned) { jarVersion = "1.0"; jarNameSimple = jarNameWithoutExt; newJarName = jarNameWithoutExt + "-" + jarVersion + ".jar"; } else { newJarName = jarName; } } else { jarVersion = "1.0"; jarNameSimple = jarNameWithoutExt; newJarName = jarNameWithoutExt + "-" + jarVersion + ".jar"; } jar_version.add(jarNameSimple + "#" + jarVersion); String targetDirectory = geronimoRepository + "/org/ofbiz/" + jarNameSimple + "/" + jarVersion; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { Debug.logFatal("Unable to create target directory - " + targetDirectory, module); return null; } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } String newCompleteJarName = targetDirectory + newJarName; File newJarFile = new File(newCompleteJarName); try { FileChannel srcChannel = new FileInputStream(jarPath).getChannel(); FileChannel dstChannel = new FileOutputStream(newCompleteJarName).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); Debug.log("Created jar file : " + newJarName + " in WASCE or Geronimo repository", module); srcChannel.close(); dstChannel.close(); } catch (IOException e) { Debug.logFatal("Unable to create jar file - " + newJarName + " in WASCE or Geronimo repository (certainly already exists)", module); return null; } } } } List<ComponentConfig.WebappInfo> webApps = ComponentConfig.getAllWebappResourceInfos(); File geronimoWebXml = new File(System.getProperty("ofbiz.home") + "/framework/appserver/templates/" + geronimoVersion + "/geronimo-web.xml"); for (ComponentConfig.WebappInfo webApp : webApps) { if (null != webApp) { parseTemplate(geronimoWebXml, webApp); } } return jar_version; }
|
11
|
Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
Code Sample 2:
public static void write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } }
|
11
|
Code Sample 1:
public static String filtraDoc(HttpServletRequest request, String resource, Repository rep, String template) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = null; int sec = 0; try { URL url = rep.getResource(request, resource); if (url == null) { return "Documento " + rep.dir + "/" + resource + " no encontrado"; } br = new BufferedReader(new InputStreamReader(url.openStream(), rep.encoding)); String line = br.readLine(); while (line != null) { int pos = line.indexOf("KAttach("); if (pos > -1) { sb.append(attach(request, ++sec, line, pos, template)); } else { line = line.replaceAll("%20", "-"); sb.append(new String(line.getBytes(rep.encoding), Config.getMng().getEncoding())).append("\n"); } line = br.readLine(); } } finally { if (br != null) br.close(); } return sb.toString(); }
Code Sample 2:
public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; }
|
11
|
Code Sample 1:
public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } }
Code Sample 2:
public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); }
|
00
|
Code Sample 1:
public static void ftpUpload(FTPConfig config, String directory, File file, String remoteFileName) throws IOException { FTPClient server = new FTPClient(); server.connect(config.host, config.port); assertValidReplyCode(server.getReplyCode(), server); server.login(config.userName, config.password); assertValidReplyCode(server.getReplyCode(), server); assertValidReplyCode(server.cwd(directory), server); server.setFileTransferMode(FTP.IMAGE_FILE_TYPE); server.setFileType(FTP.IMAGE_FILE_TYPE); server.storeFile(remoteFileName, new FileInputStream(file)); assertValidReplyCode(server.getReplyCode(), server); server.sendNoOp(); server.disconnect(); }
Code Sample 2:
private Callable<Request> newRequestCall(final Request request) { return new Callable<Request>() { public Request call() { InputStream is = null; try { if (DEBUG) Log.d(TAG, "Requesting: " + request.uri); HttpGet httpGet = new HttpGet(request.uri.toString()); httpGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = mHttpClient.execute(httpGet); String mimeType = response.getHeaders("Content-Type")[0].getValue(); if (DEBUG) Log.d(TAG, "mimeType:" + mimeType); if (mimeType.startsWith("image")) { HttpEntity entity = response.getEntity(); is = getUngzippedContent(entity); Bitmap bitmap = BitmapFactory.decodeStream(is); if (mResourceCache.store(request.hash, bitmap)) { mCache.put(request.uri.toString(), new SoftReference<Bitmap>(bitmap)); if (DEBUG) Log.d(TAG, "Request successful: " + request.uri); } else { mResourceCache.invalidate(request.hash); } } } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); } finally { if (DEBUG) Log.e(TAG, "Request finished: " + request.uri); mActiveRequestsMap.remove(request); if (is != null) { notifyObservers(request.uri); } try { if (is != null) { is.close(); } } catch (IOException e) { if (DEBUG) e.printStackTrace(); } } return request; } }; }
|
11
|
Code Sample 1:
public void run() { try { IOUtils.copy(is, os); os.flush(); } catch (IOException ioe) { logger.error("Unable to copy", ioe); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
Code Sample 2:
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { String pathInfo = httpServletRequest.getPathInfo(); log.info("PathInfo: " + pathInfo); if (pathInfo == null || pathInfo.equals("") || pathInfo.equals("/")) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String fileName = pathInfo.charAt(0) == '/' ? pathInfo.substring(1) : pathInfo; log.info("FileName: " + fileName); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = getDataSource().getConnection(); ps = con.prepareStatement("select file, size from files where name=?"); ps.setString(1, fileName); rs = ps.executeQuery(); if (rs.next()) { httpServletResponse.setContentType(getServletContext().getMimeType(fileName)); httpServletResponse.setContentLength(rs.getInt("size")); OutputStream os = httpServletResponse.getOutputStream(); org.apache.commons.io.IOUtils.copy(rs.getBinaryStream("file"), os); os.flush(); } else { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (SQLException e) { throw new ServletException(e); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (ps != null) try { ps.close(); } catch (SQLException e) { } if (con != null) try { con.close(); } catch (SQLException e) { } } }
|
11
|
Code Sample 1:
public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { setHeader(resp); try { logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes"); File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif"); if (!tempFile.exists()) { logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities"); try { OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); fos.close(); } catch (ImogSerializationException mse) { logger.error(mse.getMessage(), mse); } } InputStream fis = new FileInputStream(tempFile); fis.skip(command.getLen()); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); fis.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } }
Code Sample 2:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
|
00
|
Code Sample 1:
public String merge(int width, int height) throws Exception { htErrors.clear(); sendGetImageRequests(width, height); Vector files = new Vector(); ConcurrentHTTPTransactionHandler c = new ConcurrentHTTPTransactionHandler(); c.setCache(cache); c.checkIfModified(false); for (int i = 0; i < vImageUrls.size(); i++) { if ((String) vImageUrls.get(i) != null) { c.register((String) vImageUrls.get(i)); } else { } } c.doTransactions(); vTransparency = new Vector(); for (int i = 0; i < vImageUrls.size(); i++) { if (vImageUrls.get(i) != null) { String path = c.getResponseFilePath((String) vImageUrls.get(i)); if (path != null) { String contentType = c.getHeaderValue((String) vImageUrls.get(i), "content-type"); if (contentType.startsWith("image")) { files.add(path); vTransparency.add(htTransparency.get(vRank.get(i))); } } } } if (files.size() > 1) { File output = TempFiles.getFile(); String path = output.getPath(); ImageMerger.mergeAndSave(files, vTransparency, path, ImageMerger.GIF); imageName = output.getName(); imagePath = output.getPath(); return (imageName); } else if (files.size() == 1) { File f = new File((String) files.get(0)); File out = TempFiles.getFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); byte buf[] = new byte[1024]; for (int nRead; (nRead = is.read(buf, 0, 1024)) > 0; os.write(buf, 0, nRead)) ; os.flush(); os.close(); is.close(); imageName = out.getName(); return imageName; } else return ""; }
Code Sample 2:
private void getRdfResponse(StringBuilder sb, String url) { try { String inputLine = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((inputLine = reader.readLine()) != null) { sb.append(inputLine); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
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 void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) { LogFrame.getInstance(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.trim().startsWith(DEBUG_PARAMETER_NAME + "=")) { properties.put(DEBUG_PARAMETER_NAME, arg.trim().substring(DEBUG_PARAMETER_NAME.length() + 1).trim()); if (properties.getProperty(DEBUG_PARAMETER_NAME).toLowerCase().equals(DEBUG_TRUE)) { DEBUG = true; } } else if (arg.trim().startsWith(MODE_PARAMETER_NAME + "=")) { properties.put(MODE_PARAMETER_NAME, arg.trim().substring(MODE_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(AUTOCONNECT_PARAMETER_NAME + "=")) { properties.put(AUTOCONNECT_PARAMETER_NAME, arg.trim().substring(AUTOCONNECT_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SITE_CONFIG_URL_PARAMETER_NAME + "=")) { properties.put(SITE_CONFIG_URL_PARAMETER_NAME, arg.trim().substring(SITE_CONFIG_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(LOAD_PLUGINS_PARAMETER_NAME + "=")) { properties.put(LOAD_PLUGINS_PARAMETER_NAME, arg.trim().substring(LOAD_PLUGINS_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ONTOLOGY_URL_PARAMETER_NAME + "=")) { properties.put(ONTOLOGY_URL_PARAMETER_NAME, arg.trim().substring(ONTOLOGY_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(REPOSITORY_PARAMETER_NAME + "=")) { properties.put(REPOSITORY_PARAMETER_NAME, arg.trim().substring(REPOSITORY_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ONTOLOGY_TYPE_PARAMETER_NAME + "=")) { properties.put(ONTOLOGY_TYPE_PARAMETER_NAME, arg.trim().substring(ONTOLOGY_TYPE_PARAMETER_NAME.length() + 1).trim()); if (!(properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME).equals(ONTOLOGY_TYPE_RDFXML) || properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME).equals(ONTOLOGY_TYPE_TURTLE) || properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME).equals(ONTOLOGY_TYPE_NTRIPPLES))) System.out.println("WARNING! Unknown ontology type: '" + properties.getProperty(ONTOLOGY_TYPE_PARAMETER_NAME) + "' (Known types are: '" + ONTOLOGY_TYPE_RDFXML + "', '" + ONTOLOGY_TYPE_TURTLE + "', '" + ONTOLOGY_TYPE_NTRIPPLES + "')"); } else if (arg.trim().startsWith(OWLIMSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(OWLIMSERVICE_URL_PARAMETER_NAME, arg.trim().substring(OWLIMSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_URL_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOC_ID_PARAMETER_NAME + "=")) { properties.put(DOC_ID_PARAMETER_NAME, arg.trim().substring(DOC_ID_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ANNSET_NAME_PARAMETER_NAME + "=")) { properties.put(ANNSET_NAME_PARAMETER_NAME, arg.trim().substring(ANNSET_NAME_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(EXECUTIVE_SERVICE_URL_PARAMETER_NAME + "=")) { properties.put(EXECUTIVE_SERVICE_URL_PARAMETER_NAME, arg.trim().substring(EXECUTIVE_SERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(USER_ID_PARAMETER_NAME + "=")) { properties.put(USER_ID_PARAMETER_NAME, arg.trim().substring(USER_ID_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(USER_PASSWORD_PARAMETER_NAME + "=")) { properties.put(USER_PASSWORD_PARAMETER_NAME, arg.trim().substring(USER_PASSWORD_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(EXECUTIVE_PROXY_FACTORY_PARAMETER_NAME + "=")) { properties.put(EXECUTIVE_PROXY_FACTORY_PARAMETER_NAME, arg.trim().substring(EXECUTIVE_PROXY_FACTORY_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME.length() + 1).trim()); RichUIUtils.setDocServiceProxyFactoryClassname(properties.getProperty(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME)); } else if (arg.trim().startsWith(LOAD_ANN_SCHEMAS_NAME + "=")) { properties.put(LOAD_ANN_SCHEMAS_NAME, arg.trim().substring(LOAD_ANN_SCHEMAS_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SELECT_AS_PARAMETER_NAME + "=")) { properties.put(SELECT_AS_PARAMETER_NAME, arg.trim().substring(SELECT_AS_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SELECT_ANN_TYPES_PARAMETER_NAME + "=")) { properties.put(SELECT_ANN_TYPES_PARAMETER_NAME, arg.trim().substring(SELECT_ANN_TYPES_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ENABLE_ONTOLOGY_EDITOR_PARAMETER_NAME + "=")) { properties.put(ENABLE_ONTOLOGY_EDITOR_PARAMETER_NAME, arg.trim().substring(ENABLE_ONTOLOGY_EDITOR_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(CLASSES_TO_HIDE_PARAMETER_NAME + "=")) { properties.put(CLASSES_TO_HIDE_PARAMETER_NAME, arg.trim().substring(CLASSES_TO_HIDE_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(CLASSES_TO_SHOW_PARAMETER_NAME + "=")) { properties.put(CLASSES_TO_SHOW_PARAMETER_NAME, arg.trim().substring(CLASSES_TO_SHOW_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(ENABLE_APPLICATION_LOG_PARAMETER_NAME + "=")) { properties.put(ENABLE_APPLICATION_LOG_PARAMETER_NAME, arg.trim().substring(ENABLE_APPLICATION_LOG_PARAMETER_NAME.length() + 1).trim()); } else { System.out.println("WARNING! Unknown or undefined parameter: '" + arg.trim() + "'"); } } System.out.println(startupParamsToString()); if (properties.getProperty(MODE_PARAMETER_NAME) == null || (!(properties.getProperty(MODE_PARAMETER_NAME).toLowerCase().equals(POOL_MODE)) && !(properties.getProperty(MODE_PARAMETER_NAME).toLowerCase().equals(DIRECT_MODE)))) { String err = "Mandatory parameter '" + MODE_PARAMETER_NAME + "' must be defined and must have a value either '" + POOL_MODE + "' or '" + DIRECT_MODE + "'.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) == null || properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() == 0) { String err = "Mandatory parameter '" + SITE_CONFIG_URL_PARAMETER_NAME + "' is missing.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } try { String context = System.getProperty(CONTEXT); if (context == null || "".equals(context)) { context = DEFAULT_CONTEXT; } String s = System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { File f = File.createTempFile("foo", ""); String gateHome = f.getParent().toString() + context; f.delete(); System.setProperty(GateConstants.GATE_HOME_PROPERTY_NAME, gateHome); f = new File(System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/plugins"); File f = new File(System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/gate.xml"); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) != null && properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() > 0) { File f = new File(System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME)); if (f.exists()) { f.delete(); } f.getParentFile().mkdirs(); f.createNewFile(); URL url = new URL(properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME)); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream(f); int i = is.read(); while (i != -1) { fos.write(i); i = is.read(); } fos.close(); is.close(); } try { Gate.init(); gate.Main.applyUserPreferences(); } catch (Exception e) { e.printStackTrace(); } s = BASE_PLUGIN_NAME + "," + properties.getProperty(LOAD_PLUGINS_PARAMETER_NAME); System.out.println("Loading plugins: " + s); loadPlugins(s, true); loadAnnotationSchemas(properties.getProperty(LOAD_ANN_SCHEMAS_NAME), true); } catch (Throwable e) { e.printStackTrace(); } MainFrame.getInstance().setVisible(true); MainFrame.getInstance().pack(); if (properties.getProperty(MODE_PARAMETER_NAME).toLowerCase().equals(DIRECT_MODE)) { if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(DOC_ID_PARAMETER_NAME) == null || properties.getProperty(DOC_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + DOC_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(MainFrame.getInstance(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowDocserviceConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToDocservice.getInstance().actionPerformed(null); } } else { ActionShowDocserviceConnectDialog.getInstance().actionPerformed(null); } } else { if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(USER_ID_PARAMETER_NAME) == null || properties.getProperty(USER_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + USER_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(MainFrame.getInstance(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowExecutiveConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToExecutive.getInstance().actionPerformed(null); } } else { ActionShowExecutiveConnectDialog.getInstance().actionPerformed(null); } } }
Code Sample 2:
public LinkedList<NameValuePair> getScoreboard() { InputStream is = null; String result = ""; LinkedList<NameValuePair> scores = new LinkedList<NameValuePair>(); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return null; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json = new JSONObject(result); JSONArray data = json.getJSONArray("data"); JSONArray me = json.getJSONArray("me"); for (int i = 0; i < data.length(); i++) { JSONObject single = data.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } for (int i = 0; i < me.length(); i++) { JSONObject single = me.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } System.out.println(json); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return scores; }
|
11
|
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:
private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
|
11
|
Code Sample 1:
private long generateNativeInstallExe(File nativeInstallFile, String instTemplate, File instClassFile) throws IOException { InputStream reader = getClass().getResourceAsStream("/" + instTemplate); ByteArrayOutputStream content = new ByteArrayOutputStream(); String installClassVarStr = "000000000000"; byte[] buf = new byte[installClassVarStr.length()]; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassVarStr.length()); int installClassStopPos = 0; long installClassOffset = reader.available(); int position = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallExe")); reader.read(buf, 0, buf.length); position = 1; for (int n = 0; n < 3; n++) { while ((!new String(buf).equals("clname_here_")) && (!new String(buf).equals("clstart_here")) && (!new String(buf).equals("clstop_here_"))) { content.write(buf[0]); int nextb = reader.read(); position++; shiftArray(buf); buf[buf.length - 1] = (byte) nextb; } if (new String(buf).equals("clname_here_")) { VAGlobals.printDebug(" clname_here_ found at " + (position - 1)); StringBuffer clnameBuffer = new StringBuffer(64); clnameBuffer.append(instClassName_); for (int i = clnameBuffer.length() - 1; i < 64; i++) { clnameBuffer.append('.'); } byte[] clnameBytes = clnameBuffer.toString().getBytes(); for (int i = 0; i < 64; i++) { content.write(clnameBytes[i]); position++; } reader.skip(64 - buf.length); reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstart_here")) { VAGlobals.printDebug(" clstart_here found at " + (position - 1)); buf = nf.format(installClassOffset).getBytes(); for (int i = 0; i < buf.length; i++) { content.write(buf[i]); position++; } reader.read(buf, 0, buf.length); } else if (new String(buf).equals("clstop_here_")) { VAGlobals.printDebug(" clstop_here_ found at " + (position - 1)); installClassStopPos = position - 1; content.write(buf); position += 12; reader.read(buf, 0, buf.length); } } content.write(buf); buf = new byte[2048]; int read = reader.read(buf); while (read > 0) { content.write(buf, 0, read); read = reader.read(buf); } reader.close(); FileInputStream classStream = new FileInputStream(instClassFile); read = classStream.read(buf); while (read > 0) { content.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); content.close(); byte[] contentBytes = content.toByteArray(); installClassVarStr = nf.format(contentBytes.length); byte[] installClassVarBytes = installClassVarStr.getBytes(); for (int i = 0; i < installClassVarBytes.length; i++) { contentBytes[installClassStopPos + i] = installClassVarBytes[i]; } FileOutputStream out = new FileOutputStream(nativeInstallFile); out.write(contentBytes); out.close(); return installClassOffset; }
Code Sample 2:
private void copyValidFile(File file, int cviceni) { try { String filename = String.format("%s%s%02d%s%s", validovane, File.separator, cviceni, File.separator, file.getName()); boolean copy = false; File newFile = new File(filename); if (newFile.exists()) { if (file.lastModified() > newFile.lastModified()) copy = true; else copy = false; } else { newFile.createNewFile(); copy = true; } if (copy) { String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(newFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); newFile.setLastModified(file.lastModified()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
Code Sample 2:
private void execute(File file) throws IOException { if (file == null) throw new RuntimeException("undefined file"); if (!file.exists()) throw new RuntimeException("file not found :" + file); if (!file.isFile()) throw new RuntimeException("not a file :" + file); String login = cfg.getProperty(GC_USERNAME); String password = null; if (cfg.containsKey(GC_PASSWORD)) { password = cfg.getProperty(GC_PASSWORD); } else { password = new String(Base64.decode(cfg.getProperty(GC_PASSWORD64))); } PostMethod post = null; try { HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(login + ":" + password)); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new IOException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } finally { if (post != null) post.releaseConnection(); } }
|
11
|
Code Sample 1:
public static String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } md.update(plaintext.getBytes(Charset.defaultCharset())); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String md5hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); return new BigInteger(1, digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { LOG.error(e); } return null; }
|
00
|
Code Sample 1:
public void testRegisterFactory() throws Exception { try { new URL("classpath:/"); fail("MalformedURLException expected"); } catch (MalformedURLException e) { assertTrue(true); } ClasspathURLConnection.registerFactory(); URL url = new URL("classpath:/dummy.txt"); try { url.openStream(); fail("IOException expected"); } catch (IOException e) { assertTrue(true); } ClasspathURLConnection.registerFactory(); url = new URL("classpath:/net/sf/alster/xsl/alster.xml"); InputStream in = url.openStream(); assertEquals('<', in.read()); in.close(); }
Code Sample 2:
public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); 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); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); }
|
11
|
Code Sample 1:
public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); }
Code Sample 2:
public static void copyFile(String inName, String otName) throws Exception { File inFile = null; File otFile = null; try { inFile = new File(inName); otFile = new File(otName); } catch (Exception e) { e.printStackTrace(); } if (inFile == null || otFile == null) return; FileChannel sourceChannel = new FileInputStream(inFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(otFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
public static String encriptarContrasena(String contrasena) throws NoSuchAlgorithmException, UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(contrasena.getBytes("UTF-8")); byte[] digestBytes = md.digest(); String hex = null; for (int i = 0; i < digestBytes.length; i++) { hex = Integer.toHexString(0xFF & digestBytes[i]); if (hex.length() < 2) sb.append("0"); sb.append(hex); } return new String(sb); }
Code Sample 2:
public static String md5(String s) { try { MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(s.getBytes()); return new BigInteger(1, digester.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
|
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:
protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } }
|
11
|
Code Sample 1:
private PrecomputedAnimatedModel loadPrecomputedModel_(URL url) { if (precompCache.containsKey(url.toExternalForm())) { return (precompCache.get(url.toExternalForm()).copy()); } TextureLoader.getInstance().getTexture(""); List<SharedGroup> frames = new ArrayList<SharedGroup>(); Map<String, Animation> animations = new Hashtable<String, Animation>(); if (url.toExternalForm().endsWith(".amo")) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String objFileName = reader.readLine(); objFileName = url.toExternalForm().substring(0, url.toExternalForm().lastIndexOf("/")) + "/" + objFileName; frames = loadOBJFrames(objFileName); String line; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String animName = tokenizer.nextToken(); int from = Integer.valueOf(tokenizer.nextToken()); int to = Integer.valueOf(tokenizer.nextToken()); tokenizer.nextToken(); animations.put(animName, new Animation(animName, from, to)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { frames = loadOBJFrames(url.toExternalForm()); } PrecomputedAnimatedModel precompModel = new PrecomputedAnimatedModel(frames, animations); precompCache.put(url.toExternalForm(), precompModel); return (precompModel); }
Code Sample 2:
public JythonWrapperAction(AActionBO.ActionDTO dto, URL url) throws IOException { super(dto); InputStream in = url.openStream(); InputStreamReader rin = new InputStreamReader(in); BufferedReader reader = new BufferedReader(rin); StringBuffer s = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { s.append(str); s.append("\n"); } in.close(); script = s.toString(); }
|
00
|
Code Sample 1:
public static void copyFile(String fromFile, String toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
|
11
|
Code Sample 1:
public void readEntry(String name, InputStream input) throws Exception { File file = new File(this.directory, name); OutputStream output = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { org.apache.commons.io.IOUtils.copy(input, output); } finally { output.close(); } }
Code Sample 2:
public static void main(String[] args) throws IOException { System.setProperty("java.protocol.xfile", "com.luzan.common.nfs"); if (args.length < 1) usage(); final String cmd = args[0]; if ("delete".equalsIgnoreCase(cmd)) { final String path = getParameter(args, 1); XFile xfile = new XFile(path); if (!xfile.exists()) { System.out.print("File doean't exist.\n"); System.exit(1); } xfile.delete(); } else if ("copy".equalsIgnoreCase(cmd)) { final String pathFrom = getParameter(args, 1); final String pathTo = getParameter(args, 2); final XFile xfileFrom = new XFile(pathFrom); final XFile xfileTo = new XFile(pathTo); if (!xfileFrom.exists()) { System.out.print("File doesn't exist.\n"); System.exit(1); } final String mime = getParameter(args, 3, null); final XFileInputStream in = new XFileInputStream(xfileFrom); final XFileOutputStream xout = new XFileOutputStream(xfileTo); if (!StringUtils.isEmpty(mime)) { final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfileTo.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType(mime); xfa.setContentLength(xfileFrom.length()); } } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); } }
|
00
|
Code Sample 1:
public void 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 static String md5(String s) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); String output = bigInt.toString(16); return prepad(output, 32, '0'); } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm. we are sunk."); return s; } }
|
11
|
Code Sample 1:
private final void copyTargetFileToSourceFile(File sourceFile, File targetFile) throws MJProcessorException { if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); try { if (!targetFile.exists()) { targetFile.createNewFile(); } } catch (IOException e) { throw new MJProcessorException(e.getMessage(), e); } } FileChannel in = null, out = null; try { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(targetFile).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (IOException e) { log.error(e); } finally { if (in != null) try { in.close(); } catch (IOException e) { log.error(e); } if (out != null) try { out.close(); } catch (IOException e) { log.error(e); } } }
Code Sample 2:
public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
|
00
|
Code Sample 1:
@Override public String toString() { String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } }
Code Sample 2:
protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); }
|
11
|
Code Sample 1:
protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; }
Code Sample 2:
public TempFileBinaryBody(InputStream is) throws IOException { TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".bin"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.