label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
00
Code Sample 1: @Override public TDSScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); TDSScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); } Code Sample 2: public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); final URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); if (urlConnection instanceof HttpURLConnection) { final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setRequestMethod("PUT"); return new FilterOutputStream(urlConnection.getOutputStream()) { @Override public void close() throws IOException { super.close(); int responseCode = httpURLConnection.getResponseCode(); switch(responseCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: case HttpURLConnection.HTTP_NO_CONTENT: { break; } default: { throw new IOException("PUT failed with HTTP response code " + responseCode); } } } }; } else { OutputStream result = urlConnection.getOutputStream(); final Map<Object, Object> response = getResponse(options); if (response != null) { result = new FilterOutputStream(result) { @Override public void close() throws IOException { try { super.close(); } finally { response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified()); } } }; } return result; } } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } }
11
Code Sample 1: public static void zip() throws Exception { System.out.println("zip()"); ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(new File("/zip/myzip.zip"))); ZipEntry entry = new ZipEntry("asdf.script"); zipout.putNextEntry(entry); byte buffer[] = new byte[BLOCKSIZE]; FileInputStream in = new FileInputStream(new File("/zip/asdf.script")); for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length); in.close(); zipout.closeEntry(); zipout.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static byte[] read(URL url) throws IOException { byte[] bytes; InputStream is = null; try { is = url.openStream(); bytes = readAllBytes(is); } finally { if (is != null) { is.close(); } } return bytes; } Code Sample 2: public void savaUserPerm(String userid, Collection user_perm_collect) throws DAOException, SQLException { ConnectionProvider cp = null; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; PrivilegeFactory factory = PrivilegeFactory.getInstance(); Operation op = factory.createOperation(); try { cp = ConnectionProviderFactory.getConnectionProvider(Constants.DATA_SOURCE); conn = cp.getConnection(); pstmt = conn.prepareStatement(DEL_USER_PERM); pstmt.setString(1, userid); pstmt.executeUpdate(); if ((user_perm_collect == null) || (user_perm_collect.size() <= 0)) { return; } else { conn.setAutoCommit(false); pstmt = conn.prepareStatement(ADD_USER_PERM); Iterator user_perm_ir = user_perm_collect.iterator(); while (user_perm_ir.hasNext()) { UserPermission userPerm = (UserPermission) user_perm_ir.next(); pstmt.setString(1, String.valueOf(userPerm.getUser_id())); pstmt.setString(2, String.valueOf(userPerm.getResource_id())); pstmt.setString(3, String.valueOf(userPerm.getResop_id())); pstmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); } } catch (Exception e) { e.printStackTrace(); conn.rollback(); throw new DAOException(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } } catch (Exception e) { } } }
00
Code Sample 1: private Source getStylesheetSource(String stylesheetResource) throws ApplicationContextException { if (LOG.isDebugEnabled()) { LOG.debug("Loading XSLT stylesheet from " + stylesheetResource); } try { URL url = this.getClass().getClassLoader().getResource(stylesheetResource); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException e) { throw new RuntimeException("Can't load XSLT stylesheet from " + stylesheetResource, e); } } Code Sample 2: public void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } }
11
Code Sample 1: @SuppressWarnings("finally") private void decompress(final File src) throws IOException { final String srcPath = src.getPath(); checkSourceFile(src); final boolean test = this.switches.contains(Switch.test); final File dst; if (test) dst = File.createTempFile("jaxlib-bzip", null); else { if (srcPath.endsWith(".bz2")) dst = new File(srcPath.substring(0, srcPath.length() - 4)); else { this.log.println("WARNING: Can't guess original name, using extension \".out\":").println(srcPath); dst = new File(srcPath + ".out"); } } if (!checkDestFile(dst)) return; final boolean showProgress = this.switches.contains(Switch.showProgress); BZip2InputStream in = null; FileOutputStream out = null; FileChannel outChannel = null; FileLock inLock = null; FileLock outLock = null; try { final FileInputStream in0 = new FileInputStream(src); final FileChannel inChannel = in0.getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); in = new BZip2InputStream(new BufferedXInputStream(in0, 8192)); out = new FileOutputStream(dst); outChannel = out.getChannel(); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } long pos = 0; int progress = 0; final long maxStep = showProgress ? Math.max(8192, inSize / MAX_PROGRESS) : Integer.MAX_VALUE; while (true) { final long step = outChannel.transferFrom(in, pos, maxStep); if (step <= 0) { final long a = inChannel.size(); if (a != inSize) throw error("file " + src + " has been modified concurrently by another process"); if (inChannel.position() >= inSize) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } } else { pos += step; if (showProgress) { final double p = (double) inChannel.position() / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } final long outSize = outChannel.size(); in.close(); out.close(); if (this.verbose) { final double ratio = (outSize == 0) ? (inSize * 100) : ((double) inSize / (double) outSize); this.log.print("compressed size: ").print(inSize) .print("; decompressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!test && !this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } if (test && !dst.delete()) throw error("unable to delete testfile: " + dst); } catch (final IOException ex) { IO.tryClose(in); IO.tryClose(out); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } } Code Sample 2: public void SendFile(File testfile) { try { SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234)); sock.configureBlocking(true); while (!sock.finishConnect()) { System.out.println("NOT connected!"); } System.out.println("CONNECTED!"); FileInputStream fis = new FileInputStream(testfile); FileChannel fic = fis.getChannel(); long len = fic.size(); Buffer.clear(); Buffer.putLong(len); Buffer.flip(); sock.write(Buffer); long cnt = 0; while (cnt < len) { Buffer.clear(); int add = fic.read(Buffer); cnt += add; Buffer.flip(); while (Buffer.hasRemaining()) { sock.write(Buffer); } } fic.close(); File tmpfile = getTmp().createNewFile("tmp", "tmp"); FileOutputStream fos = new FileOutputStream(tmpfile); FileChannel foc = fos.getChannel(); int mlen = -1; do { Buffer.clear(); mlen = sock.read(Buffer); Buffer.flip(); if (mlen > 0) { foc.write(Buffer); } } while (mlen > 0); foc.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; } Code Sample 2: public void aprovarCandidato(Atividade atividade) throws SQLException { Connection conn = null; String insert = "update Atividade_has_recurso_humano set ativo='true' " + "where atividade_idatividade=" + atividade.getIdAtividade() + " and " + " usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario(); try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: @Override public URLConnection openConnection(URL url, Proxy proxy) throws IOException { if (null == url) { throw new IllegalArgumentException(Messages.getString("luni.1B")); } String host = url.getHost(); if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) { return new FileURLConnection(url); } URL ftpURL = new URL("ftp", host, url.getFile()); return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy); }
11
Code Sample 1: public static String validateSession(String sessionid, String servicekey, HttpServletRequest request) { if (sessionid == null) { return "error"; } String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/validatesessionid", "sessionid", sessionid); u = SSOUtil.addParameter(u, "servicekey", servicekey); u = SSOUtil.addParameter(u, "ip", request.getRemoteHost()); u = SSOUtil.addParameter(u, "url", encodeUrl(request.getRequestURI())); u = SSOUtil.addParameter(u, "useragent", request.getHeader("User-Agent")); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } } Code Sample 2: @SuppressWarnings("unchecked") public void handle(Map<String, Object> data, String urlPath) { try { URL url = new URL(urlPath); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; CMGroup currentGroup = null; List<CMGroup> groups = (List<CMGroup>) data.get(CMConstants.GROUP); List<CMTag> tags = (List<CMTag>) data.get(CMConstants.TAG); List<CMTagGroup> tagGroups = (List<CMTagGroup>) data.get(CMConstants.TAG_GROUP); while ((line = reader.readLine()) != null) { CMGroup group = null; try { group = FetchUtil.getCMGroup(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMGroup error:" + line); } if (group != null) { if (currentGroup != null) { groups.add(currentGroup); } currentGroup = group; } CMTag tag = null; try { tag = FetchUtil.getCMTag(line); } catch (Exception e) { CMLog.getLogger(this).severe("getCMTag error:" + line); } if (tag != null) { CMTagGroup tagGroup = new CMTagGroup(); tagGroup.setGroupName(currentGroup.getName()); tagGroup.setTagName(tag.getName()); tags.add(tag); tagGroups.add(tagGroup); } } groups.add(currentGroup); reader.close(); } catch (MalformedURLException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } catch (IOException e) { CMLog.getLogger(this).severe("GTagHandler error:" + e.getMessage()); e.printStackTrace(); } }
11
Code Sample 1: public static void main(String[] args) { JFileChooser askDir = new JFileChooser(); askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); askDir.setMultiSelectionEnabled(false); int returnVal = askDir.showOpenDialog(null); if (returnVal == JFileChooser.CANCEL_OPTION) { System.exit(returnVal); } File startDir = askDir.getSelectedFile(); ArrayList<File> files = new ArrayList<File>(); goThrough(startDir, files); SearchClient client = new SearchClient("VZFo5W5i"); MyID3 singleton = new MyID3(); for (File song : files) { try { MusicMetadataSet set = singleton.read(song); IMusicMetadata meta = set.getSimplified(); String qu = song.getName(); if (meta.getAlbum() != null) { qu = meta.getAlbum(); } else if (meta.getArtist() != null) { qu = meta.getArtist(); } if (qu.length() > 2) { ImageSearchRequest req = new ImageSearchRequest(qu); ImageSearchResults res = client.imageSearch(req); if (res.getTotalResultsAvailable().doubleValue() > 1) { System.out.println("Downloading " + res.listResults()[0].getUrl()); URL url = new URL(res.listResults()[0].getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); int realSize = con.getContentLength(); if (realSize > 0) { String mime = con.getContentType(); InputStream stream = con.getInputStream(); byte[] realData = new byte[realSize]; for (int i = 0; i < realSize; i++) { stream.read(realData, i, 1); } stream.close(); ImageData imgData = new ImageData(realData, mime, qu, 0); meta.addPicture(imgData); File temp = File.createTempFile("tempsong", "mp3"); singleton.write(song, temp, set, meta); FileChannel inChannel = new FileInputStream(temp).getChannel(); FileChannel outChannel = new FileOutputStream(song).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } temp.delete(); } } } } catch (ID3ReadException e) { } catch (MalformedURLException e) { } catch (UnsupportedEncodingException e) { } catch (ID3WriteException e) { } catch (IOException e) { } catch (SearchException e) { } } } Code Sample 2: public static Image load(final InputStream input, String format, Point dimension) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); dotOutput.delete(); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); ImageLoader loader = new ImageLoader(); ImageData[] imageData = loader.load(dotOutput.getAbsolutePath()); return new Image(Display.getDefault(), imageData[0]); } } catch (SWTException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
11
Code Sample 1: private void fileCopier(String filenameFrom, String filenameTo) { FileInputStream fromStream = null; FileOutputStream toStream = null; try { fromStream = new FileInputStream(new File(filenameFrom)); if (new File(filenameTo).exists()) { new File(filenameTo).delete(); } File dirr = new File(getContactPicPath()); if (!dirr.exists()) { dirr.mkdir(); } toStream = new FileOutputStream(new File(filenameTo)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fromStream.read(buffer)) != -1) toStream.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { Errmsg.errmsg(e); } catch (IOException e) { Errmsg.errmsg(e); } finally { try { if (fromStream != null) { fromStream.close(); } if (toStream != null) { toStream.close(); } } catch (IOException e) { Errmsg.errmsg(e); } } } Code Sample 2: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
00
Code Sample 1: public static void loadPackage1(String ycCode) { InputStream input = null; try { TrustManager[] trustAllCerts = new TrustManager[] { new FakeTrustManager() }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); URL url = Retriever.getPackage1Url(String.valueOf(YouthClub.getMiniModel().getBasics().getTeamId()), ycCode); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new FakeHostnameVerifier()); uc.setConnectTimeout(CONNECTION_TIMEOUT); uc.setReadTimeout(CONNECTION_TIMEOUT); input = uc.getInputStream(); StringBuilder sb = new StringBuilder(); int c; while ((c = input.read()) != -1) { sb.append((char) c); } Document doc = YouthClub.getMiniModel().getXMLParser().parseString(sb.toString()); String target = System.getProperty("user.home") + System.getProperty("file.separator") + "youthclub_" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date()) + ".xml"; YouthClub.getMiniModel().getXMLParser().writeXML(doc, target); Debug.log("YC XML saved to " + target); } catch (Exception e) { Debug.logException(e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } } Code Sample 2: public static String loadSite(String spec) throws IOException { URL url = new URL(spec); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String output = ""; String str; while ((str = in.readLine()) != null) { output += str + "\n"; } in.close(); return output; }
00
Code Sample 1: private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } } Code Sample 2: public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) startWindow(prop); else if (tag.equals("splitpanel")) startSplitPanel(prop); else if (tag.equals("desktoppane")) startDesktopPane(prop); else if (tag.equals("tabcontrol")) startTabcontrol(prop); else if (tag.equals("panel")) startPanel(prop); else if (tag.equals("statusbar")) startStatusbar(prop); else if (tag.equals("toolbar")) startToolbar(prop); else if (tag.equals("toolbarbutton")) startToolbarbutton(prop); else if (tag.equals("menu")) startMenu(prop); else if (tag.equals("menuitem")) startMenuitem(prop); else if (tag.equals("separator")) menu.addSeparator(); else if (tag.equals("choice")) startChoice(prop); else if (tag.equals("list")) startList(prop); else if (tag.equals("option")) startOption(prop); else if (tag.equals("label")) startLabel(prop); else if (tag.equals("button")) startButton(prop); else if (tag.equals("groupbox")) startGroupbox(prop); else if (tag.equals("radiobutton")) startRadioButton(prop); else if (tag.equals("checkbox")) startCheckbox(prop); else if (tag.equals("image")) startImage(prop); else if (tag.equals("textarea")) startTextArea(prop); else if (tag.equals("singlelineedit")) startSingleLineEdit(prop); else if (tag.equals("treeview")) startTreeview(prop); else if (tag.equals("treeitem")) startTreeitem(prop); else if (tag.equals("table")) startTable(prop); else if (tag.equals("header")) startHeader(prop); else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.addRow(); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("rmbmenuitem")) { if (prop == null) { System.err.println("datawindow.menuitem without properties"); return; } String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); JMenuItem mi = new JMenuItem(label); mi.setActionCommand(action); mi.addActionListener(win); rmbmenu.add(mi); } else if (tag.equals("rmbseparator")) { rmbmenu.addSeparator(); } else if (tag.equals("script")) { win.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; win.script += buffer + "\n"; } r.close(); win.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[win] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
11
Code Sample 1: private void copyFile(File src_file, File dest_file) { InputStream src_stream = null; OutputStream dest_stream = null; try { int b; src_stream = new BufferedInputStream(new FileInputStream(src_file)); dest_stream = new BufferedOutputStream(new FileOutputStream(dest_file)); while ((b = src_stream.read()) != -1) dest_stream.write(b); } catch (Exception e) { XRepository.getLogger().warning(this, "Error on copying the plugin file!"); XRepository.getLogger().warning(this, e); } finally { try { src_stream.close(); dest_stream.close(); } catch (Exception ex2) { } } } Code Sample 2: protected void zipDirectory(File dir, File zipfile) throws IOException, IllegalArgumentException { if (!dir.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytes_read; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); } out.close(); }
00
Code Sample 1: public void run() { runCounter++; try { LOGGER.info("Fetching feed [" + runCounter + "] " + _feedInfo); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); disableSSLCertificateChecking(httpClient); if (_proxy != null && _feedInfo.getUseProxy()) { LOGGER.info("Configuring proxy " + _proxy); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxy); } if (_feedInfo.getUsername() != null) { Credentials credentials; if (_feedInfo.getUsername().contains("/")) { String username = _feedInfo.getUsername().substring(_feedInfo.getUsername().indexOf("/") + 1); String domain = _feedInfo.getUsername().substring(0, _feedInfo.getUsername().indexOf("/")); String workstation = InetAddress.getLocalHost().getHostName(); LOGGER.info("Configuring NT credentials : username=[" + username + "] domain=[" + domain + "] workstation=[" + workstation + "]"); credentials = new NTCredentials(username, _feedInfo.getPassword(), workstation, domain); httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } else { credentials = new UsernamePasswordCredentials(_feedInfo.getUsername(), _feedInfo.getPassword()); LOGGER.info("Configuring Basic credentials " + credentials); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } } if (_feedInfo.getCookie() != null) { BasicClientCookie cookie = new BasicClientCookie(_feedInfo.getCookie().getName(), _feedInfo.getCookie().getValue()); cookie.setVersion(0); if (_feedInfo.getCookie().getDomain() != null) cookie.setDomain(_feedInfo.getCookie().getDomain()); if (_feedInfo.getCookie().getPath() != null) cookie.setPath(_feedInfo.getCookie().getPath()); LOGGER.info("Adding cookie " + cookie); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } HttpGet httpget = new HttpGet(_feedInfo.getUrl()); HttpResponse response = httpClient.execute(httpget, localContext); LOGGER.info("Response Status : " + response.getStatusLine()); LOGGER.debug("Headers : " + Arrays.toString(response.getAllHeaders())); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { LOGGER.error("Request was unsuccessful for " + _feedInfo + " : " + response.getStatusLine()); } else { SyndFeedInput input = new SyndFeedInput(); XmlReader reader = new XmlReader(response.getEntity().getContent()); SyndFeed feed = input.build(reader); if (feed.getTitle() != null) _feedInfo.setTitle(feed.getTitle()); LOGGER.debug("Feed : " + new SyndFeedOutput().outputString(feed)); LOGGER.info("Feed [" + feed.getTitle() + "] contains " + feed.getEntries().size() + " entries"); @SuppressWarnings("unchecked") List<SyndEntry> entriesList = feed.getEntries(); Collections.sort(entriesList, new SyndEntryPublishedDateComparator()); for (SyndEntry entry : entriesList) { if (VisitedEntries.getInstance().isAlreadyVisited(entry.getUri())) { LOGGER.debug("Already received " + entry.getUri()); } else { _feedInfo.addEntry(entry); LOGGER.debug("New entry " + entry.toString()); _entryDisplay.displayEntry(feed, entry, firstRun); } } LOGGER.info("Completing entries for feed " + feed.getTitle()); if (firstRun) firstRun = false; } } catch (IllegalArgumentException e) { LOGGER.error(e.getMessage(), e); } catch (FeedException e) { LOGGER.error(e.getMessage(), e); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (KeyManagementException e) { LOGGER.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); } } Code Sample 2: public static String getHash(String plaintext) { String hash = null; try { String text = plaintext; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes("UTF-8")); byte[] rawBytes = md.digest(); hash = new BASE64Encoder().encode(rawBytes); } catch (NoSuchAlgorithmException e) { } } catch (IOException e) { } return hash; }
00
Code Sample 1: public static Properties load(String classPath) throws IOException { AssertUtility.notNullAndNotSpace(classPath); Properties props = new Properties(); URL url = ClassLoader.getSystemResource(classPath); props.load(url.openStream()); return props; } Code Sample 2: public void fillData() { try { URL urlhome = OpenerIF.class.getResource("Home.html"); URLConnection uc = urlhome.openConnection(); InputStreamReader input = new InputStreamReader(uc.getInputStream()); BufferedReader in = new BufferedReader(input); String inputLine; String htmlData = ""; while ((inputLine = in.readLine()) != null) { htmlData += inputLine; } in.close(); String[] str = new String[9]; str[0] = getLibName(); str[1] = getLoginId(); str[2] = getLoginName(); str[3] = getVerusSubscriptionIdHTML(); str[4] = getPendingJobsHTMLCode(); str[5] = getFrequentlyUsedScreensHTMLCode(); str[6] = getOpenCatalogHTMLCode(); str[7] = getNewsHTML(); str[8] = getOnlineInformationHTML(); MessageFormat mf = new MessageFormat(htmlData); String htmlContent = mf.format(htmlData, str); PrintWriter fw = new PrintWriter(System.getProperty("user.home") + "/homeNGL.html"); fw.println(htmlContent); fw.flush(); fw.close(); new LocalHtmlRendererContext(panel, new SimpleUserAgentContext(), this).navigate("file:" + System.getProperty("user.home") + "/homeNGL.html"); } catch (Exception exp) { exp.printStackTrace(); } }
11
Code Sample 1: protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } Code Sample 2: public static ArrayList<Quote> fetchAllQuotes(String symbol, Date from, Date to) { try { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(from); String monthFrom = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayFrom = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearFrom = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); calendar.setTime(to); String monthTo = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayTo = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearTo = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + monthFrom + "&b=" + dayFrom + "&c=" + yearFrom + "&d=" + monthTo + "&e=" + dayTo + "&f=" + yearTo + "&g=d&ignore=.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; ArrayList<Quote> result = new ArrayList<Quote>(); reader.readLine(); while ((line = reader.readLine()) != null) { String[] values = line.split(","); String date = values[0]; Date dateQuote = new SimpleDateFormat("yyyy-MM-dd").parse(date); double open = Double.valueOf(values[1]); double high = Double.valueOf(values[2]); double low = Double.valueOf(values[3]); double close = Double.valueOf(values[4]); long volume = Long.valueOf(values[5]); double adjClose = Double.valueOf(values[6]); Quote q = new Quote(dateQuote, open, high, low, close, volume, adjClose); result.add(q); } reader.close(); Collections.reverse(result); return result; } catch (MalformedURLException e) { System.out.println("URL malformee"); } catch (IOException e) { System.out.println("Donnees illisibles"); } catch (ParseException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public TVRageShowInfo(String xmlShowName) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime")) airTime = tmp[1]; } if (airTime.length() != 0) { tmp = airTime.split(","); airTimeHour = tmp[1]; } in.close(); url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[2].indexOf(':') > -1) { tmp = tmp[2].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public static File copyFile(File fileToCopy, File copiedFile) { BufferedInputStream in = null; BufferedOutputStream outWriter = null; if (!copiedFile.exists()) { try { copiedFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } } try { in = new BufferedInputStream(new FileInputStream(fileToCopy), 4096); outWriter = new BufferedOutputStream(new FileOutputStream(copiedFile), 4096); int c; while ((c = in.read()) != -1) outWriter.write(c); in.close(); outWriter.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } return copiedFile; }
11
Code Sample 1: private void copyFile(String file) { FileChannel inChannel = null; FileChannel outChannel = null; try { Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss "); File in = new File(file); String[] name = file.split("\\\\"); File out = new File(".\\xml_archiv\\" + df.format(dt) + name[name.length - 1]); inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { System.err.println("Copy error!"); System.err.println("Error: " + e.getMessage()); } finally { if (inChannel != null) { try { inChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } if (outChannel != null) { try { outChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } } } Code Sample 2: 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 main(String[] args) throws Exception { if (args.length < 3) { usage(System.out); System.exit(1); } final File tmpFile = File.createTempFile("sej", null); tmpFile.deleteOnExit(); final FileOutputStream destination = new FileOutputStream(tmpFile); final String mainClass = args[1]; final Collection jars = new LinkedList(); for (int i = 2; i < args.length; i++) { String arg = args[i]; jars.add(arg); } JarInterpretted interpretted = new JarInterpretted(destination); JarCat rowr = new JarCat(destination, createManifest(mainClass), jars); interpretted.write(); rowr.write(); destination.close(); final File finalDestinationFile = new File(args[0]); final FileOutputStream finalDestination = new FileOutputStream(finalDestinationFile); IOUtils.copy(new FileInputStream(tmpFile), finalDestination); finalDestination.close(); Chmod chmod = new Chmod("a+rx", new File[] { finalDestinationFile }); chmod.invoke(); } Code Sample 2: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void postData(Reader data, URL endpoint, Writer output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endpoint.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) { in.close(); } } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlc != null) { urlc.disconnect(); } } }
11
Code Sample 1: public static void testclass(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.emptyClass(ClassWriter.ACC_PUBLIC, "TestClass", "java/lang/Object"); MethodInfo newMethod = writer.addMethod(ClassWriter.ACC_PUBLIC | ClassWriter.ACC_STATIC, "main", "([Ljava/lang/String;)V"); CodeAttribute attribute = newMethod.getCodeAttribute(); int constantIndex = writer.getStringConstantIndex("It's alive! It's alive!!"); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int methodRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); ArrayList instructions = new ArrayList(); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); operands = new byte[1]; operands[0] = (byte) constantIndex; instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("ldc"), 0, operands, false)); operands = new byte[2]; NetByte.intToPair(methodRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("return"), 0, null, false)); attribute.insertInstructions(0, 0, instructions); attribute.setMaxLocals(1); attribute.codeCheck(); System.out.println("constantIndex=" + constantIndex + " fieldRef=" + fieldRefIndex + " methodRef=" + methodRefIndex); writer.writeClass(new FileOutputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); writer.readClass(new FileInputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); } Code Sample 2: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
00
Code Sample 1: public static List<String> extract(String zipFilePath, String destDirPath) throws IOException { List<String> list = null; ZipFile zip = new ZipFile(zipFilePath); try { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destFile = new File(destDirPath, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { InputStream in = zip.getInputStream(entry); OutputStream out = new FileOutputStream(destFile); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { out.close(); } catch (IOException ioe) { ioe.getMessage(); } try { in.close(); } catch (IOException ioe) { ioe.getMessage(); } } } if (list == null) { list = new ArrayList<String>(); } list.add(destFile.getAbsolutePath()); } return list; } finally { try { zip.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: protected static void createBackup() throws IOException, IllegalStateException, FTPIllegalReplyException, FTPException, FileNotFoundException, FTPDataTransferException, FTPAbortedException { String cmd = "mysqldump -u " + Constants.dbUser + " -p" + Constants.dbPassword + " " + Constants.dbName + " > " + Constants.tmpDir + "Backup.sql"; FileWriter fstream = new FileWriter(Constants.tmpDir + Constants.tmpScript); BufferedWriter out = new BufferedWriter(fstream); out.write(cmd); out.close(); Process process = Runtime.getRuntime().exec(Constants.tmpDir + Constants.tmpScript); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (br.readLine() != null) { ; } String fileName = now4backup(); cmd = "\"C:\\Archivos de programa\\WinRAR\\Rar.exe\" a -m5 -ed " + Constants.tmpDir + fileName + " " + Constants.tmpDir + "Backup.sql"; process = Runtime.getRuntime().exec(cmd); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while (br.readLine() != null) { ; } FTPClient client = new FTPClient(); client.connect(Constants.ftpBackupAddr); client.login(Constants.ftpBackupUser, Constants.ftpBackupPassword); client.changeDirectory("/" + Shared.getConfig("storeName")); File f = new File(Constants.tmpDir + fileName); client.upload(f); client.disconnect(false); }
00
Code Sample 1: public boolean ponerRivalxRonda(int idJugadorDiv, int idRonda, int dato) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = " + dato + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); 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); } Code Sample 2: public void run() { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); ChannelMap cm = new ChannelMap(); for (int i = 0; i < picm.NumberOfChannels(); i++) { cm.Add(picm.GetName(i)); } String[] folder = picm.GetFolderList(); for (int i = 0; i < folder.length; i++) { cm.AddFolder(folder[i]); } sink.Request(cm, picm.GetRequestStart(), picm.GetRequestDuration(), picm.GetRequestReference()); cm = sink.Fetch(timeout); if (cm.GetIfFetchTimedOut()) { System.err.println("Signature Data Fetch Timed Out!"); picm.Clear(); } else { md.reset(); folder = cm.GetFolderList(); for (int i = 0; i < folder.length; i++) picm.AddFolder(folder[i]); int sigIdx = -1; for (int i = 0; i < cm.NumberOfChannels(); i++) { String chan = cm.GetName(i); if (chan.endsWith("/_signature")) { sigIdx = i; continue; } int idx = picm.GetIndex(chan); if (idx == -1) idx = picm.Add(chan); picm.PutTimeRef(cm, i); picm.PutDataRef(idx, cm, i); md.update(cm.GetData(i)); md.update((new Double(cm.GetTimeStart(i))).toString().getBytes()); } if (cm.NumberOfChannels() > 0) { byte[] amd = md.digest(signature.getBytes()); if (sigIdx >= 0) { if (MessageDigest.isEqual(amd, cm.GetDataAsByteArray(sigIdx)[0])) { System.err.println(pluginName + ": signature matched for: " + cm.GetName(0)); } else { System.err.println(pluginName + ": failed signature test, sending null response"); picm.Clear(); } } else { System.err.println(pluginName + ": _signature attached for: " + cm.GetName(0)); int idx = picm.Add("_signature"); picm.PutTime(0., 0.); picm.PutDataAsByteArray(idx, amd); } } } plugin.Flush(picm); } catch (Exception e) { e.printStackTrace(); } if (threadStack.size() < 4) threadStack.push(this); else sink.CloseRBNBConnection(); }
11
Code Sample 1: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static String generateHashSE(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest md; md = MessageDigest.getInstance("SHA-256"); byte[] hashSHA256 = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md.digest(hashSHA256, 0, text.length()); return convertToHex(hashSHA256); }
11
Code Sample 1: char[] DigestCalcHA1(String algorithm, String userName, String realm, String password, String nonce, String clientNonce) throws SaslException { byte[] hash; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(realm.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); hash = md.digest(); if ("md5-sess".equals(algorithm)) { md.update(hash); md.update(":".getBytes("UTF-8")); md.update(nonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(clientNonce.getBytes("UTF-8")); hash = md.digest(); } } catch (NoSuchAlgorithmException e) { throw new SaslException("No provider found for MD5 hash", e); } catch (UnsupportedEncodingException e) { throw new SaslException("UTF-8 encoding not supported by platform.", e); } return convertToHex(hash); } Code Sample 2: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw e; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw e; } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; } Code Sample 2: 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(); }
11
Code Sample 1: public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static int convertImage(InputStream is, OutputStream os, String command) throws IOException, InterruptedException { if (logger.isInfoEnabled()) { logger.info(command); } Process p = Runtime.getRuntime().exec(command); ByteArrayOutputStream errOut = new ByteArrayOutputStream(); StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), errOut, "Convert Thread (err gobbler): " + command); errGobbler.start(); StreamGobbler outGobbler = new StreamGobbler(new BufferedInputStream(is), p.getOutputStream(), "Convert Thread (out gobbler): " + command); outGobbler.start(); try { IOUtils.copy(p.getInputStream(), os); os.flush(); if (p.waitFor() != 0) { logger.error("Unable to convert, stderr: " + new String(errOut.toByteArray(), "UTF-8")); } return p.exitValue(); } finally { IOUtils.closeQuietly(os); } }
00
Code Sample 1: public static boolean copyFile(File source, File dest) throws IOException { int answer = JOptionPane.YES_OPTION; if (dest.exists()) { answer = JOptionPane.showConfirmDialog(null, "File " + dest.getAbsolutePath() + "\n already exists. Overwrite?", "Warning", JOptionPane.YES_NO_OPTION); } if (answer == JOptionPane.NO_OPTION) return false; dest.createNewFile(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } return true; } catch (Exception e) { return false; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: public void updateCoordinates(Address address) { String mapURL = "http://maps.google.com/maps/geo?output=csv"; String mapKey = "ABQIAAAAi__aT6y6l86JjbootR-p9xQd1nlEHNeAVGWQhS84yIVN5yGO2RQQPg9QLzy82PFlCzXtMNe6ofKjnA"; String location = address.getStreet() + " " + address.getZip() + " " + address.getCity(); if (logger.isDebugEnabled()) { logger.debug(location); } double[] coordinates = { 0.0, 0.0 }; String content = ""; try { location = URLEncoder.encode(location, "UTF-8"); String request = mapURL + "&q=" + location + "&key=" + mapKey; URL url = new URL(request); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } reader.close(); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error from google: " + e.getMessage()); } } if (logger.isDebugEnabled()) { logger.debug(content); } StringTokenizer tokenizer = new StringTokenizer(content, ","); int i = 0; while (tokenizer.hasMoreTokens()) { i++; String token = tokenizer.nextToken(); if (i == 3) { coordinates[0] = Double.parseDouble(token); } if (i == 4) { coordinates[1] = Double.parseDouble(token); } } if ((coordinates[0] != 0) || (coordinates[1] != 0)) { address.setLatitude(coordinates[0]); address.setLongitude(coordinates[1]); } else { if (logger.isDebugEnabled()) { logger.debug("Invalid coordinates for address " + address.getId()); } } }
11
Code Sample 1: private void copyJdbcDriverToWL(final WLPropertyPage page) { final File url = new File(page.getDomainDirectory()); final File lib = new File(url, "lib"); final File mysqlLibrary = new File(lib, NexOpenUIActivator.getDefault().getMySQLDriver()); if (!mysqlLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + NexOpenUIActivator.getDefault().getMySQLDriver())); fos = new FileOutputStream(mysqlLibrary); IOUtils.copy(driver, fos); } catch (final IOException e) { Logger.log(Logger.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); final Status status = new Status(Status.ERROR, NexOpenUIActivator.PLUGIN_ID, Status.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e); ErrorDialog.openError(page.getShell(), "Bea WebLogic MSQL support", "Could not copy the MySQL Driver jar file to Bea WL", status); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; } Code Sample 2: 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); } }
00
Code Sample 1: public String control(final String allOptions) throws SQLException { connect(); final Statement stmt = connection.createStatement(); final ResultSet rst1 = stmt.executeQuery("SELECT versionId FROM versions WHERE version='" + Concrete.version() + "'"); final long versionId; if (rst1.next()) { versionId = rst1.getInt(1); } else { disconnect(); return ""; } rst1.close(); final MessageDigest msgDigest; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { logger.throwing(SQLExecutionController.class.getSimpleName(), "control", e1); disconnect(); return ""; } msgDigest.update(allOptions.getBytes()); final ResultSet rst2 = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + Concrete.md5(msgDigest.digest()) + "'"); final long configId; if (rst2.next()) { configId = rst2.getInt(1); } else { disconnect(); return ""; } rst2.close(); final ResultSet rst4 = stmt.executeQuery("SELECT problems.md5 FROM executions " + "LEFT JOIN problems ON executions.problemId = problems.problemId WHERE " + "configId=" + configId + " AND versionId=" + versionId); final StringBuilder stb = new StringBuilder(); while (rst4.next()) { stb.append(rst4.getString(1)).append('\n'); } rst4.close(); stmt.close(); return stb.toString(); } Code Sample 2: private static <OS extends OutputStream> OS getUnzipAndDecodeOutputStream(InputStream inputStream, final OS outputStream) { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final List<Throwable> ungzipThreadThrowableList = new LinkedList<Throwable>(); Writer decoderWriter = null; Thread ungzipThread = null; try { final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); ungzipThread = new Thread(new Runnable() { public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } }); decoderWriter = Base64.newDecoder(pipedOutputStream); ungzipThread.start(); IOUtils.copy(inputStream, decoderWriter, DVK_MESSAGE_CHARSET); decoderWriter.flush(); pipedOutputStream.flush(); } catch (IOException e) { throw new RuntimeException("failed to unzip and decode input", e); } finally { IOUtils.closeQuietly(decoderWriter); IOUtils.closeQuietly(pipedOutputStream); if (ungzipThread != null) { try { ungzipThread.join(); } catch (InterruptedException ie) { throw new RuntimeException("thread interrupted while for ungzip thread to finish", ie); } } } if (!ungzipThreadThrowableList.isEmpty()) { throw new RuntimeException("ungzip failed", ungzipThreadThrowableList.get(0)); } return outputStream; }
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: public void testBasic() { CameraInfo ci = C328rCameraInfo.getInstance(); assertNotNull(ci); assertNotNull(ci.getCapabilities()); assertFalse(ci.getCapabilities().isEmpty()); System.out.println(ci.getUrl()); URL url = ci.getUrl(); try { URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static void copyCompletely(InputStream input, OutputStream output) throws IOException { if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) { try { FileChannel target = ((FileOutputStream) output).getChannel(); FileChannel source = ((FileInputStream) input).getChannel(); source.transferTo(0, Integer.MAX_VALUE, target); source.close(); target.close(); return; } catch (Exception e) { } } byte[] buf = new byte[8192]; while (true) { int length = input.read(buf); if (length < 0) break; output.write(buf, 0, length); } try { input.close(); } catch (IOException ignore) { } try { output.close(); } catch (IOException ignore) { } } Code Sample 2: public boolean connect(String host, String userName, String password) throws IOException, UnknownHostException { try { if (ftpClient != null) { if (ftpClient.isConnected()) { ftpClient.disconnect(); } } ftpClient = new FTPClient(); boolean success = false; ftpClient.connect(host); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { success = ftpClient.login(userName, password); } if (!success) { ftpClient.disconnect(); } return success; } catch (Exception ex) { throw new IOException(ex.getMessage()); } }
11
Code Sample 1: public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,pilot_id_seq.nextval)"); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); if (pilotData.id != 0) { psta.setInt(19, pilotData.id); } psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } } Code Sample 2: protected String doIt() throws java.lang.Exception { StringBuffer sql = null; int no = 0; String clientCheck = " AND AD_Client_ID=" + m_AD_Client_ID; String[] strFields = new String[] { "Value", "Name", "Description", "DocumentNote", "Help", "UPC", "SKU", "Classification", "ProductType", "Discontinued", "DiscontinuedBy", "ImageURL", "DescriptionURL" }; for (int i = 0; i < strFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFields[i]).append(" = (SELECT ").append(strFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + strFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFields[i] + " - default from existing Product=" + no); } } String[] numFields = new String[] { "C_UOM_ID", "M_Product_Category_ID", "Volume", "Weight", "ShelfWidth", "ShelfHeight", "ShelfDepth", "UnitsPerPallet", "M_Product_Family_ID" }; for (int i = 0; i < numFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFields[i]).append(" = (SELECT ").append(numFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + numFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFields[i] + " default from existing Product=" + no); } } String[] strFieldsPO = new String[] { "UPC", "PriceEffective", "VendorProductNo", "VendorCategory", "Manufacturer", "Discontinued", "DiscontinuedBy" }; for (int i = 0; i < strFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFieldsPO[i]).append(" = (SELECT ").append(strFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + strFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFieldsPO[i] + " default from existing Product PO=" + no); } } String[] numFieldsPO = new String[] { "C_UOM_ID", "C_Currency_ID", "RoyaltyAmt", "Order_Min", "Order_Pack", "CostPerOrder", "DeliveryTime_Promised" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + numFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } numFieldsPO = new String[] { "PriceList", "PricePO" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND (").append(numFieldsPO[i]).append(" IS NULL OR ").append(numFieldsPO[i]).append("=0)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } sql = new StringBuffer("UPDATE I_Product i " + "SET X12DE355 = " + "(SELECT X12DE355 FROM C_UOM u WHERE u.IsDefault='Y' AND u.AD_Client_ID IN (0,i.AD_Client_ID) AND ROWNUM=1) " + "WHERE X12DE355 IS NULL AND C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set UOM Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_UOM_ID = (SELECT C_UOM_ID FROM C_UOM u WHERE u.X12DE355=i.X12DE355 AND u.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set UOM=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid UOM, ' " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid UOM=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET ProductCategory_Value=(SELECT Value FROM M_Product_Category" + " WHERE IsDefault='Y' AND AD_Client_ID=").append(m_AD_Client_ID).append(" AND ROWNUM=1) " + "WHERE ProductCategory_Value IS NULL AND M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Category Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET M_Product_Category_ID=(SELECT M_Product_Category_ID FROM M_Product_Category c" + " WHERE i.ProductCategory_Value=c.Value AND i.AD_Client_ID=c.AD_Client_ID) " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set Category=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProdCategorty,' " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Category=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET ISO_Code=(SELECT ISO_Code FROM C_Currency c" + " INNER JOIN C_AcctSchema a ON (a.C_Currency_ID=c.C_Currency_ID)" + " INNER JOIN AD_ClientInfo fo ON (a.C_AcctSchema_ID=fo.C_AcctSchema1_ID)" + " WHERE fo.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_Currency_ID IS NULL AND ISO_Code IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Currency Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_Currency_ID=(SELECT C_Currency_ID FROM C_Currency c" + " WHERE i.ISO_Code=c.ISO_Code AND c.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt- Set Currency=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Currency,' " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Currency=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProductType,' " + "WHERE ProductType NOT IN ('I','S')" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid ProductType=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value not unique,' " + "WHERE I_IsImported<>'Y'" + " AND Value IN (SELECT Value FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY Value HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique Value=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=UPC not unique,' " + "WHERE I_IsImported<>'Y'" + " AND UPC IN (SELECT UPC FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY UPC HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique UPC=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Mandatory Value,' " + "WHERE Value IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - No Mandatory Value=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET VendorProductNo=Value " + "WHERE C_BPartner_ID IS NOT NULL AND VendorProductNo IS NULL" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - VendorProductNo Set to Value=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=VendorProductNo not unique,' " + "WHERE I_IsImported<>'Y'" + " AND C_BPartner_ID IS NOT NULL" + " AND (C_BPartner_ID, VendorProductNo) IN " + " (SELECT C_BPartner_ID, VendorProductNo FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY C_BPartner_ID, VendorProductNo HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique VendorProductNo=" + no); } int C_TaxCategory_ID = 0; try { PreparedStatement pstmt = DB.prepareStatement("SELECT C_TaxCategory_ID FROM C_TaxCategory WHERE IsDefault='Y'" + clientCheck); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { C_TaxCategory_ID = rs.getInt(1); } rs.close(); pstmt.close(); } catch (SQLException e) { throw new Exception("doIt - TaxCategory", e); } log.fine("doIt - C_TaxCategory_ID=" + C_TaxCategory_ID); int noInsert = 0; int noUpdate = 0; int noInsertPO = 0; int noUpdatePO = 0; log.fine("doIt - start inserting/updating ..."); sql = new StringBuffer("SELECT I_Product_ID, M_Product_ID, C_BPartner_ID " + "FROM I_Product WHERE I_IsImported='N'").append(clientCheck); Connection conn = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); try { PreparedStatement pstmt_insertProduct = conn.prepareStatement("INSERT INTO M_Product (M_Product_ID," + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,IsSummary,M_Product_Category_ID,C_TaxCategory_ID," + "ProductType,ImageURL,DescriptionURL,M_Product_Family_ID) " + "SELECT ?," + "AD_Client_ID,AD_Org_ID,'Y',CURRENT_TIMESTAMP,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,'N',M_Product_Category_ID," + C_TaxCategory_ID + "," + "ProductType,ImageURL,DescriptionURL,M_Product_Category_ID " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_updateProduct = conn.prepareStatement("UPDATE M_PRODUCT " + "SET Value=aux.value" + ",Name=aux.Name" + ",Description=aux.Description" + ",DocumentNote=aux.DocumentNote" + ",Help=aux.Help" + ",UPC=aux.UPC" + ",SKU=aux.SKU" + ",C_UOM_ID=aux.C_UOM_ID" + ",M_Product_Category_ID=aux.M_Product_Category_ID" + ",Classification=aux.Classification" + ",ProductType=aux.ProductType" + ",Volume=aux.Volume" + ",Weight=aux.Weight" + ",ShelfWidth=aux.ShelfWidth" + ",ShelfHeight=aux.ShelfHeight" + ",ShelfDepth=aux.ShelfDepth" + ",UnitsPerPallet=aux.UnitsPerPallet" + ",Discontinued=aux.Discontinued" + ",DiscontinuedBy=aux.DiscontinuedBy" + ",Updated=current_timestamp" + ",UpdatedBy=aux.UpdatedBy" + " from (SELECT Value,Name,Description,DocumentNote,Help,UPC,SKU,C_UOM_ID,M_Product_Category_ID,Classification,ProductType,Volume,Weight,ShelfWidth,ShelfHeight,ShelfDepth,UnitsPerPallet,Discontinued,DiscontinuedBy,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux" + " WHERE M_Product_ID=?"); PreparedStatement pstmt_updateProductPO = conn.prepareStatement("UPDATE M_Product_PO " + "SET IsCurrentVendor='Y'" + ",C_UOM_ID=aux1.C_UOM_ID" + ",C_Currency_ID=aux1.C_Currency_ID" + ",UPC=aux1.UPC" + ",PriceList=aux1.PriceList" + ",PricePO=aux1.PricePO" + ",RoyaltyAmt=aux1.RoyaltyAmt" + ",PriceEffective=aux1.PriceEffective" + ",VendorProductNo=aux1.VendorProductNo" + ",VendorCategory=aux1.VendorCategory" + ",Manufacturer=aux1.Manufacturer" + ",Discontinued=aux1.Discontinued" + ",DiscontinuedBy=aux1.DiscontinuedBy" + ",Order_Min=aux1.Order_Min" + ",Order_Pack=aux1.Order_Pack" + ",CostPerOrder=aux1.CostPerOrder" + ",DeliveryTime_Promised=aux1.DeliveryTime_Promised" + ",Updated=current_timestamp" + ",UpdatedBy=aux1.UpdatedBy" + " from (SELECT 'Y',C_UOM_ID,C_Currency_ID,UPC,PriceList,PricePO,RoyaltyAmt,PriceEffective,VendorProductNo,VendorCategory,Manufacturer,Discontinued,DiscontinuedBy,Order_Min,Order_Pack,CostPerOrder,DeliveryTime_Promised,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux1" + " WHERE M_Product_ID=? AND C_BPartner_ID=?"); PreparedStatement pstmt_insertProductPO = conn.prepareStatement("INSERT INTO M_Product_PO (M_Product_ID,C_BPartner_ID, " + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "IsCurrentVendor,C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised) " + "SELECT ?,?, " + "AD_Client_ID,AD_Org_ID,'Y',d,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "'Y',C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_setImported = conn.prepareStatement("UPDATE I_Product SET I_IsImported='Y', M_Product_ID=?, " + "Updated=CURRENT_TIMESTAMP, Processed='Y' WHERE I_Product_ID=?"); PreparedStatement pstmt = DB.prepareStatement(sql.toString()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int I_Product_ID = rs.getInt(1); int M_Product_ID = rs.getInt(2); int C_BPartner_ID = rs.getInt(3); boolean newProduct = M_Product_ID == 0; log.fine("I_Product_ID=" + I_Product_ID + ", M_Product_ID=" + M_Product_ID + ", C_BPartner_ID=" + C_BPartner_ID); if (newProduct) { M_Product_ID = DB.getNextID(m_AD_Client_ID, "M_Product", null); pstmt_insertProduct.setInt(1, M_Product_ID); pstmt_insertProduct.setInt(2, I_Product_ID); try { no = pstmt_insertProduct.executeUpdate(); log.finer("Insert Product = " + no); noInsert++; } catch (SQLException ex) { log.warning("Insert Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } else { pstmt_updateProduct.setInt(1, I_Product_ID); pstmt_updateProduct.setInt(2, M_Product_ID); try { no = pstmt_updateProduct.executeUpdate(); log.finer("Update Product = " + no); noUpdate++; } catch (SQLException ex) { log.warning("Update Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (C_BPartner_ID != 0) { no = 0; if (!newProduct) { pstmt_updateProductPO.setInt(1, I_Product_ID); pstmt_updateProductPO.setInt(2, M_Product_ID); pstmt_updateProductPO.setInt(3, C_BPartner_ID); try { no = pstmt_updateProductPO.executeUpdate(); log.finer("Update Product_PO = " + no); noUpdatePO++; } catch (SQLException ex) { log.warning("Update Product_PO - " + ex.toString()); noUpdate--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (no == 0) { pstmt_insertProductPO.setInt(1, M_Product_ID); pstmt_insertProductPO.setInt(2, C_BPartner_ID); pstmt_insertProductPO.setInt(3, I_Product_ID); try { no = pstmt_insertProductPO.executeUpdate(); log.finer("Insert Product_PO = " + no); noInsertPO++; } catch (SQLException ex) { log.warning("Insert Product_PO - " + ex.toString()); noInsert--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } } pstmt_setImported.setInt(1, M_Product_ID); pstmt_setImported.setInt(2, I_Product_ID); no = pstmt_setImported.executeUpdate(); conn.commit(); } rs.close(); pstmt.close(); pstmt_insertProduct.close(); pstmt_updateProduct.close(); pstmt_insertProductPO.close(); pstmt_updateProductPO.close(); pstmt_setImported.close(); conn.close(); conn = null; } catch (SQLException e) { try { if (conn != null) { conn.close(); } conn = null; } catch (SQLException ex) { } log.log(Level.SEVERE, "doIt", e); throw new Exception("doIt", e); } finally { if (conn != null) { conn.close(); } conn = null; } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='N', Updated=CURRENT_TIMESTAMP " + "WHERE I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); StringBuffer infoReturn = new StringBuffer(""); infoReturn.append("<tr><td>@Errors@</td><td>").append(no).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Inserted@</td><td>").append(noInsert).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Updated@</td><td>").append(noUpdate).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Inserted@</td><td>").append(noInsertPO).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Updated@</td><td>").append(noUpdatePO).append("</td></tr>"); return infoReturn.toString(); }
00
Code Sample 1: public byte[] uniqueID(String name, String topic) { String key; byte[] id; synchronized (cache_) { key = name + "|" + topic; id = (byte[]) cache_.get(key); if (id == null) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); md.update(name.getBytes()); md.update(topic.getBytes()); id = md.digest(); cache_.put(key, id); if (debug_) { System.out.println("Cached " + key + " [" + id[0] + "," + id[1] + ",...]"); } } catch (NoSuchAlgorithmException e) { throw new Error("SHA not available!"); } } } return id; } Code Sample 2: public void testReplicateAfterWrite2Slave() throws Exception { int nDocs = 50; for (int i = 0; i < nDocs; i++) { index(masterClient, "id", i, "name", "name = " + i); } String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=disableReplication"; URL url = new URL(masterUrl); InputStream stream = url.openStream(); try { stream.close(); } catch (IOException e) { } masterClient.commit(); NamedList masterQueryRsp = query("*:*", masterClient); SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response"); assertEquals(nDocs, masterQueryResult.getNumFound()); Thread.sleep(100); index(slaveClient, "id", 551, "name", "name = " + 551); slaveClient.commit(true, true); index(slaveClient, "id", 552, "name", "name = " + 552); slaveClient.commit(true, true); index(slaveClient, "id", 553, "name", "name = " + 553); slaveClient.commit(true, true); index(slaveClient, "id", 554, "name", "name = " + 554); slaveClient.commit(true, true); index(slaveClient, "id", 555, "name", "name = " + 555); slaveClient.commit(true, true); NamedList slaveQueryRsp = query("id:555", slaveClient); SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(1, slaveQueryResult.getNumFound()); masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=enableReplication"; url = new URL(masterUrl); stream = url.openStream(); try { stream.close(); } catch (IOException e) { } Thread.sleep(3000); slaveQueryRsp = query("id:555", slaveClient); slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response"); assertEquals(0, slaveQueryResult.getNumFound()); }
11
Code Sample 1: public final void copyFile(final File fromFile, final File toFile) throws IOException { this.createParentPathIfNeeded(toFile); final FileChannel sourceChannel = new FileInputStream(fromFile).getChannel(); final FileChannel targetChannel = new FileOutputStream(toFile).getChannel(); final long sourceFileSize = sourceChannel.size(); sourceChannel.transferTo(0, sourceFileSize, targetChannel); } Code Sample 2: public static List<String> unTar(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); TarArchiveInputStream in = new TarArchiveInputStream(inputStream); TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextTarEntry(); } in.close(); return result; }
11
Code Sample 1: @Override public void run() { try { File[] inputFiles = new File[this.previousFiles != null ? this.previousFiles.length + 1 : 1]; File copiedInput = new File(this.randomFolder, this.inputFile.getName()); IOUtils.copyFile(this.inputFile, copiedInput); inputFiles[inputFiles.length - 1] = copiedInput; if (previousFiles != null) { for (int i = 0; i < this.previousFiles.length; i++) { File prev = this.previousFiles[i]; File copiedPrev = new File(this.randomFolder, prev.getName()); IOUtils.copyFile(prev, copiedPrev); inputFiles[i] = copiedPrev; } } org.happycomp.radiog.Activator activator = org.happycomp.radiog.Activator.getDefault(); if (this.exportedMP3File != null) { EncodingUtils.encodeToWavAndThenMP3(inputFiles, this.exportedWavFile, this.exportedMP3File, this.deleteOnExit, this.randomFolder, activator.getCommandsMap()); } else { EncodingUtils.encodeToWav(inputFiles, this.exportedWavFile, randomFolder, activator.getCommandsMap()); } if (encodeMonitor != null) { encodeMonitor.setEncodingFinished(true); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } Code Sample 2: @Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } }
11
Code Sample 1: public boolean updatenum(int num, String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("update addwuliao set innum=? where pid=?"); pm.setInt(1, num); pm.setString(2, pid); int a = pm.executeUpdate(); if (a == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; } Code Sample 2: public static final int executeSql(final Connection conn, final String sql, final boolean rollback) throws SQLException { if (null == sql) return 0; Statement stmt = null; try { stmt = conn.createStatement(); final int updated = stmt.executeUpdate(sql); return updated; } catch (final SQLException e) { if (rollback) conn.rollback(); throw e; } finally { closeAll(null, stmt, null); } }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } } Code Sample 2: private void read(String url) { session.beginTransaction(); try { Document doc = reader.read(new URL(url).openStream()); Element root = doc.getRootElement(); Dict dic = new Dict(); Vector<Cent> v = new Vector<Cent>(); for (Object o : root.elements()) { Element e = (Element) o; if (e.getName().equals("key")) { dic.setName(e.getTextTrim()); } else if (e.getName().equals("audio")) { dic.setAudio(e.getTextTrim()); } else if (e.getName().equals("pron")) { dic.setPron(e.getTextTrim()); } else if (e.getName().equals("def")) { dic.setDef(e.getTextTrim()); } else if (e.getName().equals("sent")) { Cent cent = new Cent(); for (Object subo : e.elements()) { Element sube = (Element) subo; if (sube.getName().equals("orig")) { cent.setOrig(sube.getTextTrim()); } else if (sube.getName().equals("trans")) { cent.setTrans(sube.getTextTrim()); } } v.add(cent); } } if (dic.getName() == null || "".equals(dic.getName())) { session.getTransaction().commit(); return; } session.save(dic); dic.setCent(new HashSet<Cent>()); for (Cent c : v) { c.setDict(dic); dic.getCent().add(c); } session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } }
11
Code Sample 1: public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } } Code Sample 2: public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
00
Code Sample 1: public int openUrl(String url, String method, Bundle params) { int result = 0; try { if (method.equals("GET")) { url = url + "?" + Utility.encodeUrl(params); } String response = ""; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK"); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(Utility.encodeUrl(params).getBytes("UTF-8")); } response = Utility.read(conn.getInputStream()); JSONObject json = new JSONObject(response); try { int code = json.getInt("result"); if (code > 0) result = 1; } catch (Exception e) { result = json.getInt("error_code"); errmessage = json.getString("error_msg"); } } catch (Exception e) { result = -1; } return result; } Code Sample 2: protected void copy(URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { in = url.openStream(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } }
00
Code Sample 1: public static void executeUpdate(Database db, String... statements) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(db); con.setAutoCommit(false); stmt = con.createStatement(); for (String statement : statements) { stmt.executeUpdate(statement); } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } throw e; } finally { closeStatement(stmt); closeConnection(con); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public byte[] getHTTPByte(String sUrl) { HttpURLConnection connection = null; InputStream inputStream = null; ByteArrayOutputStream os = null; try { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); connection.connect(); int httpStatus = connection.getResponseCode(); if (httpStatus != 200) log.info("getHTTPConent error httpStatus - " + httpStatus); inputStream = new BufferedInputStream(connection.getInputStream()); os = new ByteArrayOutputStream(); InputStream is = new BufferedInputStream(inputStream); byte bytes[] = new byte[40960]; int nRead = -1; while ((nRead = is.read(bytes, 0, 40960)) > 0) { os.write(bytes, 0, nRead); } os.close(); is.close(); inputStream.close(); } catch (IOException e) { log.warn("SpiderUtil getHTTPConent IOException -> ", e); } finally { if (inputStream != null) try { os.close(); inputStream.close(); } catch (IOException e) { } } return os.toByteArray(); } Code Sample 2: public void uploadFile(String filename) throws RQLException { checkFtpClient(); OutputStream out = null; try { out = ftpClient.storeFileStream(filename); IOUtils.copy(new FileReader(filename), out); out.close(); ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Upload of local file with name " + filename + " via FTP to server " + server + " failed.", ex); } }
00
Code Sample 1: private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); } Code Sample 2: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
11
Code Sample 1: public static void main(String[] args) { try { { byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1)); System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1)); byte[] dbytes = decode(encodeBytes(bytes1)); System.out.print(encodeBytes(bytes1) + " decoded: "); for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n")); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); byte[] bytes = new byte[0]; int b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, temp, 0, bytes.length); temp[bytes.length] = (byte) b; bytes = temp; } b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.show(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); fos.write(bytes); fos.close(); fis = new java.io.FileInputStream("test.gif_out"); b64is = new Base64.InputStream(fis, ENCODE); byte[] ebytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[ebytes.length + 1]; System.arraycopy(ebytes, 0, temp, 0, ebytes.length); temp[ebytes.length] = (byte) b; ebytes = temp; } b64is.close(); String s = new String(ebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif_out"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.show(); fos = new java.io.FileOutputStream("test.gif.b64_out"); fos.write(ebytes); fis = new java.io.FileInputStream("test.gif.b64_out"); b64is = new Base64.InputStream(fis, DECODE); byte[] edbytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[edbytes.length + 1]; System.arraycopy(edbytes, 0, temp, 0, edbytes.length); temp[edbytes.length] = (byte) b; edbytes = temp; } b64is.close(); iicon = new javax.swing.ImageIcon(edbytes); jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.show(); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); byte[] rbytes = new byte[0]; int b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rbytes.length + 1]; System.arraycopy(rbytes, 0, temp, 0, rbytes.length); temp[rbytes.length] = (byte) b; rbytes = temp; } fis.close(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE); b64os.write(rbytes); b64os.close(); fis = new java.io.FileInputStream("test.gif.b64_out2"); byte[] rebytes = new byte[0]; b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rebytes.length + 1]; System.arraycopy(rebytes, 0, temp, 0, rebytes.length); temp[rebytes.length] = (byte) b; rebytes = temp; } fis.close(); String s = new String(rebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif.b64_out2"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.show(); fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream(fos, DECODE); b64os.write(rebytes); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.show(); } { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while ((b = b64is.read()) >= 0) fos.write(b); fos.close(); b64is.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static String genDigest(String info) { MessageDigest alga; byte[] digesta = null; try { alga = MessageDigest.getInstance("SHA-1"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return byte2hex(digesta); } Code Sample 2: public static String get(String u, String usr, String pwd) { String response = ""; 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())); StringBuffer sb = new StringBuffer(0); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); logger.debug("Response: " + sb.toString()); response = sb.toString(); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; }
00
Code Sample 1: @Test public void test_lookupType_TooShortName() throws Exception { URL url = new URL(baseUrl + "/lookupType/A"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente = '" + id + "'"; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("GET REQUEST OR RESPONSE - Send content: " + file.getAbsolutePath()); FileInputStream in = null; try { in = new FileInputStream(file); int bytes = IOUtils.copy(in, out); LOGGER.debug("wrote bytes: " + bytes); out.flush(); } finally { IOUtils.closeQuietly(in); } } 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 actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("LOAD")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (chooser.showOpenDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(file)); ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); int read = is.read(); while (read != -1) { bos.write(read); read = is.read(); } is.close(); _changed = true; setImage(bos.toByteArray()); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("SAVE")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (_data != null && chooser.showSaveDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); os.write(_data); os.flush(); os.close(); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("DELETE")) { if (_data != null) { int result = JOptionPane.showConfirmDialog(getTopLevelAncestor(), GuiStrings.getString("message.removeimg"), GuiStrings.getString("title.confirm"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { removeImage(); _changed = true; } } } } Code Sample 2: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); }
00
Code Sample 1: public void restoreDrivers() throws ExplorerException { try { drivers.clear(); URL url = URLUtil.getResourceURL("default_drivers.xml"); loadDefaultDrivers(url.openStream()); } catch (IOException e) { throw new ExplorerException(e); } } Code Sample 2: public PVBrowserSearchDocument(URL url, PVBrowserModel applicationModel) { this(applicationModel); if (url != null) { try { data.loadFromXML(url.openStream()); loadOpenPVsFromData(); setHasChanges(false); setSource(url); } catch (java.io.IOException exception) { System.err.println(exception); displayWarning("Open Failed!", exception.getMessage(), exception); } } }
11
Code Sample 1: private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; } Code Sample 2: private static List<InputMethodDescriptor> loadIMDescriptors() { String nm = SERVICES + InputMethodDescriptor.class.getName(); Enumeration<URL> en; LinkedList<InputMethodDescriptor> imdList = new LinkedList<InputMethodDescriptor>(); NativeIM nativeIM = ContextStorage.getNativeIM(); imdList.add(nativeIM); try { en = ClassLoader.getSystemResources(nm); ClassLoader cl = ClassLoader.getSystemClassLoader(); while (en.hasMoreElements()) { URL url = en.nextElement(); InputStreamReader isr = new InputStreamReader(url.openStream(), "UTF-8"); BufferedReader br = new BufferedReader(isr); String str = br.readLine(); while (str != null) { str = str.trim(); int comPos = str.indexOf("#"); if (comPos >= 0) { str = str.substring(0, comPos); } if (str.length() > 0) { imdList.add((InputMethodDescriptor) cl.loadClass(str).newInstance()); } str = br.readLine(); } } } catch (Exception e) { } return imdList; }
00
Code Sample 1: public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException { InputStream input = null; BufferedOutputStream bos = null; File tempUnit = null; try { URL url = null; int total = 0; try { url = new URL(urlStr); input = url.openStream(); URLConnection urlConnection; urlConnection = url.openConnection(); total = urlConnection.getContentLength(); } catch (IOException e) { throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e); } String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1); tempUnit = null; try { if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit"); File parent = tempUnit.getParentFile(); FileUtils.forceMkdir(parent); if (!tempUnit.exists()) FileUtils.touch(tempUnit); bos = new BufferedOutputStream(new FileOutputStream(tempUnit)); } catch (FileNotFoundException e) { throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (IOException e) { throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (DeployToolException e) { throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e); } logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr)); int size = -1; try { size = IOUtils.copy(input, bos); bos.flush(); } catch (IOException e) { logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit)); } if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr)); } finally { if (input != null) IOUtils.closeQuietly(input); if (bos != null) IOUtils.closeQuietly(bos); } logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath())); return tempUnit.getAbsolutePath(); } Code Sample 2: public List<Mosque> getAllMosquaisFromDataBase() { List<Mosque> mosquais = new ArrayList<Mosque>(); InputStream is = null; String result = ""; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (MyMapActivity.DEVELOPER_MODE) { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.mLatitude + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.mLongitude + "")); } else { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.myLocation.getLatitude() + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.myLocation.getLongitude() + "")); } nameValuePairs.add(new BasicNameValuePair(Param.RAYON, DataBaseQuery.rayon * Param.KM_MARGE + "")); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Param.URI_SELECT_ALL_DATA_BASE); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); Mosque mosquai = new Mosque(json_data.getInt(Param.ID), json_data.getString(Param.NOM), json_data.getDouble(Param.LATITUDE), json_data.getDouble(Param.LONGITUDE), json_data.getString(Param.INFO), json_data.getInt(Param.HAVE_PICTURE) == 1 ? true : false, json_data.getString(Param.PICTURE)); mosquais.add(mosquai); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return mosquais; }
11
Code Sample 1: public Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; } Code Sample 2: private static void copy(File source, File target) throws IOException { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(source); to = new FileOutputStream(target); 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 static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; } Code Sample 2: private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } }
00
Code Sample 1: private void retrieveData() { StringBuffer obsBuf = new StringBuffer(); try { URL url = new URL(getProperty("sourceURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String lineIn = null; while ((lineIn = in.readLine()) != null) { if (GlobalProps.DEBUG) { logger.log(Level.FINE, "WebSource retrieveData: " + lineIn); } obsBuf.append(lineIn); } String fmt = getProperty("dataFormat"); if (GlobalProps.DEBUG) { logger.log(Level.FINE, "Raw: " + obsBuf.toString()); } if ("NWS XML".equals(fmt)) { obs = new NWSXmlObservation(obsBuf.toString()); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't connect to: " + getProperty("sourceURL")); if (GlobalProps.DEBUG) { e.printStackTrace(); } } } Code Sample 2: public static void upper() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); URL url = new URL("https://test.ctpe.net/payment/query"); URLConnection conn = url.openConnection(); String data = "<Request version='1.0'> " + "<Header> " + " <Security sender='ff80808109c5bcc00109c5bce9f1003a'/> " + "</Header> " + "<Query entity='ff80808109c5bcc00109c5bce9f50056' level='CHANNEL' mode='INTEGRATOR_TEST'> " + " <User login='ff80808109c5bcc00109c5bce9f20042' pwd='geheim'/> " + " <Period from='2006-03-04' to='2006-03-04'/> " + " <Types> " + " <Type code='RF'/> " + " <Type code='PA'/> " + " <Type code='RV'/> " + " </Types> " + "</Query> " + "</Request> "; conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("load=" + data); wr.flush(); wr.close(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); }
00
Code Sample 1: private String doExecute(AbortableHttpRequest method) throws Throwable { HttpClient client = CLIENT.newInstance(); HttpResponse rsp = client.execute((HttpUriRequest) method); HttpEntity entity = rsp.getEntity(); if (entity == null) throw new RequestError("No entity in method"); InputStream in = null; try { in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder inStr = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { inStr.append(line).append("\r\n"); } entity.consumeContent(); return inStr.toString(); } catch (IOException ex) { LOG.error("IO exception: " + ex.getMessage()); throw ex; } catch (RuntimeException ex) { method.abort(); throw ex; } finally { if (in != null) in.close(); } } Code Sample 2: public static String MD5(String str, String encoding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.reset(); try { messageDigest.update(str.getBytes(encoding)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
11
Code Sample 1: public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } } Code Sample 2: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText("Cargar Imagen"); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } } }); } return buttonImagen; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void zip(ZipArchiveOutputStream zos, File efile, String base) throws IOException { if (efile.isDirectory()) { File[] lf = efile.listFiles(); base = base + File.separator + efile.getName(); for (File file : lf) { zip(zos, file, base); } } else { ZipArchiveEntry entry = new ZipArchiveEntry(efile, base + File.separator + efile.getName()); zos.setEncoding("utf-8"); zos.putArchiveEntry(entry); InputStream is = new FileInputStream(efile); IOUtils.copy(is, zos); is.close(); zos.closeArchiveEntry(); } }
11
Code Sample 1: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; } Code Sample 2: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public void deleteGroupInstruction(int id, int rank) throws FidoDatabaseException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from InstructionGroups " + "where InstructionId = " + id + " and Rank = " + rank; stmt.executeUpdate(sql); bumpAllRowsUp(stmt, id, rank); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: private InputStream callService(String text) { InputStream in = null; try { URL url = new URL(SERVLET_URL); URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.connect(); DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); dataStream.writeBytes(text); dataStream.flush(); dataStream.close(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; }
11
Code Sample 1: private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); }
11
Code Sample 1: public static void copy(File source, File target) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER); while (in.read(buffer) != -1) { buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } buffer.clear(); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { close(in); close(out); } } Code Sample 2: public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); }
11
Code Sample 1: public void write(File file) throws Exception { if (getGEDCOMFile() != null) { size = getGEDCOMFile().length(); if (!getGEDCOMFile().renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(getGEDCOMFile())); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } Code Sample 2: public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
11
Code Sample 1: private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; 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"); } to = null; from = null; } Code Sample 2: public Void doInBackground() { setProgress(0); for (int i = 0; i < uploadFiles.size(); i++) { String filePath = uploadFiles.elementAt(i).getFilePath(); String fileName = uploadFiles.elementAt(i).getFileName(); String fileMsg = "Uploading file " + (i + 1) + "/" + uploadFiles.size() + "\n"; this.publish(fileMsg); try { File inFile = new File(filePath); FileInputStream in = new FileInputStream(inFile); byte[] inBytes = new byte[(int) chunkSize]; int count = 1; int maxCount = (int) (inFile.length() / chunkSize); if (inFile.length() % chunkSize > 0) { maxCount++; } int readCount = 0; readCount = in.read(inBytes); while (readCount > 0) { File splitFile = File.createTempFile("upl", null, null); String splitName = splitFile.getPath(); FileOutputStream out = new FileOutputStream(splitFile); out.write(inBytes, 0, readCount); out.close(); boolean chunkFinal = (count == maxCount); fileMsg = " - Sending chunk " + count + "/" + maxCount + ": "; this.publish(fileMsg); boolean uploadSuccess = false; int uploadTries = 0; while (!uploadSuccess && uploadTries <= 5) { uploadTries++; boolean uploadStatus = upload(splitName, fileName, count, chunkFinal); if (uploadStatus) { fileMsg = "OK\n"; this.publish(fileMsg); uploadSuccess = true; } else { fileMsg = "ERROR\n"; this.publish(fileMsg); uploadSuccess = false; } } if (!uploadSuccess) { fileMsg = "There was an error uploading your files. Please let the pipeline administrator know about this problem. Cut and paste the messages in this box, and supply them.\n"; this.publish(fileMsg); errorFlag = true; return null; } float thisProgress = (count * 100) / (maxCount); float completeProgress = (i * (100 / uploadFiles.size())); float totalProgress = completeProgress + (thisProgress / uploadFiles.size()); setProgress((int) totalProgress); splitFile.delete(); readCount = in.read(inBytes); count++; } } catch (Exception e) { this.publish(e.toString()); } } return null; }
00
Code Sample 1: public static void sendData(final HashMap<String, String> data) { YProgressWindowRepeat y = new YProgressWindowRepeat(I18N.t("Send Data to yaams.de")); try { final StringBuffer send = new StringBuffer("1=1"); for (final String key : data.keySet()) { send.append("&"); send.append(key); send.append("="); send.append(URLEncoder.encode(data.get(key), "UTF-8")); } final URL url = new URL("http://www.rpg-studio.de/libraries/abttools/yaamsFeedback.php"); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(send.toString()); wr.flush(); final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; final StringBuffer erg = new StringBuffer(""); while ((line = rd.readLine()) != null) { erg.append(line); } JOptionPane.showMessageDialog(null, erg.toString(), I18N.t("Feedback"), JOptionPane.INFORMATION_MESSAGE); wr.close(); rd.close(); } catch (final Throwable t) { YException.error("Can not send feedback to http://www.rpg-studio.de/libraries/abttools/yaamsFeedback.php", t); } y.close(); } Code Sample 2: private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
00
Code Sample 1: public static boolean downFile(String url, String username, String password, String remotePath, Date DBLastestDate, String localPath) { File dFile = new File(localPath); if (!dFile.exists()) { dFile.mkdir(); } boolean success = false; FTPClient ftp = new FTPClient(); ftp.setConnectTimeout(connectTimeout); System.out.println("FTP begin!!"); try { int reply; ftp.connect(url); ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.changeWorkingDirectory(remotePath); String[] filesName = ftp.listNames(); if (DBLastestDate == null) { System.out.println(" 初次下载,全部下载 "); for (String string : filesName) { if (!string.matches("[0-9]{12}")) { continue; } File localFile = new File(localPath + "/" + string); OutputStream is = new FileOutputStream(localFile); ftp.retrieveFile(string, is); is.close(); } } else { System.out.println(" 加一下载 "); Date date = DBLastestDate; long ldate = date.getTime(); Date nowDate = new Date(); String nowDateStr = Constants.DatetoString(nowDate, Constants.Time_template_LONG); String fileName; do { ldate += 60 * 1000; Date converterDate = new Date(ldate); fileName = Constants.DatetoString(converterDate, Constants.Time_template_LONG); File localFile = new File(localPath + "/" + fileName); OutputStream is = new FileOutputStream(localFile); if (!ftp.retrieveFile(fileName, is)) { localFile.delete(); } is.close(); } while (fileName.compareTo(nowDateStr) < 0); } ftp.logout(); success = true; } catch (IOException e) { System.out.println("FTP timeout return"); e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } Code Sample 2: public void download(String ftpServer, String user, String password, String fileName, File destination) throws MalformedURLException, IOException { if (ftpServer != null && fileName != null && destination != null) { StringBuffer sb = new StringBuffer("ftp://"); if (user != null && password != null) { sb.append(user); sb.append(':'); sb.append(password); sb.append('@'); } sb.append(ftpServer); sb.append('/'); sb.append(fileName); sb.append(";type=i"); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL(sb.toString()); URLConnection urlc = url.openConnection(); bis = new BufferedInputStream(urlc.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(destination)); int i; while ((i = bis.read()) != -1) { bos.write(i); } } finally { if (bis != null) try { bis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } else { System.out.println("Input not available"); } }
00
Code Sample 1: private static String func(String sf) { int total = 0, temp; String fnctn[] = { "sin", "cos", "tan", "log", "ln", "sqrt", "!" }, temp2 = ""; int pos[] = new int[7]; for (int n = 0; n < fnctn.length; n++) { pos[n] = sf.lastIndexOf(fnctn[n]); } for (int m = 0; m < fnctn.length; m++) { total += pos[m]; } if (total == -7) { return sf; } for (int i = pos.length; i > 1; i--) { for (int j = 0; j < i - 1; j++) { if (pos[j] < pos[j + 1]) { temp = pos[j]; pos[j] = pos[j + 1]; pos[j + 1] = temp; temp2 = fnctn[j]; fnctn[j] = fnctn[j + 1]; fnctn[j + 1] = temp2; } } } if (fnctn[0].equals("sin")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.sine(sf, pos[0], false)); } else { return func(Functions.asin(sf, pos[0], false)); } } else if (fnctn[0].equals("cos")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.cosine(sf, pos[0], false)); } else { return func(Functions.acos(sf, pos[0], false)); } } else if (fnctn[0].equals("tan")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.tangent(sf, pos[0], false)); } else { return func(Functions.atan(sf, pos[0], false)); } } else if (fnctn[0].equals("log")) { return func(Functions.logarithm(sf, pos[0])); } else if (fnctn[0].equals("ln")) { return func(Functions.lnat(sf, pos[0])); } else if (fnctn[0].equals("sqrt")) { return func(Functions.sqroot(sf, pos[0])); } else { return func(Functions.factorial(sf, pos[0])); } } Code Sample 2: public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } }
11
Code Sample 1: public static String generateNonce(boolean is32) { Random random = new Random(); String result = String.valueOf(random.nextInt(9876599) + 123400); if (is32) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(result.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
00
Code Sample 1: private void downloadFile(String url, File destFile) { try { System.out.println("Downloading " + url + " to " + destFile + "..."); destFile.getParentFile().mkdirs(); OutputStream out = new FileOutputStream(destFile); URLConnection conn = new URL(url).openConnection(); InputStream in = conn.getInputStream(); int totalSize = conn.getContentLength(), downloadedSize = 0, size; byte[] buffer = new byte[32768]; ProgressMonitor pm = new ProgressMonitor(null, "Downloading " + url, "", 0, totalSize); pm.setMillisToDecideToPopup(100); pm.setMillisToPopup(500); boolean canceled = false; while ((size = in.read(buffer)) > 0 && !(canceled = pm.isCanceled())) { out.write(buffer, 0, size); pm.setProgress(downloadedSize += size); pm.setNote((100 * downloadedSize / totalSize) + "% finished"); } in.close(); out.close(); if (canceled) { destFile.delete(); fatalError("Starting canceled", "Downloading canceled. Exiting..."); } pm.close(); } catch (IOException ex) { ex.printStackTrace(); destFile.delete(); fatalError("Download Error", "Couldn't download file " + url + ": " + ex); } } Code Sample 2: private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; }
11
Code Sample 1: public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } try { String fichTable; if (sys) { fichTable = ConfigNat.getInstallFolder() + "/xsl/tablesEmbosseuse/" + tableBraille; } else { fichTable = ConfigNat.getUserEmbossTableFolder() + "/" + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(ConfigNat.getUserTempFolder() + "Table_pour_chaines.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: @Test public void testCascadeTraining() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("parity8.train"), new FileOutputStream(temp)); Fann fann = new FannShortcut(8, 1); Trainer trainer = new Trainer(fann); float desiredError = .00f; float mse = trainer.cascadeTrain(temp.getPath(), 30, 1, desiredError); assertTrue("" + mse, mse <= desiredError); } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: private void saveFile(InputStream in, String fullPath) { try { File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(in, out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: protected HttpURLConnection openConnection(final String url) throws IOException { final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("User-Agent", userAgent); connection.setRequestProperty("Accept", "application/xhtml+xml,application/xml,text/xml;q=0.9,*/*;q=0.8"); connection.setRequestProperty("Accept-Language", "ja,en-us;q=0.7,en;q=0.3"); connection.setRequestProperty("Accept-Encoding", "deflate"); connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("Authorization", "Basic ".concat(base64Encode((username.concat(":").concat(password)).getBytes("UTF-8")))); return connection; } Code Sample 2: public static String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } md.update(plaintext.getBytes(Charset.defaultCharset())); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
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 static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: @Before public void BeforeTheTest() throws Exception { URL url = ProfileParserTest.class.getClassLoader().getResource("ca/uhn/hl7v2/conf/parser/tests/example_ack.xml"); URLConnection conn = url.openConnection(); InputStream instream = conn.getInputStream(); if (instream == null) throw new Exception("can't find the xml file"); BufferedReader in = new BufferedReader(new InputStreamReader(instream)); int tmp = 0; StringBuffer buf = new StringBuffer(); while ((tmp = in.read()) != -1) { buf.append((char) tmp); } profileString = buf.toString(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: @Test public void testWriteAndReadSecondLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile directory2 = new RFile(directory1, "directory2"); RFile file = new RFile(directory2, "testreadwrite2nd.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } Code Sample 2: public static InputStream getInputStream(String name) throws java.io.IOException { URL url = getURL(name); if (url != null) { return url.openStream(); } throw new FileNotFoundException("UniverseData: Resource \"" + name + "\" not found."); }
00
Code Sample 1: private static void init(String url) throws Exception { XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); reader.setContentHandler(new ConfigurationHandler()); InputSource isource = new InputSource((new URL(url)).openStream()); isource.setSystemId(url); reader.parse(isource); } Code Sample 2: public void addRegisterInfo(HttpServletRequest request) throws ApplicationException { String[] pids = request.getParameterValues("pid"); if (pids == null || pids.length <= 0) throw new ApplicationException("��ѡ��Ҫ���IJ�Ʒ"); RegisterDao registerDao = new RegisterDao(); Register register = registerDao.findPojoById(StrFun.getString(request, "rid"), Register.class); if (register.audit) throw new ApplicationException("��������Ѿ���ˣ��������µ���Ʒ"); DBConnect dbc = null; Connection conn = null; try { dbc = DBConnect.createDBConnect(); conn = dbc.getConnection(); conn.setAutoCommit(false); for (String pid : pids) { RegisterInfo pd = new RegisterInfo(); pd.rid = StrFun.getInt(request, "rid"); pd.pid = Integer.parseInt(pid); pd.productName = StrFun.getString(request, "productName_" + pid); pd.regAmount = StrFun.getInt(request, "regAmount_" + pid); pd.regPrice = StrFun.getInt(request, "regPrice_" + pid); pd.regSalePrice = StrFun.getInt(request, "regSalePrice_" + pid); pd.userNo = ServerUtil.getUserFromSession(request).userNo; if (pd.regAmount <= 0) throw new ApplicationException("�����������Ϊ��"); String sql = "insert into SS_RegisterInfo " + "(pid, rid, productName, regAmount, regPrice, regSalePrice, userNo) " + "values(" + "'" + pd.pid + "', " + "'" + pd.rid + "', " + "'" + pd.productName + "', " + "'" + pd.regAmount + "', " + "'" + pd.regPrice + "', " + "'" + pd.regSalePrice + "', " + "'" + pd.userNo + "' " + ")"; conn.createStatement().executeUpdate(sql); } conn.commit(); } catch (Exception e) { e.printStackTrace(); if (conn != null) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } throw new ApplicationException(e.getMessage(), e); } finally { if (dbc != null) try { dbc.close(); } catch (Exception e) { e.printStackTrace(); } } }
11
Code Sample 1: public final String hashPassword(final String password) { try { if (salt == null) { salt = new byte[16]; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(System.currentTimeMillis()); sr.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] hash = md.digest(); for (int i = 0; i < (1999); i++) { md.reset(); hash = md.digest(hash); } return byteToString(hash, 60); } catch (Exception exception) { log.error(exception); return null; } } Code Sample 2: private String getMD5Password(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm; StringBuffer hexString = new StringBuffer(); String md5Password = ""; mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } md5Password = hexString.toString(); return md5Password; }
11
Code Sample 1: public void copyDependancyFiles() { for (String[] depStrings : getDependancyFiles()) { String source = depStrings[0]; String target = depStrings[1]; try { File sourceFile = PluginManager.getFile(source); IOUtils.copyEverything(sourceFile, new File(WEB_ROOT + target)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: public static boolean copyFile(File sourceFile, File destFile) throws IOException { long flag = 0; if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); flag = destination.transferFrom(source, 0, source.size()); } catch (Exception e) { Logger.getLogger(FileUtils.class.getPackage().getName()).log(Level.WARNING, "ERROR: Problem copying file", e); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } if (flag == 0) return false; else return true; }
11
Code Sample 1: private void loadServers() { try { URL url = new URL(VirtualDeckConfig.SERVERS_URL); cmbServer.addItem("Local"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; if (in.readLine().equals("[list]")) { while ((str = in.readLine()) != null) { String[] host_line = str.split(";"); Host h = new Host(); h.setIp(host_line[0]); h.setPort(Integer.parseInt(host_line[1])); h.setName(host_line[2]); getServers().add(h); cmbServer.addItem(h.getName()); } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
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 PersistenceUnitInfo getPersistenceUnitInfo() { if (this.persistenceUnitInfo == null) { this.persistenceUnitInfo = new PersistenceUnitInfo() { private List<ClassTransformer> transformers; private List<String> managedClasses; private List<String> mappingFileNames; private ClassLoader classLoader; public String getPersistenceUnitName() { return "jomc-standalone"; } public String getPersistenceProviderClassName() { return getPersistenceProvider().getClass().getName(); } public PersistenceUnitTransactionType getTransactionType() { return PersistenceUnitTransactionType.JTA; } public DataSource getJtaDataSource() { try { return (DataSource) getContext().lookup(getEnvironment().getJtaDataSourceJndiName()); } catch (final NamingException e) { getLogger().fatal(e); throw new RuntimeException(e); } } public DataSource getNonJtaDataSource() { return null; } public List<String> getMappingFileNames() { try { if (this.mappingFileNames == null) { this.mappingFileNames = new LinkedList<String>(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); for (final Enumeration<URL> e = this.getNewTempClassLoader().getResources("META-INF/persistence.xml"); e.hasMoreElements(); ) { final URL url = e.nextElement(); final InputStream in = url.openStream(); final Document doc = documentBuilder.parse(in); in.close(); final NodeList persistenceUnits = doc.getElementsByTagNameNS(PERSISTENCE_NS, "persistence-unit"); for (int i = persistenceUnits.getLength() - 1; i >= 0; i--) { final Element persistenceUnit = (Element) persistenceUnits.item(i); final NodeList mappingFiles = persistenceUnit.getElementsByTagNameNS(PERSISTENCE_NS, "mapping-file"); for (int j = mappingFiles.getLength() - 1; j >= 0; j--) { final Element mappingFile = (Element) mappingFiles.item(j); this.mappingFileNames.add(mappingFile.getFirstChild().getNodeValue()); } } } } return this.mappingFileNames; } catch (final SAXException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final IOException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final ParserConfigurationException e) { getLogger().fatal(e); throw new RuntimeException(e); } } public List<URL> getJarFileUrls() { try { final List<URL> jarFileUrls = new LinkedList<URL>(); for (final Enumeration<URL> unitUrls = this.getClassLoader().getResources("META-INF/persistence.xml"); unitUrls.hasMoreElements(); ) { final URL unitUrl = unitUrls.nextElement(); final String externalForm = unitUrl.toExternalForm(); final String jarUrl = externalForm.substring(0, externalForm.indexOf("META-INF")); jarFileUrls.add(new URL(jarUrl)); } return jarFileUrls; } catch (final IOException e) { getLogger().fatal(e); throw new RuntimeException(e.getMessage(), e); } } public URL getPersistenceUnitRootUrl() { return getEnvironment().getJpaRootUrl(); } public List<String> getManagedClassNames() { try { if (this.managedClasses == null) { this.managedClasses = new LinkedList<String>(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); for (final Enumeration<URL> e = this.getNewTempClassLoader().getResources("META-INF/persistence.xml"); e.hasMoreElements(); ) { final URL url = e.nextElement(); final InputStream in = url.openStream(); final Document doc = documentBuilder.parse(in); in.close(); final NodeList persistenceUnits = doc.getElementsByTagNameNS(PERSISTENCE_NS, "persistence-unit"); for (int i = persistenceUnits.getLength() - 1; i >= 0; i--) { final Element persistenceUnit = (Element) persistenceUnits.item(i); final NodeList classes = persistenceUnit.getElementsByTagNameNS(PERSISTENCE_NS, "class"); for (int j = classes.getLength() - 1; j >= 0; j--) { final Element clazz = (Element) classes.item(j); this.managedClasses.add(clazz.getFirstChild().getNodeValue()); } } } } return this.managedClasses; } catch (final SAXException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final IOException e) { getLogger().fatal(e); throw new RuntimeException(e); } catch (final ParserConfigurationException e) { getLogger().fatal(e); throw new RuntimeException(e); } } public boolean excludeUnlistedClasses() { return false; } public Properties getProperties() { return getEnvironment().getProperties(); } public ClassLoader getClassLoader() { if (this.classLoader == null) { this.classLoader = this.getClass().getClassLoader(); if (this.classLoader == null) { this.classLoader = ClassLoader.getSystemClassLoader(); } this.classLoader = new URLClassLoader(new URL[] { getEnvironment().getJpaRootUrl() }, this.classLoader); } return this.classLoader; } public void addTransformer(final ClassTransformer transformer) { if (this.transformers == null) { this.transformers = new LinkedList<ClassTransformer>(); } this.transformers.add(transformer); } public ClassLoader getNewTempClassLoader() { final List<URL> jarFileUrls = this.getJarFileUrls(); jarFileUrls.add(getEnvironment().getJpaRootUrl()); return new URLClassLoader(jarFileUrls.toArray(new URL[jarFileUrls.size()])); } }; } return this.persistenceUnitInfo; }
00
Code Sample 1: public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setInt(2, q.getDisciplina().getIdDisciplina()); stmt.setInt(3, idTopico); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } }
11
Code Sample 1: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { assertTrue(resourceName.startsWith("/")); final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
11
Code Sample 1: private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; } Code Sample 2: public void run() { counter = 0; Log.debug("Fetching news"); Session session = botService.getSession(); if (session == null) { Log.warn("No current IRC session"); return; } final List<Channel> channels = session.getChannels(); if (channels.isEmpty()) { Log.warn("No channel for the current IRC session"); return; } if (StringUtils.isEmpty(feedURL)) { Log.warn("No feed provided"); return; } Log.debug("Creating feedListener"); FeedParserListener feedParserListener = new DefaultFeedParserListener() { public void onChannel(FeedParserState state, String title, String link, String description) throws FeedParserException { Log.debug("onChannel:" + title + "," + link + "," + description); } public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; } public void onCreated(FeedParserState state, Date date) throws FeedParserException { } }; if (parser != null) { InputStream is = null; try { Log.debug("Reading feedURL"); is = new URL(feedURL).openStream(); parser.parse(feedParserListener, is, feedURL); Log.debug("Parsing done"); } catch (IOException ioe) { Log.error(ioe.getMessage(), ioe); } catch (FeedPollerCancelException fpce) { } catch (FeedParserException e) { for (Channel channel : channels) { channel.say(e.getMessage()); } } finally { IOUtil.closeQuietly(is); } } else { Log.warn("Wasn't able to create feed parser"); } }
00
Code Sample 1: public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout, Map<String, String> headers) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); if (username != null || password != null) { byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } Code Sample 2: private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile, boolean overwrite) throws IOException, DirNotFoundException, FileNotFoundException, FileExistsAlreadyException { File destDir = new File(destFile.getParent()); if (!destDir.exists()) { throw new DirNotFoundException(destDir.getAbsolutePath()); } if (!sourceFile.exists()) { throw new FileNotFoundException(sourceFile.getAbsolutePath()); } if (!overwrite && destFile.exists()) { throw new FileExistsAlreadyException(destFile.getAbsolutePath()); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); } Code Sample 2: public static void copyFile(String oldPath, String newPath) throws IOException { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); } }
00
Code Sample 1: public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; } Code Sample 2: @SuppressWarnings("finally") private void decompress(final File src) throws IOException { final String srcPath = src.getPath(); checkSourceFile(src); final boolean test = this.switches.contains(Switch.test); final File dst; if (test) dst = File.createTempFile("jaxlib-bzip", null); else { if (srcPath.endsWith(".bz2")) dst = new File(srcPath.substring(0, srcPath.length() - 4)); else { this.log.println("WARNING: Can't guess original name, using extension \".out\":").println(srcPath); dst = new File(srcPath + ".out"); } } if (!checkDestFile(dst)) return; final boolean showProgress = this.switches.contains(Switch.showProgress); BZip2InputStream in = null; FileOutputStream out = null; FileChannel outChannel = null; FileLock inLock = null; FileLock outLock = null; try { final FileInputStream in0 = new FileInputStream(src); final FileChannel inChannel = in0.getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); in = new BZip2InputStream(new BufferedXInputStream(in0, 8192)); out = new FileOutputStream(dst); outChannel = out.getChannel(); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } long pos = 0; int progress = 0; final long maxStep = showProgress ? Math.max(8192, inSize / MAX_PROGRESS) : Integer.MAX_VALUE; while (true) { final long step = outChannel.transferFrom(in, pos, maxStep); if (step <= 0) { final long a = inChannel.size(); if (a != inSize) throw error("file " + src + " has been modified concurrently by another process"); if (inChannel.position() >= inSize) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } } else { pos += step; if (showProgress) { final double p = (double) inChannel.position() / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } final long outSize = outChannel.size(); in.close(); out.close(); if (this.verbose) { final double ratio = (outSize == 0) ? (inSize * 100) : ((double) inSize / (double) outSize); this.log.print("compressed size: ").print(inSize) .print("; decompressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!test && !this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } if (test && !dst.delete()) throw error("unable to delete testfile: " + dst); } catch (final IOException ex) { IO.tryClose(in); IO.tryClose(out); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } }
11
Code Sample 1: public static void copyFile(File from, File to) throws FileNotFoundException, IOException { requireFile(from); requireFile(to); if (to.isDirectory()) { to = new File(to, getFileName(from)); } FileChannel sourceChannel = new FileInputStream(from).getChannel(); FileChannel destinationChannel = new FileOutputStream(to).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void loadMemcachedConfigFromURL(URL url, XMLInputFactory factory, List<MemcachedClientConfig> memcachedClientconfigs, List<MemcachedClientSocketPoolConfig> memcachedClientSocketPoolConfigs, List<MemcachedClientClusterConfig> memcachedClientClusterConfig) { MemcachedClientConfig node = null; MemcachedClientSocketPoolConfig socketnode = null; MemcachedClientClusterConfig clusternode = null; InputStream in = null; XMLEventReader r = null; try { in = url.openStream(); r = factory.createXMLEventReader(in); String servers = null; String weights = null; while (r.hasNext()) { XMLEvent event = r.nextEvent(); if (event.isStartElement()) { StartElement start = event.asStartElement(); String tag = start.getName().getLocalPart(); if (tag.equalsIgnoreCase("client")) { node = new MemcachedClientConfig(); if (start.getAttributeByName(new QName("", "name")) != null) node.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client name can't not be null!"); if (start.getAttributeByName(new QName("", "socketpool")) != null) node.setSocketPool(start.getAttributeByName(new QName("", "socketpool")).getValue()); else throw new RuntimeException("memcached client socketpool can't not be null!"); if (start.getAttributeByName(new QName("", "compressEnable")) != null) node.setCompressEnable(Boolean.parseBoolean(start.getAttributeByName(new QName("", "compressEnable")).getValue())); else node.setCompressEnable(true); if (start.getAttributeByName(new QName("", "defaultEncoding")) != null) node.setDefaultEncoding(start.getAttributeByName(new QName("", "defaultEncoding")).getValue()); else node.setDefaultEncoding("UTF-8"); continue; } if (tag.equalsIgnoreCase("errorHandler") && node != null) { event = r.peek(); if (event.isCharacters()) { node.setErrorHandler(event.asCharacters().getData()); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("socketpool")) { socketnode = new MemcachedClientSocketPoolConfig(); servers = null; weights = null; if (start.getAttributeByName(new QName("", "name")) != null) socketnode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached client socketpool name can't not be null!"); if (start.getAttributeByName(new QName("", "failover")) != null) socketnode.setFailover(Boolean.parseBoolean(start.getAttributeByName(new QName("", "failover")).getValue())); if (start.getAttributeByName(new QName("", "initConn")) != null) socketnode.setInitConn(Integer.parseInt(start.getAttributeByName(new QName("", "initConn")).getValue())); if (start.getAttributeByName(new QName("", "minConn")) != null) socketnode.setMinConn(Integer.parseInt(start.getAttributeByName(new QName("", "minConn")).getValue())); if (start.getAttributeByName(new QName("", "maxConn")) != null) socketnode.setMaxConn(Integer.parseInt(start.getAttributeByName(new QName("", "maxConn")).getValue())); if (start.getAttributeByName(new QName("", "maintSleep")) != null) socketnode.setMaintSleep(Integer.parseInt(start.getAttributeByName(new QName("", "maintSleep")).getValue())); if (start.getAttributeByName(new QName("", "nagle")) != null) socketnode.setNagle(Boolean.parseBoolean(start.getAttributeByName(new QName("", "nagle")).getValue())); if (start.getAttributeByName(new QName("", "socketTO")) != null) socketnode.setSocketTo(Integer.parseInt(start.getAttributeByName(new QName("", "socketTO")).getValue())); if (start.getAttributeByName(new QName("", "maxIdle")) != null) socketnode.setMaxIdle(Integer.parseInt(start.getAttributeByName(new QName("", "maxIdle")).getValue())); if (start.getAttributeByName(new QName("", "aliveCheck")) != null) socketnode.setAliveCheck(Boolean.parseBoolean(start.getAttributeByName(new QName("", "aliveCheck")).getValue())); continue; } if (tag.equalsIgnoreCase("servers") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { servers = event.asCharacters().getData(); socketnode.setServers(servers); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("weights") && socketnode != null) { event = r.peek(); if (event.isCharacters()) { weights = event.asCharacters().getData(); socketnode.setWeights(weights); r.nextEvent(); } continue; } if (tag.equalsIgnoreCase("cluster")) { clusternode = new MemcachedClientClusterConfig(); if (start.getAttributeByName(new QName("", "name")) != null) clusternode.setName(start.getAttributeByName(new QName("", "name")).getValue()); else throw new RuntimeException("memcached cluster name can't not be null!"); if (start.getAttributeByName(new QName("", "mode")) != null) clusternode.setMode(start.getAttributeByName(new QName("", "mode")).getValue()); continue; } if (tag.equalsIgnoreCase("memCachedClients") && clusternode != null) { event = r.peek(); if (event.isCharacters()) { String clients = event.asCharacters().getData(); if (clients != null && !clients.equals("")) { clusternode.setMemCachedClients(clients.split(",")); } r.nextEvent(); } continue; } } if (event.isEndElement()) { EndElement end = event.asEndElement(); if (node != null && end.getName().getLocalPart().equalsIgnoreCase("client")) { memcachedClientconfigs.add(node); Logger.info(new StringBuilder().append(" add memcachedClient config :").append(node.getName())); continue; } if (socketnode != null && end.getName().getLocalPart().equalsIgnoreCase("socketpool")) { memcachedClientSocketPoolConfigs.add(socketnode); Logger.info(new StringBuilder().append(" add socketpool config :").append(socketnode.getName())); continue; } if (clusternode != null && end.getName().getLocalPart().equalsIgnoreCase("cluster")) { memcachedClientClusterConfig.add(clusternode); Logger.info(new StringBuilder().append(" add cluster config :").append(clusternode.getName())); continue; } } } } catch (Exception e) { Logger.error(new StringBuilder("MemcachedManager loadConfig error !").append(" config url :").append(url.getFile()).toString()); node = null; } finally { try { if (r != null) r.close(); if (in != null) in.close(); r = null; in = null; } catch (Exception ex) { throw new RuntimeException("processConfigURL error !", ex); } } }
11
Code Sample 1: public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void main(String[] args) throws Exception { final URL url = new URL("http://www.ebi.ac.uk/Tools/webservices/psicquic/registry/registry?action=ACTIVE&format=txt"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; Map<String, String> psiqcuicServices = new HashMap<String, String>(); while ((str = in.readLine()) != null) { final int idx = str.indexOf('='); psiqcuicServices.put(str.substring(0, idx), str.substring(idx + 1, str.length())); } in.close(); System.out.println("Found " + psiqcuicServices.size() + " active service(s)."); for (Object o : psiqcuicServices.keySet()) { String serviceName = (String) o; String serviceUrl = psiqcuicServices.get(serviceName); System.out.println(serviceName + " -> " + serviceUrl); UniversalPsicquicClient client = new UniversalPsicquicClient(serviceUrl); try { SearchResult<?> result = client.getByInteractor("brca2", 0, 50); System.out.println("Interactions found: " + result.getTotalCount()); for (BinaryInteraction binaryInteraction : result.getData()) { String interactorIdA = binaryInteraction.getInteractorA().getIdentifiers().iterator().next().getIdentifier(); String interactorIdB = binaryInteraction.getInteractorB().getIdentifiers().iterator().next().getIdentifier(); String interactionAc = "-"; if (!binaryInteraction.getInteractionAcs().isEmpty()) { CrossReference cr = (CrossReference) binaryInteraction.getInteractionAcs().iterator().next(); interactionAc = cr.getIdentifier(); } System.out.println("\tInteraction (" + interactionAc + "): " + interactorIdA + " interacts with " + interactorIdB); } } catch (Throwable e) { System.err.println("Service is down! " + serviceName + "(" + serviceUrl + ")"); } } } Code Sample 2: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
11
Code Sample 1: private String readJsonString() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER_URL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TAG, "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } Code Sample 2: public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public boolean download(String url) { HttpGet httpGet = new HttpGet(url); String filename = FileUtils.replaceNonAlphanumericCharacters(url); String completePath = directory + File.separatorChar + filename; int retriesLeft = MAX_RETRIES; while (retriesLeft > 0) { try { HttpResponse response = httpClient.execute(httpGet); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { logger.info("Downloading file from " + url + " -> " + completePath); IOUtils.copy(resEntity.getContent(), new FileOutputStream(completePath)); logger.info("File " + filename + " was downloaded successfully."); setFileSize(new File(completePath).length()); setFilename(filename); return true; } else { logger.warn("Trouble downloading file from " + url + ". Status was: " + response.getStatusLine()); } } catch (ClientProtocolException e) { logger.error("Protocol error. This is probably serious, and there's no need " + "to continue trying to download this file.", e); return false; } catch (IOException e) { logger.warn("IO trouble: " + e.getMessage() + ". Retries left: " + retriesLeft); } retriesLeft--; } return false; } Code Sample 2: public static void transfer(File src, File dest, boolean removeSrc) throws FileNotFoundException, IOException { Log.warning("source: " + src); Log.warning("dest: " + dest); if (!src.canRead()) { throw new IOException("can not read src file: " + src); } if (!dest.getParentFile().isDirectory()) { if (!dest.getParentFile().mkdirs()) { throw new IOException("failed to make directories: " + dest.getParent()); } } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); Log.warning("starting transfer from position " + fcin.position() + " to size " + fcin.size()); fcout.transferFrom(fcin, 0, fcin.size()); Log.warning("closing streams and channels"); fcin.close(); fcout.close(); fis.close(); fos.close(); if (removeSrc) { Log.warning("deleting file " + src); src.delete(); } }
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 convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static 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; } Code Sample 2: public static boolean update(Funcionario objFuncionario) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "update funcionario " + " set nome = ? , cpf = ? , telefone = ? , email = ?, senha = ?, login = ?, id_cargo = ?" + " where id_funcionario = ?"; pst = c.prepareStatement(sql); pst.setString(1, objFuncionario.getNome()); pst.setString(2, objFuncionario.getCpf()); pst.setString(3, objFuncionario.getTelefone()); pst.setString(4, objFuncionario.getEmail()); pst.setString(5, objFuncionario.getSenha()); pst.setString(6, objFuncionario.getLogin()); pst.setLong(7, (objFuncionario.getCargo()).getCodigo()); pst.setLong(8, objFuncionario.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e1.getMessage()); } System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
00
Code Sample 1: public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static String read(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringWriter res = new StringWriter(); PrintWriter writer = new PrintWriter(new BufferedWriter(res)); String line; while ((line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); return res.toString(); }
00
Code Sample 1: public static long download(String address, String localFileName) throws Exception { OutputStream out = null; URLConnection conn = null; InputStream in = null; long numWritten = 0; try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } System.out.println(localFileName + "\t" + numWritten); } catch (Exception exception) { System.out.println("Error: " + exception); throw exception; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } return numWritten; } } Code Sample 2: public static byte[] resolveRef(String url) throws MalformedURLException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); URL addressurl = new URL(url); InputStream in = addressurl.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer, 0, bufferSize)) != -1) { out.write(buffer, 0, bytesRead); out.flush(); } return out.toByteArray(); }
11
Code Sample 1: public static void main(String[] args) throws IOException { System.setProperty("java.protocol.xfile", "com.luzan.common.nfs"); if (args.length < 1) usage(); final String cmd = args[0]; if ("delete".equalsIgnoreCase(cmd)) { final String path = getParameter(args, 1); XFile xfile = new XFile(path); if (!xfile.exists()) { System.out.print("File doean't exist.\n"); System.exit(1); } xfile.delete(); } else if ("copy".equalsIgnoreCase(cmd)) { final String pathFrom = getParameter(args, 1); final String pathTo = getParameter(args, 2); final XFile xfileFrom = new XFile(pathFrom); final XFile xfileTo = new XFile(pathTo); if (!xfileFrom.exists()) { System.out.print("File doesn't exist.\n"); System.exit(1); } final String mime = getParameter(args, 3, null); final XFileInputStream in = new XFileInputStream(xfileFrom); final XFileOutputStream xout = new XFileOutputStream(xfileTo); if (!StringUtils.isEmpty(mime)) { final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfileTo.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType(mime); xfa.setContentLength(xfileFrom.length()); } } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); } } Code Sample 2: public static void main(String[] args) { File file = null; try { file = File.createTempFile("TestFileChannel", ".dat"); final ByteBuffer buffer = ByteBuffer.allocateDirect(4); final ByteChannel output = new FileOutputStream(file).getChannel(); buffer.putInt(MAGIC_INT); buffer.flip(); output.write(buffer); output.close(); final ByteChannel input = new FileInputStream(file).getChannel(); buffer.clear(); while (buffer.hasRemaining()) { input.read(buffer); } input.close(); buffer.flip(); final int file_int = buffer.getInt(); if (file_int != MAGIC_INT) { System.out.println("TestFileChannel FAILURE"); System.out.println("Wrote " + Integer.toHexString(MAGIC_INT) + " but read " + Integer.toHexString(file_int)); } else { System.out.println("TestFileChannel SUCCESS"); } } catch (Exception e) { System.out.println("TestFileChannel FAILURE"); e.printStackTrace(System.out); } finally { if (null != file) { file.delete(); } } }
11
Code Sample 1: protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; } Code Sample 2: public String md5Encode(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(pass.getBytes()); byte[] result = md.digest(); return new String(result); }