label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException(className + "Cannot overwrite existing file: " + dest.getAbsolutePath()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
Code Sample 2:
public void deleteRole(AuthSession authSession, RoleBean roleBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (roleBean.getRoleId() == null) throw new IllegalArgumentException("role id is null"); String sql = "delete from WM_AUTH_ACCESS_GROUP where ID_ACCESS_GROUP=? "; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, roleBean.getRoleId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete role"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
11
|
Code Sample 1:
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); } } } }
Code Sample 2:
public List<SuspectFileProcessingStatus> retrieve() throws Exception { BufferedOutputStream bos = null; try { String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/"); listFilePath = listFilePath.concat(".xml"); if (!new File(getDownloadDirectoryPath()).exists()) { FileUtils.forceMkdir(new File(getDownloadDirectoryPath())); } FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath); bos = new BufferedOutputStream(listFileOutputStream); InputStream is = null; if (getUseProxy()) { is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort()); IOUtils.copyLarge(is, bos); } else { URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null); } bos.flush(); bos.close(); File listFile = new File(listFilePath); if (!listFile.exists()) { throw new IllegalStateException("The list file did not get created"); } if (isLoggingInfo()) { logInfo("Downloaded list file : " + listFile); } List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>(); String loadType = GeneralConstants.LOAD_TYPE_FULL; String feedType = GeneralConstants.EMPTY_TOKEN; String listName = getListName(); String errorCode = ""; String description = ""; SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description); sfpsList.add(sfps); if (isLoggingInfo()) { logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps); } return sfpsList; } finally { if (null != bos) { bos.close(); } } }
|
11
|
Code Sample 1:
public static void unzip(File zipInFile, File outputDir) throws Exception { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(zipInFile); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipInFile)); ZipEntry entry = (ZipEntry) zipInputStream.getNextEntry(); File curOutDir = outputDir; while (entry != null) { if (entry.isDirectory()) { curOutDir = new File(curOutDir, entry.getName()); curOutDir.mkdirs(); continue; } File outFile = new File(curOutDir, entry.getName()); File tempDir = outFile.getParentFile(); if (!tempDir.exists()) tempDir.mkdirs(); outFile.createNewFile(); BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream(outFile)); int n; byte[] buf = new byte[1024]; while ((n = zipInputStream.read(buf, 0, 1024)) > -1) outstream.write(buf, 0, n); outstream.flush(); outstream.close(); zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); } zipInputStream.close(); zipFile.close(); }
Code Sample 2:
private void fileCopy(final File src, final File dest) throws IOException { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
00
|
Code Sample 1:
private void checkRoundtrip(byte[] content) throws Exception { InputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(); CodecUtil.encodeQuotedPrintableBinary(in, out); in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray())); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); assertEquals(content, out.toByteArray()); }
Code Sample 2:
String fetch_m3u(String m3u) { InputStream pstream = null; if (m3u.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; return line; } return null; }
|
11
|
Code Sample 1:
public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; this.logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; this.logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; this.logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { this.logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
Code Sample 2:
public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
|
00
|
Code Sample 1:
protected static String encodePassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); return HexString.bufferToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
Code Sample 2:
public InputStream getResource(FCValue name) throws FCException { Element el = _factory.getElementWithID(name.getAsString()); if (el == null) { throw new FCException("Could not find resource \"" + name + "\""); } String urlString = el.getTextTrim(); if (!urlString.startsWith("http")) { try { log.debug("Get resource: " + urlString); URL url; if (urlString.startsWith("file:")) { url = new URL(urlString); } else { url = getClass().getResource(urlString); } return url.openStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } else { try { FCService http = getRuntime().getServiceFor(FCService.HTTP_DOWNLOAD); return http.perform(new FCValue[] { name }).getAsInputStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } }
|
00
|
Code Sample 1:
public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
Code Sample 2:
private RatingServiceSelectionResponseType contactService(String xmlInputString) throws Exception { OutputStream outputStream = null; RatingServiceSelectionResponseType rType = null; try { URL url = new URL(ENDPOINT_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); outputStream = connection.getOutputStream(); outputStream.write(xmlInputString.getBytes()); outputStream.flush(); outputStream.close(); rType = readURLConnection(connection); connection.disconnect(); } catch (Exception e) { throw e; } finally { if (outputStream != null) { outputStream.close(); outputStream = null; } } return rType; }
|
00
|
Code Sample 1:
public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long 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, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
Code Sample 2:
public int doEndTag() throws JspException { JspWriter saida = pageContext.getOut(); HttpURLConnection urlConnection = null; try { URL requisicao = new URL(((HttpServletRequest) pageContext.getRequest()).getRequestURL().toString()); URL link = new URL(requisicao, url); urlConnection = (HttpURLConnection) link.openConnection(); BufferedReader entrada = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "ISO-8859-1")); String linha = entrada.readLine(); while (linha != null) { saida.write(linha + "\n"); linha = entrada.readLine(); } entrada.close(); } catch (Exception e) { try { saida.write("Erro ao incluir o conte�do da URL \"" + url + "\""); } catch (IOException e1) { } } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return super.doEndTag(); }
|
11
|
Code Sample 1:
public void setRemoteConfig(String s) { try { HashMap<String, String> map = new HashMap<String, String>(); URL url = new URL(s); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.startsWith("#")) continue; String[] split = line.split("="); if (split.length >= 2) { map.put(split[0], split[1]); } } MethodAndFieldSetter.setMethodsAndFields(this, map); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@Deprecated public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception { List<SearchKeyResult> outVec = new ArrayList<SearchKeyResult>(); String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, UTF8); URL url = new URL(uri); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); Pattern regex = Pattern.compile("pub.*?<a\\s+href\\s*=\"(.*?)\".*?>\\s*(\\w+)\\s*</a>.*?(\\d+-\\d+-\\d+).*?<a\\s+href\\s*=\".*?\".*?>\\s*(.+?)\\s*</a>", Pattern.CANON_EQ); String line; while ((line = input.readLine()) != null) { Matcher regexMatcher = regex.matcher(line); while (regexMatcher.find()) { String id = regexMatcher.group(2); String downUrl = iKeyServer + regexMatcher.group(1); String downDate = regexMatcher.group(3); String name = decodeHTML(regexMatcher.group(4)); outVec.add(new SearchKeyResult(id, name, downDate, downUrl)); } } IOUtils.closeQuietly(input); return outVec; }
|
11
|
Code Sample 1:
public boolean authorize(String username, String password, String filename) { open(filename); boolean isAuthorized = false; StringBuffer encPasswd = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } String encPassword = encPasswd.toString(); String tempPassword = getPassword(username); System.out.println("epass" + encPassword); System.out.println("pass" + tempPassword); if (tempPassword.equals(encPassword)) { isAuthorized = true; } else { isAuthorized = false; } close(); return isAuthorized; }
Code Sample 2:
public static String toPWD(String pwd) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(pwd.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
11
|
Code Sample 1:
public static String hash(String arg) throws NoSuchAlgorithmException { String input = arg; String output; MessageDigest md = MessageDigest.getInstance("SHA"); md.update(input.getBytes()); output = Hex.encodeHexString(md.digest()); return output; }
Code Sample 2:
private static synchronized byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance(algoritmo); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
|
00
|
Code Sample 1:
public void run() { m_stats.setRunning(); URL url = m_stats.url; if (url != null) { try { URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; handleHTTPConnection(httpConnection, m_stats); } else { System.out.println("Unknown URL Connection Type " + url); } } catch (java.io.IOException ioe) { m_stats.setStatus(m_stats.IOError); m_stats.setErrorString("Error making or reading from connection" + ioe.toString()); } } m_stats.setDone(); m_manager.threadFinished(this); }
Code Sample 2:
public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } }
|
00
|
Code Sample 1:
public void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } }
Code Sample 2:
private void testURL(String urlStr) throws MalformedURLException, IOException { HttpURLConnection conn = null; try { URL url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); int code = conn.getResponseCode(); assertEquals(HttpURLConnection.HTTP_OK, code); } finally { if (conn != null) { conn.disconnect(); } } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { log.debug("Copying file: '" + src + "' to '" + dest + "'"); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
00
|
Code Sample 1:
public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (queue == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); getQueue().post(eventObj); return eventDoc.getEvent().getEventId(); }
Code Sample 2:
public FTPClient sample1a(String server, int port, String username, String password) throws SocketException, IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); return ftpClient; }
|
00
|
Code Sample 1:
protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } }
Code Sample 2:
public int getDBVersion() throws MigrationException { int dbVersion; PreparedStatement ps; try { Connection conn = getConnection(); ps = conn.prepareStatement("SELECT version FROM " + getTablename()); try { ResultSet rs = ps.executeQuery(); try { if (rs.next()) { dbVersion = rs.getInt(1); if (rs.next()) { throw new MigrationException("Too many version in table: " + getTablename()); } } else { ps.close(); ps = conn.prepareStatement("INSERT INTO " + getTablename() + " (version) VALUES (?)"); ps.setInt(1, 1); try { ps.executeUpdate(); } finally { ps.close(); } dbVersion = 1; } } finally { rs.close(); } } finally { ps.close(); } } catch (SQLException e) { logger.log(Level.WARNING, "Could not access " + tablename + ": " + e); dbVersion = 0; Connection conn = getConnection(); try { if (!conn.getAutoCommit()) { conn.rollback(); } conn.setAutoCommit(false); } catch (SQLException e1) { throw new MigrationException("Could not reset transaction state", e1); } } return dbVersion; }
|
11
|
Code Sample 1:
@Override public int onPut(Operation operation) { synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections++; if (logger.isDebugEnabled()) { logger.debug("Connection accepted, total number of connections: " + MuleObexRequestHandler.connections); } } int result = ResponseCodes.OBEX_HTTP_OK; try { headers = operation.getReceivedHeaders(); if (!this.maxFileSize.equals(ObexServer.UNLIMMITED_FILE_SIZE)) { Long fileSize = (Long) headers.getHeader(HeaderSet.LENGTH); if (fileSize == null) { result = ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED; } if (fileSize > this.maxFileSize) { result = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE; } } if (result != ResponseCodes.OBEX_HTTP_OK) { InputStream in = operation.openInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); data = out.toByteArray(); if (interrupted) { data = null; result = ResponseCodes.OBEX_HTTP_GONE; } } return result; } catch (IOException e) { return ResponseCodes.OBEX_HTTP_UNAVAILABLE; } finally { synchronized (this) { this.notify(); } synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections--; if (logger.isDebugEnabled()) { logger.debug("Connection closed, total number of connections: " + MuleObexRequestHandler.connections); } } } }
Code Sample 2:
public void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
|
11
|
Code Sample 1:
public void copyAffix(MailAffix affix, long mailId1, long mailId2) throws Exception { File file = new File(this.getResDir(mailId1) + affix.getAttachAlias()); if (file.exists()) { File file2 = new File(this.getResDir(mailId2) + affix.getAttachAlias()); if (!file2.exists()) { file2.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); in.close(); out.close(); } } else { log.debug(file.getAbsolutePath() + file.getName() + "�����ڣ������ļ�ʧ�ܣ���������"); } }
Code Sample 2:
public static void copy(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
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 static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest); } } byte[] buffer = new byte[1]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
Code Sample 2:
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } }
|
11
|
Code Sample 1:
public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); }
Code Sample 2:
private static void createNonCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { if (line.charAt(0) != ' ') { String[] spaceSplit = PerlHelp.split(line); if (spaceSplit[0].indexOf('_') < 0) { s.add(spaceSplit[0]); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "nonCompound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
Code Sample 2:
public void copieFichier(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
@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(); } }
Code Sample 2:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
|
00
|
Code Sample 1:
public String[] retrieveFasta(String id) throws Exception { URL url = new URL("http://www.ebi.ac.uk/ena/data/view/" + id + "&display=fasta"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String header = reader.readLine(); StringBuffer seq = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { seq.append(line); } reader.close(); return new String[] { header, seq.toString() }; }
Code Sample 2:
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); EntityManager em = EMF.get().createEntityManager(); String url = req.getRequestURL().toString(); String key = req.getParameter("key"); String format = req.getParameter("format"); if (key == null || !key.equals(Keys.APPREGKEY)) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (format != null && format.equals("xml")) resp.getWriter().print(Error.notAuthorised("").toXML(em)); else resp.getWriter().print(Error.notAuthorised("").toJSON(em)); em.close(); return; } String appname = req.getParameter("name"); if (appname == null || appname.equals("")) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.noAppId(null).toXML(em)); else resp.getWriter().print(Error.noAppId(null).toJSON(em)); em.close(); return; } StringBuffer appkey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + appname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { appkey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } ClientApp app = new ClientApp(); app.setName(appname); app.setKey(appkey.toString()); app.setNumreceipts(0L); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(app); tx.commit(); } catch (Throwable t) { log.severe("Error persisting application " + app.getName() + ": " + t.getMessage()); tx.rollback(); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); em.close(); return; } resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(app.toXML(em)); else resp.getWriter().print(app.toJSON(em)); em.close(); }
|
00
|
Code Sample 1:
public static void download(String address, String localFileName, String rawClass, double newVer, int newStage) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int totalBytes = 0; int dlBytes = 0; try { if (!Main.Updates.current.hasFile(rawClass)) { Main.Updates.current.addFile(newVer, newStage, rawClass); } Main.Updates.current.getFile(rawClass).downloading = true; Main.Updates.setImage(rawClass, "refresh.png"); java.io.File folder = new java.io.File(localFileName); folder.createNewFile(); URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); totalBytes = conn.getContentLength(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; double incr = java.lang.Math.floor(totalBytes / 1000); Main.Interface.Update.prgStatus.setMaximum(1000); Main.Interface.Update.prgStatus.setString("0.0%"); while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; dlBytes += numRead; int newVal = (dlBytes != totalBytes ? (int) java.lang.Math.floor(dlBytes / incr) : 1000); Main.Interface.Update.prgStatus.setValue(newVal); Main.Interface.Update.prgStatus.setString((newVal / 10) + "." + (newVal % 10) + "%"); } Main.Updates.current.getFile(rawClass).downloading = false; Main.Updates.current.getFile(rawClass).version = newVer; Main.Updates.current.getFile(rawClass).stage = newStage; Main.Updates.setImage(rawClass, "updater.png"); Main.Updates.updateTable(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ioe) { } } }
Code Sample 2:
protected void setRankOrder() { this.rankOrder = new int[values.length]; for (int i = 0; i < rankOrder.length; i++) { rankOrder[i] = i; assert (!Double.isNaN(values[i])); } for (int i = rankOrder.length - 1; i >= 0; i--) { boolean swapped = false; for (int j = 0; j < i; j++) if (values[rankOrder[j]] < values[rankOrder[j + 1]]) { int r = rankOrder[j]; rankOrder[j] = rankOrder[j + 1]; rankOrder[j + 1] = r; } } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { if (args.length == 0) { System.out.println("Usage: \nGZIPcompress file\n" + "\tUses GZIP compression to compress " + "the file to test.gz"); System.exit(1); } BufferedReader in = new BufferedReader(new FileReader(args[0])); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("test.gz"))); System.out.println("Writing file"); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); System.out.println("Reading file"); BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("test.gz")))); String s; while ((s = in2.readLine()) != null) System.out.println(s); }
Code Sample 2:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream contentIn2 = getClass().getResourceAsStream(CONTENT2_FILE); sourceOut = emptySource.getOutputStream(); try { IOUtils.copy(contentIn2, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn2.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT2_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
|
00
|
Code Sample 1:
protected void logout() { Session session = getConnection().getSession(); session.removeAttribute("usercookie.object"); String urlIn = GeoNetworkContext.url + "/" + GeoNetworkContext.logoutService; Element results = null; String cookie = (String) session.getAttribute("usercookie.object"); if (cookie != null) { try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); log.debug("CheckLogout to GeoNetwork returned " + Xml.getString(results)); } finally { in.close(); } } catch (Exception e) { throw new RuntimeException("User logout to GeoNetwork failed: ", e); } } log.debug("GeoNetwork logout done"); }
Code Sample 2:
private static long writeVMDKFile(String absoluteFile, String urlString) throws Exception { URL urlCon = new URL(urlString); HttpsURLConnection conn = (HttpsURLConnection) urlCon.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Expect", "100-continue"); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Length", "1024"); InputStream in = conn.getInputStream(); String localpath = localPath + "/" + absoluteFile; OutputStream out = new FileOutputStream(new File(localpath)); byte[] buf = new byte[102400]; int len = 0; long written = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); written = written + len; } System.out.println(" Exported File " + absoluteFile + " : " + written); in.close(); out.close(); return written; }
|
00
|
Code Sample 1:
public int next() { int sequenceValue = current(); try { Update update = dbi.getUpdate(); update.setTableName(sequenceTable); update.assignValue("SEQUENCE_VALUE", --sequenceValue); Search search = new Search(); search.addAttributeCriteria(sequenceTable, "SEQUENCE_NAME", Search.EQUAL, sequenceName); update.where(search); int affectedRows = dbi.getConnection().createStatement().executeUpdate(update.toString()); if (affectedRows == 1) { dbi.getConnection().commit(); } else { dbi.getConnection().rollback(); } } catch (SQLException sqle) { System.err.println("SQLException occurred in current(): " + sqle.getMessage()); } return sequenceValue; }
Code Sample 2:
public static OutputStream getOutputStream(String path) throws ResourceException { URL url = getURL(path); if (url != null) { try { return url.openConnection().getOutputStream(); } catch (IOException e) { throw new ResourceException(e); } } else { throw new ResourceException("Error obtaining resource, invalid path: " + path); } }
|
00
|
Code Sample 1:
protected byte[] createFileID() { try { COSDocument cosDoc = cosGetDoc(); if (cosDoc == null) { return null; } ILocator locator = cosDoc.getLocator(); if (locator == null) { return null; } IRandomAccess ra = cosDoc.stGetDoc().getRandomAccess(); if (ra == null) { ra = new RandomAccessByteArray(StringTools.toByteArray("DummyValue")); } MessageDigest digest = MessageDigest.getInstance("MD5"); long time = System.currentTimeMillis(); digest.update(String.valueOf(time).getBytes()); digest.update(locator.getFullName().getBytes()); digest.update(String.valueOf(ra.getLength()).getBytes()); COSInfoDict infoDict = getInfoDict(); if (infoDict != null) { for (Iterator it = infoDict.cosGetDict().iterator(); it.hasNext(); ) { COSObject object = (COSObject) it.next(); digest.update(object.stringValue().getBytes()); } } return digest.digest(); } catch (Exception e) { throw new IllegalStateException(e); } }
Code Sample 2:
public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
|
00
|
Code Sample 1:
@Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (IOException e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_FULL_PREFIX) + Constants.SERVLET_FULL_PREFIX.length() + 1); boolean notScale = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_NOT_SCALE)); ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { String mimetype = fedoraAccess.getMimeTypeForStream(uuid, FedoraUtils.IMG_FULL_STREAM); if (mimetype == null) { mimetype = "image/jpeg"; } ImageMimeType loadFromMimeType = ImageMimeType.loadFromMimeType(mimetype); if (loadFromMimeType == ImageMimeType.JPEG || loadFromMimeType == ImageMimeType.PNG) { StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_FULL/content"); InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to close stream.", e); } finally { is = null; } } } } else { Image rawImg = KrameriusImageSupport.readImage(uuid, FedoraUtils.IMG_FULL_STREAM, this.fedoraAccess, 0, loadFromMimeType); BufferedImage scaled = null; if (!notScale) { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 1250, 1000); } else { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 2500, 2000); } KrameriusImageSupport.writeImageToStream(scaled, "JPG", os); resp.setContentType(ImageMimeType.JPEG.getValue()); resp.setStatus(HttpURLConnection.HTTP_OK); } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } catch (XPathExpressionException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to create XPath expression.", e); } finally { os.flush(); } } }
|
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 final String crypt(String password, String salt) throws NoSuchAlgorithmException { String magic = "$1$"; byte finalState[]; MessageDigest ctx, ctx1; long l; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx = MessageDigest.getInstance("MD5"); ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1 = MessageDigest.getInstance("MD5"); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { for (int i = 0; i < (pl > 16 ? 16 : pl); i++) ctx.update(finalState[i]); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState[0]); } else { ctx.update(password.getBytes()[0]); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { ctx1 = MessageDigest.getInstance("MD5"); if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); }
|
11
|
Code Sample 1:
@Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
Code Sample 2:
public void doRender() throws IOException { File file = new File(fileName); if (!file.exists()) { logger.error("Static resource not found: " + fileName); isNotFound = true; return; } if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript"); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, servletResponse.getOutputStream()); logger.debug("Static resource rendered: ".concat(fileName)); } catch (FileNotFoundException e) { logger.error("Static resource not found: " + fileName); isNotFound = true; } finally { IOUtils.closeQuietly(in); } }
|
11
|
Code Sample 1:
@RequestMapping(value = "/verdocumentoFisico.html", method = RequestMethod.GET) public String editFile(ModelMap model, @RequestParam("id") int idAnexo) { Anexo anexo = anexoService.selectById(idAnexo); model.addAttribute("path", anexo.getAnexoCaminho()); try { InputStream is = new FileInputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); IOUtils.copy(is, fos); Runtime.getRuntime().exec("chmod 777 " + config.tempDir + anexo.getAnexoCaminho()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "verdocumentoFisico"; }
Code Sample 2:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; }
|
00
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public boolean authenticate(String userName, String loginPassword) { if (!systemConfigManager.getBool("ldap", "authEnable")) { return false; } String ldapName = userName; AkteraUser user = userDAO.findUserByName(userName); if (user != null && StringTools.isNotTrimEmpty(user.getLdapName())) { ldapName = user.getLdapName(); } String server = systemConfigManager.getString("ldap", "authHost"); if (StringTools.isTrimEmpty(server)) { return false; } int port = NumberTools.toInt(systemConfigManager.get("ldap", "authPort"), 389); String type = StringTools.trim(systemConfigManager.getString("ldap", "authType")); String baseDn = StringTools.trim(systemConfigManager.getString("ldap", "authBaseDn")); String userDn = StringTools.trim(systemConfigManager.getString("ldap", "authUserDn")); String password = StringTools.trim(systemConfigManager.getString("ldap", "authPassword")); String query = StringTools.trim(systemConfigManager.getString("ldap", "authQuery")); String bindDn = StringTools.trim(systemConfigManager.getString("ldap", "authBindDn")); String passwordAttributeName = StringTools.trim(systemConfigManager.getString("ldap", "authPasswordAttributeName")); Map<String, Object> params = new HashMap<String, Object>(); params.put("userName", userName); params.put("ldapName", ldapName); params.put("loginName", StringTools.isTrimEmpty(ldapName) ? userName : ldapName); query = StringTools.replaceTemplate(query, params); bindDn = StringTools.replaceTemplate(bindDn, params); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port + "/" + baseDn); env.put(Context.SECURITY_AUTHENTICATION, "simple"); if ("ldapAuthBind".equals(type)) { env.put(Context.SECURITY_PRINCIPAL, bindDn); env.put(Context.SECURITY_CREDENTIALS, loginPassword); try { DirContext ctx = new InitialDirContext(env); try { ctx.close(); } catch (Exception ignored) { } return true; } catch (Exception ignored) { return false; } } if (StringTools.isTrimEmpty(userDn) || StringTools.isTrimEmpty(password)) { return false; } env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = null; NamingEnumeration<SearchResult> results = null; try { ctx = new InitialDirContext(env); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", query, controls); if (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); if (attributes.get(passwordAttributeName) == null) { return false; } String pass = new String((byte[]) attributes.get(passwordAttributeName).get()); if (pass.startsWith("{SHA}") || pass.startsWith("{MD5}")) { String method = pass.substring(1, pass.indexOf('}')); MessageDigest digest = MessageDigest.getInstance(method); digest.update(loginPassword.getBytes(), 0, loginPassword.length()); if (pass.equals("{" + method + "}" + Base64.encode(digest.digest()))) { return true; } } else { if (pass.equals(loginPassword)) { return true; } } } } catch (Exception x) { } finally { if (results != null) { try { results.close(); } catch (Exception e) { } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { } } } return false; }
|
00
|
Code Sample 1:
private void saveFile(File destination) { InputStream in = null; OutputStream out = null; try { if (fileScheme) in = new BufferedInputStream(new FileInputStream(source.getPath())); else in = new BufferedInputStream(getContentResolver().openInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) out.write(buffer); Toast.makeText(this, R.string.saveas_file_saved, Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); String username = "test"; String password = "test"; int providerId = 1; if (request.getParameter("providerId") != null) providerId = Integer.parseInt(request.getParameter("providerId")); String thisPageContextAddress = "http://localhost:8080" + request.getContextPath(); String thisPageServingAddress = thisPageContextAddress + "/index.jsp"; String token = ""; String token_timeout = (String) request.getParameter("token_timeout"); String referer = request.getHeader("Referer"); if (token_timeout != null && token_timeout.equals("true")) { System.out.println("token timeout for referer" + referer); if (referer != null) { if (request.getSession().getServletContext().getAttribute("token_timeout_processing_lock") == null) { request.getSession().getServletContext().setAttribute("token_timeout_processing_lock", true); byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); out.println(token); request.getSession().getServletContext().removeAttribute("token_timeout_processing_lock"); } else out.println("token_timeout_processing_lock"); } } else { if (request.getSession().getServletContext().getAttribute("token") == null || request.getSession().getServletContext().getAttribute("token").equals("")) { byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); } out.write("\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <title>AJAX test </title>\n"); out.write(" <link rel=\"stylesheet\" href=\"css/default.css\" type=\"text/css\" />\n"); out.write("\n"); out.write(" <script type=\"text/javascript\" src=\"../OpenLayers-2.8/OpenLayers.js\"></script>\n"); out.write(" <script type=\"text/javascript\">\n"); out.write("\n"); out.write(" var map, layer;\n"); out.write("\n"); out.write(" var token = \""); out.print(request.getSession().getServletContext().getAttribute("token")); out.write("\";\n"); out.write("\n"); out.write("\n"); out.write(" function init(){\n"); out.write("\n"); out.write(" OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;\n"); out.write("\n"); out.write(" var options = {\n"); out.write(" maxExtent: new OpenLayers.Bounds(0, 0, 3000000, 9000000),\n"); out.write(" tileSize :new OpenLayers.Size(250, 250),\n"); out.write(" units: 'm',\n"); out.write(" projection: 'EPSG:3006',\n"); out.write(" resolutions : [1.3,2.6,4,6.6,13.2,26.5,66.1,132.3,264.6,793.8,1322.9,2645.8,13229.2,26458.3]\n"); out.write(" }\n"); out.write("\n"); out.write(" map = new OpenLayers.Map('swedenMap', options);\n"); out.write("\n"); out.write(" layer = new OpenLayers.Layer.TMS(\"TMS\", \"http://localhost:8080/WebGISTileServer/TMSServletProxy/\",\n"); out.write(" { layername: token + '/7', type: 'png' });\n"); out.write("\n"); out.write(" map.addLayer(layer);\n"); out.write("\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoom() );\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoomBar() );\n"); out.write(" map.addControl( new OpenLayers.Control.MouseDefaults());\n"); out.write(" map.addControl( new OpenLayers.Control.MousePosition());\n"); out.write("\n"); out.write(" map.setCenter(new OpenLayers.LonLat(555555, 6846027), 2);\n"); out.write(" }\n"); out.write(" </script>\n"); out.write(" </head>\n"); out.write(" <body onload=\"init()\">\n"); out.write("\n"); out.write(" <div id=\"container\">\n"); out.write("\n"); out.write(" <div id=\"header\">\n"); out.write(" <h1 id=\"logo\">\n"); out.write(" <span>ASP</span> MapServices\n"); out.write(" <small>Web mapping. <span>EASY</span></small>\n"); out.write(" </h1>\n"); out.write("\n"); out.write(" <ul id=\"menu\">\n"); out.write(" <li><a href=\"default.html\">Home</a></li>\n"); out.write(" <li><a href=\"demo_world.jsp\">Demonstration</a></li>\n"); out.write(" <li style=\"border-right: none;\"><a href=\"contact.html\">Contact</a></li>\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div id=\"body\">\n"); out.write(" <ul id=\"maps-menu\">\n"); out.write(" <li><a href=\"demo_world.jsp\">World</a></li>\n"); out.write(" <li><a href=\"demo_sweden_rt90.jsp\">Sweden RT90</a></li>\n"); out.write(" <li><a href=\"demo_sweden_sweref99.jsp\">Sweden SWEREF99</a></li>\n"); out.write(" </ul>\n"); out.write("\n"); out.write(" <div id=\"swedenMap\" style=\"height:600px\"></div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </body>\n"); out.write("\n"); out.write("\n"); out.write(" </head>\n"); out.write("\n"); out.write("</html>"); } out.write('\n'); out.write('\n'); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
|
11
|
Code Sample 1:
public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); }
Code Sample 2:
public static void copyFile(File src, File dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); try { byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } catch (IOException e) { throw e; } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } } catch (IOException e) { logger.error("Error coping file from " + src + " to " + dst, e); } }
|
11
|
Code Sample 1:
@Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
11
|
Code Sample 1:
@Override @RemoteMethod public synchronized boolean copy(int idAnexo) { try { Anexo anexo = selectById(idAnexo); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Usuario usuario = (Usuario) auth.getPrincipal(); if (anexo.getAssinado() == 1 && anexo.getIdAssinadoPor() != usuario.getIdUsuario()) { deleteAnexoFromTemp(anexo); return false; } Carteira carteiraUsuario = carteiraService.selectById(usuario.getIdCarteira()); DocumentoDetalhes documentoDetalhes = anexo.getDocumentoDetalhes(); Set<Documento> documentos = documentoDetalhes.getDocumentosByCarteira(); boolean havePermission = false; for (Documento documento : documentos) { Carteira carteiraDocumento = documento.getCarteira(); if (carteiraDocumento != null) { if (carteiraDocumento.getIdCarteira() == carteiraUsuario.getIdCarteira()) { havePermission = true; System.out.println("tem permisssao: " + havePermission); break; } } } if (!havePermission) { System.out.println("Não tem permissao."); return false; } FileInputStream fis = new FileInputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); IOUtils.copy(fis, fos); String txtHistorico = "(Edição) -" + anexo.getAnexoNome() + "-"; txtHistorico += usuario.getUsuLogin(); Historico historico = new Historico(); historico.setCarteira(carteiraUsuario); historico.setDataHoraHistorico(new Date()); historico.setHistorico(txtHistorico); historico.setDocumentoDetalhes(documentoDetalhes); historico.setUsuario(usuario); historicoService.save(historico); return deleteAnexoFromTemp(anexo); } catch (FileNotFoundException e) { System.out.println("FileNotFoundException"); e.printStackTrace(); return false; } catch (IOException e) { System.out.println("IOException"); e.printStackTrace(); return false; } catch (Exception e) { System.out.println("AnexoServiceImpl.copy ERRO DESCONHECIDO"); e.printStackTrace(); return false; } }
Code Sample 2:
private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
|
00
|
Code Sample 1:
public int saveRoom(String name, String icon, String stringid) { DBConnection con = null; int categoryId = -1; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String query = "INSERT INTO cafe_Chat_Category " + "(cafe_Chat_Category_pid,cafe_Chat_Category_name, cafe_Chat_Category_icon) " + "VALUES (null,?,?) "; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, name); ps.setString(2, icon); ps.executeUpdate(); query = "SELECT cafe_Chat_Category_id FROM cafe_Chat_Category " + "WHERE cafe_Chat_Category_name=? "; ps = con.prepareStatement(query); ps.setString(1, name); ResultSet rs = ps.executeQuery(); if (rs.next()) { query = "INSERT INTO cafe_Chatroom (cafe_chatroom_category, cafe_chatroom_name, cafe_chatroom_stringid) " + "VALUES (?,?,?) "; ps = con.prepareStatement(query); ps.setInt(1, rs.getInt("cafe_Chat_Category_id")); categoryId = rs.getInt("cafe_Chat_Category_id"); ps.setString(2, name); ps.setString(3, stringid); ps.executeUpdate(); } con.commit(); con.setAutoCommit(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException sqle) { } } finally { if (con != null) con.release(); } return categoryId; }
Code Sample 2:
private static String executeQueryWithSaxon(String queryFile) throws XPathException, FileNotFoundException, IOException, URISyntaxException { URL url = DocumentTableTest.class.getResource(queryFile); URI uri = url.toURI(); String query = IOUtils.toString(url.openStream()); Configuration config = new Configuration(); config.setHostLanguage(Configuration.XQUERY); StaticQueryContext staticContext = new StaticQueryContext(config); staticContext.setBaseURI(uri.toString()); XQueryExpression exp = staticContext.compileQuery(query); Properties props = new Properties(); props.setProperty(SaxonOutputKeys.WRAP, "no"); props.setProperty(OutputKeys.INDENT, "no"); props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter res_sw = new StringWriter(); DynamicQueryContext dynamicContext = new DynamicQueryContext(config); exp.run(dynamicContext, new StreamResult(res_sw), props); return res_sw.toString(); }
|
00
|
Code Sample 1:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
Code Sample 2:
public static String getMD5(String in) { if (in == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(in.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xFF & hash[i]); if (hex.length() == 1) { hex = "0" + hex; } hexString.append(hex); } return hexString.toString(); } catch (Exception e) { Debug.logException(e); } return null; }
|
11
|
Code Sample 1:
public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } }
Code Sample 2:
public String readFile(String filename) throws UnsupportedEncodingException, FileNotFoundException, IOException { File f = new File(baseDir); f = new File(f, filename); StringWriter w = new StringWriter(); Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); IOUtils.copy(fr, w); fr.close(); w.close(); String contents = w.toString(); return contents; }
|
00
|
Code Sample 1:
private void findFile() throws SchedulerException { java.io.InputStream f = null; String furl = null; File file = new File(getFileName()); if (!file.exists()) { URL url = classLoadHelper.getResource(getFileName()); if (url != null) { try { furl = URLDecoder.decode(url.getPath(), "UTF-8"); file = new File(furl); f = url.openStream(); } catch (java.io.UnsupportedEncodingException uee) { } catch (IOException ignor) { } } } else { try { f = new java.io.FileInputStream(file); } catch (FileNotFoundException e) { } } if (f == null && isFailOnFileNotFound()) { throw new SchedulerException("File named '" + getFileName() + "' does not exist. f == null && isFailOnFileNotFound()"); } else if (f == null) { getLog().warn("File named '" + getFileName() + "' does not exist. f == null"); } else { fileFound = true; try { if (furl != null) this.filePath = furl; else this.filePath = file.getAbsolutePath(); f.close(); } catch (IOException ioe) { getLog().warn("Error closing jobs file " + getFileName(), ioe); } } }
Code Sample 2:
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } }
|
00
|
Code Sample 1:
protected static boolean checkVersion(String address) { Scanner scanner = null; try { URL url = new URL(address); InputStream iS = url.openStream(); scanner = new Scanner(iS); if (scanner == null && DEBUG) System.out.println("SCANNER NULL"); String firstLine = scanner.nextLine(); double latestVersion = Double.valueOf(firstLine.trim()); double thisVersion = JCards.VERSION; if (thisVersion >= latestVersion) { JCards.latestVersion = true; } else { displaySimpleAlert(null, JCards.VERSION_PREFIX + latestVersion + " is available online!\n" + "Look under the file menu for a link to the download site."); } } catch (Exception e) { if (VERBOSE || DEBUG) { System.out.println("Can't decide latest version"); e.printStackTrace(); } return false; } return true; }
Code Sample 2:
public void sortingByBubble(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } }
|
11
|
Code Sample 1:
private String MD5Sum(String input) { String hashtext = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; }
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; }
|
11
|
Code Sample 1:
public static void copy(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
private InputStream open(String url) throws IOException { debug(url); if (!useCache) { return new URL(url).openStream(); } File f = new File(System.getProperty("java.io.tmpdir", "."), Digest.SHA1.encrypt(url) + ".xml"); debug("Cache : " + f); if (f.exists()) { return new FileInputStream(f); } InputStream in = new URL(url).openStream(); OutputStream out = new FileOutputStream(f); IOUtils.copyTo(in, out); out.flush(); out.close(); in.close(); return new FileInputStream(f); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
|
00
|
Code Sample 1:
public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
Code Sample 2:
public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } }
|
11
|
Code Sample 1:
public static void copyFile(File file, File destination) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(file)); out = new BufferedOutputStream(new FileOutputStream(destination)); int c; while ((c = in.read()) != -1) out.write(c); } finally { try { if (out != null) out.close(); } catch (Exception e) { } try { if (in != null) in.close(); } catch (Exception e) { } } }
Code Sample 2:
public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; }
Code Sample 2:
public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } }
|
00
|
Code Sample 1:
public static boolean isLinkHtmlContent(String address) { boolean isHtml = false; URLConnection conn = null; try { if (!address.startsWith("http://")) { address = "http://" + address; } URL url = new URL(address); conn = url.openConnection(); if (conn.getContentType().equals("text/html") && !conn.getHeaderField(0).contains("404")) { isHtml = true; } } catch (Exception e) { logger.error("Address attempted: " + conn.getURL()); logger.error("Error Message: " + e.getMessage()); } return isHtml; }
Code Sample 2:
public void testReleaseOnEntityWriteTo() throws Exception { HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/random/20000"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); assertEquals(1, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
|
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) { logger.error(Logger.SECURITY_FAILURE, "Problem encoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
public Object run() { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { userHome + sep + ".themes", System.getProperty("swing.metacitythemedir"), "/usr/share/themes", "/usr/gnome/share/themes", "/opt/gnome2/share/themes" }; URL themeDir = null; for (int i = 0; i < dirs.length; i++) { if (dirs[i] == null) { continue; } File dir = new File(dirs[i] + sep + arg + sep + "metacity-1"); if (new File(dir, "metacity-theme-1.xml").canRead()) { try { themeDir = dir.toURL(); } catch (MalformedURLException ex) { themeDir = null; } break; } } if (themeDir == null) { String filename = "resources/metacity/" + arg + "/metacity-1/metacity-theme-1.xml"; URL url = getClass().getResource(filename); if (url != null) { String str = url.toString(); try { themeDir = new URL(str.substring(0, str.lastIndexOf('/')) + "/"); } catch (MalformedURLException ex) { themeDir = null; } } } return themeDir; } else if (type == GET_USER_THEME) { try { userHome = System.getProperty("user.home"); String theme = System.getProperty("swing.metacitythemename"); if (theme != null) { return theme; } URL url = new URL(new File(userHome).toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); char[] buf = new char[1024]; StringBuffer strBuf = new StringBuffer(); int n; while ((n = reader.read(buf)) >= 0) { strBuf.append(buf, 0, n); } reader.close(); String str = strBuf.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); int i = strLowerCase.indexOf("<entry name=\"theme\""); if (i >= 0) { i = strLowerCase.indexOf("<stringvalue>", i); if (i > 0) { i += "<stringvalue>".length(); int i2 = str.indexOf("<", i); return str.substring(i, i2); } } } } catch (MalformedURLException ex) { } catch (IOException ex) { } return null; } else if (type == GET_IMAGE) { return new ImageIcon((URL) arg).getImage(); } else { return null; } }
Code Sample 2:
public static String digest(String value, String algorithm) throws Exception { MessageDigest algo = MessageDigest.getInstance(algorithm); algo.reset(); algo.update(value.getBytes("UTF-8")); return StringTool.byteArrayToString(algo.digest()); }
|
00
|
Code Sample 1:
public void testResolveURL() throws Exception { System.out.println("resolveURL"); File bigFile = new File("./src/test/java/big.json"); File smallFile = new File("./src/test/java/sample1.json"); Object[] urls = new Object[] { "http://json-schema.org/schema", "http://json-schema.org/hyper-schema", "http://json-schema.org/json-ref", "http://json-schema.org/interfaces", "http://json-schema.org/geo", "http://json-schema.org/card", "http://json-schema.org/calendar", "http://json-schema.org/address", bigFile }; JSONSchemaURIResolverImpl uriResolver = new JSONSchemaURIResolverImpl(); JSONSchemaURIResolverImpl uriResolver2 = new JSONSchemaURIResolverImpl(); try { InputStream is = new URL((String) urls[0]).openStream(); is.close(); } catch (ConnectException cex) { for (int i = 2; i < urls.length; i++) { if (urls[i] instanceof String) { String url = (String) urls[i]; uriResolver.register(new URL(url), new File("./src/test/java/" + url.replace(":", "_").replace("/", "_") + ".schema.json")); } else if (urls[i] instanceof File) { uriResolver.register(((File) urls[i]).toURI().toURL(), urls[i]); } } } catch (Exception ex) { } for (int i = 2; i < urls.length; i++) { if (urls[i] instanceof String) { String url = (String) urls[i]; uriResolver2.register(new URL(url), new File("./src/test/java/" + url.replace(":", "_").replace("/", "_") + ".schema.json")); } else if (urls[i] instanceof File) { uriResolver2.register(((File) urls[i]).toURI().toURL(), urls[i]); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver.resolveURI(new URI((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver.resolveURL(new URL((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver2.resolveURI(new URI((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); assertTrue((new URL((String) source)).equals(uriResolver2.lastURL)); assertFalse((new URL((String) source)).equals(uriResolver2.lastMapped)); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver2.resolveURL(new URL((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); assertTrue((new URL((String) source)).equals(uriResolver2.lastURL)); assertFalse((new URL((String) source)).equals(uriResolver2.lastMapped)); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } uriResolver2.register(new URL("ftp://localhost/1"), bigFile); uriResolver2.register(new URL("ftp://localhost/2"), smallFile); uriResolver2.register(new URL("ftp://localhost/2#2"), smallFile); try { Reader r1 = uriResolver2.resolveURL(new URL("ftp://localhost/2"), null).getReader(); Reader r2 = uriResolver2.resolveURL(new URL("ftp://localhost/2#2"), null).getReader(); int ch = 0; while ((ch = r1.read()) != -1) { assertEquals(ch, r2.read()); } assertEquals(-1, r2.read()); } catch (Throwable th) { fail("Failed while testing identity of same mapped files. Error: " + th); } uriResolver2.register(new URL("ftp://localhost/1"), null); uriResolver2.register(new URL("ftp://localhost/2"), null); uriResolver2.register(new URL("ftp://localhost/2#2"), null); uriResolver2.register(new URL("ftp://localhost/1"), bigFile, true); uriResolver2.register(new URL("ftp://localhost/2"), smallFile, true); uriResolver2.register(new URL("ftp://localhost/2#2"), smallFile, true); uriResolver2.unregister(new URL("ftp://localhost/1"), true); uriResolver2.unregister(new URL("ftp://localhost/2"), true); uriResolver2.unregister(new URL("ftp://localhost/2#2"), true); }
Code Sample 2:
public static InputStreamReader getInputStreamReader(String name) throws java.io.IOException { URL url = getURL(name); if (url != null) { return new InputStreamReader(url.openStream()); } throw new FileNotFoundException("UniverseData: Resource \"" + name + "\" not found."); }
|
11
|
Code Sample 1:
public Object process(Atom oAtm) throws IOException { File oFile; FileReader oFileRead; String sPathHTML; char cBuffer[]; Object oReplaced; final String sSep = System.getProperty("file.separator"); if (DebugFile.trace) { DebugFile.writeln("Begin FileDumper.process([Job:" + getStringNull(DB.gu_job, "") + ", Atom:" + String.valueOf(oAtm.getInt(DB.pg_atom)) + "])"); DebugFile.incIdent(); } if (bHasReplacements) { sPathHTML = getProperty("workareasput"); if (!sPathHTML.endsWith(sSep)) sPathHTML += sSep; sPathHTML += getParameter("gu_workarea") + sSep + "apps" + sSep + "Mailwire" + sSep + "html" + sSep + getParameter("gu_pageset") + sSep; sPathHTML += getParameter("nm_pageset").replace(' ', '_') + ".html"; if (DebugFile.trace) DebugFile.writeln("PathHTML = " + sPathHTML); oReplaced = oReplacer.replace(sPathHTML, oAtm.getItemMap()); bHasReplacements = (oReplacer.lastReplacements() > 0); } else { oReplaced = null; if (null != oFileStr) oReplaced = oFileStr.get(); if (null == oReplaced) { sPathHTML = getProperty("workareasput"); if (!sPathHTML.endsWith(sSep)) sPathHTML += sSep; sPathHTML += getParameter("gu_workarea") + sSep + "apps" + sSep + "Mailwire" + sSep + "html" + sSep + getParameter("gu_pageset") + sSep + getParameter("nm_pageset").replace(' ', '_') + ".html"; if (DebugFile.trace) DebugFile.writeln("PathHTML = " + sPathHTML); oFile = new File(sPathHTML); cBuffer = new char[new Long(oFile.length()).intValue()]; oFileRead = new FileReader(oFile); oFileRead.read(cBuffer); oFileRead.close(); if (DebugFile.trace) DebugFile.writeln(String.valueOf(cBuffer.length) + " characters readed"); oReplaced = new String(cBuffer); oFileStr = new SoftReference(oReplaced); } } String sPathJobDir = getProperty("storage"); if (!sPathJobDir.endsWith(sSep)) sPathJobDir += sSep; sPathJobDir += "jobs" + sSep + getParameter("gu_workarea") + sSep + getString(DB.gu_job) + sSep; FileWriter oFileWrite = new FileWriter(sPathJobDir + getString(DB.gu_job) + "_" + String.valueOf(oAtm.getInt(DB.pg_atom)) + ".html", true); oFileWrite.write((String) oReplaced); oFileWrite.close(); iPendingAtoms--; if (DebugFile.trace) { DebugFile.writeln("End FileDumper.process([Job:" + getStringNull(DB.gu_job, "") + ", Atom:" + String.valueOf(oAtm.getInt(DB.pg_atom)) + "])"); DebugFile.decIdent(); } return oReplaced; }
Code Sample 2:
private static void createNonCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { if (line.charAt(0) != ' ') { String[] spaceSplit = PerlHelp.split(line); if (spaceSplit[0].indexOf('_') < 0) { s.add(spaceSplit[0]); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "nonCompound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void copyResource(String resource, File targetDir) { InputStream is = FragmentFileSetTest.class.getResourceAsStream(resource); Assume.assumeNotNull(is); int i = resource.lastIndexOf("/"); String filename; if (i == -1) { filename = resource; } else { filename = resource.substring(i + 1); } try { FileOutputStream fos = new FileOutputStream(new File(targetDir, filename)); IOUtils.copy(is, fos); fos.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private void createGraphicalViewer(Composite parent) { viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)); registerEditPartViewer(viewer); configureEditPartViewer(viewer); viewer.setEditPartFactory(new GraphicalEditPartsFactory(getSite().getShell())); viewer.setContents(getContractEditor().getContract()); ContextMenuProvider provider = new ContractContextMenuProvider(getGraphicalViewer(), getContractEditor().getActionRegistry()); getGraphicalViewer().setContextMenu(provider); getSite().registerContextMenu(provider, getGraphicalViewer()); }
Code Sample 2:
protected void createGraphicalViewer(Composite parent) { final RulerComposite rc = new RulerComposite(parent, SWT.NONE); viewer = new ScrollingGraphicalViewer(); viewer.createControl(rc); editDomain.addViewer(viewer); rc.setGraphicalViewer(viewer); viewer.getControl().setBackground(ColorConstants.white); viewer.setEditPartFactory(new EditPartFactory() { public EditPart createEditPart(EditPart context, Object model) { return new RecorderEditPart(TopLevelModel.getRecorderModel()); } }); viewer.setContents(TopLevelModel.getRecorderModel()); Control control = viewer.getControl(); System.out.println("widget: " + control); DropTarget dt = new DropTarget(control, DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT); dt.setTransfer(new Transfer[] { TextTransfer.getInstance() }); dt.addDropListener(new SensorTransferDropTargetListener(viewer)); }
|
00
|
Code Sample 1:
private void getViolationsReportByProductOfferIdYearMonthDay() throws IOException { String xmlFile9Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportByProductOfferIdYearMonthDay.xml"; URL url9; url9 = new URL(bmReportingWSUrl); URLConnection connection9 = url9.openConnection(); HttpURLConnection httpConn9 = (HttpURLConnection) connection9; FileInputStream fin9 = new FileInputStream(xmlFile9Send); ByteArrayOutputStream bout9 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin9, bout9); fin9.close(); byte[] b9 = bout9.toByteArray(); httpConn9.setRequestProperty("Content-Length", String.valueOf(b9.length)); httpConn9.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn9.setRequestProperty("SOAPAction", soapAction); httpConn9.setRequestMethod("POST"); httpConn9.setDoOutput(true); httpConn9.setDoInput(true); OutputStream out9 = httpConn9.getOutputStream(); out9.write(b9); out9.close(); InputStreamReader isr9 = new InputStreamReader(httpConn9.getInputStream()); BufferedReader in9 = new BufferedReader(isr9); String inputLine9; StringBuffer response9 = new StringBuffer(); while ((inputLine9 = in9.readLine()) != null) { response9.append(inputLine9); } in9.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: " + "getViolationsReportByProductOfferIdYearMonthDay\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response9.toString()); }
Code Sample 2:
public static String encrypt(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes("UTF-8")); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public void copy(File from, String to) throws SystemException { assert from != null; File dst = new File(folder, to); dst.getParentFile().mkdirs(); FileChannel in = null; FileChannel out = null; try { if (!dst.exists()) dst.createNewFile(); in = new FileInputStream(from).getChannel(); out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { throw new SystemException(e); } finally { try { if (in != null) in.close(); } catch (Exception e1) { } try { if (out != null) out.close(); } catch (Exception e1) { } } }
Code Sample 2:
public void testWriteThreadsNoCompression() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.loadProfiles(CommandLineProcessorFactory.PROFILE.DB, CommandLineProcessorFactory.PROFILE.REST_CLIENT, CommandLineProcessorFactory.PROFILE.COLLECTOR); final LocalLogFileWriter writer = (LocalLogFileWriter) bootstrap.getBean(LogFileWriter.class); writer.init(); writer.setCompressionCodec(null); File fileInput = new File(baseDir, "testWriteOneFile/input"); fileInput.mkdirs(); File fileOutput = new File(baseDir, "testWriteOneFile/output"); fileOutput.mkdirs(); writer.setBaseDir(fileOutput); int fileCount = 100; int lineCount = 100; File[] inputFiles = createInput(fileInput, fileCount, lineCount); ExecutorService exec = Executors.newFixedThreadPool(fileCount); final CountDownLatch latch = new CountDownLatch(fileCount); for (int i = 0; i < fileCount; i++) { final File file = inputFiles[i]; final int count = i; exec.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { FileStatus.FileTrackingStatus status = FileStatus.FileTrackingStatus.newBuilder().setFileDate(System.currentTimeMillis()).setDate(System.currentTimeMillis()).setAgentName("agent1").setFileName(file.getName()).setFileSize(file.length()).setLogType("type1").build(); BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = reader.readLine()) != null) { writer.write(status, new ByteArrayInputStream((line + "\n").getBytes())); } } finally { IOUtils.closeQuietly(reader); } LOG.info("Thread[" + count + "] completed "); latch.countDown(); return true; } }); } latch.await(); exec.shutdown(); LOG.info("Shutdown thread service"); writer.close(); File[] outputFiles = fileOutput.listFiles(); assertNotNull(outputFiles); File testCombinedInput = new File(baseDir, "combinedInfile.txt"); testCombinedInput.createNewFile(); FileOutputStream testCombinedInputOutStream = new FileOutputStream(testCombinedInput); try { for (File file : inputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedInputOutStream); } } finally { testCombinedInputOutStream.close(); } File testCombinedOutput = new File(baseDir, "combinedOutfile.txt"); testCombinedOutput.createNewFile(); FileOutputStream testCombinedOutOutStream = new FileOutputStream(testCombinedOutput); try { System.out.println("----------------- " + testCombinedOutput.getAbsolutePath()); for (File file : outputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedOutOutStream); } } finally { testCombinedOutOutStream.close(); } FileUtils.contentEquals(testCombinedInput, testCombinedOutput); }
|
00
|
Code Sample 1:
private ShaderProgram loadShaderProgram() { ShaderProgram sp = null; String vertexProgram = null; String fragmentProgram = null; Shader[] shaders = new Shader[2]; try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.vert"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.vert"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.vert"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); vertexProgram = new String(buffer); vertexProgram = vertexProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.vert"); e.printStackTrace(); } try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/simple.frag"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/simple.frag"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/simple.frag"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); fragmentProgram = new String(buffer); fragmentProgram = fragmentProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load simple.frag"); e.printStackTrace(); } if (vertexProgram != null && fragmentProgram != null) { shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); sp = new GLSLShaderProgram(); sp.setShaders(shaders); } return sp; }
Code Sample 2:
public static String doGet(String http_url, String get_data) { URL url; try { if ((get_data != "") && (get_data != null)) { url = new URL(http_url + "?" + get_data); } else { url = new URL(http_url); } URLConnection conn = url.openConnection(); InputStream stream = new BufferedInputStream(conn.getInputStream()); try { StringBuffer b = new StringBuffer(); int ch; while ((ch = stream.read()) != -1) b.append((char) ch); return b.toString(); } finally { stream.close(); } } catch (IOException e) { ; } catch (ClassCastException e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public String encryptLdapPassword(String algorithm) { String sEncrypted = _password; if ((_password != null) && (_password.length() > 0)) { algorithm = Val.chkStr(algorithm); boolean bMD5 = algorithm.equalsIgnoreCase("MD5"); boolean bSHA = algorithm.equalsIgnoreCase("SHA") || algorithm.equalsIgnoreCase("SHA1") || algorithm.equalsIgnoreCase("SHA-1"); if (bSHA || bMD5) { String sAlgorithm = "MD5"; if (bSHA) { sAlgorithm = "SHA"; } try { MessageDigest md = MessageDigest.getInstance(sAlgorithm); md.update(getPassword().getBytes("UTF-8")); sEncrypted = "{" + sAlgorithm + "}" + (new BASE64Encoder()).encode(md.digest()); } catch (NoSuchAlgorithmException e) { sEncrypted = null; e.printStackTrace(System.err); } catch (UnsupportedEncodingException e) { sEncrypted = null; e.printStackTrace(System.err); } } } return sEncrypted; }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; final StringBuilder sbValueBeforeMD5 = new StringBuilder(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.fatal("", e); return; } try { final long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(sId); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuilder sb = new StringBuilder(); for (int j = 0; j < array.length; ++j) { final int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { logger.fatal("", e); } }
|
00
|
Code Sample 1:
private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; }
Code Sample 2:
public static boolean insereMidia(final Connection con, Midia mid, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodMidia(con, mid); GeraID.gerarCodDescricao(con, desc); String titulo = mid.getTitulo().replaceAll("['\"]", ""); String coment = mid.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO midia VALUES(" + mid.getCodigo() + ", '" + titulo + "', '" + coment + "','" + mid.getUrl() + "', '" + mid.getTipo() + "', " + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO mid_aut VALUES(" + mid.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "MIDIA: Database error", JOptionPane.ERROR_MESSAGE); System.err.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getMessage()); } } }
|
11
|
Code Sample 1:
public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long 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, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
protected void processAnnotationsJndi(URL url) { try { URLConnection urlConn = url.openConnection(); DirContextURLConnection dcUrlConn; if (!(urlConn instanceof DirContextURLConnection)) { sm.getString("contextConfig.jndiUrlNotDirContextConn", url); return; } dcUrlConn = (DirContextURLConnection) urlConn; dcUrlConn.setUseCaches(false); String type = dcUrlConn.getHeaderField(ResourceAttributes.TYPE); if (ResourceAttributes.COLLECTION_TYPE.equals(type)) { Enumeration<String> dirs = dcUrlConn.list(); while (dirs.hasMoreElements()) { String dir = dirs.nextElement(); URL dirUrl = new URL(url.toString() + '/' + dir); processAnnotationsJndi(dirUrl); } } else { if (url.getPath().endsWith(".class")) { InputStream is = null; try { is = dcUrlConn.getInputStream(); processAnnotationsStream(is); } catch (IOException e) { logger.error(sm.getString("contextConfig.inputStreamJndi", url), e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } } catch (IOException e) { logger.error(sm.getString("contextConfig.jndiUrl", url), e); } }
Code Sample 2:
@edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" }) public static String md5Encode(String val) { String output = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(val.getBytes()); byte[] digest = md.digest(); output = base64Encode(digest); } catch (Exception e) { } return output; }
|
00
|
Code Sample 1:
public void readEntry(String name, InputStream input) throws Exception { File file = new File(this.directory, name); OutputStream output = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { org.apache.commons.io.IOUtils.copy(input, output); } finally { output.close(); } }
Code Sample 2:
public static void initStaticStuff() { Enumeration<URL> urls = null; try { urls = Play.class.getClassLoader().getResources("play.static"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { try { Class.forName(line); } catch (Exception e) { System.out.println("! Cannot init static : " + line); } } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } }
|
00
|
Code Sample 1:
public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); }
Code Sample 2:
private static void updateLeapSeconds() throws IOException, MalformedURLException, NumberFormatException { URL url = new URL("http://cdf.gsfc.nasa.gov/html/CDFLeapSeconds.txt"); InputStream in; try { in = url.openStream(); } catch (IOException ex) { url = LeapSecondsConverter.class.getResource("CDFLeapSeconds.txt"); in = url.openStream(); System.err.println("Using local copy of leap seconds!!!"); } BufferedReader r = new BufferedReader(new InputStreamReader(in)); String s = ""; leapSeconds = new ArrayList(50); withoutLeapSeconds = new ArrayList(50); String lastLine = s; while (s != null) { s = r.readLine(); if (s == null) { System.err.println("Last leap second read from " + url + " " + lastLine); continue; } if (s.startsWith(";")) { continue; } String[] ss = s.trim().split("\\s+", -2); if (ss[0].compareTo("1972") < 0) { continue; } int iyear = Integer.parseInt(ss[0]); int imonth = Integer.parseInt(ss[1]); int iday = Integer.parseInt(ss[2]); int ileap = (int) (Double.parseDouble(ss[3])); double us2000 = TimeUtil.createTimeDatum(iyear, imonth, iday, 0, 0, 0, 0).doubleValue(Units.us2000); leapSeconds.add(Long.valueOf(((long) us2000) * 1000L - 43200000000000L + (long) (ileap - 32) * 1000000000)); withoutLeapSeconds.add(us2000); } leapSeconds.add(Long.MAX_VALUE); withoutLeapSeconds.add(Double.MAX_VALUE); lastUpdateMillis = System.currentTimeMillis(); }
|
11
|
Code Sample 1:
@SuppressWarnings("static-access") @RequestMapping(value = "/upload/upload.html", method = RequestMethod.POST) protected void save(HttpServletRequest request, HttpServletResponse response) throws ServletException { UPLOAD_DIRECTORY = uploadDiretory(); File diretorioUsuario = new File(UPLOAD_DIRECTORY); boolean diretorioCriado = false; if (!diretorioUsuario.exists()) { diretorioCriado = diretorioUsuario.mkdir(); if (!diretorioCriado) throw new RuntimeException("Não foi possível criar o diretório do usuário"); } PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(UPLOAD_DIRECTORY + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
Code Sample 2:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
|
00
|
Code Sample 1:
@Override public void start() { try { ftp = new FTPClient(); ftp.connect(this.url.getHost(), this.url.getPort() == -1 ? this.url.getDefaultPort() : this.url.getPort()); String username = "anonymous"; String password = ""; if (this.url.getUserInfo() != null) { username = this.url.getUserInfo().split(":")[0]; password = this.url.getUserInfo().split(":")[1]; } ftp.login(username, password); long startPos = 0; if (getFile().exists()) startPos = getFile().length(); else getFile().createNewFile(); ftp.download(this.url.getPath(), getFile(), startPos, new FTPDTImpl()); ftp.disconnect(true); } catch (Exception ex) { ex.printStackTrace(); speedTimer.cancel(); } }
Code Sample 2:
@SuppressWarnings("unchecked") public static void main(String[] args) { System.out.println("Starting encoding test...."); Properties p = new Properties(); try { InputStream pStream = ClassLoader.getSystemResourceAsStream("sample_weather.properties"); p.load(pStream); } catch (Exception e) { System.err.println("Could not load properties file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } if (WeatherUpdater.DEBUG) { System.out.println("hostname: " + p.getProperty("weather.hostname")); } if (WeatherUpdater.DEBUG) { System.out.println("database: " + p.getProperty("weather.database")); } if (WeatherUpdater.DEBUG) { System.out.println("username: " + p.getProperty("weather.username")); } if (WeatherUpdater.DEBUG) { System.out.println("password: " + p.getProperty("weather.password")); } SqlAccount sqlAccount = new SqlAccount(p.getProperty("weather.hostname"), p.getProperty("weather.database"), p.getProperty("weather.username"), p.getProperty("weather.password")); DatabaseInterface dbi = null; try { dbi = new DatabaseInterface(sqlAccount); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Established connection to database."); String query = "SELECT * FROM Current_Weather WHERE ZipCode = '99702'"; ResultTable results; System.out.println("Executing query: " + query); try { results = dbi.executeQuery(query); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Got results from query."); System.out.println("Converted results into the following table:"); System.out.println(results); System.out.println(); Class<? extends ResultEncoder> encoder_class; Class<? extends ResultDecoder> decoder_class; try { encoder_class = (Class<? extends ResultEncoder>) Class.forName(p.getProperty("mysms.coding.resultEncoder")); decoder_class = (Class<? extends ResultDecoder>) Class.forName(p.getProperty("mysms.coding.resultDecoder")); } catch (Exception e) { System.err.println("Could not find specified encoder: " + p.getProperty("result.encoder")); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Found class of encoder: " + encoder_class); System.out.println("Found class of decoder: " + decoder_class); ResultEncoder encoder; ResultDecoder decoder; try { encoder = encoder_class.newInstance(); if (encoder_class.equals(decoder_class) && decoder_class.isInstance(encoder)) { decoder = (ResultDecoder) encoder; } else { decoder = decoder_class.newInstance(); } } catch (Exception e) { System.err.println("Could not create instances of encoder and decoder."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Created instances of encoder and decoder."); if (decoder.equals(encoder)) { System.out.println("Decoder and encoder are same object."); } ByteBuffer buffer; try { buffer = encoder.encode(null, results); } catch (Exception e) { System.err.println("Could not encode results."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Encoded results to ByteBuffer with size: " + buffer.capacity()); File temp; try { temp = File.createTempFile("encoding_test", ".results"); temp.deleteOnExit(); FileChannel out = new FileOutputStream(temp).getChannel(); out.write(buffer); out.close(); } catch (Exception e) { System.err.println("Could not write buffer to file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Wrote buffer to file: \"" + temp.getName() + "\" with length: " + temp.length()); ByteBuffer re_buffer; try { FileInputStream in = new FileInputStream(temp.getAbsolutePath()); byte[] temp_buffer = new byte[(int) temp.length()]; int totalRead = 0; int numRead = 0; while (totalRead < temp_buffer.length) { numRead = in.read(temp_buffer, totalRead, temp_buffer.length - totalRead); if (numRead < 0) { break; } else { totalRead += numRead; } } re_buffer = ByteBuffer.wrap(temp_buffer); in.close(); } catch (Exception e) { System.err.println("Could not read from temporary file into buffer."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Read file back into buffer with length: " + re_buffer.capacity()); ResultTable re_results; try { re_results = decoder.decode(null, re_buffer); } catch (Exception e) { System.err.println("Could not decode buffer into a ResultTable."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Decoded buffer back into the following table:"); System.out.println(re_results); System.out.println(); System.out.println("... encoding test complete."); }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
|
00
|
Code Sample 1:
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"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
public static boolean copy(File source, File target, boolean owrite) { if (!source.exists()) { log.error("Invalid input to copy: source " + source + "doesn't exist"); return false; } else if (!source.isFile()) { log.error("Invalid input to copy: source " + source + "isn't a file."); return false; } else if (target.exists() && !owrite) { log.error("Invalid input to copy: target " + target + " exists."); return false; } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); byte buffer[] = new byte[1024]; int read = -1; while ((read = in.read(buffer, 0, 1024)) != -1) out.write(buffer, 0, read); out.flush(); out.close(); in.close(); return true; } catch (IOException e) { log.error("Copy failed: ", e); return false; } }
|
11
|
Code Sample 1:
private static void copy(File in, File out) throws IOException { if (!out.getParentFile().isDirectory()) out.getParentFile().mkdirs(); FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + 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.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
|
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 readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
protected void innerProcess(CrawlURI curi) throws InterruptedException { if (!curi.isHttpTransaction()) { return; } if (!TextUtils.matches("^text.*$", curi.getContentType())) { return; } long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue(); try { maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue(); } catch (AttributeNotFoundException e) { logger.severe("Missing max-size-bytes attribute when processing " + curi.toString()); } if (maxsize < curi.getContentSize() && maxsize > -1) { return; } String regexpr = ""; try { regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR); } catch (AttributeNotFoundException e2) { logger.severe("Missing strip-reg-exp when processing " + curi.toString()); return; } ReplayCharSequence cs = null; try { cs = curi.getHttpRecorder().getReplayCharSequence(); } catch (Exception e) { curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage()); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr.length() == 0) { s = cs.toString(); } else { Matcher m = TextUtils.getMatcher(regexpr, cs); s = m.replaceAll(" "); TextUtils.recycleMatcher(m); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); if (logger.isLoggable(Level.FINEST)) { logger.finest("Recalculated content digest for " + curi.toString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue)); } curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
Code Sample 2:
public void run() { try { int id = getID() - 1; String file = id + ".dem"; String data = URLEncoder.encode("file", "UTF-8") + "=" + URLEncoder.encode(file, "UTF-8"); data += "&" + URLEncoder.encode("hash", "UTF-8") + "=" + URLEncoder.encode(getMD5Digest("tf2invite" + file), "UTF-8"); URL url = new URL("http://94.23.189.99/ftp.php"); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); String line; BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { System.out.println(line); if (line.startsWith("demo=")) msg("2The last gather demo has been uploaded successfully: " + line.split("=")[1]); } rd.close(); wr.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static Version getWebRelease(String url) { InputStream is = null; try { is = new URL(url).openStream(); Reader reader = new InputStreamReader(new BufferedInputStream(is), "UTF-8"); String word = findWord(reader, "<description>Release:", "</description>").trim(); if (!isValid(word)) { word = "0"; } return new Version(word); } catch (Throwable ex) { LOGGER.log(Level.WARNING, null, ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } } return null; }
Code Sample 2:
private void copyFileToDir(MyFile file, MyFile to, wlPanel panel) throws IOException { Utilities.print("started copying " + file.getAbsolutePath() + "\n"); FileOutputStream fos = new FileOutputStream(new File(to.getAbsolutePath())); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath())); FileChannel fic = fis.getChannel(); Date d1 = new Date(); long amount = foc.transferFrom(fic, rest, fic.size() - rest); fic.close(); foc.force(false); foc.close(); Date d2 = new Date(); long time = d2.getTime() - d1.getTime(); double secs = time / 1000.0; double rate = amount / secs; frame.getStatusArea().append(secs + "s " + "amount: " + Utilities.humanReadable(amount) + " rate: " + Utilities.humanReadable(rate) + "/s\n", "black"); panel.updateView(); }
|
00
|
Code Sample 1:
public Source resolve(String href, String base) throws TransformerException { if (href.endsWith(".txt")) { try { URL url = new URL(new URL(base), href); java.io.InputStream in = url.openConnection().getInputStream(); java.io.InputStreamReader reader = new java.io.InputStreamReader(in, "iso-8859-1"); StringBuffer sb = new StringBuffer(); while (true) { int c = reader.read(); if (c < 0) break; sb.append((char) c); } com.icl.saxon.expr.TextFragmentValue tree = new com.icl.saxon.expr.TextFragmentValue(sb.toString(), url.toString(), (com.icl.saxon.Controller) transformer); return tree.getFirst(); } catch (Exception err) { throw new TransformerException(err); } } else { return null; } }
Code Sample 2:
public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { Logger.error(Encryptor.class, nsae.getMessage(), nsae); } catch (UnsupportedEncodingException uee) { Logger.error(Encryptor.class, uee.getMessage(), uee); } byte raw[] = mDigest.digest(); return (new BASE64Encoder()).encode(raw); }
|
11
|
Code Sample 1:
public String loadGeneratorXML() { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.getFolienKonvertierungsServer().getUrl()); System.out.println("Connected to " + this.getFolienKonvertierungsServer().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return null; } if (!ftp.login(this.getFolienKonvertierungsServer().getFtpBenutzer(), this.getFolienKonvertierungsServer().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String path; if (this.getFolienKonvertierungsServer().getDefaultPath().length() > 0) { path = "/" + this.getFolienKonvertierungsServer().getDefaultPath() + "/" + this.getId() + "/"; } else { path = "/" + this.getId() + "/"; } if (!ftp.changeWorkingDirectory(path)) System.err.println("Konnte Verzeichnis nicht wechseln: " + path); System.err.println("Arbeitsverzeichnis: " + ftp.printWorkingDirectory()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); InputStream inStream = ftp.retrieveFileStream("generator.xml"); if (inStream == null) { System.err.println("Job " + this.getId() + ": Datei generator.xml wurde nicht gefunden"); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(inStream)); generatorXML = ""; String zeile = ""; while ((zeile = in.readLine()) != null) { generatorXML += zeile + "\n"; } in.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei generator.xml konnte nicht vom Webserver kopiert werden."); e.printStackTrace(); } catch (Exception e) { System.err.println("Job " + this.getId() + ": Datei generator.xml konnte nicht vom Webserver kopiert werden."); e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } if (generatorXML != null && generatorXML.length() == 0) { generatorXML = null; } return generatorXML; }
Code Sample 2:
public boolean uploadFromServlet(InputStream is, String serverFileName, String serverPath, String serverUrl, int serverPort, String userName, String passWord) throws IOException { FTPClient ftp = new FTPClient(); FTPClientConfig conf = new FTPClientConfig(); conf.setServerLanguageCode("zh_CN"); conf.setServerTimeZoneId("Asia/Chongqing"); try { ftp.configure(conf); int reply; ftp.setDefaultPort(serverPort); ftp.connect(serverUrl); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server refused connection."); } } catch (IOException e) { disconnectFtp(ftp); } try { if (!ftp.login(userName, passWord)) { throw new IOException("Can not log in with given username and password."); } if (!ftp.changeWorkingDirectory(serverPath)) { throw new IOException("Can not change to working directory."); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.storeFile(serverFileName, is)) { throw new IOException("Can not store file to FTP server."); } is.close(); } catch (SocketException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); return false; } } } return true; }
|
11
|
Code Sample 1:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
Code Sample 2:
public void 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 String encrypt(String password, Long digestSeed) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(password.getBytes("UTF-8")); algorithm.update(digestSeed.toString().getBytes("UTF-8")); byte[] messageDigest = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xff & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Code Sample 2:
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnClear) { passwordField.setText(""); } for (int i = 0; i < 10; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; sql = "select password from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } setVisible(false); setTries(0); Error.log(4003, "Senha de uso �nico verificada positivamente."); Error.log(4002, "Autentica��o etapa 3 encerrada."); ManagerWindow mw = new ManagerWindow(login); mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); int tries = getTries(); if (tries == 0) { Error.log(4004, "Primeiro erro da senha de uso �nico contabilizado."); } else if (tries == 1) { Error.log(4005, "Segundo erro da senha de uso �nico contabilizado."); } else if (tries == 2) { Error.log(4006, "Terceiro erro da senha de uso �nico contabilizado."); Error.log(4007, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 3."); Error.log(4002, "Autentica��o etapa 3 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } }
|
11
|
Code Sample 1:
public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); }
Code Sample 2:
@Test public void testEncryptDecrypt() throws IOException { BlockCipher cipher = new SerpentEngine(); Random rnd = new Random(); byte[] key = new byte[256 / 8]; rnd.nextBytes(key); byte[] iv = new byte[cipher.getBlockSize()]; rnd.nextBytes(iv); byte[] data = new byte[1230000]; new Random().nextBytes(data); ByteArrayOutputStream bout = new ByteArrayOutputStream(); CryptOutputStream eout = new CryptOutputStream(bout, cipher, key); eout.write(data); eout.close(); byte[] eData = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(eData); CryptInputStream din = new CryptInputStream(bin, cipher, key); bout = new ByteArrayOutputStream(); IOUtils.copy(din, bout); eData = bout.toByteArray(); Assert.assertTrue(Arrays.areEqual(data, eData)); }
|
11
|
Code Sample 1:
public void testQueryForBinary() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + "images/photo.png"); assertNotNull(source); assertEquals(false, source.exists()); OutputStream os = source.getOutputStream(); assertNotNull(os); String content = "foo is a bar"; os.write(content.getBytes()); os.flush(); os.close(); QueryResultSource qResult = (QueryResultSource) resolveSource(BASE_URL + "images?/*[contains(local-name(), 'photo.png')]"); assertNotNull(qResult); Collection results = qResult.getChildren(); assertEquals(1, results.size()); Iterator it = results.iterator(); JCRNodeSource rSrc = (JCRNodeSource) it.next(); InputStream rSrcIn = rSrc.getInputStream(); ByteArrayOutputStream actualOut = new ByteArrayOutputStream(); IOUtils.copy(rSrcIn, actualOut); rSrcIn.close(); assertEquals(content, actualOut.toString()); actualOut.close(); rSrc.delete(); }
Code Sample 2:
public String openFileAsText(String resource) throws IOException { StringWriter wtr = new StringWriter(); InputStreamReader rdr = new InputStreamReader(openFile(resource)); try { IOUtils.copy(rdr, wtr); } finally { IOUtils.closeQuietly(rdr); } return wtr.toString(); }
|
11
|
Code Sample 1:
public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; }
Code Sample 2:
public static String md5(String str) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(str.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); String md5 = hexString.toString(); Log.v(FileUtil.class.getName(), md5); return md5; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
|
11
|
Code Sample 1:
public void handleRequestInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { final String servetPath = httpServletRequest.getServletPath(); final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH); final String currentToken = getETagValue(httpServletRequest); httpServletResponse.setHeader(ETAG, currentToken); final Date modifiedDate = new Date(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE)); final Calendar calendar = Calendar.getInstance(); final Date now = calendar.getTime(); calendar.setTime(modifiedDate); calendar.add(Calendar.MINUTE, getEtagExpiration()); if (currentToken.equals(previousToken) && (now.getTime() < calendar.getTime().getTime())) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED); httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE)); if (LOG.isDebugEnabled()) { LOG.debug("ETag the same, will return 304"); } } else { httpServletResponse.setDateHeader(LAST_MODIFIED, (new Date()).getTime()); final String width = httpServletRequest.getParameter(Constants.WIDTH); final String height = httpServletRequest.getParameter(Constants.HEIGHT); final ImageNameStrategy imageNameStrategy = imageService.getImageNameStrategy(servetPath); String code = imageNameStrategy.getCode(servetPath); String fileName = imageNameStrategy.getFileName(servetPath); final String imageRealPathPrefix = getRealPathPrefix(httpServletRequest.getServerName().toLowerCase()); String original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); final File origFile = new File(original); if (!origFile.exists()) { code = Constants.NO_IMAGE; fileName = imageNameStrategy.getFileName(code); original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); } String resizedImageFileName = null; if (width != null && height != null && imageService.isSizeAllowed(width, height)) { resizedImageFileName = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code, width, height); } final File imageFile = getImageFile(original, resizedImageFileName, width, height); final FileInputStream fileInputStream = new FileInputStream(imageFile); IOUtils.copy(fileInputStream, httpServletResponse.getOutputStream()); fileInputStream.close(); } }
Code Sample 2:
public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } }
|
00
|
Code Sample 1:
public static AddUserResponse napiUserAdd(String user, String pass, String email) throws TimeoutException, InterruptedException, IOException { if (user.matches("^[a-zA-Z0-9]{2,20}$") == false) { return AddUserResponse.NAPI_ADD_USER_BAD_LOGIN; } if (pass.equals("")) { return AddUserResponse.NAPI_ADD_USER_BAD_PASS; } if (email.matches("^[a-zA-Z0-9\\-\\_]{1,30}@[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)+$") == false) { return AddUserResponse.NAPI_ADD_USER_BAD_EMAIL; } URLConnection conn = null; ClientHttpRequest httpPost = null; InputStreamReader responseStream = null; URL url = new URL("http://www.napiprojekt.pl/users_add.php"); conn = url.openConnection(Global.getProxy()); httpPost = new ClientHttpRequest(conn); httpPost.setParameter("login", user); httpPost.setParameter("haslo", pass); httpPost.setParameter("mail", email); httpPost.setParameter("z_programu", "true"); responseStream = new InputStreamReader(httpPost.post(), "Cp1250"); BufferedReader responseReader = new BufferedReader(responseStream); String response = responseReader.readLine(); if (response.indexOf("login już istnieje") != -1) { return AddUserResponse.NAPI_ADD_USER_LOGIN_EXISTS; } if (response.indexOf("na podany e-mail") != -1) { return AddUserResponse.NAPI_ADD_USER_EMAIL_EXISTS; } if (response.indexOf("NPc0") == 0) { return AddUserResponse.NAPI_ADD_USER_OK; } return AddUserResponse.NAPI_ADD_USER_BAD_UNKNOWN; }
Code Sample 2:
protected static byte[] hashPassword(byte[] saltBytes, String plaintextPassword) throws AssertionError { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw (AssertionError) new AssertionError("No MD5 message digest supported.").initCause(ex); } digest.update(saltBytes); try { digest.update(plaintextPassword.getBytes("utf-8")); } catch (UnsupportedEncodingException ex) { throw (AssertionError) new AssertionError("No UTF-8 encoding supported.").initCause(ex); } byte[] passwordBytes = digest.digest(); return passwordBytes; }
|
00
|
Code Sample 1:
public static boolean BMPfromURL(URL url, MainClass mc) { TextField TF = mc.TF; PixCanvas canvas = mc.canvas; Image image = null; try { image = Toolkit.getDefaultToolkit().createImage(BMPReader.getBMPImage(url.openStream())); } catch (IOException e) { return false; } if (image == null) { TF.setText("Error not a typical image BMP format"); return false; } MediaTracker tr = new MediaTracker(canvas); tr.addImage(image, 0); try { tr.waitForID(0); } catch (InterruptedException e) { } ; if (tr.isErrorID(0)) { Tools.debug(OpenOther.class, "Tracker error " + tr.getErrorsAny().toString()); return false; } PixObject po = new PixObject(url, image, canvas, false, null); mc.vimages.addElement(po); TF.setText(url.toString()); canvas.repaint(); return true; }
Code Sample 2:
public static Class[] findSubClasses(Class baseClass) { String packagePath = "/" + baseClass.getPackage().getName().replace('.', '/'); URL url = baseClass.getResource(packagePath); if (url == null) { return new Class[0]; } List<Class> derivedClasses = new ArrayList<Class>(); try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection) connection).getJarFile(); Enumeration e = jarFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryName = entry.getName(); if (entryName.endsWith(".class")) { String clazzName = entryName.substring(0, entryName.length() - 6); clazzName = clazzName.replace('/', '.'); try { Class clazz = Class.forName(clazzName); if (isConcreteSubclass(baseClass, clazz)) { derivedClasses.add(clazz); } } catch (Throwable ignoreIt) { } } } } else if (connection instanceof FileURLConnection) { File file = new File(url.getFile()); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { String filename = files[i].getName(); if (filename.endsWith(".class")) { filename = filename.substring(0, filename.length() - 6); String clazzname = baseClass.getPackage().getName() + "." + filename; try { Class clazz = Class.forName(clazzname); if (isConcreteSubclass(baseClass, clazz)) { derivedClasses.add(clazz); } } catch (Throwable ignoreIt) { } } } } } catch (IOException ignoreIt) { } return derivedClasses.toArray(new Class[derivedClasses.size()]); }
|
11
|
Code Sample 1:
public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.update(p_plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static void init(Locale language) throws IOException { URL url = ClassLoader.getSystemResource("locales/" + language.getISO3Language() + ".properties"); if (url == null) { throw new IOException("Could not load resource locales/" + language.getISO3Language() + ".properties"); } PROPS.clear(); PROPS.load(url.openStream()); }
|
00
|
Code Sample 1:
public boolean refresh() { try { synchronized (text) { stream = (new URL(url)).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } text = sb.toString(); } price = 0; date = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return false; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; }
Code Sample 2:
@SmallTest public void testSha1() throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-1"); int numTests = mTestData.length; for (int i = 0; i < numTests; i++) { digest.update(mTestData[i].input.getBytes()); byte[] hash = digest.digest(); String encodedHash = encodeHex(hash); assertEquals(encodedHash, mTestData[i].result); } }
|
11
|
Code Sample 1:
private static boolean computeMovieAverages(String completePath, String MovieAveragesOutputFileName, String MovieIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TShortObjectHashMap MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalMovies = MovieLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CustomerRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); short[] itr = MovieLimitsTHash.keys(); Arrays.sort(itr); ByteBuffer buf; for (i = 0; i < totalMovies; i++) { short currentMovie = itr[i]; a = (TIntArrayList) MovieLimitsTHash.get(currentMovie); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 5); inC.read(buf, (startIndex - 1) * 5); } else { buf = ByteBuffer.allocate(5); inC.read(buf, (startIndex - 1) * 5); } buf.flip(); int bufsize = buf.capacity() / 5; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getInt(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(6); outbuf.putShort(currentMovie); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
@SuppressWarnings("unchecked") private void appendAttachments(final Part part) throws MessagingException, IOException { if (part.isMimeType("message/*")) { JcrMessage jcrMessage = new JcrMessage(); Message attachedMessage = null; if (part.getContent() instanceof Message) { attachedMessage = (Message) part.getContent(); } else { attachedMessage = new MStorMessage(null, (InputStream) part.getContent()); } jcrMessage.setFlags(attachedMessage.getFlags()); jcrMessage.setHeaders(attachedMessage.getAllHeaders()); jcrMessage.setReceived(attachedMessage.getReceivedDate()); jcrMessage.setExpunged(attachedMessage.isExpunged()); jcrMessage.setMessage(attachedMessage); messages.add(jcrMessage); } else if (part.isMimeType("multipart/*")) { Multipart multi = (Multipart) part.getContent(); for (int i = 0; i < multi.getCount(); i++) { appendAttachments(multi.getBodyPart(i)); } } else if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotEmpty(part.getFileName())) { JcrFile attachment = new JcrFile(); String name = null; if (StringUtils.isNotEmpty(part.getFileName())) { name = part.getFileName(); for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { return; } } } else { String[] contentId = part.getHeader("Content-Id"); if (contentId != null && contentId.length > 0) { name = contentId[0]; } else { name = "attachment"; } } int count = 0; for (JcrFile attach : attachments) { if (attach.getName().equals(name)) { count++; } } if (count > 0) { name += "_" + count; } attachment.setName(name); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); attachment.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); attachment.setMimeType(part.getContentType()); attachment.setLastModified(java.util.Calendar.getInstance()); attachments.add(attachment); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public String readFile(String filename) throws UnsupportedEncodingException, FileNotFoundException, IOException { File f = new File(baseDir); f = new File(f, filename); StringWriter w = new StringWriter(); Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); IOUtils.copy(fr, w); fr.close(); w.close(); String contents = w.toString(); return contents; }
|
11
|
Code Sample 1:
public Logging() throws Exception { File home = new File(System.getProperty("user.home"), ".jorgan"); if (!home.exists()) { home.mkdirs(); } File logging = new File(home, "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
@Override public void loadData() { try { String url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=11&f=2099&g=d&ignore=.csv"; URLConnection conn = (new URL(url)).openConnection(); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); String str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double open = Double.parseDouble(split[1]); final double high = Double.parseDouble(split[2]); final double low = Double.parseDouble(split[3]); final double close = Double.parseDouble(split[4]); final int volume = Integer.parseInt(split[5]); final double adjClose = Double.parseDouble(split[6]); final HistoricalPrice price = new HistoricalPrice(date, open, high, low, close, volume, adjClose); historicalPrices.add(price); } in.close(); url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=17&f=2008&g=v&ignore=.csv"; conn = (new URL(url)).openConnection(); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double amount = Double.parseDouble(split[1]); final Dividend dividend = new Dividend(date, amount); dividends.add(dividend); } in.close(); } catch (final IOException ioe) { logger.error("Error parsing historical prices for " + getSymbol(), ioe); } }
|
00
|
Code Sample 1:
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; }
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:
private void doProcess(HttpServletRequest request, HttpServletResponse resp) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Analyzer analyzer = new Analyzer(); ServletContext context = getServletContext(); String xml = context.getRealPath("data\\log.xml"); String xsd = context.getRealPath("data\\log.xsd"); String grs = context.getRealPath("reports\\" + request.getParameter("type") + ".grs"); String pdf = context.getRealPath("html\\report.pdf"); System.out.println("omg: " + request.getParameter("type")); System.out.println("omg: " + request.getParameter("pc")); int pcount = Integer.parseInt(request.getParameter("pc")); String[] params = new String[pcount]; for (int i = 0; i < pcount; i++) { params[i] = request.getParameter("p" + i); } try { analyzer.generateReport(xml, xsd, grs, pdf, params); } catch (Exception e) { e.printStackTrace(); } File file = new File(pdf); byte[] bs = tryLoadFile(pdf); if (bs == null) throw new NullPointerException(); resp.setHeader("Content-Disposition", " filename=\"" + file.getName() + "\";"); resp.setContentLength(bs.length); InputStream is = new ByteArrayInputStream(bs); IOUtils.copy(is, resp.getOutputStream()); }
Code Sample 2:
private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
|
00
|
Code Sample 1:
private static List lookupForImplementations(final Class clazz, final ClassLoader loader, final String[] defaultImplementations, final boolean onlyFirst, final boolean returnInstances) throws ClassNotFoundException { if (clazz == null) { throw new IllegalArgumentException("Argument 'clazz' cannot be null!"); } ClassLoader classLoader = loader; if (classLoader == null) { classLoader = clazz.getClassLoader(); } String interfaceName = clazz.getName(); ArrayList tmp = new ArrayList(); ArrayList toRemove = new ArrayList(); String className = System.getProperty(interfaceName); if (className != null && className.trim().length() > 0) { tmp.add(className.trim()); } Enumeration en = null; try { en = classLoader.getResources("META-INF/services/" + clazz.getName()); } catch (IOException e) { e.printStackTrace(); } while (en != null && en.hasMoreElements()) { URL url = (URL) en.nextElement(); InputStream is = null; try { is = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; do { line = reader.readLine(); boolean remove = false; if (line != null) { if (line.startsWith("#-")) { remove = true; line = line.substring(2); } int pos = line.indexOf('#'); if (pos >= 0) { line = line.substring(0, pos); } line = line.trim(); if (line.length() > 0) { if (remove) { toRemove.add(line); } else { tmp.add(line); } } } } while (line != null); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } if (defaultImplementations != null) { for (int i = 0; i < defaultImplementations.length; i++) { tmp.add(defaultImplementations[i].trim()); } } if (!clazz.isInterface()) { int m = clazz.getModifiers(); if (!Modifier.isAbstract(m) && Modifier.isPublic(m) && !Modifier.isStatic(m)) { tmp.add(interfaceName); } } tmp.removeAll(toRemove); ArrayList res = new ArrayList(); for (Iterator it = tmp.iterator(); it.hasNext(); ) { className = (String) it.next(); try { Class c = Class.forName(className, false, classLoader); if (c != null) { if (clazz.isAssignableFrom(c)) { if (returnInstances) { Object o = null; try { o = c.newInstance(); } catch (Throwable e) { e.printStackTrace(); } if (o != null) { res.add(o); if (onlyFirst) { return res; } } } else { res.add(c); if (onlyFirst) { return res; } } } else { logger.warning("MetaInfLookup: Class '" + className + "' is not a subclass of class : " + interfaceName); } } } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Cannot create implementation of interface: " + interfaceName, e); } } if (res.size() == 0) { throw new ClassNotFoundException("Cannot find any implemnetation of class " + interfaceName); } return res; }
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 "!!"; } }
|
00
|
Code Sample 1:
public boolean delMail(MailObject mail) throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_MAIL_DEL + mail.getId()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isXmlContentType(response)) { HTTPUtil.consume(response.getEntity()); return true; } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
public UserAgentContext getUserAgentContext() { return new UserAgentContext() { public HttpRequest createHttpRequest() { return new HttpRequest() { private byte[] bytes; private Vector<ReadyStateChangeListener> readyStateChangeListeners = new Vector<ReadyStateChangeListener>(); public void abort() { } public void addReadyStateChangeListener(ReadyStateChangeListener readyStateChangeListener) { readyStateChangeListeners.add(readyStateChangeListener); } public String getAllResponseHeaders() { return null; } public int getReadyState() { return bytes != null ? STATE_COMPLETE : STATE_UNINITIALIZED; } public byte[] getResponseBytes() { return bytes; } public String getResponseHeader(String arg0) { return null; } public Image getResponseImage() { return bytes != null ? Toolkit.getDefaultToolkit().createImage(bytes) : null; } public String getResponseText() { return new String(bytes); } public Document getResponseXML() { return null; } public int getStatus() { return 200; } public String getStatusText() { return "OK"; } public void open(String method, String url) { open(method, url, false); } public void open(String method, URL url) { open(method, url, false); } public void open(String mehod, URL url, boolean async) { try { URLConnection connection = url.openConnection(); bytes = new byte[connection.getContentLength()]; InputStream inputStream = connection.getInputStream(); inputStream.read(bytes); inputStream.close(); for (ReadyStateChangeListener readyStateChangeListener : readyStateChangeListeners) { readyStateChangeListener.readyStateChanged(); } } catch (IOException e) { } } public void open(String method, String url, boolean async) { open(method, URLHelper.createURL(url), async); } public void open(String method, String url, boolean async, String arg3) { open(method, URLHelper.createURL(url), async); } public void open(String method, String url, boolean async, String arg3, String arg4) { open(method, URLHelper.createURL(url), async); } }; } public String getAppCodeName() { return null; } public String getAppMinorVersion() { return null; } public String getAppName() { return null; } public String getAppVersion() { return null; } public String getBrowserLanguage() { return null; } public String getCookie(URL arg0) { return null; } public String getPlatform() { return null; } public int getScriptingOptimizationLevel() { return 0; } public Policy getSecurityPolicy() { return null; } public String getUserAgent() { return null; } public boolean isCookieEnabled() { return false; } public boolean isMedia(String arg0) { return false; } public boolean isScriptingEnabled() { return false; } public void setCookie(URL arg0, String arg1) { } }; }
|
11
|
Code Sample 1:
public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { final ServletOutputStream outputStream = res.getOutputStream(); if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; if (ByteArrayInputStream.class.isAssignableFrom(r.getClass())) res.addHeader("Content-Length", Integer.toString(in.available())); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } outputStream.flush(); } }
Code Sample 2:
public static void copyWithClose(InputStream is, OutputStream os) throws IOException { try { IOUtils.copy(is, os); } catch (IOException ioe) { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
|
11
|
Code Sample 1:
private void googleImageSearch() { bottomShowing = true; googleSearched = true; googleImageLocation = 0; googleImages = new Vector<String>(); custom = ""; int r = JOptionPane.showConfirmDialog(this, "Customize google search?", "Google Search", JOptionPane.YES_NO_OPTION); if (r == JOptionPane.YES_OPTION) { custom = JOptionPane.showInputDialog("Custom Search", ""); } else { custom = artist; } try { String u = "http://images.google.com/images?q=" + custom; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String lin = new String(); while ((lin = readIn.readLine()) != null) { while (lin.contains("href=\"/imgres?imgurl=")) { while (!lin.contains(">")) { lin += readIn.readLine(); } String s = lin.substring(lin.indexOf("href=\"/imgres?imgurl="), lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); lin = lin.substring(lin.indexOf(">", lin.indexOf("href=\"/imgres?imgurl="))); if (s.contains("&") && s.indexOf("http://") < s.indexOf("&")) { s = s.substring(s.indexOf("http://"), s.indexOf("&")); } else { s = s.substring(s.indexOf("http://"), s.length()); } googleImages.add(s); } } readIn.close(); } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton1.setEnabled(false); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); }
Code Sample 2:
private String checkForUpdate() { InputStream is = null; try { URL url = new URL(CHECK_UPDATES_URL); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "TinyLaF"); Object content = conn.getContent(); if (!(content instanceof InputStream)) { return "An exception occured while checking for updates." + "\n\nException was: Content is no InputStream"; } is = (InputStream) content; } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } } catch (MalformedURLException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } try { BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buff = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buff.append(line); } in.close(); return buff.toString(); } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } }
|
00
|
Code Sample 1:
public SM2Client(String umn, String authorizationID, String protocol, String serverName, Map props, CallbackHandler handler) { super(SM2_MECHANISM + "-" + umn, authorizationID, protocol, serverName, props, handler); this.umn = umn; complete = false; state = 0; if (sha == null) try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException x) { cat.error("SM2Client()", x); throw new RuntimeException(String.valueOf(x)); } sha.update(String.valueOf(umn).getBytes()); sha.update(String.valueOf(authorizationID).getBytes()); sha.update(String.valueOf(protocol).getBytes()); sha.update(String.valueOf(serverName).getBytes()); sha.update(String.valueOf(properties).getBytes()); sha.update(String.valueOf(Thread.currentThread().getName()).getBytes()); uid = new BigInteger(1, sha.digest()).toString(26); Ec = null; }
Code Sample 2:
public void testStorageString() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", r.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); try { r.getOutputStream(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } try { r.getWriter(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); }
|
00
|
Code Sample 1:
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = new URL(System.getenv("plugg_home") + "/" + systemId); System.out.println("SystemId = " + systemId); return new InputSource(url.openStream()); }
Code Sample 2:
private static MimeType getMimeType(URL url) { String mimeTypeString = null; String charsetFromWebServer = null; String contentType = null; InputStream is = null; MimeType mimeTypeFromWebServer = null; MimeType mimeTypeFromFileSuffix = null; MimeType mimeTypeFromMagicNumbers = null; String fileSufix = null; if (url == null) return null; try { try { is = url.openConnection().getInputStream(); contentType = url.openConnection().getContentType(); } catch (IOException e) { } if (contentType != null) { StringTokenizer st = new StringTokenizer(contentType, ";"); if (st.hasMoreTokens()) mimeTypeString = st.nextToken().toLowerCase(); if (st.hasMoreTokens()) charsetFromWebServer = st.nextToken().toLowerCase(); if (charsetFromWebServer != null) { st = new StringTokenizer(charsetFromWebServer, "="); charsetFromWebServer = null; if (st.hasMoreTokens()) st.nextToken(); if (st.hasMoreTokens()) charsetFromWebServer = st.nextToken().toUpperCase(); } } mimeTypeFromWebServer = mimeString2mimeTypeMap.get(mimeTypeString); fileSufix = getFileSufix(url); mimeTypeFromFileSuffix = getMimeType(fileSufix); mimeTypeFromMagicNumbers = guessTypeUsingMagicNumbers(is, charsetFromWebServer); } finally { IOUtils.closeQuietly(is); } return decideBetweenThreeMimeTypes(mimeTypeFromWebServer, mimeTypeFromFileSuffix, mimeTypeFromMagicNumbers); }
|
00
|
Code Sample 1:
public static String md5EncodeString(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (s == null) return null; if (StringUtils.isBlank(s)) return ""; MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes("UTF-8")); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); 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); } return hexString.toString(); }
Code Sample 2:
public static void saveZipComponents(ZipComponents zipComponents, File zipFile) throws FileNotFoundException, IOException, Exception { ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile)); for (ZipComponent comp : zipComponents.getComponents()) { ZipEntry newEntry = new ZipEntry(comp.getName()); zipOutStream.putNextEntry(newEntry); if (comp.isDirectory()) { } else { if (comp.getName().endsWith("document.xml") || comp.getName().endsWith("document.xml.rels")) { } InputStream inputStream = comp.getInputStream(); IOUtils.copy(inputStream, zipOutStream); inputStream.close(); } } zipOutStream.close(); }
|
11
|
Code Sample 1:
public RawTableData(int selectedId) { selectedProjectId = selectedId; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjectDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "documents.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&projectid=" + selectedProjectId + "&filename=" + URLEncoder.encode(username, "UTF-8") + "documents.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("doc"); int num = nodelist.getLength(); rawTableData = new String[num][11]; imageNames = new String[num]; for (int i = 0; i < num; i++) { rawTableData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "did")); rawTableData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "t")); rawTableData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); rawTableData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "d")); rawTableData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "l")); String firstname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "fn")); String lastname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ln")); rawTableData[i][5] = firstname + " " + lastname; rawTableData[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dln")); rawTableData[i][7] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "rsid")); rawTableData[i][8] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); imageNames[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); rawTableData[i][9] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ucin")); rawTableData[i][10] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dtid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
Code Sample 2:
public void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.