label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
@Override public boolean setupDatabaseSchema() { Configuration cfg = Configuration.getInstance(); Connection con = getConnection(); if (null == con) return false; try { String sql = FileTool.readFile(cfg.getProperty("database.sql.rootdir") + System.getProperty("file.separator") + cfg.getProperty("database.sql.mysql.setupschema")); sql = sql.replaceAll(MYSQL_SQL_SCHEMA_REPLACEMENT, StateSaver.getInstance().getDatabaseSettings().getSchema()); con.setAutoCommit(false); Statement stmt = con.createStatement(); String[] sqlParts = sql.split(";"); for (String sqlPart : sqlParts) { if (sqlPart.trim().length() > 0) stmt.executeUpdate(sqlPart); } con.commit(); JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionsuccess"), language.getProperty("dialog.information.title"), JOptionPane.INFORMATION_MESSAGE); return true; } catch (SQLException e) { Logger.logException(e); } try { if (con != null) con.rollback(); } catch (SQLException e) { Logger.logException(e); } JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionerror"), language.getProperty("dialog.error.title"), JOptionPane.ERROR_MESSAGE); return false; }
Code Sample 2:
public HttpResponse executeWithoutRewriting(HttpUriRequest request, HttpContext context) throws IOException { int code = -1; long start = SystemClock.elapsedRealtime(); try { HttpResponse response; mConnectionAllocated.set(null); if (NetworkStatsEntity.shouldLogNetworkStats()) { int uid = android.os.Process.myUid(); long startTx = NetStat.getUidTxBytes(uid); long startRx = NetStat.getUidRxBytes(uid); response = mClient.execute(request, context); HttpEntity origEntity = response == null ? null : response.getEntity(); if (origEntity != null) { long now = SystemClock.elapsedRealtime(); long elapsed = now - start; NetworkStatsEntity entity = new NetworkStatsEntity(origEntity, mAppName, uid, startTx, startRx, elapsed, now); response.setEntity(entity); } } else { response = mClient.execute(request, context); } code = response.getStatusLine().getStatusCode(); return response; } finally { try { long elapsed = SystemClock.elapsedRealtime() - start; ContentValues values = new ContentValues(); values.put(Checkin.Stats.COUNT, 1); values.put(Checkin.Stats.SUM, elapsed / 1000.0); values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_REQUEST + ":" + mAppName); mResolver.insert(Checkin.Stats.CONTENT_URI, values); if (mConnectionAllocated.get() == null && code >= 0) { values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_REUSED + ":" + mAppName); mResolver.insert(Checkin.Stats.CONTENT_URI, values); } String status = code < 0 ? "IOException" : Integer.toString(code); values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_STATUS + ":" + mAppName + ":" + status); mResolver.insert(Checkin.Stats.CONTENT_URI, values); } catch (Exception e) { Log.e(TAG, "Error recording stats", e); } } }
|
00
|
Code Sample 1:
void acessResource(ClassLoader cl, String resource) throws IOException { URL url = cl.getResource(resource); if (url == null) { println("Ups can't find resource " + resource); } else { println("URL OK " + resource + " ->" + url); InputStream is = url.openStream(); try { is.read(); } finally { is.close(); } println("Read OK " + resource + " ->" + url); } }
Code Sample 2:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
|
00
|
Code Sample 1:
public static String getAnalysisServletOutput(String inputXml) { java.io.BufferedWriter bWriter = null; URLConnection connection = null; String resultString = ""; bWriter = null; connection = null; String target = ServletConstant.ANALYSIS_SERVLET; String message = "\nTHIS MESSAGE IS SENT FROM THE CLIENT APPLET \n\r"; try { URL url = new URL(target); connection = (HttpURLConnection) url.openConnection(); ((HttpURLConnection) connection).setRequestMethod("POST"); connection.setDoOutput(true); bWriter = new java.io.BufferedWriter(new java.io.OutputStreamWriter(connection.getOutputStream())); bWriter.write(message); bWriter.flush(); bWriter.close(); java.io.BufferedReader bReader = null; bReader = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream())); String line; StringBuffer sb = new StringBuffer(); while ((line = bReader.readLine()) != null) { sb.append(line); } resultString = sb.toString(); bReader.close(); ((HttpURLConnection) connection).disconnect(); } catch (java.io.IOException ex) { resultString += ex.toString(); } finally { if (bWriter != null) { try { bWriter.close(); } catch (Exception ex) { resultString += ex.toString(); } } if (connection != null) { try { ((HttpURLConnection) connection).disconnect(); } catch (Exception ex) { resultString += ex.toString(); } } } return resultString; }
Code Sample 2:
public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
11
|
Code Sample 1:
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
@Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } }
Code Sample 2:
public String getDefaultPaletteXML() { URL url = getClass().getResource("xml/palettes.xml"); StringBuffer contents = new StringBuffer(); try { InputStream inputStream = url.openStream(); int i; while (true) { i = inputStream.read(); if (i == -1) break; char c = (char) i; contents.append(c); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return contents.toString(); }
|
11
|
Code Sample 1:
private static boolean hardCopy(File sourceFile, File destinationFile, StringBuffer errorLog) { boolean result = true; try { notifyCopyStart(destinationFile); destinationFile.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destinationFile); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { result = false; handleException("\n Error in method: copy!\n", e, errorLog); } finally { notifyCopyEnd(destinationFile); } return result; }
Code Sample 2:
public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
private void getLines(PackageManager pm) throws PackageManagerException { final Pattern p = Pattern.compile("\\s*deb\\s+(ftp://|http://)(\\S+)\\s+((\\S+\\s*)*)(./){0,1}"); Matcher m; if (updateUrlAndFile == null) updateUrlAndFile = new ArrayList<UrlAndFile>(); BufferedReader f; String protocol; String host; String shares; String adress; try { f = new BufferedReader(new FileReader(sourcesList)); while ((protocol = f.readLine()) != null) { m = p.matcher(protocol); if (m.matches()) { protocol = m.group(1); host = m.group(2); if (m.group(3).trim().equalsIgnoreCase("./")) shares = ""; else shares = m.group(3).trim(); if (shares == null) adress = protocol + host; else { shares = shares.replace(" ", "/"); if (!host.endsWith("/") && !shares.startsWith("/")) host = host + "/"; adress = host + shares; while (adress.contains("//")) adress = adress.replace("//", "/"); adress = protocol + adress; } if (!adress.endsWith("/")) adress = adress + "/"; String changelogdir = adress; changelogdir = changelogdir.substring(changelogdir.indexOf("//") + 2); if (changelogdir.endsWith("/")) changelogdir = changelogdir.substring(0, changelogdir.lastIndexOf("/")); changelogdir = changelogdir.replace('/', '_'); changelogdir = changelogdir.replaceAll("\\.", "_"); changelogdir = changelogdir.replaceAll("-", "_"); changelogdir = changelogdir.replaceAll(":", "_COLON_"); adress = adress + "Packages.gz"; final String serverFileLocation = adress.replaceAll(":", "_COLON_"); final NameFileLocation nfl = new NameFileLocation(); try { final GZIPInputStream in = new GZIPInputStream(new ConnectToServer(pm).getInputStream(adress)); final String rename = new File(nfl.rename(serverFileLocation, listsDir)).getCanonicalPath(); final FileOutputStream out = new FileOutputStream(rename); final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); final File file = new File(rename); final UrlAndFile uaf = new UrlAndFile(protocol + host, file, changelogdir); updateUrlAndFile.add(uaf); } catch (final Exception e) { final String message = "URL: " + adress + " caused exception"; if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } } f.close(); } catch (final FileNotFoundException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("sourcesList.corrupt", "Entry not found sourcesList.corrupt"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } catch (final IOException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("SearchForServerFile.getLines.IOException", "Entry not found SearchForServerFile.getLines.IOException"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } }
Code Sample 2:
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { try { if (vtf == null) { LOG.debug("Serializing from database"); existDocument.stream(out); } else { LOG.debug("Serializing from buffer"); InputStream is = vtf.getByteStream(); IOUtils.copy(is, out); out.flush(); IOUtils.closeQuietly(is); vtf.delete(); vtf = null; } } catch (PermissionDeniedException e) { LOG.debug(e.getMessage()); throw new NotAuthorizedException(this); } finally { IOUtils.closeQuietly(out); } }
|
11
|
Code Sample 1:
@Override public void save(String arxivId, InputStream inputStream, String encoding) { String filename = StringUtil.arxivid2filename(arxivId, "tex"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(String.format("%s/%s", LATEX_DOCUMENT_DIR, filename)), encoding); IOUtils.copy(inputStream, writer, encoding); writer.flush(); writer.close(); inputStream.close(); } catch (IOException e) { logger.error("Failed to save the Latex source with id='{}'", arxivId, e); throw new RuntimeException(e); } }
Code Sample 2:
private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } }
|
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 void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); }
|
11
|
Code Sample 1:
public void covertFile(File file) throws IOException { if (!file.isFile()) { return; } Reader reader = null; OutputStream os = null; File newfile = null; String filename = file.getName(); boolean succeed = false; try { newfile = new File(file.getParentFile(), filename + ".bak"); reader = new InputStreamReader(new FileInputStream(file), fromEncoding); os = new FileOutputStream(newfile); IOUtils.copy(reader, os, toEncoding); } catch (Exception e) { e.printStackTrace(); throw new IOException("Encoding error for file [" + file.getAbsolutePath() + "]"); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } try { file.delete(); succeed = newfile.renameTo(file); } catch (Exception e) { throw new IOException("Clear bak error for file [" + file.getAbsolutePath() + "]"); } if (succeed) { System.out.println("Changed encoding for file [" + file.getAbsolutePath() + "]"); } }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { LOGGER.info("Copying file '" + src.getAbsolutePath() + "' to '" + dst.getAbsolutePath() + "'"); FileChannel in = null; FileChannel out = null; try { FileInputStream fis = new FileInputStream(src); in = fis.getChannel(); FileOutputStream fos = new FileOutputStream(dst); out = fos.getChannel(); out.transferFrom(in, 0, in.size()); } finally { try { if (in != null) in.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } if (out != null) { try { out.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } }
|
00
|
Code Sample 1:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } }
Code Sample 2:
public void run() { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); ChannelMap cm = new ChannelMap(); for (int i = 0; i < picm.NumberOfChannels(); i++) { cm.Add(picm.GetName(i)); } String[] folder = picm.GetFolderList(); for (int i = 0; i < folder.length; i++) { cm.AddFolder(folder[i]); } sink.Request(cm, picm.GetRequestStart(), picm.GetRequestDuration(), picm.GetRequestReference()); cm = sink.Fetch(timeout); if (cm.GetIfFetchTimedOut()) { System.err.println("Signature Data Fetch Timed Out!"); picm.Clear(); } else { md.reset(); folder = cm.GetFolderList(); for (int i = 0; i < folder.length; i++) picm.AddFolder(folder[i]); int sigIdx = -1; for (int i = 0; i < cm.NumberOfChannels(); i++) { String chan = cm.GetName(i); if (chan.endsWith("/_signature")) { sigIdx = i; continue; } int idx = picm.GetIndex(chan); if (idx == -1) idx = picm.Add(chan); picm.PutTimeRef(cm, i); picm.PutDataRef(idx, cm, i); md.update(cm.GetData(i)); md.update((new Double(cm.GetTimeStart(i))).toString().getBytes()); } if (cm.NumberOfChannels() > 0) { byte[] amd = md.digest(signature.getBytes()); if (sigIdx >= 0) { if (MessageDigest.isEqual(amd, cm.GetDataAsByteArray(sigIdx)[0])) { System.err.println(pluginName + ": signature matched for: " + cm.GetName(0)); } else { System.err.println(pluginName + ": failed signature test, sending null response"); picm.Clear(); } } else { System.err.println(pluginName + ": _signature attached for: " + cm.GetName(0)); int idx = picm.Add("_signature"); picm.PutTime(0., 0.); picm.PutDataAsByteArray(idx, amd); } } } plugin.Flush(picm); } catch (Exception e) { e.printStackTrace(); } if (threadStack.size() < 4) threadStack.push(this); else sink.CloseRBNBConnection(); }
|
11
|
Code Sample 1:
private byte[] hash(String toHash) { try { MessageDigest md5 = MessageDigest.getInstance("MD5", "BC"); md5.update(toHash.getBytes("ISO-8859-1")); return md5.digest(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
Code Sample 2:
public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); }
|
00
|
Code Sample 1:
private void parseTemplate(File templateFile, Map dataMap) throws ContainerException { Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(templateFile)); } catch (FileNotFoundException e) { throw new ContainerException(e); } String targetDirectoryName = args.length > 1 ? args[1] : null; if (targetDirectoryName == null) { targetDirectoryName = target; } String targetDirectory = ofbizHome + targetDirectoryName + args[0]; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { throw new ContainerException("Unable to create target directory - " + targetDirectory); } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } Writer writer = null; try { writer = new FileWriter(targetDirectory + templateFile.getName()); } catch (IOException e) { throw new ContainerException(e); } try { FreeMarkerWorker.renderTemplate(templateFile.getAbsolutePath(), reader, dataMap, writer); } catch (Exception e) { throw new ContainerException(e); } try { writer.flush(); writer.close(); } catch (IOException e) { throw new ContainerException(e); } }
Code Sample 2:
public void connect() throws IOException { if (this.connection == null) { this.connection = (HttpURLConnection) (new URL(url)).openConnection(); this.connection.setRequestMethod("POST"); this.connection.setUseCaches(false); this.connection.setDoOutput(true); } }
|
11
|
Code Sample 1:
public static File getClassLoaderFile(String filename) throws IOException { Resource resource = new ClassPathResource(filename); try { return resource.getFile(); } catch (IOException e) { } InputStream is = null; FileOutputStream os = null; try { String tempFilename = RandomStringUtils.randomAlphanumeric(20); File file = File.createTempFile(tempFilename, null); is = resource.getInputStream(); os = new FileOutputStream(file); IOUtils.copy(is, os); return file; } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
Code Sample 2:
public ManageUsers() { if (System.getProperty("user.home") != null) { dataFile = new File(System.getProperty("user.home") + File.separator + "MyRx" + File.separator + "MyRx.dat"); File dataFileDir = new File(System.getProperty("user.home") + File.separator + "MyRx"); dataFileDir.mkdirs(); } else { dataFile = new File("MyRx.dat"); } try { dataFile.createNewFile(); } catch (IOException e1) { logger.error(e1); JOptionPane.showMessageDialog(Menu.getMainMenu(), e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } File oldDataFile = new File("MyRx.dat"); if (oldDataFile.exists()) { FileChannel src = null, dst = null; try { src = new FileInputStream(oldDataFile.getAbsolutePath()).getChannel(); dst = new FileOutputStream(dataFile.getAbsolutePath()).getChannel(); dst.transferFrom(src, 0, src.size()); if (!oldDataFile.delete()) { oldDataFile.deleteOnExit(); } } catch (FileNotFoundException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { try { src.close(); dst.close(); } catch (IOException e) { logger.error(e); } } } }
|
11
|
Code Sample 1:
@Before public void BeforeTheTest() throws Exception { URL url = ProfileParserTest.class.getClassLoader().getResource("ca/uhn/hl7v2/conf/parser/tests/example_ack.xml"); URLConnection conn = url.openConnection(); InputStream instream = conn.getInputStream(); if (instream == null) throw new Exception("can't find the xml file"); BufferedReader in = new BufferedReader(new InputStreamReader(instream)); int tmp = 0; StringBuffer buf = new StringBuffer(); while ((tmp = in.read()) != -1) { buf.append((char) tmp); } profileString = buf.toString(); }
Code Sample 2:
private String getTextResponse(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); BufferedReader in = null; try { con.connect(); assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder builder = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } return builder.toString(); } finally { if (in != null) { in.close(); } con.disconnect(); } }
|
00
|
Code Sample 1:
public static void copy(final File src, File dst, final boolean overwrite) throws IOException, IllegalArgumentException { if (!src.isFile() || !src.exists()) { throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); } if (dst.exists()) { if (dst.isDirectory()) { dst = new File(dst, src.getName()); } else if (dst.isFile()) { if (!overwrite) { throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); } } else { throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); } } final File dstParent = dst.getParentFile(); if (!dstParent.exists()) { if (!dstParent.mkdirs()) { throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); } } long fileSize = src.length(); if (fileSize > 20971520l) { final FileInputStream in = new FileInputStream(src); final FileOutputStream out = new FileOutputStream(dst); try { int doneCnt = -1; final int bufSize = 32768; final byte buf[] = new byte[bufSize]; while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) { if (doneCnt == 0) { Thread.yield(); } else { out.write(buf, 0, doneCnt); } } out.flush(); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } } } else { final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } } } }
Code Sample 2:
public int executeUpdateJT(String sql, Object[][] paramsList) { Connection connection = null; connection = this.getConnection(); try { connection.setAutoCommit(false); } catch (SQLException e1) { e1.printStackTrace(); } PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < paramsList.length; i++) { if (connection != null && !connection.isClosed()) { InputStream is = null; if (paramsList[i].length > 0) { for (int j = 0; j < paramsList[i].length; j++) { Object obj = paramsList[i][j]; if (obj.getClass().equals(Class.forName("java.io.File"))) { File file = (File) obj; is = new FileInputStream(file); preparedStatement.setBinaryStream(j + 1, is, (int) file.length()); } else if (obj.getClass().equals(Class.forName("java.util.Date"))) { java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); preparedStatement.setString(j + 1, sdf.format((Date) obj)); } else { preparedStatement.setObject(j + 1, obj); } } } preparedStatement.executeUpdate(); if (is != null) { is.close(); } ; } } } catch (Exception e) { System.out.println("发生错误,数据回滚!"); e.printStackTrace(); try { connection.rollback(); return 0; } catch (SQLException e1) { e1.printStackTrace(); } } try { connection.commit(); return 1; } catch (SQLException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { log.error("未能正确关闭数据库连接!", e); System.out.println("未能正确关闭数据库连接!"); e.printStackTrace(); } } return -1; }
|
00
|
Code Sample 1:
private static BundleInfo[] getBundleInfoArray(String location) throws IOException { URL url = new URL(location + BUNDLE_LIST_FILE); BufferedReader br = null; List<BundleInfo> list = new ArrayList<BundleInfo>(); try { br = new BufferedReader(new InputStreamReader(url.openStream())); while (true) { String line = br.readLine(); if (line == null) { break; } int pos1 = line.indexOf('='); if (pos1 < 0) { continue; } BundleInfo info = new BundleInfo(); info.bundleSymbolicName = line.substring(0, pos1); info.location = line.substring(pos1 + 1); list.add(info); } if (!setBundleInfoName(location + BUNDLE_NAME_LIST_FILE + "_" + Locale.getDefault().getLanguage(), list)) { setBundleInfoName(location + BUNDLE_NAME_LIST_FILE, list); } return list.toArray(BUNDLE_INFO_EMPTY_ARRAY); } finally { if (br != null) { br.close(); } } }
Code Sample 2:
private File downloadURL(URL url) { MerlotDebug.msg("Downloading URL: " + url); String filename = url.getFile(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } File userPluginsDir = new File(XMLEditorSettings.USER_MERLOT_DIR, "plugins"); File cache = new File(userPluginsDir, filename); try { if (!userPluginsDir.exists()) { userPluginsDir.mkdirs(); } URLConnection connection = url.openConnection(); if (cache.exists() && cache.canRead()) { connection.connect(); long remoteTimestamp = connection.getLastModified(); if (remoteTimestamp == 0 || remoteTimestamp > cache.lastModified()) { cache = downloadContent(connection, cache); } else { MerlotDebug.msg("Using cached version for URL: " + url); } } else { cache = downloadContent(connection, cache); } } catch (IOException ex) { MerlotDebug.exception(ex); } if (cache != null && cache.exists()) { return cache; } else { return null; } }
|
00
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
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:
private ScrollingGraphicalViewer createGraphicalViewer(final Composite parent) { final ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); _root = new EditRootEditPart(); viewer.setRootEditPart(_root); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); final KeyHandler keyHandler = new GraphicalViewerKeyHandler(viewer) { @SuppressWarnings("unchecked") @Override public boolean keyPressed(final KeyEvent event) { if (event.stateMask == SWT.MOD1 && event.keyCode == SWT.DEL) { final List<? extends EditorPart> objects = viewer.getSelectedEditParts(); if (objects == null || objects.isEmpty()) return true; final GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE); final CompoundCommand compoundCmd = new CompoundCommand("Delete"); for (int i = 0; i < objects.size(); i++) { final EditPart object = (EditPart) objects.get(i); deleteReq.setEditParts(object); final Command cmd = object.getCommand(deleteReq); if (cmd != null) compoundCmd.add(cmd); } getCommandStack().execute(compoundCmd); return true; } if (event.stateMask == SWT.MOD3 && (event.keyCode == SWT.ARROW_DOWN || event.keyCode == SWT.ARROW_LEFT || event.keyCode == SWT.ARROW_RIGHT || event.keyCode == SWT.ARROW_UP)) { final List<? extends EditorPart> objects = viewer.getSelectedEditParts(); if (objects == null || objects.isEmpty()) return true; final GroupRequest moveReq = new ChangeBoundsRequest(RequestConstants.REQ_MOVE); final CompoundCommand compoundCmd = new CompoundCommand("Move"); for (int i = 0; i < objects.size(); i++) { final EditPart object = (EditPart) objects.get(i); moveReq.setEditParts(object); final LocationCommand cmd = (LocationCommand) object.getCommand(moveReq); if (cmd != null) { cmd.setLocation(new Point(event.keyCode == SWT.ARROW_LEFT ? -1 : event.keyCode == SWT.ARROW_RIGHT ? 1 : 0, event.keyCode == SWT.ARROW_DOWN ? 1 : event.keyCode == SWT.ARROW_UP ? -1 : 0)); cmd.setRelative(true); compoundCmd.add(cmd); } } getCommandStack().execute(compoundCmd); return true; } return super.keyPressed(event); } }; keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), getActionRegistry().getAction(GEFActionConstants.DIRECT_EDIT)); viewer.setKeyHandler(keyHandler); viewer.setContents(getEditorInput().getAdapter(NamedUuidEntity.class)); viewer.addDropTargetListener(createTransferDropTargetListener(viewer)); return viewer; }
Code Sample 2:
public boolean receiveFile(FileDescriptor fileDescriptor) { try { byte[] block = new byte[1024]; int sizeRead = 0; int totalRead = 0; File dir = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dir.exists()) { dir.mkdirs(); } File file = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); if (!file.exists()) { file.createNewFile(); } SSLSocket sslsocket = getFileTransferConectionConnectMode(ServerAdress.getServerAdress()); OutputStream fileOut = new FileOutputStream(file); InputStream dataIn = sslsocket.getInputStream(); while ((sizeRead = dataIn.read(block)) >= 0) { totalRead += sizeRead; fileOut.write(block, 0, sizeRead); propertyChangeSupport.firePropertyChange("fileByte", 0, totalRead); } fileOut.close(); dataIn.close(); sslsocket.close(); if (fileDescriptor.getName().contains(".snapshot")) { try { File fileData = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); File dirData = new File(Constants.PREVAYLER_DATA_DIRETORY + Constants.FILE_SEPARATOR); File destino = new File(dirData, fileData.getName()); boolean success = fileData.renameTo(destino); if (!success) { deleteDir(Constants.DOWNLOAD_DIR); return false; } deleteDir(Constants.DOWNLOAD_DIR); } catch (Exception e) { e.printStackTrace(); } } else { if (Server.isServerOpen()) { FileChannel inFileChannel = new FileInputStream(file).getChannel(); File dirServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getName()); if (!fileServer.exists()) { fileServer.createNewFile(); } inFileChannel.transferTo(0, inFileChannel.size(), new FileOutputStream(fileServer).getChannel()); inFileChannel.close(); } } if (totalRead == fileDescriptor.getSize()) { return true; } } catch (Exception e) { logger.error("Receive File:", e); } return false; }
|
00
|
Code Sample 1:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } }
Code Sample 2:
public static void main(String[] arg) throws IOException { XmlPullParserFactory PULL_PARSER_FACTORY; try { PULL_PARSER_FACTORY = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); PULL_PARSER_FACTORY.setNamespaceAware(true); DasParser dp = new DasParser(PULL_PARSER_FACTORY); URL url = new URL("http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/features?segment=P05067"); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String aLine, xml = ""; while ((aLine = br.readLine()) != null) { xml += aLine; } WritebackDocument wbd = dp.parse(xml); System.out.println("FIN" + wbd); } catch (XmlPullParserException xppe) { throw new IllegalStateException("Fatal Exception thrown at initialisation. Cannot initialise the PullParserFactory required to allow generation of the DAS XML.", xppe); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void copyFile2(String src, String dest) throws IOException { String newLine = System.getProperty("line.separator"); FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + QZ.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(QZ.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
|
00
|
Code Sample 1:
@Override protected final Boolean doInBackground(Void... v) { Bitmap bmp = ((BitmapDrawable) ((ImageView) findViewById(R.id.post_img)).getDrawable()).getBitmap(); HttpURLConnection con; try { URL url = new URL(POST_URL); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Accept-Language", "multipart/form-data"); con.setRequestProperty("X-RAW", "true"); } catch (MalformedURLException e) { e.printStackTrace(); finish(); return false; } catch (IOException e) { e.printStackTrace(); finish(); return false; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); bmp.compress(CompressFormat.JPEG, 100, bos); OutputStream os = null; try { os = con.getOutputStream(); os.write(bos.toByteArray()); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); try { os.close(); } catch (IOException e1) { e1.printStackTrace(); } return false; } InputStream is = null; BufferedReader reader; try { is = con.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); is.close(); } catch (IOException e) { e.printStackTrace(); try { is.close(); } catch (IOException e1) { e1.printStackTrace(); } return false; } String s; try { while ((s = reader.readLine()) != null) { Log.v(TAG, s); } } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return true; }
Code Sample 2:
private static String processStr(String srcStr, String sign) throws NoSuchAlgorithmException, NullPointerException { if (null == srcStr) { throw new java.lang.NullPointerException("��Ҫ���ܵ��ַ�ΪNull"); } MessageDigest digest; String algorithm = "MD5"; String result = ""; digest = MessageDigest.getInstance(algorithm); digest.update(srcStr.getBytes()); byte[] byteRes = digest.digest(); int length = byteRes.length; for (int i = 0; i < length; i++) { result = result + byteHEX(byteRes[i], sign); } return result; }
|
11
|
Code Sample 1:
private final void copyTargetFileToSourceFile(File sourceFile, File targetFile) throws MJProcessorException { if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); try { if (!targetFile.exists()) { targetFile.createNewFile(); } } catch (IOException e) { throw new MJProcessorException(e.getMessage(), e); } } FileChannel in = null, out = null; try { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(targetFile).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (IOException e) { log.error(e); } finally { if (in != null) try { in.close(); } catch (IOException e) { log.error(e); } if (out != null) try { out.close(); } catch (IOException e) { log.error(e); } } }
Code Sample 2:
@Test public void testGrantLicense() throws Exception { context.turnOffAuthorisationSystem(); Item item = Item.create(context); String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); LicenseUtils.grantLicense(context, item, defaultLicense); StringWriter writer = new StringWriter(); IOUtils.copy(item.getBundles("LICENSE")[0].getBitstreams()[0].retrieve(), writer); String license = writer.toString(); assertThat("testGrantLicense 0", license, equalTo(defaultLicense)); context.restoreAuthSystemState(); }
|
11
|
Code Sample 1:
Object onSuccess() { this.mErrorExist = true; this.mErrorMdp = true; if (this.mNewMail.equals(mClient.getEmail()) || !this.mNewMail.equals(mClient.getEmail()) && !mClientManager.exists(this.mNewMail)) { this.mErrorExist = false; if (mNewMdp != null && mNewMdpConfirm != null) { if (this.mNewMdp.equals(this.mNewMdpConfirm)) { this.mErrorMdp = false; MessageDigest sha1Instance; try { sha1Instance = MessageDigest.getInstance("SHA1"); sha1Instance.reset(); sha1Instance.update(this.mNewMdp.getBytes()); byte[] digest = sha1Instance.digest(); BigInteger bigInt = new BigInteger(1, digest); String vHashPassword = bigInt.toString(16); mClient.setMdp(vHashPassword); } catch (NoSuchAlgorithmException e) { mLogger.error(e.getMessage(), e); } } } else { this.mErrorMdp = false; } if (!this.mErrorMdp) { mClient.setAdresse(this.mNewAdresse); mClient.setEmail(this.mNewMail); mClient.setNom(this.mNewNom); mClient.setPrenom((this.mNewPrenom != null ? this.mNewPrenom : "")); Client vClient = new Client(mClient); mClientManager.save(vClient); mComponentResources.discardPersistentFieldChanges(); return "Client/List"; } } return errorZone.getBody(); }
Code Sample 2:
public static String encrypt(String text) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String result = ""; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes()); byte[] hash = digest.digest(); char buffer[] = new char[hash.length * 2]; for (int i = 0, x = 0; i < hash.length; i++) { buffer[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; buffer[x++] = HEX_CHARS[hash[i] & 0xf]; } result = new String(buffer); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
|
00
|
Code Sample 1:
public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } }
Code Sample 2:
private static String fetchUrl(String url, boolean keepLineEnds) throws IOException, MalformedURLException { URLConnection destConnection = (new URL(url)).openConnection(); BufferedReader br; String inputLine; StringBuffer doc = new StringBuffer(); String contentEncoding; destConnection.setRequestProperty("Accept-Encoding", "gzip"); if (proxyAuth != null) destConnection.setRequestProperty("Proxy-Authorization", proxyAuth); destConnection.connect(); contentEncoding = destConnection.getContentEncoding(); if ((contentEncoding != null) && contentEncoding.equals("gzip")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(destConnection.getInputStream()))); } else { br = new BufferedReader(new InputStreamReader(destConnection.getInputStream())); } while ((inputLine = br.readLine()) != null) { if (keepLineEnds) doc.append(inputLine + "\n"); else doc.append(inputLine); } br.close(); return doc.toString(); }
|
11
|
Code Sample 1:
public boolean copyDirectoryTree(File srcPath, File dstPath) { try { if (srcPath.isDirectory()) { if (!dstPath.exists()) dstPath.mkdir(); String files[] = srcPath.list(); for (int i = 0; i < files.length; i++) copyDirectoryTree(new File(srcPath, files[i]), new File(dstPath, files[i])); } else { if (!srcPath.exists()) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath + "' does not exist.\n"; lastErrMsgLog = errMsgLog; return (false); } else { InputStream in = new FileInputStream(srcPath); OutputStream out = new FileOutputStream(dstPath); byte[] buf = new byte[10240]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } } return (true); } catch (Exception e) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath.getName() + "' to '" + dstPath.getName() + "\n " + e + "\n"; lastErrMsgLog = errMsgLog; return (false); } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public String getMatches() { StringBuilder builder = new StringBuilder(""); try { URL url = new URL(LIVE_SCORE_URL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { builder.append(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
Code Sample 2:
protected String getCitations(String ticket, String query) throws IOException { String urlQuery; try { urlQuery = "http://www.jstor.org/search/BasicResults?hp=" + MAX_CITATIONS + "&si=1&gw=jtx&jtxsi=1&jcpsi=1&artsi=1&Query=" + URLEncoder.encode(query, "UTF-8") + "&wc=on&citationAction=saveAll"; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } URL url = new URL(urlQuery); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", ticket); return getCookie(COOKIE_CITATIONS, conn); }
|
00
|
Code Sample 1:
private static Document getDocument(URL url, String applicationVersion, boolean addHeader, int timeOut) throws IOException, ParserConfigurationException, SAXException { HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setConnectTimeout(1000 * timeOut); huc.setRequestMethod("GET"); if (addHeader) { huc.setRequestProperty("JavaPEG-Version", applicationVersion); } huc.connect(); int code = huc.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { throw new IOException("Invaild HTTP response: " + code); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse(huc.getInputStream()); }
Code Sample 2:
@Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { File result = new File(parent, doc.getName()); if (doc instanceof XMLDOMDocument) { new PlainXMLDocumentWriter(result).writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { IOUtils.copy(bin.getContent().getInputStream(), new FileOutputStream(result)); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
|
00
|
Code Sample 1:
public static final void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.apache.org/"); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); try { System.out.println(reader.readLine()); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { reader.close(); } } }
Code Sample 2:
private static byte[] get256RandomBits() throws IOException { URL url = null; try { url = new URL(SRV_URL); } catch (MalformedURLException e) { e.printStackTrace(); } HttpsURLConnection hu = (HttpsURLConnection) url.openConnection(); hu.setConnectTimeout(2500); InputStream is = hu.getInputStream(); byte[] content = new byte[is.available()]; is.read(content); is.close(); hu.disconnect(); byte[] randomBits = new byte[32]; String line = new String(content); Matcher m = DETAIL.matcher(line); if (m.find()) { for (int i = 0; i < 32; i++) randomBits[i] = (byte) (Integer.parseInt(m.group(1).substring(i * 2, i * 2 + 2), 16) & 0xFF); } return randomBits; }
|
00
|
Code Sample 1:
public Component loadComponent(URI uri, URI origuri) throws ComponentException { if (usePrivMan) PrivilegeManager.enablePrivilege("UniversalConnect"); ConzillaRDFModel model = factory.createModel(origuri, uri); RDFParser parser = new com.hp.hpl.jena.rdf.arp.StanfordImpl(); java.net.URL url = null; try { url = uri.getJavaURL(); } catch (java.net.MalformedURLException e) { throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage()); } try { InputSource source = new InputSource(url.openStream()); source.setSystemId(origuri.toString()); parser.parse(source, new ModelConsumer(model)); factory.getTotalModel().addModel(model); } catch (org.xml.sax.SAXException se) { se.getException().printStackTrace(); throw new ComponentException("Format error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } catch (java.io.IOException se) { throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } catch (org.w3c.rdf.model.ModelException se) { throw new ComponentException("Model error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } return model; }
Code Sample 2:
public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } }
|
00
|
Code Sample 1:
public void loginMD5() throws Exception { GetMethod get = new GetMethod("http://login.yahoo.com/config/login?.src=www&.done=http://www.yahoo.com"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); client.executeMethod(get); parseResponse(get.getResponseBodyAsStream()); MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes("US-ASCII")); String hash1 = new String(digest.digest(), "US-ASCII"); String hash2 = hash1 + challenge; digest.update(hash2.getBytes("US-ASCII")); String hash = new String(digest.digest(), "US-ASCII"); NameValuePair[] pairs = { new NameValuePair("login", login), new NameValuePair("password", hash), new NameValuePair(".save", "1"), new NameValuePair(".tries", "1"), new NameValuePair(".src", "www"), new NameValuePair(".md5", "1"), new NameValuePair(".hash", "1"), new NameValuePair(".js", "1"), new NameValuePair(".last", ""), new NameValuePair(".promo", ""), new NameValuePair(".intl", "us"), new NameValuePair(".bypass", ""), new NameValuePair(".u", u), new NameValuePair(".v", "0"), new NameValuePair(".challenge", challenge), new NameValuePair(".yplus", ""), new NameValuePair(".emailCode", ""), new NameValuePair("pkg", ""), new NameValuePair("stepid", ""), new NameValuePair(".ev", ""), new NameValuePair("hasMsgr", "0"), new NameValuePair(".chkP", "Y"), new NameValuePair(".done", "http://www.yahoo.com"), new NameValuePair(".persistent", "y") }; get = new GetMethod("http://login.yahoo.com/config/login"); get.setRequestHeader("user-agent", "Mozilla/5.0 (Macintosh; U; PPC MacOS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1"); get.addRequestHeader("Accept", "*/*"); get.addRequestHeader("Accept-Language", "en-us, ja;q=0.21, de-de;q=0.86, de;q=0.79, fr-fr;q=0.71, fr;q=0.64, nl-nl;q=0.57, nl;q=0.50, it-it;q=0.43, it;q=0.36, ja-jp;q=0.29, en;q=0.93, es-es;q=0.14, es;q=0.07"); get.setQueryString(pairs); client.executeMethod(get); get.getResponseBodyAsString(); }
Code Sample 2:
public void serviceDocument(final TranslationRequest request, final TranslationResponse response, final Document document) throws Exception { response.addHeaders(document.getResponseHeaders()); try { IOUtils.copy(document.getInputStream(), response.getOutputStream()); response.setEndState(ResponseStateOk.getInstance()); } catch (Exception e) { response.setEndState(new ResponseStateException(e)); log.warn("Error parsing XML of " + document, e); } }
|
00
|
Code Sample 1:
private void updateViewerContent(ScrollingGraphicalViewer viewer) { BioPAXGraph graph = (BioPAXGraph) viewer.getContents().getModel(); if (!graph.isMechanistic()) return; Map<String, Color> highlightMap = new HashMap<String, Color>(); for (Object o : graph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (node.isHighlighted()) { highlightMap.put(node.getIDHash(), node.getHighlightColor()); } } for (Object o : graph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (edge.isHighlighted()) { highlightMap.put(edge.getIDHash(), edge.getHighlightColor()); } } HighlightLayer hLayer = (HighlightLayer) ((ChsScalableRootEditPart) viewer.getRootEditPart()).getLayer(HighlightLayer.HIGHLIGHT_LAYER); hLayer.removeAll(); hLayer.highlighted.clear(); viewer.deselectAll(); graph.recordLayout(); PathwayHolder p = graph.getPathway(); if (withContent != null) { p.updateContentWith(withContent); } BioPAXGraph newGraph = main.getRootGraph().excise(p); newGraph.setAsRoot(); viewer.setContents(newGraph); boolean layedout = newGraph.fetchLayout(); if (!layedout) { new CoSELayoutAction(main).run(); } viewer.deselectAll(); GraphAnimation.run(viewer); for (Object o : newGraph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (highlightMap.containsKey(node.getIDHash())) { node.setHighlightColor(highlightMap.get(node.getIDHash())); node.setHighlight(true); } } for (Object o : newGraph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (highlightMap.containsKey(edge.getIDHash())) { edge.setHighlightColor(highlightMap.get(edge.getIDHash())); edge.setHighlight(true); } } }
Code Sample 2:
protected String readFileUsingFileUrl(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
|
11
|
Code Sample 1:
public static String hashJopl(String password, String algorithm, String prefixKey, boolean useDefaultEncoding) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); if (useDefaultEncoding) { digest.update(password.getBytes()); } else { for (char c : password.toCharArray()) { digest.update((byte) (c >> 8)); digest.update((byte) c); } } byte[] digestedPassword = digest.digest(); BASE64Encoder encoder = new BASE64Encoder(); String encodedDigestedStr = encoder.encode(digestedPassword); return prefixKey + encodedDigestedStr; } catch (NoSuchAlgorithmException ne) { return password; } }
Code Sample 2:
public static String md5(String source) { MessageDigest md; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { md = MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte[] digested = md.digest(); for (int i = 0; i < digested.length; i++) { pw.printf("%02x", digested[i]); } pw.flush(); return sw.getBuffer().toString(); } catch (NoSuchAlgorithmException e) { return null; } }
|
00
|
Code Sample 1:
private static void copyFile(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); FileChannel inc = in.getChannel(); FileChannel outc = out.getChannel(); inc.transferTo(0, inc.size(), outc); inc.close(); outc.close(); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
public void invoke(String args[]) { System.err.println("invoked with args of size " + args.length); try { for (int i = 0; i < args.length; i++) { System.err.println("processing URL: " + args[i]); URL url = new URL(args[i]); AnnotatedLinearObjectParser parserObj = findParserForURL(url); if (parserObj == null) { continue; } InputStream data = url.openStream(); CompMapViewerWrapper wrapper = ((CompMapViewerProvider) sp).getWrapper(); wrapper.parseIntoDataModel(data, new URLImpl(url.toString()), parserObj, false); JFrame f = wrapper.getViewer().getMainFrame(); f.show(); } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void _save(PortletRequest req, PortletResponse res, PortletConfig config, ActionForm form) throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "Property File save Failed " + e, e); } SessionMessages.add(req, "message", "message.usermanager.display.save"); }
Code Sample 2:
protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException { log("Retrieving url: " + urlString); DefaultHttpClient httpclient = new DefaultHttpClient(); if (this.archiveAccessSpecification.getUserID() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword())); } HttpGet httpget = new HttpGet(urlString); log("about to do request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); log("-------------- Request results --------------"); log("Status line: " + response.getStatusLine()); if (entity != null) { log("Response content length: " + entity.getContentLength()); } log("contents"); byte[] bytes = null; if (entity != null) { bytes = getBytesFromInputStream(entity.getContent()); entity.consumeContent(); } log("Status code :" + response.getStatusLine().getStatusCode()); log(response.getStatusLine().getReasonPhrase()); if (response.getStatusLine().getStatusCode() != 200) return null; return bytes; }
|
11
|
Code Sample 1:
public void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
@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 createResource(String resourceUri, boolean publish, User user) throws IOException { PermissionAPI perAPI = APILocator.getPermissionAPI(); Logger.debug(this.getClass(), "createResource"); resourceUri = stripMapping(resourceUri); String hostName = getHostname(resourceUri); String path = getPath(resourceUri); String folderName = getFolderName(path); String fileName = getFileName(path); fileName = deleteSpecialCharacter(fileName); if (fileName.startsWith(".")) { return; } Host host = HostFactory.getHostByHostName(hostName); Folder folder = FolderFactory.getFolderByPath(folderName, host); boolean hasPermission = perAPI.doesUserHavePermission(folder, PERMISSION_WRITE, user, false); if (hasPermission) { if (!checkFolderFilter(folder, fileName)) { throw new IOException("The file doesn't comply the folder's filter"); } if (host.getInode() != 0 && folder.getInode() != 0) { File file = new File(); file.setTitle(fileName); file.setFileName(fileName); file.setShowOnMenu(false); file.setLive(publish); file.setWorking(true); file.setDeleted(false); file.setLocked(false); file.setModDate(new Date()); String mimeType = FileFactory.getMimeType(fileName); file.setMimeType(mimeType); String author = user.getFullName(); file.setAuthor(author); file.setModUser(author); file.setSortOrder(0); file.setShowOnMenu(false); try { Identifier identifier = null; if (!isResource(resourceUri)) { WebAssetFactory.createAsset(file, user.getUserId(), folder, publish); identifier = IdentifierCache.getIdentifierFromIdentifierCache(file); } else { File actualFile = FileFactory.getFileByURI(path, host, false); identifier = IdentifierCache.getIdentifierFromIdentifierCache(actualFile); WebAssetFactory.createAsset(file, user.getUserId(), folder, identifier, false, false); WebAssetFactory.publishAsset(file); String assetsPath = FileFactory.getRealAssetsRootPath(); new java.io.File(assetsPath).mkdir(); java.io.File workingIOFile = FileFactory.getAssetIOFile(file); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath()); if (file != null && file.getInode() > 0) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(workingIOFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); java.io.File newVersionFile = FileFactory.getAssetIOFile(file); vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath()); FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); } java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file); for (Tree tree : parentTrees) { Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode()); if (newTree.getChild() == 0) { newTree.setParent(tree.getParent()); newTree.setChild(file.getInode()); newTree.setRelationType(tree.getRelationType()); newTree.setTreeOrder(0); TreeFactory.saveTree(newTree); } } } List<Permission> permissions = perAPI.getPermissions(folder); for (Permission permission : permissions) { Permission filePermission = new Permission(); filePermission.setPermission(permission.getPermission()); filePermission.setRoleId(permission.getRoleId()); filePermission.setInode(identifier.getInode()); perAPI.save(filePermission); } } catch (Exception ex) { Logger.debug(this, ex.toString()); } } } else { throw new IOException("You don't have access to add that folder/host"); } }
Code Sample 2:
public void execute() throws MojoExecutionException, MojoFailureException { try { this.getLog().info("copy source web.xml - " + this.getWebXml() + " to build dir (source web.xml required if mergewebxml execution is enabled)"); File destination = new File(this.getBuildDir(), "web.xml"); if (!destination.exists()) { destination.getParentFile().mkdirs(); destination.createNewFile(); } FileIOUtils.copyFile(this.getWebXml(), destination); for (int i = 0; i < this.getCompileTarget().length; i++) { File moduleFile = null; for (Iterator it = this.getProject().getCompileSourceRoots().iterator(); it.hasNext() && moduleFile == null; ) { File check = new File(it.next().toString() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } for (Iterator it = this.getProject().getResources().iterator(); it.hasNext(); ) { Resource r = (Resource) it.next(); File check = new File(r.getDirectory() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } ClassLoader loader = this.fixThreadClasspath(); if (moduleFile == null) { try { String classpath = "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"; InputStream is = loader.getResourceAsStream(classpath); System.out.println("Looking for classpath: " + classpath + "(" + (is != null) + ")"); if (is != null) { File temp = new File(this.getBuildDir(), this.getCompileTarget()[i].concat(".gwt.xml")); FileOutputStream fos = new FileOutputStream(temp); FileIOUtils.copyStream(is, fos); moduleFile = temp; } } catch (IOException e) { this.getLog().info(e); } } GwtWebInfProcessor processor = null; try { if (moduleFile != null) { getLog().info("Module file: " + moduleFile.getAbsolutePath()); processor = new GwtWebInfProcessor(this.getCompileTarget()[i], moduleFile, destination.getAbsolutePath(), destination.getAbsolutePath(), this.isWebXmlServletPathAsIs()); processor.process(); } else { throw new MojoExecutionException("module file null"); } } catch (ExitException e) { this.getLog().info(e.getMessage()); } } } catch (Exception e) { throw new MojoExecutionException("Unable to merge web.xml", e); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); }
Code Sample 2:
public void uploadFile(File inputFile, String targetFile) throws IOException { System.out.println("Uploading " + inputFile.getName() + " to " + targetFile); File outputFile = new File(targetFile); if (targetFile.endsWith("/")) { outputFile = new File(outputFile, inputFile.getName()); } else if (outputFile.getParentFile().exists() == false) { outputFile.getParentFile().mkdirs(); } if (inputFile.renameTo(outputFile) == false) { InputStream in = new FileInputStream(inputFile); OutputStream out = new FileOutputStream(outputFile); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); } }
|
00
|
Code Sample 1:
private static <T> Collection<T> loadFromServices(Class<T> interf) throws Exception { ClassLoader classLoader = DSServiceLoader.class.getClassLoader(); Enumeration<URL> e = classLoader.getResources("META-INF/services/" + interf.getName()); Collection<T> services = new ArrayList<T>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) { break; } int comment = line.indexOf('#'); if (comment >= 0) { line = line.substring(0, comment); } String name = line.trim(); if (name.length() == 0) { continue; } Class<?> clz = Class.forName(name, true, classLoader); Class<? extends T> impl = clz.asSubclass(interf); Constructor<? extends T> ctor = impl.getConstructor(); T svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; }
Code Sample 2:
protected BufferedImage handleRaremapsException() { if (params.uri.startsWith("http://www.raremaps.com/cgi-bin/gallery.pl/detail/")) try { params.uri = params.uri.replace("cgi-bin/gallery.pl/detail", "maps/medium"); URL url = new URL(params.uri); URLConnection connection = url.openConnection(); return processNewUri(connection); } catch (Exception e) { } return null; }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(final String infile, final 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)); final byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (final java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (final Exception exc) { } try { out.close(); } catch (final Exception exc) { } } return success; }
Code Sample 2:
public void invoke(InputStream is) throws AgentException { try { addHeader("Content-Type", "application/zip"); addHeader("Content-Length", String.valueOf(is.available())); connection.setDoOutput(true); connection.connect(); OutputStream os = connection.getOutputStream(); boolean success = false; try { IOUtils.copy(is, os); success = true; } finally { try { os.flush(); os.close(); } catch (IOException x) { if (success) throw x; } } connection.disconnect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AgentException("Failed to execute REST call at " + connection.getURL() + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (ConnectException e) { throw new AgentException("Failed to connect to beehive at " + connection.getURL()); } catch (IOException e) { throw new AgentException("Failed to connect to beehive", e); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { FileChannel fc = new FileOutputStream("src/com/aaron/nio/data.txt").getChannel(); fc.write(ByteBuffer.wrap("dfsdf ".getBytes())); fc.close(); fc = new RandomAccessFile("src/com/aaron/nio/data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("中文的 ".getBytes())); fc.close(); fc = new FileInputStream("src/com/aaron/nio/data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(1024); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { System.out.print(buff.getChar()); } fc.close(); }
Code Sample 2:
public static void copyFile(File oldPathFile, File newPathFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(oldPathFile)); out = new BufferedOutputStream(new FileOutputStream(newPathFile)); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (in.read(buffer) > 0) out.write(buffer); } finally { if (null != in) in.close(); if (null != out) out.close(); } }
|
11
|
Code Sample 1:
private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); }
Code Sample 2:
public void updateCoordinates(Address address) { String mapURL = "http://maps.google.com/maps/geo?output=csv"; String mapKey = "ABQIAAAAi__aT6y6l86JjbootR-p9xQd1nlEHNeAVGWQhS84yIVN5yGO2RQQPg9QLzy82PFlCzXtMNe6ofKjnA"; String location = address.getStreet() + " " + address.getZip() + " " + address.getCity(); if (logger.isDebugEnabled()) { logger.debug(location); } double[] coordinates = { 0.0, 0.0 }; String content = ""; try { location = URLEncoder.encode(location, "UTF-8"); String request = mapURL + "&q=" + location + "&key=" + mapKey; URL url = new URL(request); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } reader.close(); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error from google: " + e.getMessage()); } } if (logger.isDebugEnabled()) { logger.debug(content); } StringTokenizer tokenizer = new StringTokenizer(content, ","); int i = 0; while (tokenizer.hasMoreTokens()) { i++; String token = tokenizer.nextToken(); if (i == 3) { coordinates[0] = Double.parseDouble(token); } if (i == 4) { coordinates[1] = Double.parseDouble(token); } } if ((coordinates[0] != 0) || (coordinates[1] != 0)) { address.setLatitude(coordinates[0]); address.setLongitude(coordinates[1]); } else { if (logger.isDebugEnabled()) { logger.debug("Invalid coordinates for address " + address.getId()); } } }
|
00
|
Code Sample 1:
public Resultado procesar() { if (resultado != null) return resultado; int[] a = new int[elems.size()]; Iterator iter = elems.iterator(); int w = 0; while (iter.hasNext()) { a[w] = ((Integer) iter.next()).intValue(); w++; } int n = a.length; long startTime = System.currentTimeMillis(); int i, j, temp; for (i = 0; i < n - 1; i++) { for (j = i; j < n - 1; j++) { if (a[i] > a[j + 1]) { temp = a[i]; a[i] = a[j + 1]; a[j + 1] = temp; pasos++; } } } long endTime = System.currentTimeMillis(); resultado = new Resultado((int) (endTime - startTime), pasos, a.length); System.out.println("Resultado BB: " + resultado); return resultado; }
Code Sample 2:
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long time = System.currentTimeMillis(); String text = request.getParameter("text"); String parsedQueryString = request.getQueryString(); if (text == null) { String[] fonts = new File(ctx.getRealPath("/WEB-INF/fonts/")).list(); text = "accepted params: text,font,size,color,background,nocache,aa,break"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>"); out.println("Usage: " + request.getServletPath() + "?params[]<BR>"); out.println("Acceptable Params are: <UL>"); out.println("<LI><B>text</B><BR>"); out.println("The body of the image"); out.println("<LI><B>font</B><BR>"); out.println("Available Fonts (in folder '/WEB-INF/fonts/') <UL>"); for (int i = 0; i < fonts.length; i++) { if (!"CVS".equals(fonts[i])) { out.println("<LI>" + fonts[i]); } } out.println("</UL>"); out.println("<LI><B>size</B><BR>"); out.println("An integer, i.e. size=100"); out.println("<LI><B>color</B><BR>"); out.println("in rgb, i.e. color=255,0,0"); out.println("<LI><B>background</B><BR>"); out.println("in rgb, i.e. background=0,0,255"); out.println("transparent, i.e. background=''"); out.println("<LI><B>aa</B><BR>"); out.println("antialias (does not seem to work), aa=true"); out.println("<LI><B>nocache</B><BR>"); out.println("if nocache is set, we will write out the image file every hit. Otherwise, will write it the first time and then read the file"); out.println("<LI><B>break</B><BR>"); out.println("An integer greater than 0 (zero), i.e. break=20"); out.println("</UL>"); out.println("</UL>"); out.println("Example:<BR>"); out.println("<img border=1 src=\"" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100\"><BR>"); out.println("<img border=1 src='" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100'><BR>"); out.println("</body>"); out.println("</html>"); return; } String myFile = (request.getQueryString() == null) ? "empty" : PublicEncryptionFactory.digestString(parsedQueryString).replace('\\', '_').replace('/', '_'); myFile = Config.getStringProperty("PATH_TO_TITLE_IMAGES") + myFile + ".png"; File file = new File(ctx.getRealPath(myFile)); if (!file.exists() || (request.getParameter("nocache") != null)) { StringTokenizer st = null; Iterator i = hm.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); if (parsedQueryString.indexOf(key) > -1) { String val = (String) entry.getValue(); parsedQueryString = UtilMethods.replace(parsedQueryString, key, val); } } st = new StringTokenizer(parsedQueryString, "&"); while (st.hasMoreTokens()) { try { String x = st.nextToken(); String key = x.split("=")[0]; String val = x.split("=")[1]; if ("text".equals(key)) { text = val; } } catch (Exception e) { } } text = URLDecoder.decode(text, "UTF-8"); Logger.debug(this.getClass(), "building title image:" + file.getAbsolutePath()); file.createNewFile(); try { String font_file = "/WEB-INF/fonts/arial.ttf"; if (request.getParameter("font") != null) { font_file = "/WEB-INF/fonts/" + request.getParameter("font"); } font_file = ctx.getRealPath(font_file); float size = 20.0f; if (request.getParameter("size") != null) { size = Float.parseFloat(request.getParameter("size")); } Color background = Color.white; if (request.getParameter("background") != null) { if (request.getParameter("background").equals("transparent")) try { background = new Color(Color.TRANSLUCENT); } catch (Exception e) { } else try { st = new StringTokenizer(request.getParameter("background"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); background = new Color(x, y, z); } catch (Exception e) { } } Color color = Color.black; if (request.getParameter("color") != null) { try { st = new StringTokenizer(request.getParameter("color"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); color = new Color(x, y, z); } catch (Exception e) { Logger.info(this, e.getMessage()); } } int intBreak = 0; if (request.getParameter("break") != null) { try { intBreak = Integer.parseInt(request.getParameter("break")); } catch (Exception e) { } } java.util.ArrayList<String> lines = null; if (intBreak > 0) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); int start = 0; String line = null; int offSet; for (; ; ) { try { for (; isWhitespace(text.charAt(start)); ++start) ; if (isWhitespace(text.charAt(start + intBreak - 1))) { lines.add(text.substring(start, start + intBreak)); start += intBreak; } else { for (offSet = -1; !isWhitespace(text.charAt(start + intBreak + offSet)); ++offSet) ; lines.add(text.substring(start, start + intBreak + offSet)); start += intBreak + offSet; } } catch (Exception e) { if (text.length() > start) lines.add(leftTrim(text.substring(start))); break; } } } else { java.util.StringTokenizer tokens = new java.util.StringTokenizer(text, "|"); if (tokens.hasMoreTokens()) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); for (; tokens.hasMoreTokens(); ) lines.add(leftTrim(tokens.nextToken())); } } Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(font_file)); font = font.deriveFont(size); BufferedImage buffer = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = buffer.createGraphics(); if (request.getParameter("aa") != null) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } FontRenderContext fc = g2.getFontRenderContext(); Rectangle2D fontBounds = null; Rectangle2D textLayoutBounds = null; TextLayout tl = null; boolean useTextLayout = false; useTextLayout = Boolean.parseBoolean(request.getParameter("textLayout")); int width = 0; int height = 0; int offSet = 0; if (1 < lines.size()) { int heightMultiplier = 0; int maxWidth = 0; for (; heightMultiplier < lines.size(); ++heightMultiplier) { fontBounds = font.getStringBounds(lines.get(heightMultiplier), fc); tl = new TextLayout(lines.get(heightMultiplier), font, fc); textLayoutBounds = tl.getBounds(); if (maxWidth < Math.ceil(fontBounds.getWidth())) maxWidth = (int) Math.ceil(fontBounds.getWidth()); } width = maxWidth; int boundHeigh = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); height = boundHeigh * lines.size(); offSet = ((int) (boundHeigh * 0.2)) * (lines.size() - 1); } else { fontBounds = font.getStringBounds(text, fc); tl = new TextLayout(text, font, fc); textLayoutBounds = tl.getBounds(); width = (int) fontBounds.getWidth(); height = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); } buffer = new BufferedImage(width, height - offSet, BufferedImage.TYPE_INT_ARGB); g2 = buffer.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(font); g2.setColor(background); if (!background.equals(new Color(Color.TRANSLUCENT))) g2.fillRect(0, 0, width, height); g2.setColor(color); if (1 < lines.size()) { for (int numLine = 0; numLine < lines.size(); ++numLine) { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(lines.get(numLine), 0, -y * (numLine + 1)); } } else { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(text, 0, -y); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(buffer, "png", out); out.close(); } catch (Exception ex) { Logger.info(this, ex.toString()); } } response.setContentType("image/png"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); OutputStream os = response.getOutputStream(); byte[] buf = new byte[4096]; int i = 0; while ((i = bis.read(buf)) != -1) { os.write(buf, 0, i); } os.close(); bis.close(); Logger.debug(this.getClass(), "time to build title: " + (System.currentTimeMillis() - time) + "ms"); return; }
|
11
|
Code Sample 1:
public boolean copy(long id) { boolean bool = false; this.result = null; Connection conn = null; Object vo = null; try { PojoParser parser = PojoParser.getInstances(); conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id); String pk = parser.getPriamryKey(cls); this.getClass().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 }); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, vo); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; }
Code Sample 2:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void copy(File source, File destination) { if (!destination.exists()) { destination.mkdir(); } File files[] = source.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { copy(files[i], new File(destination, files[i].getName())); } else { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(destination, files[i].getName())).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { log.error("Could not write to " + destination.getAbsolutePath(), ioe); } } } } }
|
11
|
Code Sample 1:
private void copyFile(String sourceFilename, String destDirname) throws BuildException { log("Copying file " + sourceFilename + " to " + destDirname); File destFile = getDestFile(sourceFilename, destDirname); InputStream inStream = null; OutputStream outStream = null; try { inStream = new BufferedInputStream(new FileInputStream(sourceFilename)); outStream = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] buffer = new byte[1024]; int n = 0; while ((n = inStream.read(buffer)) != -1) outStream.write(buffer, 0, n); } catch (Exception e) { throw new BuildException("Failed to copy file \"" + sourceFilename + "\" to directory \"" + destDirname + "\""); } finally { try { if (inStream != null) inStream.close(); } catch (IOException e) { } try { if (outStream != null) outStream.close(); } catch (IOException e) { } } }
Code Sample 2:
public static boolean copyFile(File outFile, File inFile) { InputStream inStream = null; OutputStream outStream = null; try { if (outFile.createNewFile()) { inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0) outStream.write(buffer, 0, length); inStream.close(); outStream.close(); } else return false; } catch (IOException iox) { iox.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
public void xtestURL2() throws Exception { URL url = new URL(IOTest.URL); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream("C:/Temp/testURL2.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
Code Sample 2:
public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); }
|
00
|
Code Sample 1:
public String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
|
11
|
Code Sample 1:
public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } }
Code Sample 2:
public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
|
11
|
Code Sample 1:
public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); }
Code Sample 2:
@Override protected svm_model loadModel(InputStream inputStream) throws IOException { File tmpFile = File.createTempFile("tmp", ".mdl"); FileOutputStream output = new FileOutputStream(tmpFile); try { IOUtils.copy(inputStream, output); return libsvm.svm.svm_load_model(tmpFile.getPath()); } finally { output.close(); tmpFile.delete(); } }
|
00
|
Code Sample 1:
@Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
Code Sample 2:
private Drawable fetchImage(String iconUrl, Context ctx) { URL url; HttpClient httpClient = new DefaultHttpClient(); try { if (PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean("use.urlimg.com", true)) { iconUrl = iconUrl.substring(iconUrl.indexOf("//") + 2); iconUrl = "http://urlimg.com/width/100/" + iconUrl; } Log.d(ImageCache.class.getName(), "Loading image from: " + iconUrl); HttpGet httpGet = new HttpGet(iconUrl); HttpResponse response = httpClient.execute(httpGet); InputStream content = response.getEntity().getContent(); Drawable d = Drawable.createFromStream(content, "src"); content.close(); httpGet.abort(); return d; } catch (IOException e) { Log.e(ImageCache.class.getName(), "IOException while fetching: " + iconUrl); return TELKA; } finally { } }
|
00
|
Code Sample 1:
protected Set<String> moduleNamesFromReader(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); Set<String> names = new HashSet<String>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); Matcher m = nonCommentPattern.matcher(line); if (m.find()) { names.add(m.group().trim()); } } return names; }
Code Sample 2:
public static void find(String pckgname, Class<?> tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = tosubclass.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } }
|
00
|
Code Sample 1:
public static Bitmap loadBitmap(String token, String id, final String type) { String imageUrl = XMLfunctions.URL; imageUrl = imageUrl.replace("{0}", token); imageUrl = imageUrl.replace("{1}", id); InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; }
Code Sample 2:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }
|
11
|
Code Sample 1:
public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } File directory = new File("lib/"); File dest = new File(directory, file.getName()); File parent = dest.getParentFile(); while (parent != null && !parent.equals(directory)) { parent = parent.getParentFile(); } if (parent.equals(directory)) { return file; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return dest; }
Code Sample 2:
private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
|
11
|
Code Sample 1:
public void uploadFile(ActionEvent event) throws IOException { InputFile inputFile = (InputFile) event.getSource(); synchronized (inputFile) { ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); String fileNewPath = arrangeUplodedFilePath(context.getRealPath(""), inputFile.getFile().getName()); File file = new File(fileNewPath); System.out.println(fileNewPath); DataInputStream inStream = new DataInputStream(new FileInputStream(inputFile.getFile())); DataOutputStream outStream = new DataOutputStream(new FileOutputStream(file)); int i = 0; byte[] buffer = new byte[512]; while ((i = inStream.read(buffer, 0, 512)) != -1) outStream.write(buffer, 0, i); } }
Code Sample 2:
public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; }
|
11
|
Code Sample 1:
private boolean writeResource(PluginProxy eclipseInstallPlugin, ResourceProxy translation, LocaleProxy locale) throws Exception { String translationResourceName = determineTranslatedResourceName(translation, locale); String pluginNameInDirFormat = eclipseInstallPlugin.getName().replace(Messages.getString("Characters_period"), File.separator); if (translation.getRelativePath().contains(pluginNameInDirFormat)) { return writeResourceToBundleClasspath(translation, locale); } else if (translationResourceName.contains(File.separator)) { String resourcePath = translationResourceName.substring(0, translationResourceName.lastIndexOf(File.separatorChar)); File resourcePathDirectory = new File(directory.getPath() + File.separatorChar + resourcePath); resourcePathDirectory.mkdirs(); } File fragmentResource = new File(directory.getPath() + File.separatorChar + translationResourceName); File translatedResource = new File(translation.getFileResource().getAbsolutePath()); FileChannel inputChannel = new FileInputStream(translatedResource).getChannel(); FileChannel outputChannel = new FileOutputStream(fragmentResource).getChannel(); inputChannel.transferTo(0, inputChannel.size(), outputChannel); inputChannel.close(); outputChannel.close(); return true; }
Code Sample 2:
public boolean chequearMarca(int a, int m, int d) { boolean existe = false; try { cantidadArchivos = obtenerCantidad() + 1; String filenametxt = ""; String filenamezip = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (ano == a && mes == m && dia == d) existe = true; input.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } return (existe); }
|
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 { int maxCount = 67076096; long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
static final void saveStatus(JWAIMStatus status, DBConnector connector) throws IOException { Connection con = null; PreparedStatement ps = null; Statement st = null; try { con = connector.getDB(); con.setAutoCommit(false); st = con.createStatement(); st.executeUpdate("DELETE FROM status"); ps = con.prepareStatement("INSERT INTO status VALUES (?, ?)"); ps.setString(1, "jwaim.status"); ps.setBoolean(2, status.getJWAIMStatus()); ps.addBatch(); ps.setString(1, "logging.status"); ps.setBoolean(2, status.getLoggingStatus()); ps.addBatch(); ps.setString(1, "stats.status"); ps.setBoolean(2, status.getStatsStatus()); ps.addBatch(); ps.executeBatch(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new IOException(e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } if (ps != null) { try { ps.close(); } catch (SQLException ignore) { } } if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } }
|
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 final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
public String translate(String before, int translateType) throws CoreException { if (before == null) throw new IllegalArgumentException("before is null."); if ((translateType != ENGLISH_TO_JAPANESE) && (translateType != JAPANESE_TO_ENGLISH)) { throw new IllegalArgumentException("Invalid translateType. value=" + translateType); } try { URL url = new URL(config.getTranslatorSiteUrl()); URLConnection connection = url.openConnection(); sendTranslateRequest(before, translateType, connection); String afterContents = receiveTranslatedResponse(connection); String afterStartKey = config.getTranslationResultStart(); String afterEndKey = config.getTranslationResultEnd(); int startLength = afterStartKey.length(); int startPos = afterContents.indexOf(afterStartKey); if (startPos != -1) { int endPos = afterContents.indexOf(afterEndKey, startPos); if (endPos != -1) { String after = afterContents.substring(startPos + startLength, endPos); after = replaceEntities(after); return after; } else { throwCoreException(ERROR_END_KEYWORD_NOT_FOUND, "End keyword not found.", null); } } else { throwCoreException(ERROR_START_KEYWORD_NOT_FOUND, "Start keyword not found.", null); } } catch (IOException e) { throwCoreException(ERROR_IO, e.getMessage(), e); } throw new IllegalStateException("CoreException not occurd."); }
Code Sample 2:
public static byte[] sendParamPost(String urlString, String param) { try { URL url = new URL(urlString + "?" + param); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setDefaultUseCaches(false); urlConn.setDoInput(true); urlConn.setRequestMethod("POST"); urlConn.connect(); OutputStream ops = urlConn.getOutputStream(); ops.close(); InputStream is = urlConn.getInputStream(); byte[] resultBytes = new byte[urlConn.getContentLength()]; byte[] tempByte = new byte[1024]; int length = 0; int index = 0; while ((length = is.read(tempByte)) != -1) { System.arraycopy(tempByte, 0, resultBytes, index, length); index += length; } is.close(); return resultBytes; } catch (Exception e) { e.printStackTrace(); return null; } }
|
11
|
Code Sample 1:
public static byte[] encrypt(String passphrase, byte[] data) throws Exception { byte[] dataTemp; try { Security.addProvider(new com.sun.crypto.provider.SunJCE()); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes()); DESKeySpec key = new DESKeySpec(md.digest()); SecretKeySpec DESKey = new SecretKeySpec(key.getKey(), "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, DESKey); dataTemp = cipher.doFinal(data); } catch (Exception e) { throw e; } return dataTemp; }
Code Sample 2:
Object onSuccess() { this.mErrorExist = true; this.mErrorMdp = true; if (!mClientManager.exists(this.mNewMail)) { this.mErrorExist = false; if (mNewMdp.equals(mNewMdpConfirm)) { this.mErrorMdp = false; MessageDigest sha1Instance; try { sha1Instance = MessageDigest.getInstance("SHA1"); sha1Instance.reset(); sha1Instance.update(this.mNewMdp.getBytes()); byte[] digest = sha1Instance.digest(); BigInteger bigInt = new BigInteger(1, digest); String vHashPassword = bigInt.toString(16); Client vClient = new Client(this.mNewNom, (this.mNewPrenom != null ? this.mNewPrenom : ""), this.mNewMail, vHashPassword, this.mNewAdresse, 1); mClientManager.save(vClient); mComponentResources.discardPersistentFieldChanges(); return "Client/List"; } catch (NoSuchAlgorithmException e) { mLogger.error(e.getMessage(), e); } } } return errorZone.getBody(); }
|
00
|
Code Sample 1:
public static String recoverPassword(String token) { try { token = encryptGeneral1(token); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(token, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recover_password"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String password = root.getTextContent(); password = decryptGeneral1(password); return password; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
Code Sample 2:
void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } }
|
00
|
Code Sample 1:
protected void configure() { Enumeration<URL> resources = null; try { resources = classLoader.getResources(resourceName); } catch (IOException e) { binder().addError(e.getMessage(), e); return; } int resourceCount = 0; while (resources.hasMoreElements()) { URL url = resources.nextElement(); log.debug(url + " ..."); try { InputStream stream = url.openStream(); Properties props = new Properties(); props.load(stream); resourceCount++; addComponentsFromProperties(props, classLoader); } catch (IOException e) { binder().addError(e.getMessage(), e); } } log.info("Added components from " + resourceCount + " resources."); }
Code Sample 2:
private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
|
00
|
Code Sample 1:
private ProgramYek getYek(String keyFilename) { File f = new File(keyFilename); InputStream is = null; try { is = new FileInputStream(f); } catch (java.io.FileNotFoundException ee) { } catch (Exception e) { System.out.println("** Exception reading key: " + e); } if (is == null) { try { URL url = ChiselResources.getResourceByName(ProgramYek.getVidSys(), ChiselResources.LOADFROMCLASSPATH); if (url == null) { } else { is = url.openStream(); } } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } ProgramYek y = null; if (is != null) { try { y = ProgramYek.read(is); } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } else { File chk = new File(checkFilename); if (chk.exists()) { System.out.println("This is the evaluation version of " + appname); y = new ProgramYek(appname, "Evaluation", "", 15); ProgramYek.serialize(y, keyFilename); } } return y; }
Code Sample 2:
private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
protected void doRequest(HttpServletRequest request, HttpServletResponse response, boolean inGet) throws ServletException, IOException { response.setHeader("Server", WebConsoleServlet.SERVER_STRING); try { String requestedFilename = request.getRequestURI().substring(1); URL url = new URL(getJarFileName() + "/"); JarURLConnection jarConnection = (JarURLConnection) (url.openConnection()); JarFile jarFile = jarConnection.getJarFile(); String negotiatedFilename = null; ZipEntry zipEntry = null; zipEntry = negotiateImageFile(jarFile, requestedFilename, isIE6OrEarlier(request.getHeader("User-Agent"))); if (zipEntry == null) { zipEntry = jarFile.getEntry(requestedFilename); } else { negotiatedFilename = zipEntry.getName(); } if (zipEntry == null || zipEntry.isDirectory()) { handleFileNotFound(inGet, request, response); return; } int fileSize = (int) zipEntry.getSize(); response.setContentLength(fileSize); if (negotiatedFilename != null) { response.setContentType(getContentType(negotiatedFilename)); } else { response.setContentType(getContentType(request.getRequestURI())); } InputStream in = jarFile.getInputStream(zipEntry); BufferedInputStream bufferedInputStream = new BufferedInputStream(in); byte[] file = new byte[fileSize]; int bytesRead = bufferedInputStream.read(file); bufferedInputStream.close(); if (bytesRead == fileSize && cachingEnabled) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); java.util.Date today = new java.util.Date(); String date = formatter.format(GenericUtils.addOrSubstractDaysFromDate(today, 365)); response.setHeader("Expires", date); } OutputStream outputStream = response.getOutputStream(); outputStream.write(file); } catch (FileNotFoundException e) { handleFileNotFound(inGet, request, response); } catch (IOException e) { } catch (Throwable t) { Application.getApplication().logExceptionEvent(EventLogMessage.EventType.WEB_ERROR, t); } }
Code Sample 2:
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); 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; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); }
|
11
|
Code Sample 1:
public void convert(CSVReader reader, Writer writer, int nbTotalRows) throws IOException, InterruptedException { Validate.notNull(reader, "CSVReader"); Validate.notNull(writer, "Writer"); Writer bufferedWriter = new BufferedWriter(writer); File fileForColsDef = createTempFileForCss(); BufferedWriter colsDefWriter = new BufferedWriter(new FileWriter(fileForColsDef)); File fileForTable = createTempFileForTable(); BufferedWriter tableWriter = new BufferedWriter(new FileWriter(fileForTable)); try { int currentRow = 0; String[] nextLine = reader.readNext(); if (nextLine != null) { int[] colsCharCount = new int[nextLine.length]; writeTableRowHeader(tableWriter, nextLine); while ((nextLine = reader.readNext()) != null) { currentRow++; if (progress != null) { float percent = ((float) currentRow / (float) nbTotalRows) * 100f; progress.updateProgress(ConvertionStepEnum.PROCESSING_ROWS, percent); } writeTableRow(tableWriter, nextLine, colsCharCount); } writeTableStart(colsDefWriter, colsCharCount); writeColsDefinitions(colsDefWriter, colsCharCount); } writeConverterInfos(bufferedWriter); writeTableEnd(tableWriter); flushAndClose(tableWriter); flushAndClose(colsDefWriter); BufferedReader colsDefReader = new BufferedReader(new FileReader(fileForColsDef)); BufferedReader tableReader = new BufferedReader(new FileReader(fileForTable)); mergeFiles(bufferedWriter, colsDefReader, tableReader); } finally { closeQuietly(tableWriter); closeQuietly(colsDefWriter); fileForTable.delete(); fileForColsDef.delete(); } }
Code Sample 2:
public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } }
|
11
|
Code Sample 1:
public static void copy(File source, File target) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER); while (in.read(buffer) != -1) { buffer.flip(); while (buffer.hasRemaining()) { out.write(buffer); } buffer.clear(); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { close(in); close(out); } }
Code Sample 2:
public static void translateTableAttributes(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table_att", nsDefinition); String filename = baseDir + "table_att.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + "_att.xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + "_att.json", baseDir + tableName + "_att.xsl"); }
|
00
|
Code Sample 1:
int[] slowSort() { int[] values = getValues(); int n = values.length; for (int pass = 1; pass < n; pass++) { for (int i = 0; i < n - pass; i++) { if (values[i] > values[i + 1]) { int temp = values[i]; values[i] = values[i + 1]; values[i + 1] = temp; } } } return values; }
Code Sample 2:
public static int save(File inputFile, File outputFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFile); outputFile.getParentFile().mkdirs(); out = new FileOutputStream(outputFile); } catch (Exception e) { e.getMessage(); } try { return IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { if (out != null) { out.close(); } } catch (IOException ioe) { ioe.getMessage(); } try { if (in != null) { in.close(); } } catch (IOException ioe) { ioe.getMessage(); } } }
|
11
|
Code Sample 1:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final 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:
String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
|
11
|
Code Sample 1:
private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } to = null; from = null; }
Code Sample 2:
public static void main(String[] a) throws Exception { HashMap<String, Integer> numberOfOccurencesOfThisComboe = new HashMap<String, Integer>(); HashMap<String, String> fileToCATHMapping = new HashMap<String, String>(); ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; String reducedComboForFilteringOut = allEntries[1] + allEntries[2] + allEntries[3]; fileToCATHMapping.put(fileName, reducedComboForFilteringOut); if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } for (String fileName : allFilesToBeCopied) { String reducedComboForFilteringOut = fileToCATHMapping.get(fileName); if (!numberOfOccurencesOfThisComboe.containsKey(reducedComboForFilteringOut)) { numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, 1); } else { Integer thisCounter = numberOfOccurencesOfThisComboe.get(reducedComboForFilteringOut); thisCounter = thisCounter + 1; numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, thisCounter); } } HashSet<String> isSingleElement = new HashSet<String>(); for (Entry<String, Integer> thisEntry : numberOfOccurencesOfThisComboe.entrySet()) { if (thisEntry.getValue() == 1) { System.out.println("single: " + thisEntry.getKey()); isSingleElement.add(thisEntry.getKey()); } else { System.out.println("not single: " + thisEntry.getKey()); } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { if (!isSingleElement.contains(fileToCATHMapping.get(file))) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|
00
|
Code Sample 1:
public static String encrypt(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(password.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return password; } }
Code Sample 2:
public static void main(String args[]) { org.apache.xml.security.Init.init(); String signatureFileName = args[0]; javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); try { long start = System.currentTimeMillis(); org.apache.xml.security.Init.init(); File f = new File(signatureFileName); System.out.println("Verifying " + signatureFileName); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(new java.io.FileInputStream(f)); VerifyExampleTest vf = new VerifyExampleTest(); vf.verify(doc); Constants.setSignatureSpecNSprefix("dsig"); Element sigElement = null; NodeList nodes = doc.getElementsByTagNameNS(org.apache.xml.security.utils.Constants.SignatureSpecNS, "Signature"); if (nodes.getLength() != 0) { System.out.println("Found " + nodes.getLength() + " Signature elements."); for (int i = 0; i < nodes.getLength(); i++) { sigElement = (Element) nodes.item(i); XMLSignature signature = new XMLSignature(sigElement, ""); KeyInfo ki = signature.getKeyInfo(); signature.addResourceResolver(new OfflineResolver()); if (ki != null) { if (ki.containsX509Data()) { System.out.println("Could find a X509Data element in the KeyInfo"); } KeyInfo kinfo = signature.getKeyInfo(); X509Certificate cert = null; if (kinfo.containsRetrievalMethod()) { RetrievalMethod m = kinfo.itemRetrievalMethod(0); URL url = new URL(m.getURI()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(url.openStream()); } else { cert = signature.getKeyInfo().getX509Certificate(); } if (cert != null) { System.out.println("The XML signature is " + (signature.checkSignatureValue(cert) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a Certificate"); PublicKey pk = signature.getKeyInfo().getPublicKey(); if (pk != null) { System.out.println("The XML signatur is " + (signature.checkSignatureValue(pk) ? "valid (good)" : "invalid !!!!! (bad)")); } else { System.out.println("Did not find a public key, so I can't check the signature"); } } } else { System.out.println("Did not find a KeyInfo"); } } } long end = System.currentTimeMillis(); double elapsed = end - start; System.out.println("verified:" + elapsed); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static IProject createSimplemodelEnabledJavaProject() throws CoreException { IWorkspaceDescription desc = ResourcesPlugin.getWorkspace().getDescription(); desc.setAutoBuilding(false); ResourcesPlugin.getWorkspace().setDescription(desc); String name = "TestProject"; for (int i = 0; i < 1000; i++) { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(name + i); if (project.exists()) continue; project.create(null); project.open(null); IProjectDescription description = project.getDescription(); String[] natures = description.getNatureIds(); String[] newNatures = new String[natures.length + 2]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = JavaCore.NATURE_ID; newNatures[natures.length + 1] = SimplemodelNature.NATURE_ID; description.setNatureIds(newNatures); project.setDescription(description, null); IJavaProject javaProject = JavaCore.create(project); Set<IClasspathEntry> entries = new HashSet<IClasspathEntry>(); IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall(); Path containerPath = new Path(JavaRuntime.JRE_CONTAINER); IPath vmPath = containerPath.append(vmInstall.getVMInstallType().getId()).append(vmInstall.getName()); entries.add(JavaCore.newContainerEntry(vmPath)); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall); for (LibraryLocation element : locations) { entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null)); } final Path srcPath = new Path("src"); final IFolder src = project.getFolder(srcPath); final Path binPath = new Path("bin"); final IFolder bin = project.getFolder(binPath); src.create(true, true, null); bin.create(true, true, null); entries.add(JavaCore.newSourceEntry(project.getFullPath().append(srcPath))); javaProject.setOutputLocation(project.getFullPath().append(binPath), null); javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null); return project; } throw new RuntimeException("Failed"); }
Code Sample 2:
private void gravaOp(Vector<?> op) { PreparedStatement ps = null; String sql = null; ResultSet rs = null; int seqop = 0; Date dtFabrOP = null; try { sql = "SELECT MAX(SEQOP) FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { seqop = rs.getInt(1) + 1; } rs.close(); ps.close(); con.commit(); sql = "SELECT DTFABROP FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, txtSeqOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { dtFabrOP = rs.getDate(1); } rs.close(); ps.close(); con.commit(); sql = "INSERT INTO PPOP (CODEMP,CODFILIAL,CODOP,SEQOP,CODEMPPD,CODFILIALPD,CODPROD,SEQEST,DTFABROP," + "QTDPREVPRODOP,QTDFINALPRODOP,DTVALIDPDOP,CODEMPLE,CODFILIALLE,CODLOTE,CODEMPTM,CODFILIALTM,CODTIPOMOV," + "CODEMPAX,CODFILIALAX,CODALMOX,CODEMPOPM,CODFILIALOPM,CODOPM,SEQOPM,QTDDISTIOP,QTDSUGPRODOP)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, seqop); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPESTRUTURA")); ps.setInt(7, ((Integer) op.elementAt(4)).intValue()); ps.setInt(8, ((Integer) op.elementAt(6)).intValue()); ps.setDate(9, dtFabrOP); ps.setFloat(10, ((BigDecimal) op.elementAt(7)).floatValue()); ps.setFloat(11, 0); ps.setDate(12, (Funcoes.strDateToSqlDate((String) op.elementAt(11)))); ps.setInt(13, Aplicativo.iCodEmp); ps.setInt(14, ListaCampos.getMasterFilial("EQLOTE")); ps.setString(15, ((String) op.elementAt(10))); ps.setInt(16, Aplicativo.iCodEmp); ps.setInt(17, ListaCampos.getMasterFilial("EQTIPOMOV")); ps.setInt(18, buscaTipoMov()); ps.setInt(19, ((Integer) op.elementAt(13)).intValue()); ps.setInt(20, ((Integer) op.elementAt(14)).intValue()); ps.setInt(21, ((Integer) op.elementAt(12)).intValue()); ps.setInt(22, Aplicativo.iCodEmp); ps.setInt(23, ListaCampos.getMasterFilial("PPOP")); ps.setInt(24, txtCodOP.getVlrInteger().intValue()); ps.setInt(25, txtSeqOP.getVlrInteger().intValue()); ps.setFloat(26, ((BigDecimal) op.elementAt(9)).floatValue()); ps.setFloat(27, ((BigDecimal) op.elementAt(7)).floatValue()); ps.executeUpdate(); ps.close(); con.commit(); geraRMA(seqop); } catch (SQLException e) { Funcoes.mensagemErro(null, "Erro ao gerar OP's de distribui��o!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException eb) { } } }
|
11
|
Code Sample 1:
protected void checkWeavingJar() throws IOException { OutputStream out = null; try { final File weaving = new File(getWeavingPath()); if (!weaving.exists()) { new File(getWeavingFolder()).mkdir(); weaving.createNewFile(); final Path src = new Path("weaving/openfrwk-weaving.jar"); final InputStream in = FileLocator.openStream(getBundle(), src, false); out = new FileOutputStream(getWeavingPath(), true); IOUtils.copy(in, out); Logger.log(Logger.INFO, "Put weaving jar at location " + weaving); } else { Logger.getLog().info("File openfrwk-weaving.jar already exists at " + weaving); } } catch (final SecurityException e) { Logger.log(Logger.ERROR, "[SECURITY EXCEPTION] Not enough privilegies to create " + "folder and copy NexOpen weaving jar at location " + getWeavingFolder()); Logger.logException(e); } finally { if (out != null) { out.flush(); out.close(); } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
protected static String getInitialUUID() { if (myRand == null) { myRand = new Random(); } long rand = myRand.nextLong(); String sid; try { sid = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { sid = Thread.currentThread().getName(); } StringBuffer sb = new StringBuffer(); sb.append(sid); sb.append(":"); sb.append(Long.toString(rand)); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); StringBuffer sb2 = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; sb2.append(Integer.toHexString(b)); } int begin = myRand.nextInt(); if (begin < 0) begin = begin * -1; begin = begin % 8; return sb2.toString().substring(begin, begin + 18).toUpperCase(); }
Code Sample 2:
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; }
|
11
|
Code Sample 1:
protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
Code Sample 2:
public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
|
00
|
Code Sample 1:
public static String getWhatsNew(String ver) { URL url = null; try { url = new URL("http://googlemeupdate.bravehost.com/History.htm"); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream html = null; try { html = url.openStream(); int c = 0; String Buffer = ""; String Code = ""; while (c != -1) { try { c = html.read(); } catch (IOException ex) { } Buffer = Buffer + (char) c; } Buffer = Buffer.substring(Buffer.lastIndexOf(ver) + ver.length() + 2, Buffer.indexOf("end::")).replaceAll("||", ""); return "<html>" + Buffer.substring(Buffer.indexOf("Google.mE Version: ")); } catch (IOException ex) { ex.printStackTrace(); return ""; } }
Code Sample 2:
HttpURLConnection getHttpURLConnection(String bizDocToExecute, boolean doom, boolean cmt) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); if (doom) { servletURL.append("&_DOOM=TRUE"); } if (cmt) { servletURL.append("&_CMT=TRUE"); } Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; }
|
00
|
Code Sample 1:
public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/item/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Item Deleted!"); } else { response.setDone(false); response.setMessage("Delete Item Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
Code Sample 2:
@Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } }
|
11
|
Code Sample 1:
private void anneal(final float maxGamma, final float gammaAccel, final float objectiveTolerance, final float objectiveAccel, final float scoreTolerance, final float paramTolerance, final float distanceLimit, final float randomLimit, final long randomSeed, final BufferedDocuments<Phrase> references, final int n, final int maxNbest, File stateFile, boolean keepState) { float gamma = 0; boolean annealObjective = true; double[] convergedScores = new double[n]; double[] totalLogScores = new double[n]; boolean[] isConverged = new boolean[n]; GradientPoint[] initPoints = new GradientPoint[n]; GradientPoint[] prevInitPoints = new GradientPoint[n]; GradientPoint[] bestInitPoints = new GradientPoint[n]; GradientPoint[] prevMinPoints = new GradientPoint[n]; Random rand = new Random(randomSeed); Time time = new Time(); if (stateFile != null && stateFile.length() > 0) { time.reset(); try { ObjectInputStream stream = new ObjectInputStream(new FileInputStream(stateFile)); gamma = stream.readFloat(); annealObjective = stream.readBoolean(); convergedScores = (double[]) stream.readObject(); totalLogScores = (double[]) stream.readObject(); isConverged = (boolean[]) stream.readObject(); initPoints = (GradientPoint[]) stream.readObject(); prevInitPoints = (GradientPoint[]) stream.readObject(); bestInitPoints = (GradientPoint[]) stream.readObject(); prevMinPoints = (GradientPoint[]) stream.readObject(); rand = (Random) stream.readObject(); int size = stream.readInt(); for (int id = 0; id < size; id++) { Feature feature = FEATURES.getRaw(CONFIG, stream.readUTF(), 0f); if (feature.getId() != id) throw new Exception("Features have changed"); } evaluation.read(stream); stream.close(); output.println("# Resuming from previous optimization state (" + time + ")"); output.println(); } catch (Exception e) { e.printStackTrace(); Log.getInstance().severe("Failed loading optimization state (" + stateFile + "): " + e.getMessage()); } } else { final int evaluations = ProjectedEvaluation.CFG_OPT_HISTORY_SIZE.getValue(); final GradientPoint[] randPoints = new GradientPoint[n * evaluations]; for (int i = 0; i < n; i++) { evaluation.setParallelId(i); for (int j = 0; j < evaluations; j++) { if (i != 0) randPoints[i * n + j] = getRandomPoint(rand, randPoints[0], distanceLimit, null); evaluate(references, i + ":" + j); if (i == 0) { randPoints[0] = new GradientPoint(evaluation, null); gamma = LogFeatureModel.FEAT_MODEL_GAMMA.getValue(); break; } } } for (int i = 0; i < randPoints.length; i++) if (randPoints[i] != null) randPoints[i] = new GradientPoint(evaluation, randPoints[i], output); for (int i = 0; i < n; i++) { prevInitPoints[i] = null; initPoints[i] = randPoints[i * n]; if (i != 0) for (int j = 1; j < evaluations; j++) if (randPoints[i * n + j].getScore() < initPoints[i].getScore()) initPoints[i] = randPoints[i * n + j]; bestInitPoints[i] = initPoints[i]; convergedScores[i] = Float.MAX_VALUE; } } for (int searchCount = 1; ; searchCount++) { boolean isFinished = true; for (int i = 0; i < n; i++) isFinished = isFinished && isConverged[i]; if (isFinished) { output.println("*** N-best list converged. Modifying annealing schedule. ***"); output.println(); if (annealObjective) { boolean objectiveConverged = true; for (int i = 0; objectiveConverged && i < n; i++) objectiveConverged = isConverged(bestInitPoints[i].getScore(), convergedScores[i], objectiveTolerance, SCORE_EPSILON); annealObjective = false; for (Metric<ProjectedSentenceEvaluation> metric : AbstractEvaluation.CFG_EVAL_METRICS.getValue()) if (metric.doAnnealing()) { float weight = metric.getWeight(); if (weight != 0) if (objectiveConverged) metric.setWeight(0); else { annealObjective = true; metric.setWeight(weight / objectiveAccel); } } } if (!annealObjective) { if (Math.abs(gamma) >= maxGamma) { GradientPoint bestPoint = bestInitPoints[0]; for (int i = 1; i < n; i++) if (bestInitPoints[i].getScore() < bestPoint.getScore()) bestPoint = bestInitPoints[i]; output.format("Best Score: %+.7g%n", bestPoint.getScore()); output.println(); bestPoint = new GradientPoint(evaluation, bestPoint, output); break; } gamma *= gammaAccel; if (Math.abs(gamma) + GAMMA_EPSILON >= maxGamma) gamma = gamma >= 0 ? maxGamma : -maxGamma; } for (int i = 0; i < n; i++) { convergedScores[i] = bestInitPoints[i].getScore(); initPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], gamma, output); bestInitPoints[i] = initPoints[i]; prevInitPoints[i] = null; prevMinPoints[i] = null; isConverged[i] = false; } searchCount = 0; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; if (n > 1) output.println("Minimizing point " + i); Gradient gradient = initPoints[i].getGradient(); for (int id = 0; id < FEATURES.size(); id++) output.format("GRAD %-65s %-+13.7g%n", FEATURES.getName(id), gradient.get(id)); output.println(); time.reset(); GradientPoint minPoint = minimize(initPoints[i], prevInitPoints[i], bestInitPoints[i], scoreTolerance, paramTolerance, distanceLimit, randomLimit, rand); final float[] weights = minPoint.getWeights(); for (int j = 0; j < weights.length; j++) output.format("PARM %-65s %-+13.7g%n", FEATURES.getName(j), weights[j]); output.println(); output.format("Minimum Score: %+.7g (average distance of %.2f)%n", minPoint.getScore(), minPoint.getAverageDistance()); output.println(); output.println("# Minimized gradient (" + time + ")"); output.println(); output.flush(); isConverged[i] = weights == initPoints[i].getWeights(); prevInitPoints[i] = initPoints[i]; prevMinPoints[i] = minPoint; initPoints[i] = minPoint; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; isConverged[i] = isConvergedScore("minimum", prevMinPoints[i], prevInitPoints[i], scoreTolerance) && isConvergedWeights(prevMinPoints[i], prevInitPoints[i], paramTolerance); prevMinPoints[i].setWeightsAndRescore(evaluation); evaluation.setParallelId(i); evaluate(references, Integer.toString(i)); } Set<Point> prunePoints = new HashSet<Point>(); prunePoints.addAll(Arrays.asList(bestInitPoints)); prunePoints.addAll(Arrays.asList(prevInitPoints)); prunePoints.addAll(Arrays.asList(initPoints)); evaluation.prune(prunePoints, maxNbest, output); for (int i = 0; i < n; i++) { final boolean bestIsPrev = bestInitPoints[i] == prevInitPoints[i]; final boolean bestIsInit = bestInitPoints[i] == initPoints[i]; bestInitPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], bestIsInit ? output : null); if (bestIsPrev) prevInitPoints[i] = bestInitPoints[i]; if (bestIsInit) initPoints[i] = bestInitPoints[i]; if (!bestIsPrev && prevInitPoints[i] != null) { prevInitPoints[i] = new GradientPoint(evaluation, prevInitPoints[i], null); if (prevInitPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = prevInitPoints[i]; } if (!bestIsInit) { initPoints[i] = new GradientPoint(evaluation, initPoints[i], output); if (initPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = initPoints[i]; } } for (int i = 0; i < n; i++) if (isConverged[i]) if (prevMinPoints[i] == null) { output.println("# Convergence failed: no previous minimum is defined"); output.println(); isConverged[i] = false; } else { isConverged[i] = isConvergedScore("best known", bestInitPoints[i], initPoints[i], scoreTolerance) && isConvergedScore("previous minimum", prevMinPoints[i], initPoints[i], scoreTolerance); } if (stateFile != null) { time.reset(); try { File dir = stateFile.getCanonicalFile().getParentFile(); File temp = File.createTempFile("cunei-opt-", ".tmp", dir); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(temp)); stream.writeFloat(gamma); stream.writeBoolean(annealObjective); stream.writeObject(convergedScores); stream.writeObject(totalLogScores); stream.writeObject(isConverged); stream.writeObject(initPoints); stream.writeObject(prevInitPoints); stream.writeObject(bestInitPoints); stream.writeObject(prevMinPoints); stream.writeObject(rand); stream.writeInt(FEATURES.size()); for (int id = 0; id < FEATURES.size(); id++) stream.writeUTF(FEATURES.getName(id)); evaluation.write(stream); stream.close(); if (!temp.renameTo(stateFile)) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(temp).getChannel(); out = new FileOutputStream(stateFile).getChannel(); in.transferTo(0, in.size(), out); temp.delete(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } output.println("# Saved optimization state (" + time + ")"); output.println(); } catch (IOException e) { Log.getInstance().severe("Failed writing optimization state: " + e.getMessage()); } } } if (stateFile != null && !keepState) stateFile.delete(); }
Code Sample 2:
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(); }
|
11
|
Code Sample 1:
@Test public void test() throws JDOMException, IOException { InputStream is = this.getClass().getResourceAsStream("putRegularVehicle.xml"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(is, byteArrayOutputStream); TrafficModelDefinition def = MDFReader.read(byteArrayOutputStream.toByteArray()); TrafficSimulationEngine se = new TrafficSimulationEngine(); se.init(def); int linkId = 2; int segmentId = 3; Map<Integer, Set<Integer>> linkSegments = new HashMap<Integer, Set<Integer>>(); Set<Integer> segments = new HashSet<Integer>(); segments.add(segmentId); linkSegments.put(linkId, segments); FrameProperties frameProperties = new FrameProperties(linkSegments, new HashSet<Integer>()); se.setFrameProperties(frameProperties); for (float time = 0; time < 60; time += 0.1f) { se.step(0.1f); System.out.println("*** Time: " + time); for (RoadObject roadObject : se.getDynamicObjects()) { Vehicle vehicle = (Vehicle) roadObject; System.out.println(vehicle.getVehicleId() + ":\tX=" + vehicle.getPosition() + "\tV=" + vehicle.getSpeed()); } } }
Code Sample 2:
private void copyFile(File s, File d) throws IOException { d.getParentFile().mkdirs(); FileChannel inChannel = new FileInputStream(s).getChannel(); FileChannel outChannel = new FileOutputStream(d).getChannel(); int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } inChannel.close(); outChannel.close(); d.setLastModified(s.lastModified()); }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
Code Sample 2:
public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } }
|
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:
@Override public boolean saveCart(Carrito cart, boolean completado, String date, String formPago) { Connection conexion = null; PreparedStatement insertHistorial = null; PreparedStatement insertCarrito = null; boolean exito = false; try { conexion = pool.getConnection(); conexion.setAutoCommit(false); insertHistorial = conexion.prepareStatement("INSERT INTO " + nameBD + ".HistorialCarritos VALUES (?,?,?,?,?,?)"); insertHistorial.setString(1, cart.getUser()); insertHistorial.setString(2, cart.getCodigo()); insertHistorial.setString(3, date); insertHistorial.setDouble(4, cart.getPrecio()); insertHistorial.setString(5, formPago); insertHistorial.setBoolean(6, completado); int filasAfectadas = insertHistorial.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); } else { insertCarrito = conexion.prepareStatement("INSERT INTO " + nameBD + ".Carritos VALUES (?,?,?,?,?)"); Iterator<String> iteradorProductos = cart.getArticulos().keySet().iterator(); while (iteradorProductos.hasNext()) { String key = iteradorProductos.next(); Producto prod = getProduct(key); int cantidad = cart.getArticulos().get(key); insertCarrito.setString(1, cart.getCodigo()); insertCarrito.setString(2, prod.getCodigo()); insertCarrito.setString(3, prod.getNombre()); insertCarrito.setDouble(4, prod.getPrecio()); insertCarrito.setInt(5, cantidad); filasAfectadas = insertCarrito.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); break; } insertCarrito.clearParameters(); } conexion.commit(); exito = true; } } catch (SQLException ex) { logger.log(Level.SEVERE, "Error añadiendo carrito al registro", ex); try { conexion.rollback(); } catch (SQLException ex1) { logger.log(Level.SEVERE, "Error haciendo rollback de la transacción para insertar carrito en el registro", ex1); } } finally { cerrarConexionYStatement(conexion, insertCarrito, insertHistorial); } return exito; }
|
11
|
Code Sample 1:
public List<Mosque> getAllMosquaisFromDataBase() { List<Mosque> mosquais = new ArrayList<Mosque>(); InputStream is = null; String result = ""; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (MyMapActivity.DEVELOPER_MODE) { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.mLatitude + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.mLongitude + "")); } else { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.myLocation.getLatitude() + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.myLocation.getLongitude() + "")); } nameValuePairs.add(new BasicNameValuePair(Param.RAYON, DataBaseQuery.rayon * Param.KM_MARGE + "")); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Param.URI_SELECT_ALL_DATA_BASE); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); Mosque mosquai = new Mosque(json_data.getInt(Param.ID), json_data.getString(Param.NOM), json_data.getDouble(Param.LATITUDE), json_data.getDouble(Param.LONGITUDE), json_data.getString(Param.INFO), json_data.getInt(Param.HAVE_PICTURE) == 1 ? true : false, json_data.getString(Param.PICTURE)); mosquais.add(mosquai); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return mosquais; }
Code Sample 2:
public LinkedList<NameValuePair> getScoreboard() { InputStream is = null; String result = ""; LinkedList<NameValuePair> scores = new LinkedList<NameValuePair>(); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return null; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json = new JSONObject(result); JSONArray data = json.getJSONArray("data"); JSONArray me = json.getJSONArray("me"); for (int i = 0; i < data.length(); i++) { JSONObject single = data.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } for (int i = 0; i < me.length(); i++) { JSONObject single = me.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } System.out.println(json); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return scores; }
|
00
|
Code Sample 1:
public InputStream sendGetMessage(Properties args) throws IOException { String argString = ""; if (args != null) { argString = "?" + toEncodedString(args); } URL url = new URL(servlet.toExternalForm() + argString); URLConnection con = url.openConnection(); con.setUseCaches(false); sendHeaders(con); return con.getInputStream(); }
Code Sample 2:
public List execute(ComClient comClient) throws Exception { ArrayList outStrings = new ArrayList(); SearchResult sr = Util.getSearchResultByIDAndNum(SearchManager.getInstance(), qID, dwNum); for (int i = 0; i < checkerUrls.length; i++) { String parametrizedURL = checkerUrls[i]; Iterator mtIter = sr.iterateMetatags(); while (mtIter.hasNext()) { Map.Entry mt = (Map.Entry) mtIter.next(); parametrizedURL = parametrizedURL.replaceAll("%%" + mt.getKey() + "%%", mt.getValue().toString()); if (mt.getKey().equals("fake") && ((Boolean) mt.getValue()).booleanValue()) { outStrings.add("it's a fake."); return outStrings; } } parametrizedURL = parametrizedURL.replaceAll("%%fileid%%", sr.getFileHash().toString()); System.out.println("parametrizedURL=" + parametrizedURL); try { URL url = new URL(parametrizedURL); URLConnection connection = url.openConnection(); connection.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); if (str.indexOf(fakeMarks[i]) != -1) { System.out.println("FAKEFAKEFAKE"); sr.addMetatag("fake", Boolean.TRUE); outStrings.add("it's a fake."); break; } } } catch (MalformedURLException murl_err) { murl_err.printStackTrace(); } catch (IOException io_err) { io_err.printStackTrace(); } catch (Exception err) { err.printStackTrace(); } } return outStrings; }
|
11
|
Code Sample 1:
private CharBuffer decodeToFile(ReplayInputStream inStream, String backingFilename, String encoding) throws IOException { CharBuffer charBuffer = null; BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, encoding)); File backingFile = new File(backingFilename); this.decodedFile = File.createTempFile(backingFile.getName(), WRITE_ENCODING, backingFile.getParentFile()); FileOutputStream fos; fos = new FileOutputStream(this.decodedFile); IOUtils.copy(reader, fos, WRITE_ENCODING); fos.close(); charBuffer = getReadOnlyMemoryMappedBuffer(this.decodedFile).asCharBuffer(); return charBuffer; }
Code Sample 2:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
|
00
|
Code Sample 1:
public void myCheckCredHandler(View v) { Log.d("login_section", "entered handler"); EditText Username = (EditText) findViewById(R.id.Username); EditText Password = (EditText) findViewById(R.id.user_pass); String username_S = Username.getText().toString(); String pass_S = Password.getText().toString(); TextView ltv = (TextView) findViewById(R.id.LoginPagetv); HttpClient httpclient = createHttpClient(); HttpPost httppost = new HttpPost(authenticationURL); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("login", username_S)); nameValuePairs.add(new BasicNameValuePair("password", pass_S)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity()); Log.d("login_section", responseBody); JSONObject jsonObject = new JSONObject(responseBody); if (status == this.statusOK && jsonObject.getBoolean("logged_in")) { ltv.setText("You have been logged in. :D"); etracks.setLogged(true); etracks.setUserToken(jsonObject.getString("user_token")); Intent it = new Intent(Intent.ACTION_VIEW); it.setClassName(this, etracks.class.getName()); this.finish(); startActivity(it); } else if (status == this.statusUnprocessable && !jsonObject.getBoolean("logged_in")) { if (!jsonObject.isNull("errors")) ltv.setText(jsonObject.getString("errors")); else ltv.setText("login unsuccessful"); } else Log.d("login_section", "what just happened?"); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (JSONException e) { e.printStackTrace(); } }
Code Sample 2:
public static ByteBuffer readURL(URL url) throws IOException, MalformedURLException { URLConnection connection = null; try { connection = url.openConnection(); return readInputStream(new BufferedInputStream(connection.getInputStream())); } catch (IOException e) { throw e; } }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent ae) { Window win = SwingUtilities.getWindowAncestor(invokerInfo.getComponent()); if (ae.getActionCommand().equals(LOAD)) { URLChooser uc; if (win instanceof Frame) { uc = new URLChooser((Frame) win); } else { uc = new URLChooser((Dialog) win); } uc.setTitle("Load Prototype"); uc.setLabelText(" Prototype URL: "); uc.setNullSelectionValid(false); uc.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".xml") || f.isDirectory(); } public String getDescription() { return "XML Prototype Files"; } }); uc.setResourceFilter(new ResourceFilter() { public boolean accept(ResourceDescriptor rd) { return rd.getType().equals(ResourceDescriptor.NPSNETV_PROTOTYPE); } }); GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), uc); if (uc.showDialog(null)) { URL url = uc.getSelectedURL(); try { target.applyPrototype(url); } catch (Exception e) { JOptionPane.showMessageDialog(invokerInfo.getComponent(), e, "Error Loading Prototype", JOptionPane.ERROR_MESSAGE); } } } else if (ae.getActionCommand().equals(SAVE)) { URLChooser uc; if (win instanceof Frame) { uc = new URLChooser((Frame) win); } else { uc = new URLChooser((Dialog) win); } uc.setTitle("Save Prototype"); uc.setLabelText(" Prototype URL: "); uc.setNullSelectionValid(false); uc.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".xml") || f.isDirectory(); } public String getDescription() { return "XML Prototype Files"; } }); uc.setResourceFilter(new ResourceFilter() { public boolean accept(ResourceDescriptor rd) { return rd.getType().equals(ResourceDescriptor.NPSNETV_PROTOTYPE); } }); GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), uc); if (uc.showDialog(null)) { URL url = uc.getSelectedURL(); try { PrintStream ps; HttpURLConnection huc = null; if (url.getProtocol().equals("file")) { ps = new PrintStream(new FileOutputStream(url.getFile())); } else { URLConnection urlc = url.openConnection(); urlc.setDoOutput(true); if (urlc instanceof HttpURLConnection) { huc = ((HttpURLConnection) urlc); huc.setRequestMethod("PUT"); } ps = new PrintStream(urlc.getOutputStream()); } target.writePrototype(ps); if (huc != null) { huc.getResponseCode(); } } catch (Exception e) { JOptionPane.showMessageDialog(invokerInfo.getComponent(), e, "Error Saving Prototype", JOptionPane.ERROR_MESSAGE); } } } else if (ae.getActionCommand().equals(PUBLISH)) { PublishPrototypeDialog ppd; if (win instanceof Frame) { ppd = new PublishPrototypeDialog((Frame) win, target); } else { ppd = new PublishPrototypeDialog((Dialog) win, target); } GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), ppd); ppd.show(); } else if (ae.getActionCommand().equals(VIEW_EDIT)) { ViewEditPrototypeDialog vepd; if (win instanceof Frame) { vepd = new ViewEditPrototypeDialog((Frame) win, target); } else { vepd = new ViewEditPrototypeDialog((Dialog) win, target); } GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), vepd); vepd.show(); } }
Code Sample 2:
private static Object readFileOrUrl(String path, boolean convertToString) throws IOException { URL url = null; if (path.indexOf(':') >= 2) { try { url = new URL(path); } catch (MalformedURLException ex) { } } InputStream is = null; int capacityHint = 0; if (url == null) { File file = new File(path); capacityHint = (int) file.length(); try { is = new FileInputStream(file); } catch (IOException ex) { Context.reportError(getMessage("msg.couldnt.open", path)); throw ex; } } else { try { URLConnection uc = url.openConnection(); is = uc.getInputStream(); capacityHint = uc.getContentLength(); if (capacityHint > (1 << 20)) { capacityHint = -1; } } catch (IOException ex) { Context.reportError(getMessage("msg.couldnt.open.url", url.toString(), ex.toString())); throw ex; } } if (capacityHint <= 0) { capacityHint = 4096; } byte[] data; try { try { is = new BufferedInputStream(is); data = Kit.readStream(is, capacityHint); } finally { is.close(); } } catch (IOException ex) { Context.reportError(ex.toString()); throw ex; } Object result; if (convertToString) { result = new String(data); } else { result = data; } return result; }
|
11
|
Code Sample 1:
public void copy(final File source, final File dest) throws IOException { final FileInputStream in = new FileInputStream(source); try { final FileOutputStream out = new FileOutputStream(dest); try { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { out.close(); } } finally { in.close(); } }
Code Sample 2:
public static boolean copy(InputStream is, File file) { try { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); is.close(); fos.close(); return true; } catch (Exception e) { System.err.println(e.getMessage()); return false; } }
|
00
|
Code Sample 1:
public static void writeToPetrify(TransitionSystem ts, Writer bw) throws IOException { File temp = new File("_temp"); BufferedWriter tw = new BufferedWriter(new FileWriter(temp)); BufferedReader tr = new BufferedReader(new FileReader(temp)); HashSet<ModelGraphVertex> sources = new HashSet<ModelGraphVertex>(); HashSet<ModelGraphVertex> dests = new HashSet<ModelGraphVertex>(); ArrayList transitions = ts.getEdges(); HashSet<String> events = new HashSet<String>(); for (int i = 0; i < transitions.size(); i++) { TransitionSystemEdge transition = (TransitionSystemEdge) transitions.get(i); events.add(replaceBadSymbols(transition.getIdentifier())); sources.add(transition.getSource()); dests.add(transition.getDest()); if (ts.getStateNameFlag() == TransitionSystem.ID) { tw.write("s" + transition.getSource().getId() + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write("s" + transition.getDest().getId() + "\n"); } else { tw.write(replaceBadSymbols(transition.getSource().getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getDest().getIdentifier()) + "\n"); } } tw.close(); bw.write(".model " + ts.getName().replaceAll(" ", "_") + "\n"); bw.write(".dummy "); Iterator it = events.iterator(); while (it.hasNext()) bw.write(it.next() + " "); bw.write("\n"); bw.write(".state graph" + "\n"); int c; while ((c = tr.read()) != -1) bw.write(c); tr.close(); temp.delete(); for (ModelGraphVertex dest : dests) { if (sources.contains(dest)) { sources.remove(dest); } } ModelGraphVertex source = sources.isEmpty() ? null : sources.iterator().next(); if (ts.getStateNameFlag() == TransitionSystem.ID) { if (!ts.hasExplicitEnd()) bw.write(".marking {s0}" + "\n"); else bw.write(".marking {s" + source.getId() + "}\n"); } else if (source != null) { bw.write(".marking {" + replaceBadSymbols(source.getIdentifier()) + "}\n"); } bw.write(".end"); }
Code Sample 2:
public void readContents() throws IOException { fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_START, 0.0f, "loading file")); URLConnection conn = url.openConnection(); conn.connect(); filesize = conn.getContentLength(); logger.finest("filesize: " + filesize); InputStreamReader in = new InputStreamReader(conn.getInputStream()); readFirstLine(in); readHeaderLines(in); readData(in); fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_FINISH, 1.0f, "loading file")); }
|
00
|
Code Sample 1:
public static List importSymbols(List symbols) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbols); IDQuoteFilter filter = new YahooIDQuoteFilter(); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; do { line = bufferedInput.readLine(); if (line != null) { try { IDQuote quote = filter.toIDQuote(line); quote.verify(); quotes.add(quote); } catch (QuoteFormatException e) { } } } while (line != null); bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
private static boolean isXmlApplicationFile(URL url) throws java.io.IOException { if (DEBUG) { System.out.println("Checking whether file is xml"); } String firstLine; BufferedReader fileReader = null; try { fileReader = new BomStrippingInputStreamReader(url.openStream()); firstLine = fileReader.readLine(); } finally { if (fileReader != null) fileReader.close(); } if (firstLine == null) { return false; } for (String startOfXml : STARTOFXMLAPPLICATIONFILES) { if (firstLine.length() >= startOfXml.length() && firstLine.substring(0, startOfXml.length()).equals(startOfXml)) { if (DEBUG) { System.out.println("isXMLApplicationFile = true"); } return true; } } if (DEBUG) { System.out.println("isXMLApplicationFile = false"); } return false; }
|
00
|
Code Sample 1:
public static void translateTableMetaData(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table", nsDefinition); String filename = baseDir + "table.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + ".xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + ".json", baseDir + tableName + ".xsl"); }
Code Sample 2:
public static void download(String args[], boolean forEmu) { if (args.length < 1) { System.err.println("usage: java copyURL URL [LocalFile]"); System.exit(1); } try { String check = args[1]; File chk = new File(check); String ext = check.substring(check.length() - 4); String name = check.substring(0, check.length() - 4); System.out.println("Name is:" + name); System.out.println("Ext. is:" + ext); if (!forEmu) { while (chk.canRead()) { name += "-"; chk = new File(name + ext); } args[1] = name + ext; } else { chk = new File(name + ext); chk.delete(); chk = new File(name + ext + ".tmp"); chk.delete(); } args[1] = name + ext; String dlurl = args[0]; if (dlurl.contains("download.php") && dlurl.contains("cpc-live.com")) { String newurl = "http://cpc-live.com/data/"; while (!dlurl.startsWith("type=")) { dlurl = dlurl.substring((1)); } dlurl = dlurl.replace("type=", ""); while (!dlurl.startsWith("&")) { newurl += dlurl.charAt(0); dlurl = dlurl.substring(1); } while (!dlurl.startsWith("fichier=")) { dlurl = dlurl.substring((1)); } dlurl = dlurl.replace("fichier=", ""); newurl += "/" + dlurl; dlurl = newurl; } dlurl = dlurl.replace(" ", "%20"); dlurl = dlurl.replace("(", "%28"); dlurl = dlurl.replace(")", "%29"); dlurl = dlurl.replace("[", "%5B"); dlurl = dlurl.replace("]", "%5D"); URL url = new URL(dlurl); System.out.println("Opening connection to " + dlurl + "..."); HttpURLConnection urlC = (HttpURLConnection) url.openConnection(); urlC.setRequestMethod("GET"); BufferedInputStream is = new BufferedInputStream(url.openStream()); int count = 0; try { System.out.print("Copying resource (type: " + urlC.getContentType()); Date date = new Date(urlC.getLastModified()); int size = urlC.getContentLength(); System.out.println(", modified on: " + date.toString() + ")..."); System.out.flush(); count = 0; BufferedOutputStream fos = null; try { if (args.length < 2) { String localFile = null; StringTokenizer st = new StringTokenizer(url.getFile(), "/"); while (st.hasMoreTokens()) { localFile = st.nextToken(); } fos = new BufferedOutputStream(new FileOutputStream(localFile)); } else { fos = new BufferedOutputStream(new FileOutputStream(args[1] + ".tmp")); } byte[] buf = new byte[BUFSIZE]; int len = 0; while (len >= 0) { len = is.read(buf); if (len > 0) { fos.write(buf, 0, len); } count = count + len; } } finally { fos.close(); } } finally { is.close(); } File temp = new File(args[1] + ".tmp"); File temp2 = new File(args[1]); temp.renameTo(temp2); System.out.println("\n" + count + " byte(s) copied"); if (forEmu) { CPC.download = true; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void upgradeSchema() throws IOException { Statement stmt = null; try { int i = getSchema(); if (i < SCHEMA_VERSION) { conn.setAutoCommit(false); stmt = conn.createStatement(); while (i < SCHEMA_VERSION) { String qry; switch(i) { case 1: qry = "CREATE TABLE log (id INTEGER PRIMARY KEY, context VARCHAR(16) NOT NULL, level VARCHAR(16) NOT NULL, time LONG INT NOT NULL, msg LONG VARCHAR NOT NULL, parent INT)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '2' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 2: qry = "CREATE TABLE monitor (id INTEGER PRIMARY KEY NOT NULL, status INTEGER NOT NULL)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '3' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 3: qry = "CREATE TABLE favs (id INTEGER PRIMARY KEY NOT NULL)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '4' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 4: qry = "DROP TABLE log"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '5' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 5: qry = "UPDATE settings SET val = '120000' WHERE var = 'SleepTime'"; stmt.executeUpdate(qry); qry = "UPDATE settings set val = '6' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; } i++; } conn.commit(); } } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { LOG.trace(SQL_ERROR, e2); LOG.error(e2); } LOG.trace(SQL_ERROR, e); LOG.fatal(e); throw new IOException("Error upgrading data store", e); } finally { try { if (stmt != null) { stmt.close(); } conn.setAutoCommit(true); } catch (SQLException e) { LOG.trace(SQL_ERROR, e); throw new IOException("Unable to cleanup SQL resources", e); } } }
Code Sample 2:
public void deletePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); 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 portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
|
00
|
Code Sample 1:
public static boolean insert(final CelulaFinanceira objCelulaFinanceira) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into celula_financeira " + "(descricao, id_orgao, id_gestao, " + "id_natureza_despesa, id_programa_trabalho, " + "id_unidade_orcamentaria, id_fonte_recursos, " + "valor_provisionado, gasto_previsto, gasto_real, " + "saldo_previsto, saldo_real)" + " values (?, ?, ?, ?, ?, ?, ?, TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2))"; pst = c.prepareStatement(sql); pst.setString(1, objCelulaFinanceira.getDescricao()); pst.setLong(2, (objCelulaFinanceira.getOrgao()).getCodigo()); pst.setString(3, (objCelulaFinanceira.getGestao()).getCodigo()); pst.setString(4, (objCelulaFinanceira.getNaturezaDespesa()).getCodigo()); pst.setString(5, (objCelulaFinanceira.getProgramaTrabalho()).getCodigo()); pst.setString(6, (objCelulaFinanceira.getUnidadeOrcamentaria()).getCodigo()); pst.setString(7, (objCelulaFinanceira.getFonteRecursos()).getCodigo()); pst.setDouble(8, objCelulaFinanceira.getValorProvisionado()); pst.setDouble(9, objCelulaFinanceira.getGastoPrevisto()); pst.setDouble(10, objCelulaFinanceira.getGastoReal()); pst.setDouble(11, objCelulaFinanceira.getSaldoPrevisto()); pst.setDouble(12, objCelulaFinanceira.getSaldoReal()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
|
00
|
Code Sample 1:
public void setPassword(String plaintext) throws java.security.NoSuchAlgorithmException { StringBuffer encrypted = new StringBuffer(); java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(plaintext.getBytes()); byte[] digestArray = digest.digest(); for (int i = 0; i < digestArray.length; i++) { encrypted.append(byte2hex(digestArray[i])); } setEncryptedPassword(encrypted.toString()); }
Code Sample 2:
private static String[] loadDB(String name) throws IOException { URL url = SpecialConstants.class.getResource(name); if (url == null) throw new FileNotFoundException("file " + name + " not found"); InputStream is = url.openStream(); try { InputStreamReader isr = new InputStreamReader(is, "utf8"); BufferedReader br = new BufferedReader(isr); ArrayList<String> entries = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { entries.add(line); } } String[] r = new String[entries.size()]; entries.toArray(r); return r; } finally { is.close(); } }
|
11
|
Code Sample 1:
static void copyFile(File file, File file1) throws IOException { byte abyte0[] = new byte[512]; FileInputStream fileinputstream = new FileInputStream(file); FileOutputStream fileoutputstream = new FileOutputStream(file1); int i; while ((i = fileinputstream.read(abyte0)) > 0) fileoutputstream.write(abyte0, 0, i); fileinputstream.close(); fileoutputstream.close(); }
Code Sample 2:
private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(128); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(32); for (int j = 0; j < array.length; ++j) { int b = array[j] & TWO_BYTES; if (b < PAD_BELOW) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } }
Code Sample 2:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
|
11
|
Code Sample 1:
@Override public int write(FileStatus.FileTrackingStatus fileStatus, InputStream input, PostWriteAction postWriteAction) throws WriterException, InterruptedException { String key = logFileNameExtractor.getFileName(fileStatus); int wasWritten = 0; FileOutputStreamPool fileOutputStreamPool = fileOutputStreamPoolFactory.getPoolForKey(key); RollBackOutputStream outputStream = null; File file = null; try { file = getOutputFile(key); lastWrittenFile = file; outputStream = fileOutputStreamPool.open(key, compressionCodec, file, true); outputStream.mark(); wasWritten = IOUtils.copy(input, outputStream); if (postWriteAction != null) { postWriteAction.run(wasWritten); } } catch (Throwable t) { LOG.error(t.toString(), t); if (outputStream != null && wasWritten > 0) { LOG.error("Rolling back file " + file.getAbsolutePath()); try { outputStream.rollback(); } catch (IOException e) { throwException(e); } catch (InterruptedException e) { throw e; } } throwException(t); } finally { try { fileOutputStreamPool.releaseFile(key); } catch (IOException e) { throwException(e); } } return wasWritten; }
Code Sample 2:
@Override public void setContentAsStream(InputStream input) throws IOException { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(htmlFile)); try { IOUtils.copy(input, output); } finally { output.close(); } if (this.getLastModified() != -1) { htmlFile.setLastModified(this.getLastModified()); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.