label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = 67076096; long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
private static String fetchFile(String urlLocation) { try { URL url = new URL(urlLocation); URLConnection conn = url.openConnection(); File tempFile = File.createTempFile("marla", ".jar"); OutputStream os = new FileOutputStream(tempFile); IOUtils.copy(conn.getInputStream(), os); return tempFile.getAbsolutePath(); } catch (IOException ex) { throw new MarlaException("Unable to fetch file '" + urlLocation + "' from server", ex); } } |
00
| Code Sample 1:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
Code Sample 2:
protected Control createContents(Composite parent) { this.getShell().setText("Chisio"); this.getShell().setSize(800, 600); this.getShell().setImage(ImageDescriptor.createFromFile(ChisioMain.class, "icon/chisio-icon.png").createImage()); Composite composite = new Composite(parent, SWT.BORDER); composite.setLayout(new FillLayout()); this.viewer = new ScrollingGraphicalViewer(); this.viewer.setEditDomain(this.editDomain); this.viewer.createControl(composite); this.viewer.getControl().setBackground(ColorConstants.white); this.rootEditPart = new ChsScalableRootEditPart(); this.viewer.setRootEditPart(this.rootEditPart); this.viewer.setEditPartFactory(new ChsEditPartFactory()); ((FigureCanvas) this.viewer.getControl()).setScrollBarVisibility(FigureCanvas.ALWAYS); this.viewer.addDropTargetListener(new ChsFileDropTargetListener(this.viewer, this)); this.viewer.addDragSourceListener(new ChsFileDragSourceListener(this.viewer)); CompoundModel model = new CompoundModel(); model.setAsRoot(); this.viewer.setContents(model); this.viewer.getControl().addMouseListener(this); this.popupManager = new PopupManager(this); this.popupManager.setRemoveAllWhenShown(true); this.popupManager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { ChisioMain.this.popupManager.createActions(manager); } }); KeyHandler keyHandler = new KeyHandler(); ActionRegistry a = new ActionRegistry(); keyHandler.put(KeyStroke.getPressed(SWT.DEL, 127, 0), new DeleteAction(this.viewer)); keyHandler.put(KeyStroke.getPressed('+', SWT.KEYPAD_ADD, 0), new ZoomAction(this, 1, null)); keyHandler.put(KeyStroke.getPressed('-', SWT.KEYPAD_SUBTRACT, 0), new ZoomAction(this, -1, null)); keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), a.getAction(GEFActionConstants.DIRECT_EDIT)); this.viewer.setKeyHandler(keyHandler); this.higlightColor = ColorConstants.yellow; this.createCombos(); return composite; } |
00
| Code Sample 1:
public static String readUrlText(String urlString) throws IOException { URL url = new URL(urlString); InputStream stream = url.openStream(); StringBuilder buf = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(stream)); String str; while ((str = in.readLine()) != null) { buf.append(str); buf.append(System.getProperty("line.separator")); } } catch (IOException e) { System.out.println("Error reading text from URL [" + url + "]: " + e.toString()); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { System.out.println("Error closing after reading text from URL [" + url + "]: " + e.toString()); } } } return buf.toString(); }
Code Sample 2:
protected long loadFromSource(long afterThisTime) { long startTime = System.currentTimeMillis(); QuoteDataSourceDescriptor quoteDataSourceDescriptor = (QuoteDataSourceDescriptor) dataSourceDescriptor; List<Quote> dataPool = dataPools.get(quoteDataSourceDescriptor.sourceSymbol); Calendar calendar = Calendar.getInstance(); calendar.clear(); SimpleDateFormat sdf = new SimpleDateFormat(quoteDataSourceDescriptor.dateFormat, Locale.US); Date fromDate = new Date(); Date toDate = new Date(); if (afterThisTime == FIRST_TIME_LOAD) { fromDate = quoteDataSourceDescriptor.fromDate; toDate = quoteDataSourceDescriptor.toDate; } else { calendar.setTimeInMillis(afterThisTime); fromDate = calendar.getTime(); } calendar.setTime(fromDate); int a = calendar.get(Calendar.MONTH); int b = calendar.get(Calendar.DAY_OF_MONTH); int c = calendar.get(Calendar.YEAR); calendar.setTime(toDate); int d = calendar.get(Calendar.MONTH); int e = calendar.get(Calendar.DAY_OF_MONTH); int f = calendar.get(Calendar.YEAR); BufferedReader dis; StringBuffer urlStr = new StringBuffer(); urlStr.append("http://table.finance.yahoo.com/table.csv").append("?s="); urlStr.append(quoteDataSourceDescriptor.sourceSymbol); urlStr.append("&a=" + a + "&b=" + b + "&c=" + c + "&d=" + d + "&e=" + e + "&f=" + f); urlStr.append("&g=d&ignore=.csv"); try { URL url = new URL(urlStr.toString()); System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(true); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(true); InputStreamReader isr = new InputStreamReader(conn.getInputStream()); dis = new BufferedReader(isr); String s = dis.readLine(); int iDateTime = 0; int iOpen = 1; int iHigh = 2; int iLow = 3; int iClose = 4; int iVolume = 5; int iAdjClose = 6; count = 0; calendar.clear(); while ((s = dis.readLine()) != null) { String[] items; items = s.split(","); if (items.length < 6) { break; } Date date = null; try { date = sdf.parse(items[iDateTime].trim()); } catch (ParseException ex) { ex.printStackTrace(); continue; } calendar.clear(); calendar.setTime(date); long time = calendar.getTimeInMillis(); if (time <= afterThisTime) { continue; } Quote quote = new Quote(); quote.time = time; quote.open = Float.parseFloat(items[iOpen].trim()); quote.high = Float.parseFloat(items[iHigh].trim()); quote.low = Float.parseFloat(items[iLow].trim()); quote.close = Float.parseFloat(items[iClose].trim()); quote.volume = Float.parseFloat(items[iVolume].trim()) / 100f; quote.amount = -1; quote.close_adj = Float.parseFloat(items[iAdjClose].trim()); if (quote.high * quote.low * quote.close == 0) { quote = null; continue; } dataPool.add(quote); if (count == 0) { firstTime = time; } lastTime = time; setAscending((lastTime >= firstTime) ? true : false); count++; } } catch (Exception ex) { System.out.println("Error in Reading File: " + ex.getMessage()); } long newestTime = (lastTime >= firstTime) ? lastTime : firstTime; return newestTime; } |
00
| Code Sample 1:
public List<SatelliteElementSet> parseTLE(String urlString) throws IOException { List<SatelliteElementSet> elementSets = new ArrayList<SatelliteElementSet>(); BufferedReader reader = null; try { String line = null; int i = 0; URL url = new URL(urlString); String[] lines = new String[3]; reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { i++; switch(i) { case 1: { lines[0] = line; break; } case 2: { lines[1] = line; break; } case 3: { lines[2] = line; Long catnum = Long.parseLong(StringUtils.strip(lines[1].substring(2, 7))); long setnum = Long.parseLong(StringUtils.strip(lines[1].substring(64, 68))); elementSets.add(new SatelliteElementSet(catnum, lines, setnum, Calendar.getInstance(TZ).getTime())); i = 0; break; } default: { throw new IOException("TLE string did not contain three elements"); } } } } finally { if (null != reader) { reader.close(); } } return elementSets; }
Code Sample 2:
private Response doLoad(URL url, URL referer, String postData) throws IOException { URLConnection connection = PROXY == null ? url.openConnection() : url.openConnection(PROXY); COOKIES.writeCookies(connection); connection.setRequestProperty("User-Agent", USER_AGENT); if (referer != null) { connection.setRequestProperty("Referer", referer.toString()); } if (postData != null) { connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("CONTENT_LENGTH", "" + postData.length()); OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(postData); osw.flush(); osw.close(); } connection.connect(); COOKIES.readCookies(connection); previouseUrl = url; return responceInstance(url, connection.getInputStream(), connection.getContentType()); } |
00
| Code Sample 1:
public static Vector getVectorForm(String u, String usr, String pwd) { Vector response = new Vector(); logger.debug("Attempting to call: " + u); logger.debug("Creating Authenticator: usr=" + usr + ", pwd=" + pwd); Authenticator.setDefault(new CustomAuthenticator(usr, pwd)); try { URL url = new URL(u); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { response.add(str); } in.close(); logger.debug("Response: " + response.toString()); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; }
Code Sample 2:
public TtsTrackImpl(URL url, String voiceName, VoicesCache vc) throws IOException { this.voiceCache = vc; isReady = false; URLConnection connection = url.openConnection(); frameSize = (int) (period * format.getChannels() * format.getSampleSizeInBits() * format.getSampleRate() / 8000); voice = voiceCache.allocateVoice(voiceName); TTSAudioBuffer audioBuffer = new TTSAudioBuffer(); this.voice.setAudioPlayer(audioBuffer); this.voice.speak(connection.getInputStream()); audioBuffer.flip(); } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); CompressionOutputStream out = codec.createOutputStream(System.out); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); }
Code Sample 2:
private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: destination file is unwriteable: " + toFileName); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
00
| Code Sample 1:
private InputStream getPart() throws IOException { HttpGet get = new HttpGet(url); get.addHeader("Range", "bytes=" + startAt + "-"); HttpResponse res = client.execute(get); System.out.println("requesting kBs from " + startAt + " server reply:" + res.getStatusLine()); if (res.getStatusLine().getStatusCode() == 403 || res.getStatusLine().toString().toLowerCase().contains("forbidden")) { get.abort(); get = new HttpGet(url); get.addHeader("Range", "bytes=" + startAt + "-" + (startAt + downLimit)); res = client.execute(get); System.out.println("Again requesting from kBs " + startAt + " server reply:" + res.getStatusLine()); startAt += downLimit; } else { complete = true; } return res.getEntity() == null ? null : res.getEntity().getContent(); }
Code Sample 2:
public boolean update(int idTorneo, torneo torneoModificado) { int intResult = 0; String sql = "UPDATE torneo " + "SET nombreTorneo = ?, ciudad = ?, fechaInicio = ?, fechaFinal = ?, " + " organizador = ? " + " WHERE idTorneo = " + idTorneo; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement2(torneoModificado); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } |
00
| Code Sample 1:
public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } }
Code Sample 2:
public GridDirectoryList(URL url) throws McIDASException { try { urlc = (AddeURLConnection) url.openConnection(); inputStream = new DataInputStream(new BufferedInputStream(urlc.getInputStream())); } catch (IOException e) { throw new McIDASException("Error opening URL for grids:" + e); } readDirectory(); } |
11
| Code Sample 1:
public static void copyFile(final FileInputStream in, final File out) throws IOException { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = null; try { fos = new FileOutputStream(destination); FileChannel sourceChannel = fis.getChannel(); FileChannel destinationChannel = fos.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); destinationChannel.close(); sourceChannel.close(); } finally { if (fos != null) fos.close(); fis.close(); } } |
11
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("D:/work/test.txt"); FileOutputStream fout = new FileOutputStream("D:/work/output.txt"); FileChannel inChannel = fin.getChannel(); FileChannel outChannel = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int ret = inChannel.read(buffer); if (ret == -1) break; buffer.flip(); outChannel.write(buffer); buffer.clear(); } } |
11
| Code Sample 1:
public static void writeToPetrify(TransitionSystem ts, Writer bw) throws IOException { File temp = new File("_temp"); BufferedWriter tw = new BufferedWriter(new FileWriter(temp)); BufferedReader tr = new BufferedReader(new FileReader(temp)); HashSet<ModelGraphVertex> sources = new HashSet<ModelGraphVertex>(); HashSet<ModelGraphVertex> dests = new HashSet<ModelGraphVertex>(); ArrayList transitions = ts.getEdges(); HashSet<String> events = new HashSet<String>(); for (int i = 0; i < transitions.size(); i++) { TransitionSystemEdge transition = (TransitionSystemEdge) transitions.get(i); events.add(replaceBadSymbols(transition.getIdentifier())); sources.add(transition.getSource()); dests.add(transition.getDest()); if (ts.getStateNameFlag() == TransitionSystem.ID) { tw.write("s" + transition.getSource().getId() + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write("s" + transition.getDest().getId() + "\n"); } else { tw.write(replaceBadSymbols(transition.getSource().getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getDest().getIdentifier()) + "\n"); } } tw.close(); bw.write(".model " + ts.getName().replaceAll(" ", "_") + "\n"); bw.write(".dummy "); Iterator it = events.iterator(); while (it.hasNext()) bw.write(it.next() + " "); bw.write("\n"); bw.write(".state graph" + "\n"); int c; while ((c = tr.read()) != -1) bw.write(c); tr.close(); temp.delete(); for (ModelGraphVertex dest : dests) { if (sources.contains(dest)) { sources.remove(dest); } } ModelGraphVertex source = sources.isEmpty() ? null : sources.iterator().next(); if (ts.getStateNameFlag() == TransitionSystem.ID) { if (!ts.hasExplicitEnd()) bw.write(".marking {s0}" + "\n"); else bw.write(".marking {s" + source.getId() + "}\n"); } else if (source != null) { bw.write(".marking {" + replaceBadSymbols(source.getIdentifier()) + "}\n"); } bw.write(".end"); }
Code Sample 2:
public void add(final String name, final String content) { forBundle(new BundleManipulator() { public boolean includeEntry(String entryName) { return !name.equals(entryName); } public void finish(Bundle bundle, ZipOutputStream zout) throws IOException { zout.putNextEntry(new ZipEntry(name)); IOUtils.copy(new StringReader(content), zout, "UTF-8"); } }); } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void main(String[] args) throws IOException { ReadableByteChannel in = Channels.newChannel((new FileInputStream("/home/sannies/suckerpunch-distantplanet_h1080p/suckerpunch-distantplanet_h1080p.mov"))); Movie movie = MovieCreator.build(in); in.close(); List<Track> tracks = movie.getTracks(); movie.setTracks(new LinkedList<Track>()); double startTime = 35.000; double endTime = 145.000; boolean timeCorrected = false; for (Track track : tracks) { if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) { if (timeCorrected) { throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported."); } startTime = correctTimeToNextSyncSample(track, startTime); endTime = correctTimeToNextSyncSample(track, endTime); timeCorrected = true; } } for (Track track : tracks) { long currentSample = 0; double currentTime = 0; long startSample = -1; long endSample = -1; for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) { TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i); for (int j = 0; j < entry.getCount(); j++) { if (currentTime <= startTime) { startSample = currentSample; } if (currentTime <= endTime) { endSample = currentSample; } else { break; } currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale(); currentSample++; } } movie.addTrack(new CroppedTrack(track, startSample, endSample)); } long start1 = System.currentTimeMillis(); IsoFile out = new DefaultMp4Builder().build(movie); long start2 = System.currentTimeMillis(); FileOutputStream fos = new FileOutputStream(String.format("output-%f-%f.mp4", startTime, endTime)); FileChannel fc = fos.getChannel(); out.getBox(fc); fc.close(); fos.close(); long start3 = System.currentTimeMillis(); System.err.println("Building IsoFile took : " + (start2 - start1) + "ms"); System.err.println("Writing IsoFile took : " + (start3 - start2) + "ms"); System.err.println("Writing IsoFile speed : " + (new File(String.format("output-%f-%f.mp4", startTime, endTime)).length() / (start3 - start2) / 1000) + "MB/s"); } |
00
| Code Sample 1:
public static XMLShowInfo NzbSearch(TVRageShowInfo tvrage, XMLShowInfo xmldata, int latestOrNext) { String newzbin_query = "", csvData = "", hellaQueueDir = "", newzbinUsr = "", newzbinPass = ""; String[] tmp; DateFormat tvRageDateFormat = new SimpleDateFormat("MMM/dd/yyyy"); DateFormat tvRageDateFormatFix = new SimpleDateFormat("yyyy-MM-dd"); newzbin_query = "?q=" + xmldata.showName + "+"; if (latestOrNext == 0) { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.latestSeasonNum + "x" + tvrage.latestEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.latestSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.latestAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.latestTitle; } else { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.nextSeasonNum + "x" + tvrage.nextEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.nextSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.nextAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.nextTitle; } newzbin_query += "&searchaction=Search"; newzbin_query += "&fpn=p"; newzbin_query += "&category=8category=11"; newzbin_query += "&area=-1"; newzbin_query += "&u_nfo_posts_only=0"; newzbin_query += "&u_url_posts_only=0"; newzbin_query += "&u_comment_posts_only=0"; newzbin_query += "&u_v3_retention=1209600"; newzbin_query += "&ps_rb_language=" + xmldata.language; newzbin_query += "&sort=ps_edit_date"; newzbin_query += "&order=desc"; newzbin_query += "&areadone=-1"; newzbin_query += "&feed=csv"; newzbin_query += "&ps_rb_video_format=" + xmldata.format; newzbin_query = newzbin_query.replaceAll(" ", "%20"); System.out.println("http://v3.newzbin.com/search/" + newzbin_query); try { URL url = new URL("http://v3.newzbin.com/search/" + newzbin_query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); csvData = in.readLine(); if (csvData != null) { JavaNZB.searchCount++; if (searchCount == 6) { searchCount = 0; System.out.println("Sleeping for 60 seconds"); try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } tmp = csvData.split(","); tmp[2] = tmp[2].substring(1, tmp[2].length() - 1); tmp[3] = tmp[3].substring(1, tmp[3].length() - 1); Pattern p = Pattern.compile("[\\\\</:>?\\[|\\]\"]"); Matcher matcher = p.matcher(tmp[3]); tmp[3] = matcher.replaceAll(" "); tmp[3] = tmp[3].replaceAll("&", "and"); URLConnection urlConn; DataOutputStream printout; url = new URL("http://v3.newzbin.com/api/dnzb/"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "username=" + JavaNZB.newzbinUsr + "&password=" + JavaNZB.newzbinPass + "&reportid=" + tmp[2]; printout.writeBytes(content); printout.flush(); printout.close(); BufferedReader nzbInput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String format = ""; if (xmldata.format.equals("17")) format = " Xvid"; if (xmldata.format.equals("131072")) format = " x264"; if (xmldata.format.equals("2")) format = " DVD"; if (xmldata.format.equals("4")) format = " SVCD"; if (xmldata.format.equals("8")) format = " VCD"; if (xmldata.format.equals("32")) format = " HDts"; if (xmldata.format.equals("64")) format = " WMV"; if (xmldata.format.equals("128")) format = " Other"; if (xmldata.format.equals("256")) format = " ratDVD"; if (xmldata.format.equals("512")) format = " iPod"; if (xmldata.format.equals("1024")) format = " PSP"; File f = new File(JavaNZB.hellaQueueDir, tmp[3] + format + ".nzb"); BufferedWriter out = new BufferedWriter(new FileWriter(f)); String str; System.out.println("--Downloading " + tmp[3] + format + ".nzb" + " to queue directory--"); while (null != ((str = nzbInput.readLine()))) out.write(str); nzbInput.close(); out.close(); if (latestOrNext == 0) { xmldata.episode = tvrage.latestEpisodeNum; xmldata.season = tvrage.latestSeasonNum; } else { xmldata.episode = tvrage.nextEpisodeNum; xmldata.season = tvrage.nextSeasonNum; } } else System.out.println("No new episode posted"); System.out.println(); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println("IO Exception from NzbSearch"); } return xmldata; }
Code Sample 2:
public static String encodePassword(String password, byte[] seed) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (seed == null) { seed = new byte[12]; secureRandom.nextBytes(seed); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(seed, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new sun.misc.BASE64Encoder().encode(storedPassword); } |
00
| Code Sample 1:
private static List retrieveQuotes(Report report, Symbol symbol, String prefix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, prefix, startDate, endDate); EODQuoteFilter filter = new GoogleEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("GOOGLE_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
private void handleInclude(Element elem) throws Exception { String source = getTextContent(elem); URL url = null; try { url = new URL(source); } catch (MalformedURLException e) { url = XmlConfig.class.getResource(source); } Document doc = db.parse(url.openStream()); handleDocument(doc); } |
11
| Code Sample 1:
public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("D:/work/test.txt"); FileOutputStream fout = new FileOutputStream("D:/work/output.txt"); FileChannel inChannel = fin.getChannel(); FileChannel outChannel = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int ret = inChannel.read(buffer); if (ret == -1) break; buffer.flip(); outChannel.write(buffer); buffer.clear(); } }
Code Sample 2:
public static void putNextJarEntry(JarOutputStream modelStream, String name, File file) throws IOException { JarEntry entry = new JarEntry(name); entry.setSize(file.length()); modelStream.putNextEntry(entry); InputStream fileStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(fileStream, modelStream); fileStream.close(); } |
11
| Code Sample 1:
private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } }
Code Sample 2:
private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
11
| Code Sample 1:
public static void copyFile(File source, File destination) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[4096]; int read = -1; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.flush(); out.close(); in.close(); }
Code Sample 2:
public static boolean copy(File source, File target) { try { if (!source.exists()) return false; target.getParentFile().mkdirs(); InputStream input = new FileInputStream(source); OutputStream output = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = input.read(buf)) > 0) output.write(buf, 0, len); input.close(); output.close(); return true; } catch (Exception exc) { exc.printStackTrace(); return false; } } |
00
| Code Sample 1:
private static long saveAndClosePDFDocument(PDDocument document, OutputStreamProvider outProvider) throws IOException, COSVisitorException { File tempFile = null; InputStream in = null; OutputStream out = null; try { tempFile = File.createTempFile("temp", "pdf"); OutputStream tempFileOut = new FileOutputStream(tempFile); tempFileOut = new BufferedOutputStream(tempFileOut); document.save(tempFileOut); document.close(); tempFileOut.close(); long length = tempFile.length(); in = new BufferedInputStream(new FileInputStream(tempFile)); out = new BufferedOutputStream(outProvider.getOutputStream()); IOUtils.copy(in, out); return length; } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } if (tempFile != null && !FileUtils.deleteQuietly(tempFile)) { tempFile.deleteOnExit(); } } }
Code Sample 2:
protected void invoke(String path, Object request, Callback<Object> callback) throws IOException, ClassNotFoundException { Assert.notNull(callback, "callback cant be null"); URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setDefaultUseCaches(false); connection.setRequestMethod("POST"); connection.connect(); try { ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream()); try { output.writeObject(request); output.flush(); } finally { output.close(); } ObjectInputStream input = new ObjectInputStream(connection.getInputStream()); try { for (; ; ) { Object result = input.readObject(); if (result == null) { break; } callback.onSuccess(result); } } finally { input.close(); } } finally { connection.disconnect(); } } |
00
| Code Sample 1:
private void loadHtmlHeader() { String skinUrl = getClass().getResource("/" + Properties.defaultSkinFileName).toString(); if (Properties.headerSkin != null && !Properties.headerSkin.equals("")) { try { URL url = new URL(Properties.headerSkin); if (url.getProtocol().equalsIgnoreCase("http")) { isHttpUrl = true; HttpURLConnection.setFollowRedirects(false); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("HEAD"); boolean urlExists = (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK); if (urlExists) skinUrl = Properties.headerSkin; } else if (url.getProtocol().equalsIgnoreCase("jar")) { String jarFile = Properties.headerSkin.substring(9).split("!")[0]; File skinFile = new File(jarFile); if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin; } else if (url.getProtocol().equalsIgnoreCase("file")) { File skinFile = new File(Properties.headerSkin.substring(5)); if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin; } else { File skinFile = new File(Properties.headerSkin); if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin; } } catch (Exception ex) { XohmLogger.debugPrintln("Header skin url not valid. " + ex.getMessage()); XohmLogger.debugPrintln("Loading the default skin."); ex.printStackTrace(); } } XohmLogger.debugPrintln("Header skin file = " + skinUrl); try { LocalHtmlRendererContext rendererContext = new LocalHtmlRendererContext(htmlHeaderPanel, new SimpleUserAgentContext()); rendererContext.navigate(skinUrl); headerLoaded = true; } catch (IOException urlEx) { XohmLogger.debugPrintln("Exception occured while loading the skin. " + urlEx.getMessage()); } }
Code Sample 2:
public static void copyFile(File input, File output) throws Exception { FileReader in = new FileReader(input); FileWriter out = new FileWriter(output); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
00
| Code Sample 1:
@Override protected String doWget(final URL url, final boolean post, final boolean ignore, final String... post_data) throws Exception { String msg = ""; InputStream in = null; OutputStream out = null; String data = null; try { final URLConnection urlcon = url.openConnection(); if (post) { boolean key = false; for (final String s : post_data) { msg += URLEncoder.encode(s, "UTF-8"); if (key = !key) { msg += "="; } else { msg += "&"; } } urlcon.setDoOutput(true); out = urlcon.getOutputStream(); out.write(msg.getBytes()); } in = urlcon.getInputStream(); data = ignore ? null : ""; int len; final byte[] buffer = new byte[1023]; while ((len = in.read(buffer)) >= 0) { if (!ignore) { data += new String(buffer, 0, len); } } if (LogHelper.isLogLevelEnabled(LogLevel.DEBUG, DefaultCommunicationHelper.class)) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "WGET= URL[" + url.toString() + "?" + msg + "] RETURN[" + data + "]"); } return data; } catch (final Exception ex) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.WARN, "An error occurred while submitting " + msg + " request to " + url.toString() + " with the following data: " + data, ex); throw ex; } finally { if (in != null) { try { in.close(); } catch (final Exception e) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "An error occurred while closing an input stream", e); } } if (out != null) { try { out.close(); } catch (final Exception e) { LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "An error occurred while closing an output stream", e); } } } }
Code Sample 2:
private static void copyFile(File src, File dst) throws IOException { FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } |
00
| Code Sample 1:
public static File downloadFile(Proxy proxy, URL url, File path) throws IOException { URLConnection conn = null; if (null == proxy) { conn = url.openConnection(); } else { conn = url.openConnection(proxy); } conn.connect(); File destFile = null; if (conn instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) conn; String filename = null; String hv = hc.getHeaderField("Content-Disposition"); if (null == hv) { String str = url.toString(); int index = str.lastIndexOf("/"); filename = str.substring(index + 1); } else { int index = hv.indexOf("filename="); filename = hv.substring(index).replace("\"", "").trim(); } destFile = new File(path, filename); } else { destFile = new File(path, "downloadfile" + url.toString().hashCode()); } if (destFile.exists()) { return destFile; } FileOutputStream fos = new FileOutputStream(destFile); byte[] buffer = new byte[2048]; try { while (true) { int len = conn.getInputStream().read(buffer); if (len < 0) { break; } else { fos.write(buffer, 0, len); } } fos.close(); } catch (IOException e) { destFile.delete(); throw e; } return destFile; }
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 void invoke(String args[]) { System.err.println("invoked with args of size " + args.length); try { for (int i = 0; i < args.length; i++) { System.err.println("processing URL: " + args[i]); URL url = new URL(args[i]); AnnotatedLinearObjectParser parserObj = findParserForURL(url); if (parserObj == null) { continue; } InputStream data = url.openStream(); CompMapViewerWrapper wrapper = ((CompMapViewerProvider) sp).getWrapper(); wrapper.parseIntoDataModel(data, new URLImpl(url.toString()), parserObj, false); JFrame f = wrapper.getViewer().getMainFrame(); f.show(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } |
11
| Code Sample 1:
public static String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException:" + e); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException:" + e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
private long config(final String options) throws SQLException { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } msgDigest.update(options.getBytes()); final String md5sum = Concrete.md5(msgDigest.digest()); Statement stmt = connection.createStatement(); ResultSet rst = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + md5sum + "'"); final long configId; if (rst.next()) { configId = rst.getInt(1); } else { stmt.executeUpdate("INSERT INTO configs(config, md5) VALUES ('" + options + "', '" + md5sum + "')"); ResultSet aiRst = stmt.getGeneratedKeys(); if (aiRst.next()) { configId = aiRst.getInt(1); } else { throw new SQLException("Could not retrieve generated id"); } } stmt.executeUpdate("UPDATE executions SET configId=" + configId + " WHERE executionId=" + executionId); return configId; } |
00
| Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5; StringBuilder sbValueBeforeHash = new StringBuilder(); try { md5 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new ApplicationIllegalArgumentException(e); } long time = System.nanoTime(); long rand = 0; if (secure) { rand = MySecureRand.nextLong(); } else { rand = MyRand.nextLong(); } sbValueBeforeHash.append(SId); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(time)); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(rand)); valueBeforeHash = sbValueBeforeHash.toString(); md5.update(valueBeforeHash.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterHash = sb.toString(); }
Code Sample 2:
public static Collection<Class<? extends Page>> loadPages() throws IOException { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Collection<Class<? extends Page>> pages = new ArrayList<Class<? extends Page>>(); Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName()); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); ; try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int comment = line.indexOf('#'); if (comment >= 0) line = line.substring(0, comment); String name = line.trim(); if (name.length() == 0) continue; Class<?> clz = Class.forName(name, true, ldr); Class<? extends Page> impl = clz.asSubclass(Page.class); pages.add(impl); } } catch (Exception ex) { System.out.println(ex); } finally { try { is.close(); } catch (Exception ex) { } } } return pages; } |
11
| Code Sample 1:
public void addFinance(int clubid, int quarterid, String date, String desc, String loc, BigDecimal amount) throws FinanceException, SQLException { String budgetQuery = "SELECT used, available FROM Budget WHERE club_id=" + clubid + " and quarter_id=" + quarterid + ";"; String financeUpdate = "INSERT INTO Finance (`club_id`, `transaction_date`, `description`, `location`, `amount`) VALUES ('" + clubid + "', '" + date + "', '" + desc + "', '" + "', '" + loc + "', '" + amount + "');"; Budget b = new Budget(); try { cn.setAutoCommit(false); Statement sm = cn.createStatement(); ResultSet rs = sm.executeQuery(budgetQuery); if (rs.first()) { b.used = rs.getBigDecimal(1); b.available = rs.getBigDecimal(2); } else { throw new FinanceException("No budget exists for this club!!"); } if (b.available.compareTo(amount.negate()) >= 0) { if (amount.equals(new BigDecimal(0))) ; { b.used = b.used.subtract(amount); } b.available = b.available.add(amount); sm = cn.createStatement(); sm.executeUpdate(financeUpdate); sm = cn.createStatement(); sm.executeUpdate("Update Budget SET used = " + b.used + ", amount = " + b.available + " WHERE club_id=" + clubid + " and quarter_id=" + quarterid + ";"); cn.commit(); } else { throw new FinanceException("The proposed expenditure is not within the club's budget."); } } catch (SQLException e) { cn.rollback(); throw e; } finally { cn.setAutoCommit(true); } }
Code Sample 2:
protected void onSubmit() { try { Connection conn = ((JdbcRequestCycle) getRequestCycle()).getConnection(); String sql = "insert into entry (author, accessibility) values(?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); pstmt.setInt(2, accessibility.getId()); pstmt.executeUpdate(); ResultSet insertedEntryIdRs = pstmt.getGeneratedKeys(); insertedEntryIdRs.next(); int insertedEntryId = insertedEntryIdRs.getInt(1); sql = "insert into revisions (title, entry, content, tags," + " revision_remark) values(?,?,?,?,?)"; PreparedStatement pstmt2 = conn.prepareStatement(sql); pstmt2.setString(1, getTitle()); pstmt2.setInt(2, insertedEntryId); pstmt2.setString(3, getContent()); pstmt2.setString(4, getTags()); pstmt2.setString(5, "newly added"); int insertCount = pstmt2.executeUpdate(); if (insertCount > 0) { info("Successfully added one new record."); } else { conn.rollback(); info("Addition of one new record failed."); } } catch (SQLException ex) { ex.printStackTrace(); } } |
00
| Code Sample 1:
public int update(BusinessObject o) throws DAOException { int update = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_CURRENCY")); pst.setString(1, curr.getName()); pst.setInt(2, curr.getIdBase()); pst.setDouble(3, curr.getValue()); pst.setInt(4, curr.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return update; }
Code Sample 2:
public static JuneClass loadClass(Map<String, Entity> globals, String packageName, String baseClassName) { try { JuneClass $class = null; String resourceName = (packageName.length() > 0 ? packageName.replace('.', '/') + "/" : "") + baseClassName.replace('.', '$') + ".class"; URL url = Resolver.class.getClassLoader().getResource(resourceName); if (url != null) { ClassBuilder builder = new ClassBuilder(globals); InputStream stream = url.openStream(); try { new ClassReader(new BufferedInputStream(stream)).accept(builder, ClassReader.SKIP_CODE); } finally { stream.close(); } $class = builder.$class; $class.loaded = true; } return $class; } catch (Exception e) { throw Helper.throwAny(e); } } |
11
| Code Sample 1:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
Code Sample 2:
@Override public void download(String remoteFilePath, String localFilePath) { InputStream remoteStream = null; try { remoteStream = client.get(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } OutputStream localStream = null; try { localStream = new FileOutputStream(new File(localFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { IOUtils.copy(remoteStream, localStream); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
private void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } }
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 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 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 String getWikiPage(String city) throws MalformedURLException, IOException, ParserConfigurationException, SAXException { String url = "http://api.geonames.org/wikipediaSearch?q=" + city + "&maxRows=1&lang=it&username=lorenzo.abram"; URLConnection conn = new URL(url).openConnection(); InputStream response = conn.getInputStream(); GeonamesHandler handler = new GeonamesHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(response, handler); return handler.getUrl(); }
Code Sample 2:
public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); } |
11
| Code Sample 1:
private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) { if ((organizationName == null) || (organizationName.equals(""))) { message = "invalid new_organization_name."; return false; } String tmpxml = TextUtil.xmlEscape(organizationName); String tmpdb = DBAccess.SQLEscape(organizationName); if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) { message = "invalid new_organization_name."; return false; } if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) { message = "invalid new_organization_name."; return false; } String[] orgnames = ServerConsoleServlet.getOrganizationNames(); for (int i = 0; i < orgnames.length; i++) { if (orgnames.equals(organizationName)) { message = "already exists."; return false; } } message = "create new organization: " + organizationName; File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName); if (!newOrganizationDirectory.mkdir()) { message = "cannot create directory."; return false; } File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName")); cacheDir.mkdir(); File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName")); confDir.mkdir(); File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName")); rdfDir.mkdir(); File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName")); resourceDir.mkdir(); File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete"); obsoleteDir.mkdir(); File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName")); schemaDir.mkdir(); String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate")); File templ = new File(organization_temp_dir); File[] confFiles = templ.listFiles(); for (int i = 0; i < confFiles.length; i++) { try { FileReader fr = new FileReader(confFiles[i]); FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName()); int c = -1; while ((c = fr.read()) != -1) fw.write(c); fw.flush(); fw.close(); fr.close(); } catch (IOException e) { } } SchemaModelHolder.reloadSchemaModel(organizationName); ResourceModelHolder.reloadResourceModel(organizationName); UserLogServlet.initializeUserLogDB(organizationName); MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username); ResourceModelHolder.reloadResourceModel(organizationName); message = organizationName + " is created. Restart Tomcat to activate this organization."; return true; }
Code Sample 2:
private void processHelpFile() { InputStream in = null; if (line.hasOption("helpfile")) { OutputStream out = null; try { String filename = line.getOptionValue("helpfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); baseProperties.setProperty("helpfile", filename); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return; } Properties props = new Properties(baseProperties); ClassLoader cl = this.getClass().getClassLoader(); Document doc = null; try { in = cl.getResourceAsStream(RESOURCE_PKG + "/help-doc.xml"); doc = XmlUtils.parse(in); } catch (XmlException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } transformResource(doc, "help-doc.xsl", props, "help-doc.html"); baseProperties.setProperty("helpfile", "help-doc.html"); } |
11
| Code Sample 1:
private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; }
Code Sample 2:
public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } } |
00
| Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public String Hash(String plain) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes(), 0, plain.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (Exception ex) { Log.serverlogger.warn("No such Hash algorithm", ex); return ""; } } |
11
| Code Sample 1:
public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) throws IOException { boolean resultat = false; FileInputStream fis = new FileInputStream(sRC2); FileOutputStream fos = new FileOutputStream(dEST2); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); progressEnCours.setValue(0); progressEnCours.setString(sRC2 + " : 0 %"); channelSrc.transferTo(0, channelSrc.size(), channelDest); progressEnCours.setValue(100); progressEnCours.setString(sRC2 + " : 100 %"); if (channelSrc.size() == channelDest.size()) { resultat = true; } else { resultat = false; } fis.close(); fos.close(); return (resultat); } |
00
| Code Sample 1:
public InputStream getEntry(String entryPath) throws IOException { if (!entries.contains(entryPath)) { return null; } JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (ze.getName().equals(entryPath)) { return jis; } } while (true); assert (false); return null; }
Code Sample 2:
@Override public long getLastModifiedOn() { try { final URLConnection uc = this.url.openConnection(); uc.connect(); final long res = uc.getLastModified(); try { uc.getInputStream().close(); } catch (final Exception ignore) { } return res; } catch (final IOException e) { return 0; } } |
00
| Code Sample 1:
public static String getURLContent(String urlStr) throws MalformedURLException, IOException { URL url = new URL(urlStr); log.info("url: " + url); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer buf = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } in.close(); return buf.toString(); }
Code Sample 2:
public void connect(String username, String passwordMd5) { this.username = username; this.passwordMd5 = passwordMd5; StringBuffer handshakeUrl = new StringBuffer(); handshakeUrl.append("http://ws.audioscrobbler.com/radio/handshake.php?version="); handshakeUrl.append(LastFM.VERSION); handshakeUrl.append("&platform=linux&username="); handshakeUrl.append(this.username); handshakeUrl.append("&passwordmd5="); handshakeUrl.append(this.passwordMd5); handshakeUrl.append("&language=en&player=aTunes"); URL url; try { url = new URL(handshakeUrl.toString()); URLConnection connection = url.openConnection(); InputStream inputStream = new BufferedInputStream(connection.getInputStream()); byte[] buffer = new byte[4069]; int read = 0; StringBuffer result = new StringBuffer(); while ((read = inputStream.read(buffer)) > -1) { result.append((new String(buffer, 0, read))); } String[] rows = result.toString().split("\n"); this.data = new HashMap<String, String>(); for (String row : rows) { row = row.trim(); int firstEquals = row.indexOf("="); data.put(row.substring(0, firstEquals), row.substring(firstEquals + 1)); } String streamingUrl = data.get("stream_url"); streamingUrl = streamingUrl.substring(7); int delimiter = streamingUrl.indexOf("/"); String hostname = streamingUrl.substring(0, delimiter); String path = streamingUrl.substring(delimiter + 1); String[] tokens = hostname.split(":"); hostname = tokens[0]; int port = Integer.parseInt(tokens[1]); this.lastFmSocket = new Socket(hostname, port); OutputStreamWriter osw = new OutputStreamWriter(this.lastFmSocket.getOutputStream()); osw.write("GET /" + path + " HTTP/1.0\r\n"); osw.write("Host: " + hostname + "\r\n"); osw.write("\r\n"); osw.flush(); this.lastFmInputStream = this.lastFmSocket.getInputStream(); result = new StringBuffer(); while ((read = this.lastFmInputStream.read(buffer)) > -1) { String line = new String(buffer, 0, read); result.append(line); if (line.contains("\r\n\r\n")) break; } String response = result.toString(); logger.info("Result: " + response); if (!response.startsWith("HTTP/1.0 200 OK")) { this.lastFmSocket.close(); throw new LastFmException("Could not handshake with lastfm. Check credential!"); } StringBuffer sb = new StringBuffer(); sb.append("http://"); sb.append(this.data.get("base_url")); sb.append(this.data.get("base_path")); sb.append("/xspf.php?sk="); sb.append(this.data.get("session")); sb.append("&discovery=1&desktop="); sb.append(LastFM.VERSION); logger.info(sb.toString()); this.playlistUrl = new URL(sb.toString()); this.playlist = this.playlistParser.fetchPlaylist(this.playlistUrl.toString()); Iterator<LastFmTrack> it = this.playlist.iterator(); while (it.hasNext()) { System.out.println(it.next().getCreator()); } this.connected = true; } catch (MalformedURLException e) { throw new LastFmException("Could not handshake with lastfm", e.getCause()); } catch (IOException e) { throw new LastFmException("Could not initialise lastfm", e.getCause()); } } |
11
| Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("Copy: no such source file: " + fromFileName); if (!fromFile.canRead()) throw new IOException("Copy: source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("Copy: destination file is unwriteable: " + toFileName); if (JOptionPane.showConfirmDialog(null, "Overwrite File ?", "Overwrite File", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("Copy: destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("Copy: destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("Copy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public void testRoundTrip_1(String resource) throws Exception { long start1 = System.currentTimeMillis(); File originalFile = File.createTempFile("RoundTripTest", "testRoundTrip_1"); FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(getClass().getResourceAsStream(resource), fos); fos.close(); long start2 = System.currentTimeMillis(); IsoFile isoFile = new IsoFile(new FileInputStream(originalFile).getChannel()); long start3 = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(baos); long start4 = System.currentTimeMillis(); Walk.through(isoFile); long start5 = System.currentTimeMillis(); isoFile.getBox(wbc); wbc.close(); long start6 = System.currentTimeMillis(); System.err.println("Preparing tmp copy took: " + (start2 - start1) + "ms"); System.err.println("Parsing took : " + (start3 - start2) + "ms"); System.err.println("Writing took : " + (start6 - start3) + "ms"); System.err.println("Walking took : " + (start5 - start4) + "ms"); byte[] a = IOUtils.toByteArray(getClass().getResourceAsStream(resource)); byte[] b = baos.toByteArray(); Assert.assertArrayEquals(a, b); }
Code Sample 2:
private String writeInputStreamToString(InputStream stream) { StringWriter stringWriter = new StringWriter(); try { IOUtils.copy(stream, stringWriter); } catch (IOException e) { e.printStackTrace(); } String namespaces = stringWriter.toString().trim(); return namespaces; } |
11
| Code Sample 1:
private static String calculateScenarioMD5(Scenario scenario) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); Vector<JTest> allTests = scenario.getTests(); for (JTest t : allTests) { String name = t.getTestName() + t.getTestId(); String parameters = ""; if (t instanceof RunnerTest) { parameters = ((RunnerTest) t).getPropertiesAsString(); } md.update(name.getBytes()); md.update(parameters.getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
Code Sample 2:
public static String mdFive(String string) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = new byte[32]; md.update(string.getBytes("iso-8859-1"), 0, string.length()); array = md.digest(); return convertToHex(array); } |
11
| Code Sample 1:
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } }
Code Sample 2:
public static void copy(File source, File dest) throws Exception { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
00
| Code Sample 1:
public InputStream getDaoConfig(String connectionType) throws IOException { URL url = null; InputStream inStream = null; if (connectionType.equals(SQL.ORACLE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("oracle.xml"); } else if (connectionType.equals(SQL.SQL2K)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("sql2k.xml"); } else if (connectionType.equals(SQL.CACHE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("cache.xml"); } else if (connectionType.equals(SQL.DB2)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("db2.xml"); } else { Categories.dataXml().error("* Problem: Unknown connection type: " + connectionType); } try { inStream = url.openStream(); } catch (NullPointerException npe) { Categories.dataXml().error("* Problem: Undefined resource URL: " + npe.getMessage()); throw npe; } return inStream; }
Code Sample 2:
public static byte[] sendRequestV1(String url, Map<String, Object> params, String secretCode, String method, Map<String, String> files, String encoding, String signMethod, Map<String, String> headers, String contentType) { HttpClient client = new HttpClient(); byte[] result = null; if (method.equalsIgnoreCase("get")) { GetMethod getMethod = new GetMethod(url); if (contentType == null || contentType.equals("")) getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); else getMethod.setRequestHeader("Content-Type", contentType); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); getMethod.setRequestHeader(key, headers.get(key)); } } try { NameValuePair[] getData; if (params != null) { if (secretCode == null) getData = new NameValuePair[params.size()]; else getData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); getData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature2(params, secretCode, "md5".equalsIgnoreCase(signMethod), isHMac, PARAMETER_SIGN); getData[i] = new NameValuePair(PARAMETER_SIGN, sign); } getMethod.setQueryString(getData); } client.executeMethod(getMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = getMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (bout != null) bout.close(); } } catch (Exception ex) { logger.error(ex, ex); } finally { if (getMethod != null) getMethod.releaseConnection(); } } if (method.equalsIgnoreCase("post")) { PostMethod postMethod = new PostMethod(url); if (headers != null && headers.size() > 0) { Iterator<String> keys = headers.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); postMethod.setRequestHeader(key, headers.get(key)); } } try { if (contentType == null) { if (files != null && files.size() > 0) { Part[] parts; if (secretCode == null) parts = new Part[params.size() + files.size()]; else parts = new Part[params.size() + 1 + files.size()]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); parts[i] = new StringPart(key, params.get(key).toString(), "UTF-8"); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); parts[i] = new StringPart(PARAMETER_SIGN, sign); i++; } iters = files.keySet().iterator(); while (iters.hasNext()) { String key = (String) iters.next(); if (files.get(key).toString().startsWith("http://")) { InputStream bin = null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { URL fileurl = new URL(files.get(key).toString()); bin = fileurl.openStream(); byte[] buf = new byte[500]; int count = 0; while ((count = bin.read(buf)) > 0) { bout.write(buf, 0, count); } parts[i] = new FilePart(key, new ByteArrayPartSource(fileurl.getFile().substring(fileurl.getFile().lastIndexOf("/") + 1), bout.toByteArray())); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bin != null) bin.close(); if (bout != null) bout.close(); } } else parts[i] = new FilePart(key, new File(files.get(key).toString())); i++; } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else { NameValuePair[] postData; if (params != null) { if (secretCode == null) postData = new NameValuePair[params.size()]; else postData = new NameValuePair[params.size() + 1]; Iterator<?> iters = params.keySet().iterator(); int i = 0; while (iters.hasNext()) { String key = (String) iters.next(); postData[i] = new NameValuePair(key, params.get(key).toString()); i++; } if (secretCode != null) { boolean isHMac = false; if (signMethod != null && signMethod.equalsIgnoreCase("hmac")) isHMac = true; String sign = EncryptUtil.signature(params, secretCode, isHMac, PARAMETER_SIGN); postData[i] = new NameValuePair(PARAMETER_SIGN, sign); } postMethod.setRequestBody(postData); } if (contentType == null || contentType.equals("")) postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); } } else { String content = (String) params.get(params.keySet().iterator().next()); RequestEntity entiry = new StringRequestEntity(content, contentType, "UTF-8"); postMethod.setRequestEntity(entiry); } client.executeMethod(postMethod); ByteArrayOutputStream bout = new ByteArrayOutputStream(); try { InputStream in = postMethod.getResponseBodyAsStream(); byte[] buf = new byte[500]; int count = 0; while ((count = in.read(buf)) > 0) { bout.write(buf, 0, count); } result = bout.toByteArray(); } catch (Exception ex) { logger.error(ex, ex); } finally { if (bout != null) bout.close(); } } catch (Exception e) { logger.error(e, e); } finally { if (postMethod != null) postMethod.releaseConnection(); } } return result; } |
11
| Code Sample 1:
public static void copyFile(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(); }
Code Sample 2:
private void copy(File source, File destination) { if (!destination.exists()) { destination.mkdir(); } File files[] = source.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { copy(files[i], new File(destination, files[i].getName())); } else { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(destination, files[i].getName())).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { log.error("Could not write to " + destination.getAbsolutePath(), ioe); } } } } } |
00
| Code Sample 1:
private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } if (!ftp.login(ftpUsername, ftpPassword)) { return null; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
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:
private InputStream getInputStream() throws URISyntaxException, MalformedURLException, IOException { InputStream inStream = null; try { URL url = new URI(wsdlFile).toURL(); URLConnection connection = url.openConnection(); connection.connect(); inStream = connection.getInputStream(); } catch (IllegalArgumentException ex) { inStream = new FileInputStream(wsdlFile); } return inStream; }
Code Sample 2:
private void copyFile(File sourcefile, File targetfile) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(sourcefile)); out = new BufferedOutputStream(new FileOutputStream(targetfile)); byte[] buffer = new byte[4096]; int bytesread = 0; while ((bytesread = in.read(buffer)) >= 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } |
00
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static int getUrl(final String s) { try { final URL url = new URL(s); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); int count = 0; String data = null; while ((data = reader.readLine()) != null) { System.out.printf("Results(%3d) of data: %s\n", count, data); ++count; } return count; } catch (Exception ex) { throw new RuntimeException(ex); } } |
00
| Code Sample 1:
private boolean getRemoteFiles() throws Exception { boolean resp = false; int respCode = 0; URL url = new URL(storageUrlString); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); RequestUtils requestUtils = new RequestUtils(); requestUtils.preRequestAddParameter("senderObj", "FileGetter"); requestUtils.preRequestAddParameter("wfiType", "zen"); requestUtils.preRequestAddParameter("portalID", this.portalID); requestUtils.preRequestAddParameter("userID", this.userID); addRenameFileParameters(requestUtils); requestUtils.createPostRequest(); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary()); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); try { httpURLConnection.connect(); OutputStream out = httpURLConnection.getOutputStream(); byte[] preBytes = requestUtils.getPreRequestStringBytes(); out.write(preBytes); out.flush(); byte[] postBytes = requestUtils.getPostRequestStringBytes(); out.write(postBytes); out.flush(); out.close(); respCode = httpURLConnection.getResponseCode(); if (HttpURLConnection.HTTP_OK == respCode) { resp = true; InputStream in = httpURLConnection.getInputStream(); ZipUtils.getInstance().getFilesFromStream(in, getFilesDir); in.close(); } if (respCode == 500) { resp = false; } if (respCode == 560) { resp = false; throw new Exception("Server Side Remote Exeption !!! respCode = (" + respCode + ")"); } } catch (Exception e) { e.printStackTrace(); throw new Exception("Cannot connect to: " + storageUrlString, e); } return resp; }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } |
11
| Code Sample 1:
public static void writeToFile(InputStream input, File file, ProgressListener listener, long length) { OutputStream output = null; try { output = new CountingOutputStream(new FileOutputStream(file), listener, length); IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
Code Sample 2:
public void process() { try { update("Shutdown knowledge base ...", 0); DBHelper.shutdownDB(); update("Shutdown knowledge base ...", 9); String zipDir = P.DIR.getPKBDataPath(); update("Backup in progress ...", 10); List<String> fileList = getFilesToZip(zipDir); File file = new File(fileName); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file)); byte[] readBuffer = new byte[2156]; int bytesIn = 0; for (int i = 0; i < fileList.size(); i++) { String filePath = fileList.get(i); File f = new File(filePath); FileInputStream fis = new FileInputStream(f); String zipEntryName = f.getPath().substring(zipDir.length() + 1); ZipEntry anEntry = new ZipEntry(zipEntryName); zout.putNextEntry(anEntry); while ((bytesIn = fis.read(readBuffer)) != -1) { zout.write(readBuffer, 0, bytesIn); } fis.close(); int percentage = (int) Math.round((i + 1) * 80.0 / fileList.size()); update("Backup in progress ...", 10 + percentage); } zout.close(); update("Restart knowledge base ...", 91); DBHelper.startDB(); update("Backup is done!", 100); } catch (Exception ex) { ex.printStackTrace(); update("Error occurs during backup!", 100); } } |
00
| Code Sample 1:
public Program updateProgramPath(int id, String sourcePath) throws AdaptationException { Program program = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE Programs SET " + "sourcePath = '" + sourcePath + "' " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from Programs WHERE id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program failed."; log.error(msg); throw new AdaptationException(msg); } program = getProgram(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramPath"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return program; }
Code Sample 2:
public String identify(String baseURL) throws OAIException { PrefixResolverDefault prefixResolver; XPath xpath; XPathContext xpathSupport; int ctxtNode; XObject list; Node node; boolean v2 = false; priCheckBaseURL(); try { URL url = new URL(baseURL + "?verb=Identify"); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); if (validation == VALIDATION_VERY_STRICT) { docFactory.setValidating(true); } else { docFactory.setValidating(false); } DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document xml = null; try { xml = docBuilder.parse(http.getInputStream()); } catch (IllegalArgumentException iae) { throw new OAIException(OAIException.CRITICAL_ERR, iae.getMessage()); } catch (SAXException se) { if (validation != VALIDATION_LOOSE) { throw new OAIException(OAIException.XML_PARSE_ERR, se.getMessage()); } else { try { url = new URL(baseURL + "?verb=Identify"); http.disconnect(); http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); xml = docBuilder.parse(priCreateDummyIdentify(http.getInputStream())); } catch (SAXException se2) { throw new OAIException(OAIException.XML_PARSE_ERR, se2.getMessage()); } } } try { descrNamespaceNode = xml.createElement("Identify"); descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI + "Identify"); descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID); descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR); prefixResolver = new PrefixResolverDefault(descrNamespaceNode); xpathSupport = new XPathContext(); ctxtNode = xpathSupport.getDTMHandleFromNode(xml); xpath = new XPath("/oai_id:Identify", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI_2_0); descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID_2_0); descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR); prefixResolver = new PrefixResolverDefault(descrNamespaceNode); xpath = new XPath("/oai_id:OAI-PMH", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI_1_0 + "Identify"); descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID_1_0); descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR_1_0); prefixResolver = new PrefixResolverDefault(descrNamespaceNode); } else { xpath = new XPath("oai_id:OAI-PMH/oai_id:error", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); ixmlErrors = list.nodelist(); if (getLastOAIErrorCount() > 0) { strProtocolVersion = "2"; throw new OAIException(OAIException.OAI_ERR, getLastOAIError().getCode() + ": " + getLastOAIError().getReason()); } v2 = true; } } xpath = new XPath("//oai_id:repositoryName", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strRepositoryName = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strRepositoryName = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing repositoryName"); } } xpath = new XPath("//oai_id:baseURL", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strBaseURL = node.getFirstChild().getNodeValue(); } else { if (validation != VALIDATION_LOOSE) { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing baseURL"); } } xpath = new XPath("//oai_id:protocolVersion", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strProtocolVersion = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strProtocolVersion = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing protocolVersion"); } } xpath = new XPath("//oai_id:adminEmail", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); NodeList nl = list.nodelist(); if (nl.getLength() > 0) { strAdminEmail = new String[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { strAdminEmail[i] = nl.item(i).getFirstChild().getNodeValue(); } } else { if (validation == VALIDATION_LOOSE) { strAdminEmail = new String[1]; strAdminEmail[0] = "mailto:UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing adminEmail"); } } if (v2) { xpath = new XPath("//oai_id:earliestDatestamp", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strEarliestDatestamp = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strEarliestDatestamp = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing earliestDatestamp"); } } xpath = new XPath("//oai_id:deletedRecord", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strDeletedRecord = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strDeletedRecord = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing deletedRecordp"); } } xpath = new XPath("//oai_id:granularity", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strGranularity = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strGranularity = "UNKNOWN"; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing granularity"); } } xpath = new XPath("//oai_id:compression", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); nl = list.nodelist(); if (nl.getLength() > 0) { strCompression = new String[nl.getLength()]; for (int i = 0; i < nl.getLength(); i++) { strCompression[i] = nl.item(i).getFirstChild().getNodeValue(); } } } xpath = new XPath("//oai_id:description", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); ixmlDescriptions = list.nodelist(); xpath = new XPath("//oai_id:responseDate", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strResponseDate = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strResponseDate = ""; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing responseDate"); } } xpath = new XPath("//oai_id:requestURL | //oai_id:request", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { ixmlRequest = node; } else { if (validation == VALIDATION_LOOSE) { ixmlRequest = null; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing requestURL"); } } state = STATE_IDENTIFIED; xpath = null; prefixResolver = null; xpathSupport = null; list = null; } catch (TransformerException te) { throw new OAIException(OAIException.CRITICAL_ERR, te.getMessage()); } url = null; docFactory = null; docBuilder = null; } catch (IOException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } catch (FactoryConfigurationError fce) { throw new OAIException(OAIException.CRITICAL_ERR, fce.getMessage()); } catch (ParserConfigurationException pce) { throw new OAIException(OAIException.CRITICAL_ERR, pce.getMessage()); } return strRepositoryName; } |
00
| Code Sample 1:
public JobOfferPage(JobPageLink link) { this.link = link; try { URL url = new URL(link.getUrl()); URLConnection urlConn = url.openConnection(); urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)"); urlConn.setRequestProperty("Accept-Language", "en-us"); this.content = (String) url.getContent(); } catch (IOException e) { e.printStackTrace(); } this.jobOfferHtmlList = extractJobOfferHtmlList(); }
Code Sample 2:
public static boolean copyFile(File src, File target) throws IOException { if (src == null || target == null || !src.exists()) return false; if (!target.exists()) if (!createNewFile(target)) return false; InputStream ins = new BufferedInputStream(new FileInputStream(src)); OutputStream ops = new BufferedOutputStream(new FileOutputStream(target)); int b; while (-1 != (b = ins.read())) ops.write(b); Streams.safeClose(ins); Streams.safeFlush(ops); Streams.safeClose(ops); return target.setLastModified(src.lastModified()); } |
00
| Code Sample 1:
@Override public JSONObject runCommand(JSONObject payload, HttpSession session) throws DefinedException { String sessionId = session.getId(); log.debug("Login -> runCommand SID: " + sessionId); JSONObject toReturn = new JSONObject(); boolean isOK = true; String username = null; try { username = payload.getString(ComConstants.LogIn.Request.USERNAME); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing username parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } String password = null; if (isOK) { try { password = payload.getString(ComConstants.LogIn.Request.PASSWORD); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing password parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } } if (isOK) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("SessionId=" + sessionId + ", MD5 algorithm does not exist", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } m.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, m.digest()).toString(16); UserSession userSession = pli.login(username, password); try { if (userSession != null) { session.setAttribute("user", userSession); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_OK.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_OK.getStatusMessage()); } else { log.error("SessionId=" + sessionId + ", Login failed: username=" + username + " not found"); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusMessage()); } } catch (JSONException e) { log.error("SessionId=" + sessionId + ", JSON exception occured in response", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } } log.debug("Login <- runCommand SID: " + sessionId); return toReturn; }
Code Sample 2:
@Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } if (status < 200 || status >= 400) return false; String url = this.url + "?title=Special:UserLogin&action=submitlogin&type=login&returnto=Main_Page&wpDomain=" + domain + "&wpLoginattempt=Log%20in&wpName=" + username + "&wpPassword=" + password; return true; } |
11
| Code Sample 1:
public String getRssFeedUrl(boolean searchWeb) { String rssFeedUrl = null; if (entity.getNewsFeedUrl() != null & !entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (entity.getUrl() == null || entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (searchWeb) { HttpURLConnection con = null; InputStream is = null; try { URL url = new URL(entity.getUrl()); con = (HttpURLConnection) url.openConnection(); con.connect(); is = con.getInputStream(); InputStreamReader sr = new InputStreamReader(is); BufferedReader br = new BufferedReader(sr); String ln; StringBuffer sb = new StringBuffer(); while ((ln = br.readLine()) != null) { sb.append(ln + "\n"); } rssFeedUrl = extractRssFeedUrl(sb.toString()); } catch (Exception e) { log.error(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(e); } } if (con != null) { con.disconnect(); } } } return rssFeedUrl; }
Code Sample 2:
private void getServiceReponse(String service, NameSpaceDefinition nsDefinition) throws Exception { Pattern pattern = Pattern.compile("(?i)(?:.*(xmlns(?:\\:\\w+)?=\\\"http\\:\\/\\/www\\.ivoa\\.net\\/.*" + service + "[^\\\"]*\\\").*)"); pattern = Pattern.compile(".*xmlns(?::\\w+)?=(\"[^\"]*(?i)(?:" + service + ")[^\"]*\").*"); logger.debug("read " + this.url + service); BufferedReader in = new BufferedReader(new InputStreamReader((new URL(this.url + service)).openStream())); String inputLine; BufferedWriter bfw = new BufferedWriter(new FileWriter(this.baseDirectory + service + ".xml")); boolean found = false; while ((inputLine = in.readLine()) != null) { if (!found) { Matcher m = pattern.matcher(inputLine); if (m.matches()) { nsDefinition.init("xmlns:vosi=" + m.group(1)); found = true; } } bfw.write(inputLine + "\n"); } in.close(); bfw.close(); } |
11
| Code Sample 1:
@Test public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) { } }
Code Sample 2:
public static void copyFile(String file1, String file2) { File filedata1 = new java.io.File(file1); if (filedata1.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file1)); try { int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); } catch (IOException ex1) { ex1.printStackTrace(); } finally { out.close(); in.close(); } } catch (Exception ex) { ex.printStackTrace(); } } } |
00
| Code Sample 1:
protected InputSource getInputSource(String pReferencingSystemId, String pURI) throws SAXException { URL url = null; if (pReferencingSystemId != null) { try { url = new URL(new URL(pReferencingSystemId), pURI); } catch (MalformedURLException e) { } if (url == null) { try { url = new File(new File(pReferencingSystemId).getParentFile(), pURI).toURL(); } catch (MalformedURLException e) { } } } if (url == null) { try { url = new URL(pURI); } catch (MalformedURLException e) { try { url = new File(pURI).toURL(); } catch (MalformedURLException f) { throw new SAXException("Failed to parse the URI " + pURI); } } } try { InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toString()); return isource; } catch (IOException e) { throw new SAXException("Failed to open the URL " + url, e); } }
Code Sample 2:
private void resolveFileDeclarations(Query query, Map<String, URL> sqlDeclarations) { Statement stmt = query.getStatement(); String fileDeclaration = stmt.getFile(); boolean hasFileDeclaration = fileDeclaration != null && !"".equals(fileDeclaration); if (hasFileDeclaration) { try { URL url = sqlDeclarations.get(stmt.getFile()); if (url != null) { URLConnection conn = url.openConnection(); InputStream input = conn.getInputStream(); String sqlDeclaration = StreamUtils.obtainStreamContents(input); stmt.setValue(sqlDeclaration); input.close(); } } catch (Exception e) { } } } |
11
| Code Sample 1:
public static final TreeSet<String> getValues(String baseurl, String rftId, String svcId) { TreeSet<String> values = new TreeSet<String>(); String[] fragments = rftId.split("/"); String e_repoUri = null; String e_svcId = null; try { e_repoUri = URLEncoder.encode(rftId, "UTF-8"); e_svcId = URLEncoder.encode(svcId, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("UnsupportedEncodingException resulted attempting to encode " + rftId); } String openurl = baseurl + "/" + fragments[2] + "/openurl-aDORe7" + "?rft_id=" + e_repoUri + "&svc_id=" + e_svcId + "&url_ver=Z39.88-2004"; log.info("Obtaining Content Values from: " + openurl); try { URL url = new URL(openurl); long s = System.currentTimeMillis(); URLConnection conn = url.openConnection(); int timeoutMs = 1000 * 60 * 30; conn.setConnectTimeout(timeoutMs); conn.setReadTimeout(timeoutMs); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); log.info("Query Time: " + (System.currentTimeMillis() - s) + "ms"); String line; while ((line = in.readLine()) != null) { values.add(line); } in.close(); } catch (Exception ex) { log.error("problem with openurl:" + openurl + ex.getMessage()); throw new RuntimeException(ex); } return values; }
Code Sample 2:
JSONResponse execute() throws ServerException, RtmApiException, IOException { HttpClient httpclient = new DefaultHttpClient(); URI uri; try { uri = new URI(this.request.getUrl()); HttpPost httppost = new HttpPost(uri); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(is))); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } return new JSONResponse(sb.toString()); } finally { is.close(); } } catch (URISyntaxException e) { throw new RtmApiException(e.getMessage()); } catch (ClientProtocolException e) { throw new RtmApiException(e.getMessage()); } } |
11
| Code Sample 1:
public static void main(String[] args) { String WTKdir = null; String sourceFile = null; String instrFile = null; String outFile = null; String jadFile = null; Manifest mnf; if (args.length == 0) { usage(); return; } int i = 0; while (i < args.length && args[i].startsWith("-")) { if (("-WTK".equals(args[i])) && (i < args.length - 1)) { i++; WTKdir = args[i]; } else if (("-source".equals(args[i])) && (i < args.length - 1)) { i++; sourceFile = args[i]; } else if (("-instr".equals(args[i])) && (i < args.length - 1)) { i++; instrFile = args[i]; } else if (("-o".equals(args[i])) && (i < args.length - 1)) { i++; outFile = args[i]; } else if (("-jad".equals(args[i])) && (i < args.length - 1)) { i++; jadFile = args[i]; } else { System.out.println("Error: Unrecognized option: " + args[i]); System.exit(0); } i++; } if (WTKdir == null || sourceFile == null || instrFile == null) { System.out.println("Error: Missing parameter!!!"); usage(); return; } if (outFile == null) outFile = sourceFile; FileInputStream fisJar; try { fisJar = new FileInputStream(sourceFile); } catch (FileNotFoundException e1) { System.out.println("Cannot find source jar file: " + sourceFile); e1.printStackTrace(); return; } FileOutputStream fosJar; File aux = null; try { aux = File.createTempFile("predef", "aux"); fosJar = new FileOutputStream(aux); } catch (IOException e1) { System.out.println("Cannot find temporary jar file: " + aux); e1.printStackTrace(); return; } JarFile instrJar = null; Enumeration en = null; File tempDir = null; try { instrJar = new JarFile(instrFile); en = instrJar.entries(); tempDir = File.createTempFile("jbtp", ""); tempDir.delete(); System.out.println("Create directory: " + tempDir.mkdirs()); tempDir.deleteOnExit(); } catch (IOException e) { System.out.println("Cannot open instrumented file: " + instrFile); e.printStackTrace(); return; } String[] wtklib = new java.io.File(WTKdir + File.separator + "lib").list(new OnlyJar()); String preverifyCmd = WTKdir + File.separator + "bin" + File.separator + "preverify -classpath " + WTKdir + File.separator + "lib" + File.separator + CLDC_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + MIDP_JAR + File.pathSeparator + WTKdir + File.separator + "lib" + File.separator + WMA_JAR + File.pathSeparator + instrFile; for (int k = 0; k < wtklib.length; k++) { preverifyCmd += File.pathSeparator + WTKdir + File.separator + "lib" + wtklib[k]; } preverifyCmd += " " + "-d " + tempDir.getAbsolutePath() + " "; while (en.hasMoreElements()) { JarEntry je = (JarEntry) en.nextElement(); String jeName = je.getName(); if (jeName.endsWith(".class")) jeName = jeName.substring(0, jeName.length() - 6); preverifyCmd += jeName + " "; } try { Process p = Runtime.getRuntime().exec(preverifyCmd); if (p.waitFor() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Error calling the preverify command."); while (in.ready()) { System.out.print("" + in.readLine()); } System.out.println(); in.close(); return; } } catch (Exception e) { System.out.println("Cannot execute preverify command"); e.printStackTrace(); return; } File[] listOfFiles = computeFiles(tempDir); System.out.println("-------------------------------\n" + "Files to insert: "); String[] strFiles = new String[listOfFiles.length]; int l = tempDir.toString().length() + 1; for (int j = 0; j < listOfFiles.length; j++) { strFiles[j] = listOfFiles[j].toString().substring(l); strFiles[j] = strFiles[j].replace(File.separatorChar, '/'); System.out.println(strFiles[j]); } System.out.println("-------------------------------"); try { JarInputStream jis = new JarInputStream(fisJar); mnf = jis.getManifest(); JarOutputStream jos = new JarOutputStream(fosJar, mnf); nextJar: for (JarEntry je = jis.getNextJarEntry(); je != null; je = jis.getNextJarEntry()) { String s = je.getName(); for (int k = 0; k < strFiles.length; k++) { if (strFiles[k].equals(s)) continue nextJar; } jos.putNextEntry(je); byte[] b = new byte[512]; for (int k = jis.read(b, 0, 512); k >= 0; k = jis.read(b, 0, 512)) { jos.write(b, 0, k); } } jis.close(); for (int j = 0; j < strFiles.length; j++) { FileInputStream fis = new FileInputStream(listOfFiles[j]); JarEntry je = new JarEntry(strFiles[j]); jos.putNextEntry(je); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); jos.write(b, 0, k); } fis.close(); } jos.close(); fisJar.close(); fosJar.close(); } catch (IOException e) { System.out.println("Cannot read/write jar file."); e.printStackTrace(); return; } try { FileOutputStream fos = new FileOutputStream(outFile); FileInputStream fis = new FileInputStream(aux); byte[] b = new byte[512]; while (fis.available() > 0) { int k = fis.read(b, 0, 512); fos.write(b, 0, k); } fis.close(); fos.close(); } catch (IOException e) { System.out.println("Cannot write output jar file: " + outFile); e.printStackTrace(); } Iterator it; Attributes atr; atr = mnf.getMainAttributes(); it = atr.keySet().iterator(); if (jadFile != null) { FileOutputStream fos; try { File outJarFile = new File(outFile); fos = new FileOutputStream(jadFile); PrintStream psjad = new PrintStream(fos); while (it.hasNext()) { Object ats = it.next(); psjad.println(ats + ": " + atr.get(ats)); } psjad.println("MIDlet-Jar-URL: " + outFile); psjad.println("MIDlet-Jar-Size: " + outJarFile.length()); fos.close(); } catch (IOException eio) { System.out.println("Cannot create jad file."); eio.printStackTrace(); } } }
Code Sample 2:
public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } } |
00
| Code Sample 1:
public final void saveAsCopy(String current_image, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; String source = temp_dir + key + current_image; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
Code Sample 2:
public void removeStadium(String name, String city) throws StadiumException { Connection conn = ConnectionManager.getManager().getConnection(); int id = findStadiumBy_N_C(name, city); if (id == -1) throw new StadiumException("No such stadium"); try { conn.setAutoCommit(false); PreparedStatement stm = conn.prepareStatement(Statements.SELECT_STAD_TRIBUNE); stm.setInt(1, id); ResultSet rs = stm.executeQuery(); TribuneLogic logic = TribuneLogic.getInstance(); while (rs.next()) { logic.removeTribune(rs.getInt("tribuneID")); } stm = conn.prepareStatement(Statements.DELETE_STADIUM); stm.setInt(1, id); stm.executeUpdate(); } catch (SQLException e) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } throw new StadiumException("Removing stadium failed", e); } try { conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
private Properties loadProperties(final String propertiesName) throws IOException { Properties bundle = null; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final URL url = loader.getResource(propertiesName); if (url == null) { throw new IOException("Properties file " + propertiesName + " not found"); } final InputStream is = url.openStream(); if (is != null) { bundle = new Properties(); bundle.load(is); } else { throw new IOException("Properties file " + propertiesName + " not avilable"); } return bundle; }
Code Sample 2:
private synchronized void createFTPConnection() throws FTPBrowseException { ftpClient = new FTPClient(); try { InetAddress inetAddress = InetAddress.getByName(url.getHost()); if (url.getPort() == -1) { ftpClient.connect(inetAddress); } else { ftpClient.connect(inetAddress, url.getPort()); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new FTPBrowseException(ftpClient.getReplyString()); } if (null != passwordAuthentication) { ftpClient.login(passwordAuthentication.getUserName(), new StringBuffer().append(passwordAuthentication.getPassword()).toString()); } if (url.getPath().length() > 0) { ftpClient.changeWorkingDirectory(url.getPath()); } homeDirectory = ftpClient.printWorkingDirectory(); } catch (UnknownHostException e) { throw new FTPBrowseException(e.getMessage()); } catch (SocketException e) { throw new FTPBrowseException(e.getMessage()); } catch (FTPBrowseException e) { throw e; } catch (IOException e) { throw new FTPBrowseException(e.getMessage()); } } |
00
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
protected void initializeGraphicalViewer() { getGraphicalViewer().setContents(loadModel()); getGraphicalViewer().addDropTargetListener(createTransferDropTargetListener()); getGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection().isEmpty()) { return; } loadProperties(((StructuredSelection) event.getSelection()).getFirstElement()); } }); } |
00
| Code Sample 1:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
Code Sample 2:
public void insertQuotation(final String sText, final Source aSource) throws ConfigHandlerError, com.sun.star.uno.Exception { final XTextDocument xTextDocument = (XTextDocument) this.docController.getXInterface(XTextDocument.class, this.docController.getXFrame().getController().getModel()); final XMultiServiceFactory xMultiServiceFactory = (XMultiServiceFactory) this.docController.getXInterface(XMultiServiceFactory.class, xTextDocument); final XText xText = xTextDocument.getText(); final XTextViewCursor xTextViewCursor = ((XTextViewCursorSupplier) this.docController.getXInterface(XTextViewCursorSupplier.class, this.docController.getXFrame().getController())).getViewCursor(); final XTextRange xTextRange = xTextViewCursor.getStart(); if (aSource.getSourceType() == SourceType.QUOTE || aSource.getSourceType() == SourceType.WEBQUOTE || aSource.getSourceType() == SourceType.WEBQUOTE) { final XPropertySet xQuoteProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xTextViewCursor); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String("Quotations")); } xQuoteProps.setPropertyValue("CharStyleName", new String("Citation")); final Object aBookmark = xMultiServiceFactory.createInstance("com.sun.star.text.Bookmark"); this.sourceUtils.setNameToObject(aBookmark, this.docController.getLanguageController().__("Quote: ") + aSource.getShortinfo()); final XTextContent xTextContent = (XTextContent) this.docController.getXInterface(XTextContent.class, aBookmark); xText.insertTextContent(xTextRange, xTextContent, false); this.sourceUtils.insertBibliographyEntry(xMultiServiceFactory, xTextRange, aSource, sText); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String(this.docController.getLanguageController().__("Default"))); } xQuoteProps.setPropertyValue("CharStyleName", new String(this.docController.getLanguageController().__("Default"))); } else if (aSource.getSourceType() == SourceType.IMAGE || aSource.getSourceType() == SourceType.TABLE) { xText.insertControlCharacter(xTextRange, ControlCharacter.PARAGRAPH_BREAK, false); final XTextFrame xFrame = this.sourceUtils.getTextFrame(aSource.getShortinfo(), xMultiServiceFactory); xText.insertTextContent(xTextRange, xFrame, false); final XText xFrameText = xFrame.getText(); final XTextCursor xFrameCursor = xFrameText.createTextCursor(); final Size aNewSize = new Size(); XPropertySet xBaseFrameProps = null; final Size aPageTextAreaSize = this.sourceUtils.getPageTextAreaSize(xTextDocument, xTextViewCursor); if (aSource.getSourceType() == SourceType.IMAGE) { try { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption illustration: ") + aSource.getShortinfo()); final XNameContainer xBitmapContainer = (XNameContainer) this.docController.getXInterface(XNameContainer.class, xMultiServiceFactory.createInstance("com.sun.star.drawing.BitmapTable")); final XTextContent xImage = (XTextContent) this.docController.getXInterface(XTextContent.class, xMultiServiceFactory.createInstance("com.sun.star.text.TextGraphicObject")); this.sourceUtils.setNameToObject(xImage, this.docController.getLanguageController().__("Illustration: ") + aSource.getShortinfo()); final String graphicURL = this.docController.getPathUtils().getFileURLFromSystemPath(((Image) aSource).getFile().getPath(), ((Image) aSource).getFile().getPath()); xBaseFrameProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xImage); xBaseFrameProps.setPropertyValue("AnchorType", com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH); xBaseFrameProps.setPropertyValue("GraphicURL", graphicURL); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(graphicURL.getBytes(), 0, graphicURL.length()); final String internalName = new BigInteger(1, md.digest()).toString(16); xBitmapContainer.insertByName(internalName, graphicURL); final String internalURL = (String) (xBitmapContainer.getByName(internalName)); xBaseFrameProps.setPropertyValue("GraphicURL", internalURL); float imageRatio = (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height / (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width; final Size aUsedAreaSize = new Size(this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width * 26, this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height * 26); if (aUsedAreaSize.Width >= aPageTextAreaSize.Width) { aNewSize.Width = aPageTextAreaSize.Width; aNewSize.Height = (int) (aPageTextAreaSize.Width * imageRatio); } else { aNewSize.Width = aUsedAreaSize.Width; aNewSize.Height = aUsedAreaSize.Height; } xFrameText.insertTextContent(xFrameCursor, xImage, false); xBitmapContainer.removeByName(internalName); } catch (final NoSuchAlgorithmException e) { new ASTError(e).severe(); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Illustration"), xMultiServiceFactory); } else if (aSource.getSourceType() == SourceType.TABLE) { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption table: ") + aSource.getShortinfo()); xBaseFrameProps = this.sourceUtils.createTextEmbeddedObjectCalc(xMultiServiceFactory); this.sourceUtils.setNameToObject(xBaseFrameProps, this.docController.getLanguageController().__("Table: ") + aSource.getShortinfo()); xFrameText.insertTextContent(xFrameCursor, (XTextContent) this.docController.getXInterface(XTextContent.class, xBaseFrameProps), false); final XEmbeddedObjectSupplier2 xEmbeddedObjectSupplier = (XEmbeddedObjectSupplier2) this.docController.getXInterface(XEmbeddedObjectSupplier2.class, xBaseFrameProps); final XEmbeddedObject xEmbeddedObject = xEmbeddedObjectSupplier.getExtendedControlOverEmbeddedObject(); long nAspect = xEmbeddedObjectSupplier.getAspect(); final Size aVisualAreaSize = xEmbeddedObject.getVisualAreaSize(nAspect); final XComponent xComponent = xEmbeddedObjectSupplier.getEmbeddedObject(); XSpreadsheets xSpreadsheets = ((XSpreadsheetDocument) this.docController.getXInterface(XSpreadsheetDocument.class, xComponent)).getSheets(); final XIndexAccess xIndexAccess = (XIndexAccess) this.docController.getXInterface(XIndexAccess.class, xSpreadsheets); final XSpreadsheet xSpreadsheet = (XSpreadsheet) this.docController.getXInterface(XSpreadsheet.class, xIndexAccess.getByIndex(0)); final XSheetLinkable xSheetLinkable = (XSheetLinkable) this.docController.getXInterface(XSheetLinkable.class, xSpreadsheet); xSheetLinkable.link(this.docController.getPathUtils().getFileURLFromSystemPath(((Table) aSource).getFile().getPath(), ((Table) aSource).getFile().getPath()), "", "", "", com.sun.star.sheet.SheetLinkMode.NORMAL); final CellRangeAddress aUsedArea = this.sourceUtils.getUsedArea(xSpreadsheet); final Size aUsedAreaSize = this.sourceUtils.calcCellRangeSize(xSpreadsheets, aUsedArea); if ((aUsedAreaSize.Width != aVisualAreaSize.Width) || (aUsedAreaSize.Height != aVisualAreaSize.Height)) { aNewSize.Height = (aUsedAreaSize.Height > aPageTextAreaSize.Height) ? aPageTextAreaSize.Height : aUsedAreaSize.Height; aNewSize.Width = (aUsedAreaSize.Width > aPageTextAreaSize.Width) ? aPageTextAreaSize.Width : aUsedAreaSize.Width; xEmbeddedObject.setVisualAreaSize(nAspect, aNewSize); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Table"), xMultiServiceFactory); } xBaseFrameProps.setPropertyValue("Width", aNewSize.Width); xBaseFrameProps.setPropertyValue("Height", aNewSize.Height); final XShape xShape = (XShape) this.docController.getXInterface(XShape.class, xFrame); xShape.setSize(aNewSize); } final XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier) this.docController.getXInterface(XTextFieldsSupplier.class, xMultiServiceFactory); final XRefreshable xRefreshable = (XRefreshable) this.docController.getXInterface(XRefreshable.class, xTextFieldsSupplier.getTextFields()); xRefreshable.refresh(); } |
11
| Code Sample 1:
public void setUp() { configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml"); getProject().executeTarget("setup"); tmpDir = getProject().getProperty("tmp.dir"); ftp = new FTPClient(); ftpFileSep = getProject().getProperty("ftp.filesep"); myFTPTask.setSeparator(ftpFileSep); myFTPTask.setProject(getProject()); remoteTmpDir = myFTPTask.resolveFile(tmpDir); String remoteHost = getProject().getProperty("ftp.host"); int port = Integer.parseInt(getProject().getProperty("ftp.port")); String remoteUser = getProject().getProperty("ftp.user"); String password = getProject().getProperty("ftp.password"); try { ftp.connect(remoteHost, port); } catch (Exception ex) { connectionSucceeded = false; loginSuceeded = false; System.out.println("could not connect to host " + remoteHost + " on port " + port); } if (connectionSucceeded) { try { ftp.login(remoteUser, password); } catch (IOException ioe) { loginSuceeded = false; System.out.println("could not log on to " + remoteHost + " as user " + remoteUser); } } }
Code Sample 2:
protected void entryMatched(EntryMonitor monitor, Entry entry) { FTPClient ftpClient = new FTPClient(); try { Resource resource = entry.getResource(); if (!resource.isFile()) { return; } if (server.length() == 0) { return; } String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false); ftpClient.connect(server); if (user.length() > 0) { ftpClient.login(user, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); monitor.handleError("FTP server refused connection:" + server, null); return; } ftpClient.setFileType(FTP.IMAGE_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (directory.length() > 0) { ftpClient.changeWorkingDirectory(directory); } String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate); InputStream is = new BufferedInputStream(monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath()))); boolean ok = ftpClient.storeUniqueFile(filename, is); is.close(); if (ok) { monitor.logInfo("Wrote file:" + directory + " " + filename); } else { monitor.handleError("Failed to write file:" + directory + " " + filename, null); } } catch (Exception exc) { monitor.handleError("Error posting to FTP:" + server, exc); } finally { try { ftpClient.logout(); } catch (Exception exc) { } try { ftpClient.disconnect(); } catch (Exception exc) { } } } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public void connect() throws SocketException, IOException { Log.i(TAG, "Test attempt login to " + ftpHostname + " as " + ftpUsername); ftpClient = new FTPClient(); ftpClient.connect(this.ftpHostname, this.ftpPort); ftpClient.login(ftpUsername, ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { String error = "Login failure (" + reply + ") : " + ftpClient.getReplyString(); Log.e(TAG, error); throw new IOException(error); } }
Code Sample 2:
private void initURL() { try { log.fine("Checking: " + locator); URLConnection conn = URIFactory.url(locator).openConnection(); conn.setUseCaches(false); log.info(conn.getHeaderFields().toString()); String header = conn.getHeaderField(null); if (header.contains("404")) { log.info("404 file not found: " + locator); return; } if (header.contains("500")) { log.info("500 server error: " + locator); return; } if (conn.getContentLength() > 0) { byte[] buffer = new byte[50]; conn.getInputStream().read(buffer); if (new String(buffer).trim().startsWith("<!DOCTYPE")) return; } else if (conn.getContentLength() == 0) { exists = true; return; } exists = true; length = conn.getContentLength(); } catch (Exception ioe) { System.err.println(ioe); } } |
00
| Code Sample 1:
public static String getWebContent(String remoteUrl) { StringBuffer sb = new StringBuffer(); try { java.net.URL url = new java.net.URL(remoteUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); } catch (Exception e) { logger.error("获取远程网址内容失败 - " + remoteUrl, e); } return sb.toString(); }
Code Sample 2:
public void openJadFile(URL url) { try { setStatusBar("Loading..."); jad.clear(); jad.load(url.openStream()); loadFromJad(url); } catch (FileNotFoundException ex) { System.err.println("Cannot found " + url.getPath()); } catch (NullPointerException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } catch (IllegalArgumentException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } catch (IOException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } } |
00
| Code Sample 1:
public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
private void triggerBuild(Properties props, String project, int rev) throws IOException { boolean doBld = Boolean.parseBoolean(props.getProperty(project + ".bld")); String url = props.getProperty(project + ".url"); if (!doBld || project == null || project.length() == 0) { System.out.println("BuildLauncher: Not configured to build '" + project + "'"); return; } else if (url == null) { throw new IOException("Tried to launch build for project '" + project + "' but " + project + ".url property is not defined!"); } SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); System.out.println(fmt.format(new Date()) + ": Triggering a build via: " + url); BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while (r.readLine() != null) ; System.out.println(fmt.format(new Date()) + ": Build triggered!"); LATEST_BUILD.put(project, rev); r.close(); System.out.println(fmt.format(new Date()) + ": triggerBuild() done!"); } |
11
| Code Sample 1:
public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } }
Code Sample 2:
public static File copyFile(File srcFile, File destFolder, FileCopyListener copyListener) { File dest = new File(destFolder, srcFile.getName()); try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; long totalSize = srcFile.length(); boolean canceled = false; if (copyListener == null) { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } } else { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); if (!copyListener.updateCheck(readLength, totalSize)) { canceled = true; break; } } } in.close(); out.close(); if (canceled) { dest.delete(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } |
11
| Code Sample 1:
PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
Code Sample 2:
private static void createNonCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { if (line.charAt(0) != ' ') { String[] spaceSplit = PerlHelp.split(line); if (spaceSplit[0].indexOf('_') < 0) { s.add(spaceSplit[0]); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "nonCompound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
private void createContents(final Shell shell) { Package currentPackage = Package.getPackage("org.sf.pkb.gui"); String author = currentPackage.getImplementationVendor(); String version = currentPackage.getImplementationVersion(); if (author == null || author.trim().length() == 0) { author = "Felton Fee"; } if (version != null && version.trim().length() > 0) { version = "V" + version; } else { version = ""; } FormData data = null; shell.setLayout(new FormLayout()); Label label1 = new Label(shell, SWT.NONE); label1.setImage(Resources.IMAGE_PKB); data = new FormData(); data.top = new FormAttachment(0, 20); data.left = new FormAttachment(0, 20); label1.setLayoutData(data); Label label2 = new Label(shell, SWT.NONE); label2.setText(PreferenceDialog.PKBProperty.DEFAULT_rebrand_application_title + " " + version); Font font = new Font(shell.getDisplay(), "Arial", 12, SWT.NONE); label2.setFont(font); data = new FormData(); data.top = new FormAttachment(0, 25); data.left = new FormAttachment(label1, 15); data.right = new FormAttachment(100, -25); label2.setLayoutData(data); CustomSeparator separator1 = new CustomSeparator(shell, SWT.SHADOW_IN | SWT.HORIZONTAL); data = new FormData(); data.top = new FormAttachment(label2, 20); data.left = new FormAttachment(0, 0); data.right = new FormAttachment(100, 0); separator1.setLayoutData(data); Label label3 = new Label(shell, SWT.NONE); label3.setText("Written by " + author + " <"); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(0, 15); label3.setLayoutData(data); Hyperlink link = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS); link.setText(PKBMain.CONTACT_EMAIL); link.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { Program.launch("mailto:" + PKBMain.CONTACT_EMAIL + "?subject=[" + PKBMain.PRODUCT_ALEX_PKB + "]"); } }); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(label3, 2); link.setLayoutData(data); Label label4 = new Label(shell, SWT.NONE); label4.setText(">"); data = new FormData(); data.top = new FormAttachment(separator1, 10); data.left = new FormAttachment(link, 2); data.right = new FormAttachment(100, -20); label4.setLayoutData(data); Label label6 = new Label(shell, SWT.NONE); label6.setText("Web site:"); data = new FormData(); data.top = new FormAttachment(label4, 10); data.left = new FormAttachment(0, 15); label6.setLayoutData(data); Hyperlink link1 = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS); link1.setText(PKBMain.PRODUCT_WEBSITE); link1.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { Program.launch(PKBMain.PRODUCT_WEBSITE); } }); data = new FormData(); data.top = new FormAttachment(label4, 10); data.left = new FormAttachment(label6, 2); link1.setLayoutData(data); Button closeBtn = new Button(shell, SWT.PUSH); closeBtn.setText("Close"); closeBtn.setLayoutData(data); closeBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { shell.close(); } }); data = new FormData(); data.top = new FormAttachment(label6, 10); data.right = new FormAttachment(100, -20); data.bottom = new FormAttachment(100, -10); closeBtn.setLayoutData(data); Button checkVersionBtn = new Button(shell, SWT.PUSH); checkVersionBtn.setText("Check version"); checkVersionBtn.setLayoutData(data); checkVersionBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { try { URL url = new URL(PKBMain.PRODUCT_WEBSITE + "/latest-version.txt"); Properties prop = new Properties(); prop.load(url.openStream()); Package currentPackage = Package.getPackage("org.sf.pkb.gui"); String version = currentPackage.getImplementationVersion(); if (version == null) { version = ""; } String remoteVersion = prop.getProperty("version") + " b" + prop.getProperty("build"); if (remoteVersion.trim().compareTo(version.trim()) != 0) { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You do not have the latest version. <br/> ").append("The latest version is PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3><A HREF='").append(prop.getProperty("url")).append("' TARGET='_BLANK'>Please download here </a> <br/><br/>").append("<B>It is strongly suggested to backup your knowledge base before install or unzip the new package!</B>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } else { StringBuffer buf = new StringBuffer(); buf.append("<HTML><BODY>").append("<h3 style='color: #0033FF'>You already had the latest version - ALEX PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".</h3>").append("</BODY></HTML>"); MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString()); } } catch (Exception ex) { ex.printStackTrace(); } shell.close(); } }); data = new FormData(); data.top = new FormAttachment(label6, 10); data.right = new FormAttachment(closeBtn, -5); data.bottom = new FormAttachment(100, -10); checkVersionBtn.setLayoutData(data); shell.setDefaultButton(closeBtn); }
Code Sample 2:
public ProgramProfilingSymbol deleteProfilingSymbol(int id) throws AdaptationException { ProgramProfilingSymbol profilingSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramProfilingSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program profiling " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } profilingSymbol = getProfilingSymbol(resultSet); query = "DELETE FROM ProgramProfilingSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProfilingSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return profilingSymbol; } |
11
| Code Sample 1:
public static void main(String[] args) { FTPClient client = new FTPClient(); String sFTP = "ftp.servidor.com"; String sUser = "usuario"; String sPassword = "pasword"; try { System.out.println("Conectandose a " + sFTP); client.connect(sFTP); client.login(sUser, sPassword); System.out.println(client.printWorkingDirectory()); client.changeWorkingDirectory("\\httpdocs"); System.out.println(client.printWorkingDirectory()); System.out.println("Desconectando."); client.logout(); client.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public static FTPClient getFtpClient(TopAnalysisConfig topAnalyzerConfig) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.connect(topAnalyzerConfig.getFtpServer()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new java.lang.RuntimeException("PullFileJobWorker connect ftp error!"); } if (!ftp.login(topAnalyzerConfig.getFtpUserName(), topAnalyzerConfig.getFtpPassWord())) { ftp.logout(); throw new java.lang.RuntimeException("PullFileJobWorker login ftp error!"); } logger.info("Remote system is " + ftp.getSystemName()); ftp.setFileType(FTP.BINARY_FILE_TYPE); if (topAnalyzerConfig.isLocalPassiveMode()) ftp.enterLocalPassiveMode(); return ftp; } |
11
| Code Sample 1:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
Code Sample 2:
public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); } |
11
| Code Sample 1:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static File jar(File in, String outArc, File tempDir, PatchConfigXML conf) { FileOutputStream arcFile = null; JarOutputStream jout = null; DirectoryScanner ds = null; ds = new DirectoryScanner(); ds.setCaseSensitive(true); ds.setBasedir(in); ds.scan(); ds.setCaseSensitive(true); String[] names = ds.getIncludedFiles(); ArrayList exName = new ArrayList(); if (names == null || names.length < 1) return null; File tempArc = new File(tempDir, outArc.substring(0, outArc.length())); try { Manifest mf = null; List v = new ArrayList(); for (int i = 0; i < names.length; i++) { if (names[i].toUpperCase().indexOf("MANIFEST.MF") > -1) { FileInputStream fis = new FileInputStream(in.getAbsolutePath() + "/" + names[i].replace('\\', '/')); mf = new Manifest(fis); } else v.add(names[i]); } String[] toJar = new String[v.size()]; v.toArray(toJar); tempArc.createNewFile(); arcFile = new FileOutputStream(tempArc); if (mf == null) jout = new JarOutputStream(arcFile); else jout = new JarOutputStream(arcFile, mf); byte[] buffer = new byte[1024]; for (int i = 0; i < toJar.length; i++) { if (conf != null) { if (!conf.allowFileAction(toJar[i], PatchConfigXML.OP_CREATE)) { exName.add(toJar[i]); continue; } } String currentPath = in.getAbsolutePath() + "/" + toJar[i]; String entryName = toJar[i].replace('\\', '/'); JarEntry currentEntry = new JarEntry(entryName); jout.putNextEntry(currentEntry); FileInputStream fis = new FileInputStream(currentPath); int len; while ((len = fis.read(buffer)) >= 0) jout.write(buffer, 0, len); fis.close(); jout.closeEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { jout.close(); arcFile.close(); } catch (IOException e1) { throw new RuntimeException(e1); } } return tempArc; } |
00
| Code Sample 1:
public void viewFile(int file_nx) { FTPClient ftp = new FTPClient(); boolean error = false; try { int reply; ftp.connect("tgftp.nws.noaa.gov"); ftp.login("anonymous", ""); Log.d("WXDroid", "Connected to tgftp.nws.noaa.gov."); Log.d("WXDroid", ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ftp.changeWorkingDirectory("fax"); Log.d("WXDroid", "working directory: " + ftp.printWorkingDirectory()); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); InputStream img_file = ftp.retrieveFileStream("PYAA10.gif"); String storage_state = Environment.getExternalStorageState(); if (storage_state.contains("mounted")) { String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/NOAAWX/"; File imageDirectory = new File(filepath); File local_file = new File(filepath + "PYAA10.gif"); OutputStream out = new FileOutputStream(local_file); byte[] buffer = new byte[1024]; int count; while ((count = img_file.read(buffer)) != -1) { if (Thread.interrupted() == true) { String functionName = Thread.currentThread().getStackTrace()[2].getMethodName() + "()"; throw new InterruptedException("The function " + functionName + " was interrupted."); } out.write(buffer, 0, count); } wxDroid.showImage(); out.flush(); out.close(); img_file.close(); Log.d("WXDroid", "file saved: " + filepath + " " + local_file); } else { Log.d("WXDroid", "The SD card is not mounted"); } ftp.logout(); ftp.disconnect(); } catch (IOException e) { error = true; e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException, IllegalArgumentException { if (src.isDirectory()) throw new IllegalArgumentException("Source file is a directory"); if (dest.isDirectory()) throw new IllegalArgumentException("Destination file is a directory"); int bufferSize = 4 * 1024; InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); } |
00
| Code Sample 1:
public String getProxy(String userName, String password) throws Exception { URL url = new URL(httpURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream()); outputToServlet.writeObject(userName); outputToServlet.writeObject(password); outputToServlet.flush(); outputToServlet.close(); ObjectInputStream inputFromServlet = new ObjectInputStream(conn.getInputStream()); return inputFromServlet.readObject() + ""; }
Code Sample 2:
private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; } |
11
| Code Sample 1:
public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
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:
private String searchMetabolite(String name) { { BufferedReader in = null; try { String urlName = name; URL url = new URL(urlName); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; Boolean isMetabolite = false; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("Metabolite</h1>")) { isMetabolite = true; } if (inputLine.contains("<td><a href=\"/Metabolites/") && isMetabolite) { String metName = inputLine.substring(inputLine.indexOf("/Metabolites/") + 13, inputLine.indexOf("aspx\" target") + 4); return "http://gmd.mpimp-golm.mpg.de/Metabolites/" + metName; } } in.close(); return name; } catch (IOException ex) { Logger.getLogger(GetGolmIDsTask.class.getName()).log(Level.SEVERE, null, ex); return null; } } }
Code Sample 2:
private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private 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 static void main(String[] args) { try { File fichierXSD = new File("D:/Users/Balley/données/gml/commune.xsd"); URL urlFichierXSD = fichierXSD.toURI().toURL(); InputStream isXSD = urlFichierXSD.openStream(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document documentXSD = (builder.parse(isXSD)); ChargeurGMLSchema chargeur = new ChargeurGMLSchema(documentXSD); SchemaConceptuelJeu sc = chargeur.gmlSchema2schemaConceptuel(documentXSD); System.out.println(sc.getFeatureTypes().size()); for (int i = 0; i < sc.getFeatureTypes().size(); i++) { System.out.println(sc.getFeatureTypes().get(i).getTypeName()); for (int j = 0; j < sc.getFeatureTypes().get(i).getFeatureAttributes().size(); j++) { System.out.println(" " + sc.getFeatureTypes().get(i).getFeatureAttributes().get(j).getMemberName() + " : " + sc.getFeatureTypes().get(i).getFeatureAttributes().get(j).getValueType()); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } }
Code Sample 2:
private void album(String albumTitle, String albumNbSong, URL url) { try { if (color == SWT.COLOR_WHITE) { color = SWT.COLOR_GRAY; } else { color = SWT.COLOR_WHITE; } url.openConnection(); InputStream is = url.openStream(); Image coverPicture = new Image(this.getDisplay(), is); Composite albumComposite = new Composite(main, SWT.NONE); albumComposite.setLayout(new FormLayout()); FormData data = new FormData(); data.left = new FormAttachment(0, 5); data.right = new FormAttachment(100, -5); if (prevCompo == null) { data.top = new FormAttachment(0, 0); } else { data.top = new FormAttachment(prevCompo, 0, SWT.BOTTOM); } albumComposite.setLayoutData(data); albumComposite.setBackground(Display.getDefault().getSystemColor(color)); Label cover = new Label(albumComposite, SWT.LEFT); cover.setText("cover"); cover.setImage(coverPicture); data = new FormData(75, 75); cover.setLayoutData(data); Label title = new Label(albumComposite, SWT.CENTER); title.setFont(new Font(this.getDisplay(), "Arial", 10, SWT.BOLD)); title.setText(albumTitle); data = new FormData(); data.bottom = new FormAttachment(50, -5); data.left = new FormAttachment(cover, 5); title.setBackground(Display.getDefault().getSystemColor(color)); title.setLayoutData(data); Label nbSong = new Label(albumComposite, SWT.LEFT | SWT.BOLD); nbSong.setFont(new Font(this.getDisplay(), "Arial", 8, SWT.ITALIC)); nbSong.setText("Release date : " + albumNbSong); data = new FormData(); data.top = new FormAttachment(50, 5); data.left = new FormAttachment(cover, 5); nbSong.setBackground(Display.getDefault().getSystemColor(color)); nbSong.setLayoutData(data); prevCompo = albumComposite; } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } }
Code Sample 2:
protected static String getFileContentAsString(URL url, String encoding) throws IOException { InputStream input = null; StringWriter sw = new StringWriter(); try { System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); input = url.openStream(); IOUtils.copy(input, sw, encoding); System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } finally { if (input != null) { input.close(); System.gc(); input = null; System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } } return sw.toString(); } |
00
| Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
public void read() throws LogicException { try { File file = new File(filename); URL url = file.toURI().toURL(); source = new Source(url.openConnection()); } catch (Exception e) { throw new LogicException("Failed to read " + filename + " !", e); } ArrayList<Segment> segments = new ArrayList<Segment>(); List<Element> elements = source.getChildElements(); for (Element element : elements) { Segment segment = element.getContent(); Iterator<Segment> iterator = segment.getNodeIterator(); while (iterator.hasNext()) { Segment current = iterator.next(); if (isPlainText(current)) { segments.add(current); } } } texts.clear(); sentences.clear(); for (int i = 0; i < segments.size(); i++) { ArrayList<Segment> group = new ArrayList<Segment>(); group.add(segments.get(i)); while (i < (segments.size() - 1) && segments.get(i).getEnd() == segments.get(i + 1).getBegin()) { group.add(segments.get(i + 1)); i++; } texts.add(new Text(group, tokenizer)); } ArrayList<Token> tokens = new ArrayList<Token>(); for (Text text : texts) { tokens.addAll(text.getTokens()); } sentences = tokenizer.toSentences(tokens); } |
11
| Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } }
Code Sample 2:
public void create(File target) { if ("dir".equals(type)) { File dir = new File(target, name); dir.mkdirs(); for (Resource c : children) { c.create(dir); } } else if ("package".equals(type)) { String[] dirs = name.split("\\."); File parent = target; for (String d : dirs) { parent = new File(parent, d); } parent.mkdirs(); for (Resource c : children) { c.create(parent); } } else if ("file".equals(type)) { InputStream is = getInputStream(); File file = new File(target, name); try { if (is != null) { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); fos.flush(); fos.close(); } else { PrintStream ps = new PrintStream(file); ps.print(content); ps.flush(); ps.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if ("zip".equals(type)) { try { unzip(target); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException("unknown resource type: " + type); } } |
00
| Code Sample 1:
public Program updateProgramPath(int id, String sourcePath) throws AdaptationException { Program program = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE Programs SET " + "sourcePath = '" + sourcePath + "' " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from Programs WHERE id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program failed."; log.error(msg); throw new AdaptationException(msg); } program = getProgram(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramPath"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return program; }
Code Sample 2:
public TreeMap getStrainMap() { TreeMap strainMap = new TreeMap(); String server = ""; try { Datasource[] ds = DatasourceManager.getDatasouce(alias, version, DatasourceManager.ALL_CONTAINS_GROUP); for (int i = 0; i < ds.length; i++) { if (ds[i].getDescription().startsWith(MOUSE_DBSNP)) { if (ds[i].getServer().length() == 0) { Connection con = ds[i].getConnection(); strainMap = Action.lineMode.regularSQL.GenotypeDataSearchAction.getStrainMap(con); break; } else { server = ds[i].getServer(); HashMap serverUrlMap = InitXml.getInstance().getServerMap(); String serverUrl = (String) serverUrlMap.get(server); URL url = new URL(serverUrl + servletName); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("viewType=getstrains"); buf.append("&hHead=" + hHead); buf.append("&hCheck=" + version); PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); strainMap = (TreeMap) ois.readObject(); ois.close(); } } } } catch (Exception e) { log.error("strain map", e); } return strainMap; } |
00
| Code Sample 1:
public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } }
Code Sample 2:
public RegionInfo(String name, int databaseID, int units, float xMin, float xMax, float yMin, float yMax, float zMin, float zMax, String imageURL) { this.name = name; this.databaseID = databaseID; this.units = units; this.xMin = xMin; this.xMax = xMax; this.yMin = yMin; this.yMax = yMax; this.zMin = zMin; this.zMax = zMax; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(this.name.getBytes()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos); daos.writeInt(this.databaseID); daos.writeInt(this.units); daos.writeDouble(this.xMin); daos.writeDouble(this.xMax); daos.writeDouble(this.yMin); daos.writeDouble(this.yMax); daos.writeDouble(this.zMin); daos.writeDouble(this.zMax); daos.flush(); byte[] hashValue = digest.digest(baos.toByteArray()); int hashCode = 0; for (int i = 0; i < hashValue.length; i++) { hashCode += (int) hashValue[i] << (i % 4); } this.hashcode = hashCode; } catch (Exception e) { throw new IllegalArgumentException("Error occurred while generating hashcode for region " + this.name); } if (imageURL != null) { URL url = null; try { url = new URL(imageURL); } catch (MalformedURLException murle) { } if (url != null) { BufferedImage tmpImage = null; try { tmpImage = ImageIO.read(url); } catch (Exception e) { e.printStackTrace(); } mapImage = tmpImage; } else this.mapImage = null; } else this.mapImage = null; } |
11
| Code Sample 1:
public void uploadFile(ActionEvent event) throws IOException { InputFile inputFile = (InputFile) event.getSource(); synchronized (inputFile) { ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); String fileNewPath = arrangeUplodedFilePath(context.getRealPath(""), inputFile.getFile().getName()); File file = new File(fileNewPath); System.out.println(fileNewPath); DataInputStream inStream = new DataInputStream(new FileInputStream(inputFile.getFile())); DataOutputStream outStream = new DataOutputStream(new FileOutputStream(file)); int i = 0; byte[] buffer = new byte[512]; while ((i = inStream.read(buffer, 0, 512)) != -1) outStream.write(buffer, 0, i); } }
Code Sample 2:
public static final void zip(final ZipOutputStream out, final File f, String base) throws Exception { if (f.isDirectory()) { final File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (final File element : fl) { zip(out, element, base + element.getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); final FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); } |
11
| Code Sample 1:
public static void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } } |
11
| Code Sample 1:
public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
Code Sample 2:
public void run() { Vector<Update> updates = new Vector<Update>(); if (dic != null) updates.add(dic); if (gen != null) updates.add(gen); if (res != null) updates.add(res); if (help != null) updates.add(help); for (Iterator iterator = updates.iterator(); iterator.hasNext(); ) { Update update = (Update) iterator.next(); try { File temp = File.createTempFile("fm_" + update.getType(), ".jar"); temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); URL url = new URL(update.getAction()); URLConnection conn = url.openConnection(); com.diccionarioderimas.Utils.setupProxy(conn); InputStream in = conn.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; int total = 0; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); total += read; if (total > 10000) { progressBar.setValue(progressBar.getValue() + total); total = 0; } } out.close(); in.close(); String fileTo = basePath + "diccionariorimas.jar"; if (update.getType() == Update.GENERATOR) fileTo = basePath + "generador.jar"; else if (update.getType() == Update.RESBC) fileTo = basePath + "resbc.me"; else if (update.getType() == Update.HELP) fileTo = basePath + "help.html"; if (update.getType() == Update.RESBC) { Utils.unzip(temp, new File(fileTo)); } else { Utils.copyFile(new FileInputStream(temp), new File(fileTo)); } } catch (Exception e) { e.printStackTrace(); } } setVisible(false); if (gen != null || res != null) { try { new Main(null, basePath, false); } catch (Exception e) { new ErrorDialog(frame, e); } } String restart = ""; if (dic != null) restart += "\nAlgunas de ellas s�lo estar�n disponibles despu�s de reiniciar el diccionario."; JOptionPane.showMessageDialog(frame, "Se han terminado de realizar las actualizaciones." + restart, "Actualizaciones", JOptionPane.INFORMATION_MESSAGE); } |
00
| Code Sample 1:
public static NSData sendSynchronousRequest(NSMutableURLRequest req, NSHTTPURLResponseHolder resp, NSErrorHolder error) { NSData data = null; URL url = req.URL().xmlvmGetURL(); URLConnection conn; try { conn = url.openConnection(); data = new NSData(conn.getInputStream()); } catch (IOException e) { } return data; }
Code Sample 2:
@Override protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws IOException, ClassNotFoundException { HttpPost postMethod = new HttpPost(config.getServiceUrl()); postMethod.setEntity(new ByteArrayEntity(baos.toByteArray())); HttpResponse rsp = httpClient.execute(postMethod); StatusLine sl = rsp.getStatusLine(); if (sl.getStatusCode() >= 300) { throw new IOException("Did not receive successful HTTP response: status code = " + sl.getStatusCode() + ", status message = [" + sl.getReasonPhrase() + "]"); } HttpEntity entity = rsp.getEntity(); InputStream responseBody = entity.getContent(); return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); } |
11
| Code Sample 1:
private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; }
Code Sample 2:
public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } } |
00
| Code Sample 1:
public static void refreshSession(int C_ID) { Connection con = null; try { con = getConnection(); PreparedStatement updateLogin = con.prepareStatement("UPDATE customer SET c_login = NOW(), c_expiration = DATE_ADD(NOW(), INTERVAL 2 HOUR) WHERE c_id = ?"); updateLogin.setInt(1, C_ID); updateLogin.executeUpdate(); con.commit(); updateLogin.close(); returnConnection(con); } catch (java.lang.Exception ex) { try { con.rollback(); ex.printStackTrace(); } catch (Exception se) { System.err.println("Transaction rollback failed."); } } }
Code Sample 2:
private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; } |
11
| Code Sample 1:
public static String hash(String str) { if (str == null || str.length() == 0) { throw new CaptureSecurityException("String to encript cannot be null or zero length"); } StringBuilder hexString = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (byte element : hash) { if ((0xff & element) < 0x10) { hexString.append('0').append(Integer.toHexString((0xFF & element))); } else { hexString.append(Integer.toHexString(0xFF & element)); } } } catch (NoSuchAlgorithmException e) { throw new CaptureSecurityException(e); } return hexString.toString(); }
Code Sample 2:
public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = String.valueOf(Base64Coder.encode(raw)); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; } |
00
| Code Sample 1:
public static void copyFile(File in, File out) throws EnhancedException { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (Exception e) { throw new EnhancedException("Could not copy file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + ".", e); } }
Code Sample 2:
public static String getTextFromUrl(final String url) throws IOException { final String lineSeparator = System.getProperty("line.separator"); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line).append(lineSeparator); } return result.toString(); } finally { InputOutputUtil.close(bufferedReader, inputStreamReader); } } |
11
| Code Sample 1:
public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); }
Code Sample 2:
public String[][] getProjectTreeData() { String[][] treeData = null; String filename = dms_home + FS + "temp" + FS + username + "projects.xml"; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjects"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "projects.xml"; System.out.println(urldata); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("j"); int num = nodelist.getLength(); treeData = new String[num][5]; for (int i = 0; i < num; i++) { treeData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "i")); treeData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "pi")); treeData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "p")); treeData[i][3] = ""; treeData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } return treeData; } |
11
| Code Sample 1:
public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req, ActionResponse res) throws Exception { boolean editor = false; req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, false); User user = _getUser(req); List<Role> roles = RoleFactory.getAllRolesForUser(user.getUserId()); for (Role role : roles) { if (role.getName().equals("Report Administrator") || role.getName().equals("Report Editor") || role.getName().equals("CMS Administrator")) { req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, true); editor = true; break; } } requiresInput = false; badParameters = false; newReport = false; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); String cmd = req.getParameter(Constants.CMD); Logger.debug(this, "Inside EditReportAction cmd=" + cmd); ReportForm rfm = (ReportForm) form; ArrayList<String> ds = (DbConnectionFactory.getAllDataSources()); ArrayList<DataSource> dsResults = new ArrayList<DataSource>(); for (String dataSource : ds) { DataSource d = rfm.getNewDataSource(); if (dataSource.equals(com.dotmarketing.util.Constants.DATABASE_DEFAULT_DATASOURCE)) { d.setDsName("DotCMS Datasource"); } else { d.setDsName(dataSource); } dsResults.add(d); } rfm.setDataSources(dsResults); httpReq.setAttribute("dataSources", rfm.getDataSources()); Long reportId = UtilMethods.parseLong(req.getParameter("reportId"), 0); String referrer = req.getParameter("referrer"); if (reportId > 0) { report = ReportFactory.getReport(reportId); ArrayList<String> adminRoles = new ArrayList<String>(); adminRoles.add(com.dotmarketing.util.Constants.ROLE_REPORT_ADMINISTRATOR); if (user.getUserId().equals(report.getOwner())) { _checkWritePermissions(report, user, httpReq, adminRoles); } if (cmd == null || !cmd.equals(Constants.EDIT)) { rfm.setSelectedDataSource(report.getDs()); rfm.setReportName(report.getReportName()); rfm.setReportDescription(report.getReportDescription()); rfm.setReportId(report.getInode()); rfm.setWebFormReport(report.isWebFormReport()); httpReq.setAttribute("selectedDS", report.getDs()); } } else { if (!editor) { throw new DotRuntimeException("user not allowed to create a new report"); } report = new Report(); report.setOwner(_getUser(req).getUserId()); newReport = true; } req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, report); if ((cmd != null) && cmd.equals(Constants.EDIT)) { if (Validator.validate(req, form, mapping)) { report.setReportName(rfm.getReportName()); report.setReportDescription(rfm.getReportDescription()); report.setWebFormReport(rfm.isWebFormReport()); if (rfm.isWebFormReport()) report.setDs("None"); else report.setDs(rfm.getSelectedDataSource()); String jrxmlPath = ""; String jasperPath = ""; try { HibernateUtil.startTransaction(); ReportFactory.saveReport(report); _applyPermissions(req, report); if (!rfm.isWebFormReport()) { if (UtilMethods.isSet(Config.getStringProperty("ASSET_REAL_PATH"))) { jrxmlPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"; jasperPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"; } else { jrxmlPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"); jasperPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"); } UploadPortletRequest upr = PortalUtil.getUploadPortletRequest(req); File importFile = upr.getFile("jrxmlFile"); if (importFile.exists()) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(importFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); File f = new File(jrxmlPath); FileChannel channelTo = new FileOutputStream(f).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); try { JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath); } catch (Exception e) { Logger.error(this, "Unable to compile or save jrxml: " + e.toString()); try { f = new File(jrxmlPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jrxml. This is usually a permissions problem."); } try { f = new File(jasperPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jasper. This is usually a permissions problem."); } HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", UtilMethods.htmlLineBreak(e.getMessage())); setForward(req, "portlet.ext.report.edit_report"); return; } JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath); ReportParameterFactory.deleteReportsParameters(report); _loadReportParameters(jasperReport.getParameters()); report.setRequiresInput(requiresInput); HibernateUtil.save(report); } else if (newReport) { HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", "message.report.compile.error"); setForward(req, "portlet.ext.report.edit_report"); return; } } HibernateUtil.commitTransaction(); HashMap params = new HashMap(); SessionMessages.add(req, "message", "message.report.upload.success"); params.put("struts_action", new String[] { "/ext/report/view_reports" }); referrer = com.dotmarketing.util.PortletURLUtil.getRenderURL(((ActionRequestImpl) req).getHttpServletRequest(), javax.portlet.WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, referrer); return; } catch (Exception ex) { HibernateUtil.rollbackTransaction(); Logger.error(this, "Unable to save Report: " + ex.toString()); File f; Logger.info(this, "Trying to delete jrxml"); try { f = new File(jrxmlPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jrxml. This is usually because the file doesn't exist."); } try { f = new File(jasperPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jasper. This is usually because the file doesn't exist."); } if (badParameters) { SessionMessages.add(req, "error", ex.getMessage()); } else { SessionMessages.add(req, "error", "message.report.compile.error"); } setForward(req, "portlet.ext.report.edit_report"); return; } } else { setForward(req, "portlet.ext.report.edit_report"); } } if ((cmd != null) && cmd.equals("downloadReportSource")) { ActionResponseImpl resImpl = (ActionResponseImpl) res; HttpServletResponse response = resImpl.getHttpServletResponse(); if (!downloadSourceReport(reportId, httpReq, response)) { SessionMessages.add(req, "error", "message.report.source.file.not.found"); } } setForward(req, "portlet.ext.report.edit_report"); }
Code Sample 2:
private void copyLocalFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } |
00
| Code Sample 1:
public void login(String UID, String PWD, int CTY) throws Exception { sSideURL = sSideURLCollection[CTY]; sUID = UID; sPWD = PWD; iCTY = CTY; sLoginLabel = getLoginLabel(sSideURL); String sParams = getLoginParams(); CookieHandler.setDefault(new ListCookieHandler()); URL url = new URL(sSideURL + sLoginURL); URLConnection conn = url.openConnection(); setRequestProperties(conn); conn.setDoInput(true); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(sParams); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = rd.readLine(); while (line != null) { sb.append(line + "\n"); line = rd.readLine(); } wr.close(); rd.close(); String sPage = sb.toString(); Pattern p = Pattern.compile(">Dein Penner<"); Matcher matcher = p.matcher(sPage); LogedIn = matcher.find(); }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("Copy: no such source file: " + fromFileName); if (!fromFile.canRead()) throw new IOException("Copy: source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("Copy: destination file is unwriteable: " + toFileName); if (JOptionPane.showConfirmDialog(null, "Overwrite File ?", "Overwrite File", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("Copy: destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("Copy: destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("Copy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
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 String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; } |
11
| Code Sample 1:
public void authenticate(final ConnectionHandler ch, final AuthenticationCriteria ac) throws NamingException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(this.passwordScheme); md.update(((String) ac.getCredential()).getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new NamingException(e.getMessage()); } ch.connect(this.config.getBindDn(), this.config.getBindCredential()); NamingEnumeration<SearchResult> en = null; try { en = ch.getLdapContext().search(ac.getDn(), "userPassword={0}", new Object[] { String.format("{%s}%s", this.passwordScheme, LdapUtil.base64Encode(hash)).getBytes() }, LdapConfig.getCompareSearchControls()); if (!en.hasMore()) { throw new AuthenticationException("Compare authentication failed."); } } finally { if (en != null) { en.close(); } } }
Code Sample 2:
public static String hashString(String pwd) { StringBuffer hex = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pwd.getBytes()); byte[] d = md.digest(); String plaintxt; for (int i = 0; i < d.length; i++) { plaintxt = Integer.toHexString(0xFF & d[i]); if (plaintxt.length() < 2) { plaintxt = "0" + plaintxt; } hex.append(plaintxt); } } catch (NoSuchAlgorithmException nsae) { } return hex.toString(); } |
11
| Code Sample 1:
public String digest(String algorithm, String text) { MessageDigest digester = null; try { digester = MessageDigest.getInstance(algorithm); digester.update(text.getBytes(Digester.ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] bytes = digester.digest(); if (_BASE_64) { return Base64.encode(bytes); } else { return new String(Hex.encodeHex(bytes)); } }
Code Sample 2:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); String member_type; String save_type; String action; String notice; if ((String) session.getAttribute("member_type") != null) { member_type = (String) session.getAttribute("member_type"); } else { notice = "You must login first!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } if (request.getParameter("action") != null) { action = (String) request.getParameter("action"); } else { if (member_type.equals("student")) { if (session.getAttribute("person") != null) { Person person = (Person) session.getAttribute("person"); Student student = person.getStudent(); request.setAttribute("student", student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/student.jsp"); dispatcher.forward(request, response); return; } else { notice = "You are not logged in!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (member_type.equals("alumni")) { if (session.getAttribute("person") != null) { Person person = (Person) session.getAttribute("person"); Alumni alumni = person.getAlumni(); request.setAttribute("alumni", alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/alumni.jsp"); dispatcher.forward(request, response); return; } else { notice = "You are not logged in!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (member_type.equals("hospital")) { if (session.getAttribute("person") != null) { Person person = (Person) session.getAttribute("person"); Hospital hospital = person.getHospital(); request.setAttribute("hospital", hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/hospital.jsp"); dispatcher.forward(request, response); return; } else { notice = "You are not logged in!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else { notice = "I don't understand your request. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } if (action.equals("save_student")) { Person person = (Person) session.getAttribute("person"); Student cur_student = person.getStudent(); int person_id = Integer.parseInt((String) session.getAttribute("person_id")); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String start_date = request.getParameter("start_year") + "-" + request.getParameter("start_month") + "-01"; String graduation_date = ""; if (!request.getParameter("grad_year").equals("") && !request.getParameter("grad_month").equals("")) { graduation_date = request.getParameter("grad_year") + "-" + request.getParameter("grad_month") + "-01"; } String password = ""; if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/student.jsp"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_student.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Student new_student = new Student(fname, lname, address1, address2, city, state, zip, email, password, is_admin, start_date, graduation_date); if (!new_student.getEmail().equals(cur_student.getEmail())) { if (new_student.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("student", new_student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/student.jsp"); dispatcher.forward(request, response); return; } } if (!new_student.updateStudent(person_id)) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/student.jsp"); dispatcher.forward(request, response); return; } Person updated_person = new_student.getPerson(person_id); session.setAttribute("person", updated_person); notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("save_alumni")) { Person person = (Person) session.getAttribute("person"); Alumni cur_alumni = person.getAlumni(); int person_id = Integer.parseInt((String) session.getAttribute("person_id")); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String company_name = request.getParameter("company_name"); String position = request.getParameter("position"); int mentor = 0; if (request.getParameter("mentor") != null) { mentor = 1; } String graduation_date = request.getParameter("graduation_year") + "-" + request.getParameter("graduation_month") + "-01"; String password = ""; if (request.getParameter("password") != null) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/alumni.jsp"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_alumni.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Alumni new_alumni = new Alumni(fname, lname, address1, address2, city, state, zip, email, password, is_admin, company_name, position, graduation_date, mentor); if (!new_alumni.getEmail().equals(cur_alumni.getEmail())) { if (new_alumni.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("alumni", new_alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/alumni.jsp"); dispatcher.forward(request, response); return; } } if (!new_alumni.updateAlumni(person_id)) { session.setAttribute("alumni", new_alumni); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/alumni.jsp"); dispatcher.forward(request, response); return; } Person updated_person = new_alumni.getPerson(person_id); session.setAttribute("person", updated_person); notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("save_hospital")) { Person person = (Person) session.getAttribute("person"); Hospital cur_hospital = person.getHospital(); int person_id = Integer.parseInt((String) session.getAttribute("person_id")); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String url = request.getParameter("url"); String password = ""; if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/hospital.jsp"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_hospital.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Hospital new_hospital = new Hospital(fname, lname, address1, address2, city, state, zip, email, password, is_admin, name, phone, url); if (!new_hospital.getEmail().equals(cur_hospital.getEmail())) { if (new_hospital.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("hospital", new_hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/hospital.jsp"); dispatcher.forward(request, response); return; } } if (!new_hospital.updateHospital(person_id)) { session.setAttribute("hospital", new_hospital); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/hospital.jsp"); dispatcher.forward(request, response); return; } Person updated_person = new_hospital.getPerson(person_id); session.setAttribute("person", updated_person); notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error with your request. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/member/hospital.jsp"); dispatcher.forward(request, response); return; } } |
11
| Code Sample 1:
public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } }
Code Sample 2:
static void reopen(MJIEnv env, int objref) throws IOException { int fd = env.getIntField(objref, "fd"); long off = env.getLongField(objref, "off"); if (content.get(fd) == null) { int mode = env.getIntField(objref, "mode"); int fnRef = env.getReferenceField(objref, "fileName"); String fname = env.getStringObject(fnRef); if (mode == FD_READ) { FileInputStream fis = new FileInputStream(fname); FileChannel fc = fis.getChannel(); fc.position(off); content.set(fd, fis); } else if (mode == FD_WRITE) { FileOutputStream fos = new FileOutputStream(fname); FileChannel fc = fos.getChannel(); fc.position(off); content.set(fd, fos); } else { env.throwException("java.io.IOException", "illegal mode: " + mode); } } } |
00
| Code Sample 1:
public static List<PropertiesHolder> convertToPropertiesHolders(Collection<String> locations) { List<PropertiesHolder> propertiesHolders = new ArrayList<PropertiesHolder>(); for (String path : locations) { Locale locale = null; int startIndex = path.lastIndexOf('/'); if (startIndex < 0) { startIndex = 0; } int localeIndex = path.indexOf('_', startIndex); String localeString = null; if (localeIndex > 0) { localeString = path.substring(localeIndex + 1, path.lastIndexOf('.')); } if (org.apache.commons.lang.StringUtils.isBlank(localeString)) { locale = MessageProvider.DEFAULT_LOCALE; log.info("no locale could be guessed for properties: " + path); } else { locale = StringUtils.parseLocaleString(localeString); if (locale == null) { locale = Locale.getDefault(); log.info("no locale could be guessed for properties: " + path); } } try { Properties props = new Properties(); URL url = new URL(path); if (path.endsWith(".properties")) { props.load(url.openStream()); } else if (path.endsWith(".xml")) { props.loadFromXML(url.openStream()); } else if (path.endsWith(".xls")) { } else { log.warn("unknown filetype for properties: " + path); } String bundleName = props.getProperty("webwarp-modules-bundle-id"); if (org.apache.commons.lang.StringUtils.isEmpty(bundleName)) { log.warn("bundle name is empty for path: " + path + ". Provide a bundle entry 'webwarp-modules-bundle-id' to set one."); bundleName = MessageProvider.DEFAULT_BUNDLE_NAME; } propertiesHolders.add(new PropertiesHolder(props, bundleName, locale)); } catch (Exception e) { log.error("Error reading properties from : " + path, e); } } return propertiesHolders; }
Code Sample 2:
public static void copyAll(URL url, StringBuilder ret) { Reader in = null; try { in = new InputStreamReader(new BufferedInputStream(url.openStream())); copyAll(in, ret); } catch (IOException e) { throw new RuntimeException(e); } finally { close(in); } } |
11
| Code Sample 1:
private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } }
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; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.