id
stringlengths
27
31
content
stringlengths
14
287k
max_stars_repo_path
stringlengths
52
57
crossvul-java_data_good_689_2
/* * Copyright 2011- Per Wendel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.examples.staticresources; import static spark.Spark.get; import static spark.Spark.staticFiles; /** * Example showing how serve static resources. */ public class StaticResources { public static void main(String[] args) { // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes. staticFiles.location("/public"); get("/hello", (request, response) -> { return "Hello World!"; }); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_689_2
crossvul-java_data_good_2092_0
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.cli; import hudson.model.ModifiableItemGroup; import hudson.model.TopLevelItem; import jenkins.model.Jenkins; import hudson.Extension; import hudson.model.Item; import jenkins.model.ModifiableTopLevelItemGroup; import org.kohsuke.args4j.Argument; /** * Creates a new job by reading stdin as a configuration XML file. * * @author Kohsuke Kawaguchi */ @Extension public class CreateJobCommand extends CLICommand { @Override public String getShortDescription() { return Messages.CreateJobCommand_ShortDescription(); } @Argument(metaVar="NAME",usage="Name of the job to create",required=true) public String name; protected int run() throws Exception { Jenkins h = Jenkins.getInstance(); h.checkPermission(Item.CREATE); if (h.getItemByFullName(name)!=null) { stderr.println("Job '"+name+"' already exists"); return -1; } ModifiableTopLevelItemGroup ig = h; int i = name.lastIndexOf('/'); if (i > 0) { String group = name.substring(0, i); Item item = h.getItemByFullName(group); if (item == null) { throw new IllegalArgumentException("Unknown ItemGroup " + group); } if (item instanceof ModifiableTopLevelItemGroup) { ig = (ModifiableTopLevelItemGroup) item; } else { throw new IllegalArgumentException("Can't create job from CLI in " + group); } name = name.substring(i + 1); } Jenkins.checkGoodName(name); ig.createProjectFromXML(name, stdin); return 0; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_2092_0
crossvul-java_data_bad_4612_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4612_3
crossvul-java_data_good_688_2
/* * Copyright 2011- Per Wendel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.examples.staticresources; import static spark.Spark.get; import static spark.Spark.staticFiles; /** * Example showing how serve static resources. */ public class StaticResources { public static void main(String[] args) { // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes. staticFiles.location("/public"); get("/hello", (request, response) -> { return "Hello World!"; }); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_688_2
crossvul-java_data_bad_498_0
package cc.mrbird.common.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; @Controller public class CommonController { private Logger log = LoggerFactory.getLogger(this.getClass()); @RequestMapping("common/download") public void fileDownload(String fileName, Boolean delete, HttpServletResponse response) throws IOException { String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf('_') + 1); String filePath = "file/" + fileName; File file = new File(filePath); response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(realFileName, "utf-8")); response.setContentType("multipart/form-data"); response.setCharacterEncoding("utf-8"); try (InputStream inputStream = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } } catch (Exception e) { log.error("文件下载失败", e); } finally { if (delete && file.exists()) { Files.delete(Paths.get(filePath)); } } } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_498_0
crossvul-java_data_good_416_0
package org.linlinjava.litemall.wx.web; import org.linlinjava.litemall.core.storage.StorageService; import org.linlinjava.litemall.core.util.CharUtil; import org.linlinjava.litemall.core.util.ResponseUtil; import org.linlinjava.litemall.db.domain.LitemallStorage; import org.linlinjava.litemall.db.service.LitemallStorageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/wx/storage") @Validated public class WxStorageController { @Autowired private StorageService storageService; @Autowired private LitemallStorageService litemallStorageService; private String generateKey(String originalFilename) { int index = originalFilename.lastIndexOf('.'); String suffix = originalFilename.substring(index); String key = null; LitemallStorage storageInfo = null; do { key = CharUtil.getRandomString(20) + suffix; storageInfo = litemallStorageService.findByKey(key); } while (storageInfo != null); return key; } @PostMapping("/upload") public Object upload(@RequestParam("file") MultipartFile file) throws IOException { String originalFilename = file.getOriginalFilename(); String url = storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename); Map<String, Object> data = new HashMap<>(); data.put("url", url); return ResponseUtil.ok(data); } @GetMapping("/fetch/{key:.+}") public ResponseEntity<Resource> fetch(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { return ResponseEntity.notFound().build(); } if(key.contains("../")){ return ResponseEntity.badRequest().build(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().contentType(mediaType).body(file); } @GetMapping("/download/{key:.+}") public ResponseEntity<Resource> download(@PathVariable String key) { LitemallStorage litemallStorage = litemallStorageService.findByKey(key); if (key == null) { return ResponseEntity.notFound().build(); } if(key.contains("../")){ return ResponseEntity.badRequest().build(); } String type = litemallStorage.getType(); MediaType mediaType = MediaType.parseMediaType(type); Resource file = storageService.loadAsResource(key); if (file == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_416_0
crossvul-java_data_bad_68_0
/** * Copyright (C) 2012 ZeroTurnaround LLC <support@zeroturnaround.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zeroturnaround.zip; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeroturnaround.zip.commons.FileUtils; import org.zeroturnaround.zip.commons.FilenameUtils; import org.zeroturnaround.zip.commons.IOUtils; import org.zeroturnaround.zip.transform.ZipEntryTransformer; import org.zeroturnaround.zip.transform.ZipEntryTransformerEntry; /** * ZIP file manipulation utilities. * * @author Rein Raudjärv * @author Innokenty Shuvalov * * @see #containsEntry(File, String) * @see #unpackEntry(File, String) * @see #unpack(File, File) * @see #pack(File, File) */ public final class ZipUtil { private static final String PATH_SEPARATOR = "/"; /** Default compression level */ public static final int DEFAULT_COMPRESSION_LEVEL = Deflater.DEFAULT_COMPRESSION; // Use / instead of . to work around an issue with Maven Shade Plugin private static final Logger log = LoggerFactory.getLogger("org/zeroturnaround/zip/ZipUtil".replace('/', '.')); // NOSONAR private ZipUtil() { } /* Extracting single entries from ZIP files. */ /** * Checks if the ZIP file contains the given entry. * * @param zip * ZIP file. * @param name * entry name. * @return <code>true</code> if the ZIP file contains the given entry. */ public static boolean containsEntry(File zip, String name) { ZipFile zf = null; try { zf = new ZipFile(zip); return zf.getEntry(name) != null; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Returns the compression method of a given entry of the ZIP file. * * @param zip * ZIP file. * @param name * entry name. * @return Returns <code>ZipEntry.STORED</code>, <code>ZipEntry.DEFLATED</code> or -1 if * the ZIP file does not contain the given entry. * @deprecated The compression level cannot be retrieved. This method exists only to ensure backwards compatibility with ZipUtil version 1.9, which returned the compression * method, not the level. */ @Deprecated public static int getCompressionLevelOfEntry(File zip, String name) { return getCompressionMethodOfEntry(zip, name); } /** * Returns the compression method of a given entry of the ZIP file. * * @param zip * ZIP file. * @param name * entry name. * @return Returns <code>ZipEntry.STORED</code>, <code>ZipEntry.DEFLATED</code> or -1 if * the ZIP file does not contain the given entry. */ public static int getCompressionMethodOfEntry(File zip, String name) { ZipFile zf = null; try { zf = new ZipFile(zip); ZipEntry zipEntry = zf.getEntry(name); if (zipEntry == null) { return -1; } return zipEntry.getMethod(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Checks if the ZIP file contains any of the given entries. * * @param zip * ZIP file. * @param names * entry names. * @return <code>true</code> if the ZIP file contains any of the given * entries. */ public static boolean containsAnyEntry(File zip, String[] names) { ZipFile zf = null; try { zf = new ZipFile(zip); for (int i = 0; i < names.length; i++) { if (zf.getEntry(names[i]) != null) { return true; } } return false; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single entry from a ZIP file. * * @param zip * ZIP file. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(File zip, String name) { ZipFile zf = null; try { zf = new ZipFile(zip); return doUnpackEntry(zf, name); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single entry from a ZIP file. * * @param zip * ZIP file. * @param name * entry name. * * @param charset * charset to be used to process the zip * * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(File zip, String name, Charset charset) { ZipFile zf = null; try { if (charset != null) { zf = new ZipFile(zip, charset); } else { zf = new ZipFile(zip); } return doUnpackEntry(zf, name); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single entry from a ZIP file. * * @param zf * ZIP file. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(ZipFile zf, String name) { try { return doUnpackEntry(zf, name); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Unpacks a single entry from a ZIP file. * * @param zf * ZIP file. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ private static byte[] doUnpackEntry(ZipFile zf, String name) throws IOException { ZipEntry ze = zf.getEntry(name); if (ze == null) { return null; // entry not found } InputStream is = zf.getInputStream(ze); try { return IOUtils.toByteArray(is); } finally { IOUtils.closeQuietly(is); } } /** * Unpacks a single entry from a ZIP stream. * * @param is * ZIP stream. * @param name * entry name. * @return contents of the entry or <code>null</code> if it was not found. */ public static byte[] unpackEntry(InputStream is, String name) { ByteArrayUnpacker action = new ByteArrayUnpacker(); if (!handle(is, name, action)) return null; // entry not found return action.getBytes(); } /** * Copies an entry into a byte array. * * @author Rein Raudjärv */ private static class ByteArrayUnpacker implements ZipEntryCallback { private byte[] bytes; public void process(InputStream in, ZipEntry zipEntry) throws IOException { bytes = IOUtils.toByteArray(in); } public byte[] getBytes() { return bytes; } } /** * Unpacks a single file from a ZIP archive to a file. * * @param zip * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ public static boolean unpackEntry(File zip, String name, File file) { return unpackEntry(zip, name, file, null); } /** * Unpacks a single file from a ZIP archive to a file. * * @param zip * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @param charset * charset to be used processing the zip * * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ public static boolean unpackEntry(File zip, String name, File file, Charset charset) { ZipFile zf = null; try { if (charset != null) { zf = new ZipFile(zip, charset); } else { zf = new ZipFile(zip); } return doUnpackEntry(zf, name, file); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Unpacks a single file from a ZIP archive to a file. * * @param zf * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ public static boolean unpackEntry(ZipFile zf, String name, File file) { try { return doUnpackEntry(zf, name, file); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Unpacks a single file from a ZIP archive to a file. * * @param zf * ZIP file. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. */ private static boolean doUnpackEntry(ZipFile zf, String name, File file) throws IOException { if (log.isTraceEnabled()) { log.trace("Extracting '" + zf.getName() + "' entry '" + name + "' into '" + file + "'."); } ZipEntry ze = zf.getEntry(name); if (ze == null) { return false; // entry not found } if (ze.isDirectory() || zf.getInputStream(ze) == null) { if (file.isDirectory()) { return true; } if (file.exists()) { FileUtils.forceDelete(file); } return file.mkdirs(); } InputStream in = new BufferedInputStream(zf.getInputStream(ze)); try { FileUtils.copy(in, file); } finally { IOUtils.closeQuietly(in); } return true; } /** * Unpacks a single file from a ZIP stream to a file. * * @param is * ZIP stream. * @param name * entry name. * @param file * target file to be created or overwritten. * @return <code>true</code> if the entry was found and unpacked, * <code>false</code> if the entry was not found. * @throws java.io.IOException if file is not found or writing to it fails */ public static boolean unpackEntry(InputStream is, String name, File file) throws IOException { return handle(is, name, new FileUnpacker(file)); } /** * Copies an entry into a File. * * @author Rein Raudjärv */ private static class FileUnpacker implements ZipEntryCallback { private final File file; public FileUnpacker(File file) { this.file = file; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { FileUtils.copy(in, file); } } /* Traversing ZIP files */ /** * Reads the given ZIP file and executes the given action for each entry. * <p> * For each entry the corresponding input stream is also passed to the action. If you want to stop the loop * then throw a ZipBreakException. * * @param zip * input ZIP file. * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, ZipInfoCallback) */ public static void iterate(File zip, ZipEntryCallback action) { iterate(zip, action, null); } /** * Reads the given ZIP file and executes the given action for each entry. * <p> * For each entry the corresponding input stream is also passed to the action. If you want to stop the loop * then throw a ZipBreakException. * * @param zip * input ZIP file. * @param action * action to be called for each entry. * * @param charset * Charset used to processed the ZipFile with * * @see ZipEntryCallback * @see #iterate(File, ZipInfoCallback) */ public static void iterate(File zip, ZipEntryCallback action, Charset charset) { ZipFile zf = null; try { if (charset == null) { zf = new ZipFile(zip); } else { zf = new ZipFile(zip, charset); } Enumeration<? extends ZipEntry> en = zf.entries(); while (en.hasMoreElements()) { ZipEntry e = (ZipEntry) en.nextElement(); InputStream is = zf.getInputStream(e); try { action.process(is, e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + "' with action " + action, ze); } catch (ZipBreakException ex) { break; } finally { IOUtils.closeQuietly(is); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Reads the given ZIP file and executes the given action for each given entry. * <p> * For each given entry the corresponding input stream is also passed to the action. If you want to stop the loop then throw a ZipBreakException. * * @param zip * input ZIP file. * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, String[], ZipInfoCallback) */ public static void iterate(File zip, String[] entryNames, ZipEntryCallback action) { iterate(zip, entryNames, action, null); } /** * Reads the given ZIP file and executes the given action for each given entry. * <p> * For each given entry the corresponding input stream is also passed to the action. If you want to stop the loop then throw a ZipBreakException. * * @param zip * input ZIP file. * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * @param charset * charset used to process the zip file * * @see ZipEntryCallback * @see #iterate(File, String[], ZipInfoCallback) */ public static void iterate(File zip, String[] entryNames, ZipEntryCallback action, Charset charset) { ZipFile zf = null; try { if (charset == null) { zf = new ZipFile(zip); } else { zf = new ZipFile(zip, charset); } for (int i = 0; i < entryNames.length; i++) { ZipEntry e = zf.getEntry(entryNames[i]); if (e == null) { continue; } InputStream is = zf.getInputStream(e); try { action.process(is, e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } finally { IOUtils.closeQuietly(is); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Scans the given ZIP file and executes the given action for each entry. * <p> * Only the meta-data without the actual data is read. If you want to stop the loop * then throw a ZipBreakException. * * @param zip * input ZIP file. * @param action * action to be called for each entry. * * @see ZipInfoCallback * @see #iterate(File, ZipEntryCallback) */ public static void iterate(File zip, ZipInfoCallback action) { ZipFile zf = null; try { zf = new ZipFile(zip); Enumeration<? extends ZipEntry> en = zf.entries(); while (en.hasMoreElements()) { ZipEntry e = (ZipEntry) en.nextElement(); try { action.process(e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Scans the given ZIP file and executes the given action for each given entry. * <p> * Only the meta-data without the actual data is read. If you want to stop the loop then throw a ZipBreakException. * * @param zip * input ZIP file. * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * * @see ZipInfoCallback * @see #iterate(File, String[], ZipEntryCallback) */ public static void iterate(File zip, String[] entryNames, ZipInfoCallback action) { ZipFile zf = null; try { zf = new ZipFile(zip); for (int i = 0; i < entryNames.length; i++) { ZipEntry e = zf.getEntry(entryNames[i]); if (e == null) { continue; } try { action.process(e); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + e.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Reads the given ZIP stream and executes the given action for each entry. * <p> * For each entry the corresponding input stream is also passed to the action. If you want to stop the loop * then throw a ZipBreakException. * * @param is * input ZIP stream (it will not be closed automatically). * @param action * action to be called for each entry. * @param charset * charset to process entries in * * @see ZipEntryCallback * @see #iterate(File, ZipEntryCallback) */ public static void iterate(InputStream is, ZipEntryCallback action, Charset charset) { try { ZipInputStream in = null; try { in = newCloseShieldZipInputStream(is, charset); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { try { action.process(in, entry); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + entry.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } finally { if (in != null) { in.close(); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * See {@link #iterate(InputStream, ZipEntryCallback, Charset)}. This method * is a shorthand for a version where no Charset is specified. * * @param is * input ZIP stream (it will not be closed automatically). * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, ZipEntryCallback) */ public static void iterate(InputStream is, ZipEntryCallback action) { iterate(is, action, null); } /** * Reads the given ZIP stream and executes the given action for each given entry. * <p> * For each given entry the corresponding input stream is also passed to the action. If you want to stop the loop then throw a ZipBreakException. * * @param is * input ZIP stream (it will not be closed automatically). * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * @param charset * charset to process entries in * * @see ZipEntryCallback * @see #iterate(File, String[], ZipEntryCallback) */ public static void iterate(InputStream is, String[] entryNames, ZipEntryCallback action, Charset charset) { Set<String> namesSet = new HashSet<String>(); for (int i = 0; i < entryNames.length; i++) { namesSet.add(entryNames[i]); } try { ZipInputStream in = null; try { in = newCloseShieldZipInputStream(is, charset); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { if (!namesSet.contains(entry.getName())) { // skip the unnecessary entry continue; } try { action.process(in, entry); } catch (IOException ze) { throw new ZipException("Failed to process zip entry '" + entry.getName() + " with action " + action, ze); } catch (ZipBreakException ex) { break; } } } finally { if (in != null) { in.close(); } } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * See @link{ {@link #iterate(InputStream, ZipEntryCallback, Charset)}. It is a * shorthand where no Charset is specified. * * @param is * input ZIP stream (it will not be closed automatically). * @param entryNames * names of entries to iterate * @param action * action to be called for each entry. * * @see ZipEntryCallback * @see #iterate(File, String[], ZipEntryCallback) */ public static void iterate(InputStream is, String[] entryNames, ZipEntryCallback action) { iterate(is, entryNames, action, null); } /** * Creates a new {@link ZipInputStream} based on the given {@link InputStream}. It will be buffered and close-shielded. * Closing the result stream flushes the buffers and frees up resources of the {@link ZipInputStream}. However the source stream itself remains open. */ private static ZipInputStream newCloseShieldZipInputStream(final InputStream is, Charset charset) { InputStream in = new BufferedInputStream(new CloseShieldInputStream(is)); if (charset == null) { return new ZipInputStream(in); } return ZipFileUtil.createZipInputStream(in, charset); } /** * Reads the given ZIP file and executes the given action for a single entry. * * @param zip * input ZIP file. * @param name * entry name. * @param action * action to be called for this entry. * @return <code>true</code> if the entry was found, <code>false</code> if the * entry was not found. * * @see ZipEntryCallback */ public static boolean handle(File zip, String name, ZipEntryCallback action) { ZipFile zf = null; try { zf = new ZipFile(zip); ZipEntry ze = zf.getEntry(name); if (ze == null) { return false; // entry not found } InputStream in = new BufferedInputStream(zf.getInputStream(ze)); try { action.process(in, ze); } finally { IOUtils.closeQuietly(in); } return true; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } } /** * Reads the given ZIP stream and executes the given action for a single * entry. * * @param is * input ZIP stream (it will not be closed automatically). * @param name * entry name. * @param action * action to be called for this entry. * @return <code>true</code> if the entry was found, <code>false</code> if the * entry was not found. * * @see ZipEntryCallback */ public static boolean handle(InputStream is, String name, ZipEntryCallback action) { SingleZipEntryCallback helper = new SingleZipEntryCallback(name, action); iterate(is, helper); return helper.found(); } /** * ZipEntryCallback which is only applied to single entry. * * @author Rein Raudjärv */ private static class SingleZipEntryCallback implements ZipEntryCallback { private final String name; private final ZipEntryCallback action; private boolean found; public SingleZipEntryCallback(String name, ZipEntryCallback action) { this.name = name; this.action = action; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (name.equals(zipEntry.getName())) { found = true; action.process(in, zipEntry); } } public boolean found() { return found; } } /* Extracting whole ZIP files. */ /** * Unpacks a ZIP file to the given directory. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unpack(File zip, final File outputDir) { unpack(zip, outputDir, IdentityNameMapper.INSTANCE); } /** * Unpacks a ZIP file to the given directory using a specific Charset * for the input file. * * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * * @param charset * charset used to unpack the zip file */ public static void unpack(File zip, final File outputDir, Charset charset) { unpack(zip, outputDir, IdentityNameMapper.INSTANCE, charset); } /** * Unpacks a ZIP file to the given directory. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. * @param charset * charset used to process the zip file */ public static void unpack(File zip, File outputDir, NameMapper mapper, Charset charset) { log.debug("Extracting '{}' into '{}'.", zip, outputDir); iterate(zip, new Unpacker(outputDir, mapper), charset); } /** * Unpacks a ZIP file to the given directory using a specific Charset * for the input file. * * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unpack(File zip, File outputDir, NameMapper mapper) { log.debug("Extracting '{}' into '{}'.", zip, outputDir); iterate(zip, new Unpacker(outputDir, mapper)); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unwrap(File zip, final File outputDir) { unwrap(zip, outputDir, IdentityNameMapper.INSTANCE); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param zip * input ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unwrap(File zip, File outputDir, NameMapper mapper) { log.debug("Unwrapping '{}' into '{}'.", zip, outputDir); iterate(zip, new Unwraper(outputDir, mapper)); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unpack(InputStream is, File outputDir) { unpack(is, outputDir, IdentityNameMapper.INSTANCE, null); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param charset * charset used to process the zip stream */ public static void unpack(InputStream is, File outputDir, Charset charset) { unpack(is, outputDir, IdentityNameMapper.INSTANCE, charset); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unpack(InputStream is, File outputDir, NameMapper mapper) { unpack(is, outputDir, mapper, null); } /** * Unpacks a ZIP stream to the given directory. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. * @param charset * charset to use when unpacking the stream */ public static void unpack(InputStream is, File outputDir, NameMapper mapper, Charset charset) { log.debug("Extracting {} into '{}'.", is, outputDir); iterate(is, new Unpacker(outputDir, mapper), charset); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). */ public static void unwrap(InputStream is, File outputDir) { unwrap(is, outputDir, IdentityNameMapper.INSTANCE); } /** * Unwraps a ZIP file to the given directory shaving of root dir. * If there are multiple root dirs or entries in the root of zip, * ZipException is thrown. * <p> * The output directory must not be a file. * * @param is * inputstream for ZIP file. * @param outputDir * output directory (created automatically if not found). * @param mapper * call-back for renaming the entries. */ public static void unwrap(InputStream is, File outputDir, NameMapper mapper) { log.debug("Unwrapping {} into '{}'.", is, outputDir); iterate(is, new Unwraper(outputDir, mapper)); } /** * Unpacks each ZIP entry. * * @author Rein Raudjärv */ private static class Unpacker implements ZipEntryCallback { private final File outputDir; private final NameMapper mapper; public Unpacker(File outputDir, NameMapper mapper) { this.outputDir = outputDir; this.mapper = mapper; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { String name = mapper.map(zipEntry.getName()); if (name != null) { File file = new File(outputDir, name); if (zipEntry.isDirectory()) { FileUtils.forceMkdir(file); } else { FileUtils.forceMkdir(file.getParentFile()); if (log.isDebugEnabled() && file.exists()) { log.debug("Overwriting file '{}'.", zipEntry.getName()); } FileUtils.copy(in, file); } ZTFilePermissions permissions = ZipEntryUtil.getZTFilePermissions(zipEntry); if (permissions != null) { ZTFilePermissionsUtil.getDefaultStategy().setPermissions(file, permissions); } } } } /** * Unpacks each ZIP entries. Presumes they are packed with the backslash separator. * Some archives can have this problem if they are created with some software * that is not following the ZIP specification. * * @since zt-zip 1.9 */ public static class BackslashUnpacker implements ZipEntryCallback { private final File outputDir; private final NameMapper mapper; public BackslashUnpacker(File outputDir, NameMapper mapper) { this.outputDir = outputDir; this.mapper = mapper; } public BackslashUnpacker(File outputDir) { this(outputDir, IdentityNameMapper.INSTANCE); } public void process(InputStream in, ZipEntry zipEntry) throws IOException { String name = mapper.map(zipEntry.getName()); if (name != null) { /** * We assume that EVERY backslash will denote a directory * separator. Also such broken archives don't have entries that * are just directories. Everything is a file. See the example * * Archive: backSlashTest.zip * testing: testDirectory\testfileInTestDirectory.txt OK * testing: testDirectory\testSubdirectory\testFileInTestSubdirectory.txt OK * No errors detected in compressed data of backSlashTest.zip. */ if (name.indexOf('\\') != -1) { File parentDirectory = outputDir; String[] dirs = name.split("\\\\"); // lets create all the directories and the last entry is the file as EVERY entry is a file for (int i = 0; i < dirs.length - 1; i++) { File file = new File(parentDirectory, dirs[i]); if (!file.exists()) { FileUtils.forceMkdir(file); } parentDirectory = file; } File destFile = new File(parentDirectory, dirs[dirs.length - 1]); FileUtils.copy(in, destFile); } // it could be that there are just top level files that the unpacker is used for else { File destFile = new File(outputDir, name); FileUtils.copy(in, destFile); } } } } /** * Unwraps entries excluding a single parent dir. If there are multiple roots * ZipException is thrown. * * @author Oleg Shelajev */ private static class Unwraper implements ZipEntryCallback { private final File outputDir; private final NameMapper mapper; private String rootDir; public Unwraper(File outputDir, NameMapper mapper) { this.outputDir = outputDir; this.mapper = mapper; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { String root = getRootName(zipEntry.getName()); if (rootDir == null) { rootDir = root; } else if (!rootDir.equals(root)) { throw new ZipException("Unwrapping with multiple roots is not supported, roots: " + rootDir + ", " + root); } String name = mapper.map(getUnrootedName(root, zipEntry.getName())); if (name != null) { File file = new File(outputDir, name); if (zipEntry.isDirectory()) { FileUtils.forceMkdir(file); } else { FileUtils.forceMkdir(file.getParentFile()); if (log.isDebugEnabled() && file.exists()) { log.debug("Overwriting file '{}'.", zipEntry.getName()); } FileUtils.copy(in, file); } } } private String getUnrootedName(String root, String name) { return name.substring(root.length()); } private String getRootName(final String name) { String newName = name.substring(FilenameUtils.getPrefixLength(name)); int idx = newName.indexOf(PATH_SEPARATOR); if (idx < 0) { throw new ZipException("Entry " + newName + " from the root of the zip is not supported"); } return newName.substring(0, newName.indexOf(PATH_SEPARATOR)); } } /** * Unpacks a ZIP file to its own location. * <p> * The ZIP file will be first renamed (using a temporary name). After the * extraction it will be deleted. * * @param zip * input ZIP file as well as the target directory. * * @see #unpack(File, File) */ public static void explode(File zip) { try { // Find a new unique name is the same directory File tempFile = FileUtils.getTempFileFor(zip); // Rename the archive FileUtils.moveFile(zip, tempFile); // Unpack it unpack(tempFile, zip); // Delete the archive if (!tempFile.delete()) { throw new IOException("Unable to delete file: " + tempFile); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /* Compressing single entries to ZIP files. */ /** * Compresses the given file into a ZIP file with single entry. * * @param file file to be compressed. * @return ZIP file created. */ public static byte[] packEntry(File file) { log.trace("Compressing '{}' into a ZIP file with single entry.", file); ByteArrayOutputStream result = new ByteArrayOutputStream(); try { ZipOutputStream out = new ZipOutputStream(result); ZipEntry entry = ZipEntryUtil.fromFile(file.getName(), file); InputStream in = new BufferedInputStream(new FileInputStream(file)); try { ZipEntryUtil.addEntry(entry, in, out); } finally { IOUtils.closeQuietly(in); } out.close(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } return result.toByteArray(); } /* Compressing ZIP files. */ /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * Will not include the root directory name in the archive. * * @param rootDir * root directory. * @param zip * ZIP file that will be created or overwritten. */ public static void pack(File rootDir, File zip) { pack(rootDir, zip, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * Will not include the root directory name in the archive. * * @param rootDir * root directory. * @param zip * ZIP file that will be created or overwritten. * @param compressionLevel * compression level */ public static void pack(File rootDir, File zip, int compressionLevel) { pack(rootDir, zip, IdentityNameMapper.INSTANCE, compressionLevel); } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * Will not include the root directory name in the archive. * * @param sourceDir * root directory. * @param targetZipFile * ZIP file that will be created or overwritten. * @param preserveRoot * true if the resulted archive should have the top directory entry */ public static void pack(final File sourceDir, final File targetZipFile, final boolean preserveRoot) { if (preserveRoot) { final String parentName = sourceDir.getName(); pack(sourceDir, targetZipFile, new NameMapper() { public String map(String name) { return parentName + PATH_SEPARATOR + name; } }); } else { pack(sourceDir, targetZipFile); } } /** * Compresses the given file into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param fileToPack * file that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. */ public static void packEntry(File fileToPack, File destZipFile) { packEntry(fileToPack, destZipFile, IdentityNameMapper.INSTANCE); } /** * Compresses the given file into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param fileToPack * file that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param fileName * the name for the file inside the archive */ public static void packEntry(File fileToPack, File destZipFile, final String fileName) { packEntry(fileToPack, destZipFile, new NameMapper() { public String map(String name) { return fileName; } }); } /** * Compresses the given file into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param fileToPack * file that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. */ public static void packEntry(File fileToPack, File destZipFile, NameMapper mapper) { packEntries(new File[] { fileToPack }, destZipFile, mapper); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. */ public static void packEntries(File[] filesToPack, File destZipFile) { packEntries(filesToPack, destZipFile, IdentityNameMapper.INSTANCE); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. */ public static void packEntries(File[] filesToPack, File destZipFile, NameMapper mapper) { packEntries(filesToPack, destZipFile, mapper, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param compressionLevel * ZIP file compression level (speed versus filesize), e.g. <code>Deflater.NO_COMPRESSION</code>, <code>Deflater.BEST_SPEED</code>, or * <code>Deflater.BEST_COMPRESSION</code> */ public static void packEntries(File[] filesToPack, File destZipFile, int compressionLevel) { packEntries(filesToPack, destZipFile, IdentityNameMapper.INSTANCE, compressionLevel); } /** * Compresses the given files into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param filesToPack * files that needs to be zipped. * @param destZipFile * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. * @param compressionLevel * ZIP file compression level (speed versus filesize), e.g. <code>Deflater.NO_COMPRESSION</code>, <code>Deflater.BEST_SPEED</code>, or * <code>Deflater.BEST_COMPRESSION</code> */ public static void packEntries(File[] filesToPack, File destZipFile, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into '{}'.", filesToPack, destZipFile); ZipOutputStream out = null; FileOutputStream fos = null; try { fos = new FileOutputStream(destZipFile); out = new ZipOutputStream(new BufferedOutputStream(fos)); out.setLevel(compressionLevel); for (int i = 0; i < filesToPack.length; i++) { File fileToPack = filesToPack[i]; ZipEntry zipEntry = ZipEntryUtil.fromFile(mapper.map(fileToPack.getName()), fileToPack); out.putNextEntry(zipEntry); FileUtils.copy(fileToPack, out); out.closeEntry(); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fos); } } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param sourceDir * root directory. * @param targetZip * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. */ public static void pack(File sourceDir, File targetZip, NameMapper mapper) { pack(sourceDir, targetZip, mapper, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all its sub-directories into a ZIP file. * <p> * The ZIP file must not be a directory and its parent directory must exist. * * @param sourceDir * root directory. * @param targetZip * ZIP file that will be created or overwritten. * @param mapper * call-back for renaming the entries. * @param compressionLevel * compression level */ public static void pack(File sourceDir, File targetZip, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into '{}'.", sourceDir, targetZip); if (!sourceDir.exists()) { throw new ZipException("Given file '" + sourceDir + "' doesn't exist!"); } ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetZip))); out.setLevel(compressionLevel); pack(sourceDir, out, mapper, "", true); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os) { pack(sourceDir, os, IdentityNameMapper.INSTANCE, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * @param compressionLevel * compression level * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os, int compressionLevel) { pack(sourceDir, os, IdentityNameMapper.INSTANCE, compressionLevel); } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * @param mapper * call-back for renaming the entries. * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os, NameMapper mapper) { pack(sourceDir, os, mapper, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses the given directory and all of its sub-directories into the passed in * stream. It is the responsibility of the caller to close the passed in * stream properly. * * @param sourceDir * root directory. * @param os * output stream (will be buffered in this method). * @param mapper * call-back for renaming the entries. * @param compressionLevel * compression level * * @since 1.10 */ public static void pack(File sourceDir, OutputStream os, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into a stream.", sourceDir); if (!sourceDir.exists()) { throw new ZipException("Given file '" + sourceDir + "' doesn't exist!"); } ZipOutputStream out = null; IOException error = null; try { out = new ZipOutputStream(new BufferedOutputStream(os)); out.setLevel(compressionLevel); pack(sourceDir, out, mapper, "", true); } catch (IOException e) { error = e; } finally { if (out != null && error == null) { try { out.finish(); out.flush(); } catch (IOException e) { error = e; } } } if (error != null) { throw ZipExceptionUtil.rethrow(error); } } /** * Compresses the given directory and all its sub-directories into a ZIP file. * * @param dir * root directory. * @param out * ZIP output stream. * @param mapper * call-back for renaming the entries. * @param pathPrefix * prefix to be used for the entries. * @param mustHaveChildren * if true, but directory to pack doesn't have any files, throw an exception. */ private static void pack(File dir, ZipOutputStream out, NameMapper mapper, String pathPrefix, boolean mustHaveChildren) throws IOException { String[] filenames = dir.list(); if (filenames == null) { if (!dir.exists()) { throw new ZipException("Given file '" + dir + "' doesn't exist!"); } throw new IOException("Given file is not a directory '" + dir + "'"); } if (mustHaveChildren && filenames.length == 0) { throw new ZipException("Given directory '" + dir + "' doesn't contain any files!"); } for (int i = 0; i < filenames.length; i++) { String filename = filenames[i]; File file = new File(dir, filename); boolean isDir = file.isDirectory(); String path = pathPrefix + file.getName(); // NOSONAR if (isDir) { path += PATH_SEPARATOR; // NOSONAR } // Create a ZIP entry String name = mapper.map(path); if (name != null) { ZipEntry zipEntry = ZipEntryUtil.fromFile(name, file); out.putNextEntry(zipEntry); // Copy the file content if (!isDir) { FileUtils.copy(file, out); } out.closeEntry(); } // Traverse the directory if (isDir) { pack(file, out, mapper, path, false); } } } /** * Repacks a provided ZIP file into a new ZIP with a given compression level. * <p> * * @param srcZip * source ZIP file. * @param dstZip * destination ZIP file. * @param compressionLevel * compression level. */ public static void repack(File srcZip, File dstZip, int compressionLevel) { log.debug("Repacking '{}' into '{}'.", srcZip, dstZip); RepackZipEntryCallback callback = new RepackZipEntryCallback(dstZip, compressionLevel); try { iterate(srcZip, callback); } finally { callback.closeStream(); } } /** * Repacks a provided ZIP input stream into a ZIP file with a given compression level. * <p> * * @param is * ZIP input stream. * @param dstZip * destination ZIP file. * @param compressionLevel * compression level. */ public static void repack(InputStream is, File dstZip, int compressionLevel) { log.debug("Repacking from input stream into '{}'.", dstZip); RepackZipEntryCallback callback = new RepackZipEntryCallback(dstZip, compressionLevel); try { iterate(is, callback); } finally { callback.closeStream(); } } /** * Repacks a provided ZIP file and replaces old file with the new one. * <p> * * @param zip * source ZIP file to be repacked and replaced. * @param compressionLevel * compression level. */ public static void repack(File zip, int compressionLevel) { try { File tmpZip = FileUtils.getTempFileFor(zip); repack(zip, tmpZip, compressionLevel); // Delete original zip if (!zip.delete()) { throw new IOException("Unable to delete the file: " + zip); } // Rename the archive FileUtils.moveFile(tmpZip, zip); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * RepackZipEntryCallback used in repacking methods. * * @author Pavel Grigorenko */ private static final class RepackZipEntryCallback implements ZipEntryCallback { private ZipOutputStream out; private RepackZipEntryCallback(File dstZip, int compressionLevel) { try { this.out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(dstZip))); this.out.setLevel(compressionLevel); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } public void process(InputStream in, ZipEntry zipEntry) throws IOException { ZipEntryUtil.copyEntry(zipEntry, in, out); } private void closeStream() { IOUtils.closeQuietly(out); } } /** * Compresses a given directory in its own location. * <p> * A ZIP file will be first created with a temporary name. After the * compressing the directory will be deleted and the ZIP file will be renamed * as the original directory. * * @param dir * input directory as well as the target ZIP file. * * @see #pack(File, File) */ public static void unexplode(File dir) { unexplode(dir, DEFAULT_COMPRESSION_LEVEL); } /** * Compresses a given directory in its own location. * <p> * A ZIP file will be first created with a temporary name. After the * compressing the directory will be deleted and the ZIP file will be renamed * as the original directory. * * @param dir * input directory as well as the target ZIP file. * @param compressionLevel * compression level * * @see #pack(File, File) */ public static void unexplode(File dir, int compressionLevel) { try { // Find a new unique name is the same directory File zip = FileUtils.getTempFileFor(dir); // Pack it pack(dir, zip, compressionLevel); // Delete the directory FileUtils.deleteDirectory(dir); // Rename the archive FileUtils.moveFile(zip, dir); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Compresses the given entries into an output stream. * * @param entries * ZIP entries added. * @param os * output stream for the new ZIP (does not have to be buffered) * * @since 1.9 */ public static void pack(ZipEntrySource[] entries, OutputStream os) { if (log.isDebugEnabled()) { log.debug("Creating stream from {}.", Arrays.asList(entries)); } pack(entries, os, false); } private static void pack(ZipEntrySource[] entries, OutputStream os, boolean closeStream) { try { ZipOutputStream out = new ZipOutputStream(os); for (int i = 0; i < entries.length; i++) { addEntry(entries[i], out); } out.flush(); out.finish(); if (closeStream) { out.close(); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Compresses the given entries into a new ZIP file. * * @param entries * ZIP entries added. * @param zip * new ZIP file created. */ public static void pack(ZipEntrySource[] entries, File zip) { if (log.isDebugEnabled()) { log.debug("Creating '{}' from {}.", zip, Arrays.asList(entries)); } OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(zip)); pack(entries, out, true); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param file * new entry to be added. * @param destZip * new ZIP file created. */ public static void addEntry(File zip, String path, File file, File destZip) { addEntry(zip, new FileSource(path, file), destZip); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param file * new entry to be added. */ public static void addEntry(final File zip, final String path, final File file) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, path, file, tmpFile); return true; } }); } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param destZip * new ZIP file created. */ public static void addEntry(File zip, String path, byte[] bytes, File destZip) { addEntry(zip, new ByteSource(path, bytes), destZip); } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param destZip * new ZIP file created. * @param compressionMethod * the new compression method (<code>ZipEntry.STORED</code> or <code>ZipEntry.DEFLATED</code>). */ public static void addEntry(File zip, String path, byte[] bytes, File destZip, final int compressionMethod) { addEntry(zip, new ByteSource(path, bytes, compressionMethod), destZip); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). */ public static void addEntry(final File zip, final String path, final byte[] bytes) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, path, bytes, tmpFile); return true; } }); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param compressionMethod * the new compression method (<code>ZipEntry.STORED</code> or <code>ZipEntry.DEFLATED</code>). */ public static void addEntry(final File zip, final String path, final byte[] bytes, final int compressionMethod) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, path, bytes, tmpFile, compressionMethod); return true; } }); } /** * Copies an existing ZIP file and appends it with one new entry. * * @param zip * an existing ZIP file (only read). * @param entry * new ZIP entry appended. * @param destZip * new ZIP file created. */ public static void addEntry(File zip, ZipEntrySource entry, File destZip) { addEntries(zip, new ZipEntrySource[] { entry }, destZip); } /** * Changes a zip file, adds one new entry in-place. * * @param zip * an existing ZIP file (only read). * @param entry * new ZIP entry appended. */ public static void addEntry(final File zip, final ZipEntrySource entry) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntry(zip, entry, tmpFile); return true; } }); } /** * Copies an existing ZIP file and appends it with new entries. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries appended. * @param destZip * new ZIP file created. */ public static void addEntries(File zip, ZipEntrySource[] entries, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and adding " + Arrays.asList(entries) + "."); } OutputStream destOut = null; try { destOut = new BufferedOutputStream(new FileOutputStream(destZip)); addEntries(zip, entries, destOut); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(destOut); } } /** * Copies an existing ZIP file and appends it with new entries. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries appended. * @param destOut * new ZIP destination output stream */ public static void addEntries(File zip, ZipEntrySource[] entries, OutputStream destOut) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to a stream and adding " + Arrays.asList(entries) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(destOut); copyEntries(zip, out); for (int i = 0; i < entries.length; i++) { addEntry(entries[i], out); } out.finish(); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } /** * Copies an existing ZIP file and appends it with new entries. * * @param is * an existing ZIP input stream. * @param entries * new ZIP entries appended. * @param destOut * new ZIP destination output stream * * @since 1.9 */ public static void addEntries(InputStream is, ZipEntrySource[] entries, OutputStream destOut) { if (log.isDebugEnabled()) { log.debug("Copying input stream to an output stream and adding " + Arrays.asList(entries) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(destOut); copyEntries(is, out); for (int i = 0; i < entries.length; i++) { addEntry(entries[i], out); } out.finish(); } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } /** * Changes a zip file it with with new entries. in-place. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries appended. */ public static void addEntries(final File zip, final ZipEntrySource[] entries) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addEntries(zip, entries, tmpFile); return true; } }); } /** * Copies an existing ZIP file and removes entry with a given path. * * @param zip * an existing ZIP file (only read) * @param path * path of the entry to remove * @param destZip * new ZIP file created. * @since 1.7 */ public static void removeEntry(File zip, String path, File destZip) { removeEntries(zip, new String[] { path }, destZip); } /** * Changes an existing ZIP file: removes entry with a given path. * * @param zip * an existing ZIP file * @param path * path of the entry to remove * @since 1.7 */ public static void removeEntry(final File zip, final String path) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { removeEntry(zip, path, tmpFile); return true; } }); } /** * Copies an existing ZIP file and removes entries with given paths. * * @param zip * an existing ZIP file (only read) * @param paths * paths of the entries to remove * @param destZip * new ZIP file created. * @since 1.7 */ public static void removeEntries(File zip, String[] paths, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and removing paths " + Arrays.asList(paths) + "."); } ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); copyEntries(zip, out, new HashSet<String>(Arrays.asList(paths))); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { IOUtils.closeQuietly(out); } } /** * Changes an existing ZIP file: removes entries with given paths. * * @param zip * an existing ZIP file * @param paths * paths of the entries to remove * @since 1.7 */ public static void removeEntries(final File zip, final String[] paths) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { removeEntries(zip, paths, tmpFile); return true; } }); } /** * Copies all entries from one ZIP file to another. * * @param zip * source ZIP file. * @param out * target ZIP stream. */ private static void copyEntries(File zip, final ZipOutputStream out) { // this one doesn't call copyEntries with ignoredEntries, because that has poorer performance final Set<String> names = new HashSet<String>(); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { String entryName = zipEntry.getName(); if (names.add(entryName)) { ZipEntryUtil.copyEntry(zipEntry, in, out); } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", entryName); } } }); } /** * Copies all entries from one ZIP stream to another. * * @param is * source stream (contains ZIP file). * @param out * target ZIP stream. */ private static void copyEntries(InputStream is, final ZipOutputStream out) { // this one doesn't call copyEntries with ignoredEntries, because that has poorer performance final Set<String> names = new HashSet<String>(); iterate(is, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { String entryName = zipEntry.getName(); if (names.add(entryName)) { ZipEntryUtil.copyEntry(zipEntry, in, out); } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", entryName); } } }); } /** * Copies all entries from one ZIP file to another, ignoring entries with path in ignoredEntries * * @param zip * source ZIP file. * @param out * target ZIP stream. * @param ignoredEntries * paths of entries not to copy */ private static void copyEntries(File zip, final ZipOutputStream out, final Set<String> ignoredEntries) { final Set<String> names = new HashSet<String>(); final Set<String> dirNames = filterDirEntries(zip, ignoredEntries); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { String entryName = zipEntry.getName(); if (ignoredEntries.contains(entryName)) { return; } for (String dirName : dirNames) { if (entryName.startsWith(dirName)) { return; } } if (names.add(entryName)) { ZipEntryUtil.copyEntry(zipEntry, in, out); } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", entryName); } } }); } /** * * @param zip * zip file to traverse * @param names * names of entries to filter dirs from * @return Set<String> names of entries that are dirs. * */ static Set<String> filterDirEntries(File zip, Collection<String> names) { Set<String> dirs = new HashSet<String>(); if (zip == null) { return dirs; } ZipFile zf = null; try { zf = new ZipFile(zip); for (String entryName : names) { ZipEntry entry = zf.getEntry(entryName); if (entry != null) { if (entry.isDirectory()) { dirs.add(entry.getName()); } else if (zf.getInputStream(entry) == null) { // no input stream means that this is a dir. dirs.add(entry.getName() + PATH_SEPARATOR); } } } } catch (IOException e) { ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf); } return dirs; } /** * Copies an existing ZIP file and replaces a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param file * new entry. * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(File zip, String path, File file, File destZip) { return replaceEntry(zip, new FileSource(path, file), destZip); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param path * new ZIP entry path. * @param file * new entry. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final String path, final File file) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, new FileSource(path, file), tmpFile); } }); } /** * Copies an existing ZIP file and replaces a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(File zip, String path, byte[] bytes, File destZip) { return replaceEntry(zip, new ByteSource(path, bytes), destZip); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final String path, final byte[] bytes) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, new ByteSource(path, bytes), tmpFile); } }); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param path * new ZIP entry path. * @param bytes * new entry bytes (or <code>null</code> if directory). * @param compressionMethod * the new compression method (<code>ZipEntry.STORED</code> or <code>ZipEntry.DEFLATED</code>). * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final String path, final byte[] bytes, final int compressionMethod) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, new ByteSource(path, bytes, compressionMethod), tmpFile); } }); } /** * Copies an existing ZIP file and replaces a given entry in it. * * @param zip * an existing ZIP file (only read). * @param entry * new ZIP entry. * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(File zip, ZipEntrySource entry, File destZip) { return replaceEntries(zip, new ZipEntrySource[] { entry }, destZip); } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param entry * new ZIP entry. * @return <code>true</code> if the entry was replaced. */ public static boolean replaceEntry(final File zip, final ZipEntrySource entry) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntry(zip, entry, tmpFile); } }); } /** * Copies an existing ZIP file and replaces the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * new ZIP entries to be replaced with. * @param destZip * new ZIP file created. * @return <code>true</code> if at least one entry was replaced. */ public static boolean replaceEntries(File zip, ZipEntrySource[] entries, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and replacing entries " + Arrays.asList(entries) + "."); } final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries); final int entryCount = entryByPath.size(); try { final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); try { final Set<String> names = new HashSet<String>(); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (names.add(zipEntry.getName())) { ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName()); if (entry != null) { addEntry(entry, out); } else { ZipEntryUtil.copyEntry(zipEntry, in, out); } } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", zipEntry.getName()); } } }); } finally { IOUtils.closeQuietly(out); } } catch (IOException e) { ZipExceptionUtil.rethrow(e); } return entryByPath.size() < entryCount; } /** * Changes an existing ZIP file: replaces a given entry in it. * * @param zip * an existing ZIP file. * @param entries * new ZIP entries to be replaced with. * @return <code>true</code> if at least one entry was replaced. */ public static boolean replaceEntries(final File zip, final ZipEntrySource[] entries) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return replaceEntries(zip, entries, tmpFile); } }); } /** * Copies an existing ZIP file and adds/replaces the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entries to be replaced or added. * @param destZip * new ZIP file created. */ public static void addOrReplaceEntries(File zip, ZipEntrySource[] entries, File destZip) { if (log.isDebugEnabled()) { log.debug("Copying '" + zip + "' to '" + destZip + "' and adding/replacing entries " + Arrays.asList(entries) + "."); } final Map<String, ZipEntrySource> entryByPath = entriesByPath(entries); try { final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); try { // Copy and replace entries final Set<String> names = new HashSet<String>(); iterate(zip, new ZipEntryCallback() { public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (names.add(zipEntry.getName())) { ZipEntrySource entry = (ZipEntrySource) entryByPath.remove(zipEntry.getName()); if (entry != null) { addEntry(entry, out); } else { ZipEntryUtil.copyEntry(zipEntry, in, out); } } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", zipEntry.getName()); } } }); // Add new entries for (ZipEntrySource zipEntrySource : entryByPath.values()) { addEntry(zipEntrySource, out); } } finally { IOUtils.closeQuietly(out); } } catch (IOException e) { ZipExceptionUtil.rethrow(e); } } /** * Changes a ZIP file: adds/replaces the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entries to be replaced or added. */ public static void addOrReplaceEntries(final File zip, final ZipEntrySource[] entries) { operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { addOrReplaceEntries(zip, entries, tmpFile); return true; } }); } /** * @return given entries indexed by path. */ static Map<String, ZipEntrySource> entriesByPath(ZipEntrySource... entries) { Map<String, ZipEntrySource> result = new HashMap<String, ZipEntrySource>(); for (int i = 0; i < entries.length; i++) { ZipEntrySource source = entries[i]; result.put(source.getPath(), source); } return result; } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param transformer * transformer for the given ZIP entry. * @param destZip * new ZIP file created. * @throws IllegalArgumentException if the destination is the same as the location * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(File zip, String path, ZipEntryTransformer transformer, File destZip) { if(zip.equals(destZip)){throw new IllegalArgumentException("Input (" +zip.getAbsolutePath()+ ") is the same as the destination!" + "Please use the transformEntry method without destination for in-place transformation." );} return transformEntry(zip, new ZipEntryTransformerEntry(path, transformer), destZip); } /** * Changes an existing ZIP file: transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param path * new ZIP entry path. * @param transformer * transformer for the given ZIP entry. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(final File zip, final String path, final ZipEntryTransformer transformer) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return transformEntry(zip, path, transformer, tmpFile); } }); } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param entry * transformer for a ZIP entry. * @param destZip * new ZIP file created. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(File zip, ZipEntryTransformerEntry entry, File destZip) { return transformEntries(zip, new ZipEntryTransformerEntry[] { entry }, destZip); } /** * Changes an existing ZIP file: transforms a given entry in it. * * @param zip * an existing ZIP file (only read). * @param entry * transformer for a ZIP entry. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(final File zip, final ZipEntryTransformerEntry entry) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return transformEntry(zip, entry, tmpFile); } }); } /** * Copies an existing ZIP file and transforms the given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entry transformers. * @param destZip * new ZIP file created. * @return <code>true</code> if at least one entry was replaced. */ public static boolean transformEntries(File zip, ZipEntryTransformerEntry[] entries, File destZip) { if (log.isDebugEnabled()) log.debug("Copying '" + zip + "' to '" + destZip + "' and transforming entries " + Arrays.asList(entries) + "."); try { ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destZip))); try { TransformerZipEntryCallback action = new TransformerZipEntryCallback(Arrays.asList(entries), out); iterate(zip, action); return action.found(); } finally { IOUtils.closeQuietly(out); } } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Changes an existing ZIP file: transforms a given entries in it. * * @param zip * an existing ZIP file (only read). * @param entries * ZIP entry transformers. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntries(final File zip, final ZipEntryTransformerEntry[] entries) { return operateInPlace(zip, new InPlaceAction() { public boolean act(File tmpFile) { return transformEntries(zip, entries, tmpFile); } }); } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param is * a ZIP input stream. * @param path * new ZIP entry path. * @param transformer * transformer for the given ZIP entry. * @param os * a ZIP output stream. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(InputStream is, String path, ZipEntryTransformer transformer, OutputStream os) { return transformEntry(is, new ZipEntryTransformerEntry(path, transformer), os); } /** * Copies an existing ZIP file and transforms a given entry in it. * * @param is * a ZIP input stream. * @param entry * transformer for a ZIP entry. * @param os * a ZIP output stream. * @return <code>true</code> if the entry was replaced. */ public static boolean transformEntry(InputStream is, ZipEntryTransformerEntry entry, OutputStream os) { return transformEntries(is, new ZipEntryTransformerEntry[] { entry }, os); } /** * Copies an existing ZIP file and transforms the given entries in it. * * @param is * a ZIP input stream. * @param entries * ZIP entry transformers. * @param os * a ZIP output stream. * @return <code>true</code> if at least one entry was replaced. */ public static boolean transformEntries(InputStream is, ZipEntryTransformerEntry[] entries, OutputStream os) { if (log.isDebugEnabled()) log.debug("Copying '" + is + "' to '" + os + "' and transforming entries " + Arrays.asList(entries) + "."); try { ZipOutputStream out = new ZipOutputStream(os); TransformerZipEntryCallback action = new TransformerZipEntryCallback(Arrays.asList(entries), out); iterate(is, action); // Finishes writing the contents of the ZIP output stream without closing // the underlying stream. out.finish(); return action.found(); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } private static class TransformerZipEntryCallback implements ZipEntryCallback { private final Map<String, ZipEntryTransformer> entryByPath; private final int entryCount; private final ZipOutputStream out; private final Set<String> names = new HashSet<String>(); public TransformerZipEntryCallback(List<ZipEntryTransformerEntry> entries, ZipOutputStream out) { entryByPath = transformersByPath(entries); entryCount = entryByPath.size(); this.out = out; } public void process(InputStream in, ZipEntry zipEntry) throws IOException { if (names.add(zipEntry.getName())) { ZipEntryTransformer entry = (ZipEntryTransformer) entryByPath.remove(zipEntry.getName()); if (entry != null) { entry.transform(in, zipEntry, out); } else { ZipEntryUtil.copyEntry(zipEntry, in, out); } } else if (log.isDebugEnabled()) { log.debug("Duplicate entry: {}", zipEntry.getName()); } } /** * @return <code>true</code> if at least one entry was replaced. */ public boolean found() { return entryByPath.size() < entryCount; } } /** * @return transformers by path. */ static Map<String, ZipEntryTransformer> transformersByPath(List<ZipEntryTransformerEntry> entries) { Map<String, ZipEntryTransformer> result = new HashMap<String, ZipEntryTransformer>(); for (ZipEntryTransformerEntry entry : entries) { result.put(entry.getPath(), entry.getTransformer()); } return result; } /** * Adds a given ZIP entry to a ZIP file. * * @param entry * new ZIP entry. * @param out * target ZIP stream. */ private static void addEntry(ZipEntrySource entry, ZipOutputStream out) throws IOException { out.putNextEntry(entry.getEntry()); InputStream in = entry.getInputStream(); if (in != null) { try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } } out.closeEntry(); } /* Comparing two ZIP files. */ /** * Compares two ZIP files and returns <code>true</code> if they contain same * entries. * <p> * First the two files are compared byte-by-byte. If a difference is found the * corresponding entries of both ZIP files are compared. Thus if same contents * is packed differently the two archives may still be the same. * </p> * <p> * Two archives are considered the same if * <ol> * <li>they contain same number of entries,</li> * <li>for each entry in the first archive there exists an entry with the same * in the second archive</li> * <li>for each entry in the first archive and the entry with the same name in * the second archive * <ol> * <li>both are either directories or files,</li> * <li>both have the same size,</li> * <li>both have the same CRC,</li> * <li>both have the same contents (compared byte-by-byte).</li> * </ol> * </li> * </ol> * * @param f1 * first ZIP file. * @param f2 * second ZIP file. * @return <code>true</code> if the two ZIP files contain same entries, * <code>false</code> if a difference was found or an error occurred * during the comparison. */ public static boolean archiveEquals(File f1, File f2) { try { // Check the files byte-by-byte if (FileUtils.contentEquals(f1, f2)) { return true; } log.debug("Comparing archives '{}' and '{}'...", f1, f2); long start = System.currentTimeMillis(); boolean result = archiveEqualsInternal(f1, f2); long time = System.currentTimeMillis() - start; if (time > 0) { log.debug("Archives compared in " + time + " ms."); } return result; } catch (Exception e) { log.debug("Could not compare '" + f1 + "' and '" + f2 + "':", e); return false; } } private static boolean archiveEqualsInternal(File f1, File f2) throws IOException { ZipFile zf1 = null; ZipFile zf2 = null; try { zf1 = new ZipFile(f1); zf2 = new ZipFile(f2); // Check the number of entries if (zf1.size() != zf2.size()) { log.debug("Number of entries changed (" + zf1.size() + " vs " + zf2.size() + ")."); return false; } /* * As there are same number of entries in both archives we can traverse * all entries of one of the archives and get the corresponding entries * from the other archive. * * If a corresponding entry is missing from the second archive the * archives are different and we finish the comparison. * * We guarantee that no entry of the second archive is skipped as there * are same number of unique entries in both archives. */ Enumeration<? extends ZipEntry> en = zf1.entries(); while (en.hasMoreElements()) { ZipEntry e1 = (ZipEntry) en.nextElement(); String path = e1.getName(); ZipEntry e2 = zf2.getEntry(path); // Check meta data if (!metaDataEquals(path, e1, e2)) { return false; } // Check the content InputStream is1 = null; InputStream is2 = null; try { is1 = zf1.getInputStream(e1); is2 = zf2.getInputStream(e2); if (!IOUtils.contentEquals(is1, is2)) { log.debug("Entry '{}' content changed.", path); return false; } } finally { IOUtils.closeQuietly(is1); IOUtils.closeQuietly(is2); } } } finally { closeQuietly(zf1); closeQuietly(zf2); } log.debug("Archives are the same."); return true; } /** * Compares meta-data of two ZIP entries. * <p> * Two entries are considered the same if * <ol> * <li>both entries exist,</li> * <li>both entries are either directories or files,</li> * <li>both entries have the same size,</li> * <li>both entries have the same CRC.</li> * </ol> * * @param path * name of the entries. * @param e1 * first entry (required). * @param e2 * second entry (may be <code>null</code>). * @return <code>true</code> if no difference was found. */ private static boolean metaDataEquals(String path, ZipEntry e1, ZipEntry e2) throws IOException { // Check if the same entry exists in the second archive if (e2 == null) { log.debug("Entry '{}' removed.", path); return false; } // Check the directory flag if (e1.isDirectory()) { if (e2.isDirectory()) { return true; // Let's skip the directory as there is nothing to compare } else { log.debug("Entry '{}' not a directory any more.", path); return false; } } else if (e2.isDirectory()) { log.debug("Entry '{}' now a directory.", path); return false; } // Check the size long size1 = e1.getSize(); long size2 = e2.getSize(); if (size1 != -1 && size2 != -1 && size1 != size2) { log.debug("Entry '" + path + "' size changed (" + size1 + " vs " + size2 + ")."); return false; } // Check the CRC long crc1 = e1.getCrc(); long crc2 = e2.getCrc(); if (crc1 != -1 && crc2 != -1 && crc1 != crc2) { log.debug("Entry '" + path + "' CRC changed (" + crc1 + " vs " + crc2 + ")."); return false; } // Check the time (ignored, logging only) if (log.isTraceEnabled()) { long time1 = e1.getTime(); long time2 = e2.getTime(); if (time1 != -1 && time2 != -1 && time1 != time2) { log.trace("Entry '" + path + "' time changed (" + new Date(time1) + " vs " + new Date(time2) + ")."); } } return true; } /** * Compares same entry in two ZIP files (byte-by-byte). * * @param f1 * first ZIP file. * @param f2 * second ZIP file. * @param path * name of the entry. * @return <code>true</code> if the contents of the entry was same in both ZIP * files. */ public static boolean entryEquals(File f1, File f2, String path) { return entryEquals(f1, f2, path, path); } /** * Compares two ZIP entries (byte-by-byte). . * * @param f1 * first ZIP file. * @param f2 * second ZIP file. * @param path1 * name of the first entry. * @param path2 * name of the second entry. * @return <code>true</code> if the contents of the entries were same. */ public static boolean entryEquals(File f1, File f2, String path1, String path2) { ZipFile zf1 = null; ZipFile zf2 = null; try { zf1 = new ZipFile(f1); zf2 = new ZipFile(f2); return doEntryEquals(zf1, zf2, path1, path2); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { closeQuietly(zf1); closeQuietly(zf2); } } /** * Compares two ZIP entries (byte-by-byte). . * * @param zf1 * first ZIP file. * @param zf2 * second ZIP file. * @param path1 * name of the first entry. * @param path2 * name of the second entry. * @return <code>true</code> if the contents of the entries were same. */ public static boolean entryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) { try { return doEntryEquals(zf1, zf2, path1, path2); } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } } /** * Compares two ZIP entries (byte-by-byte). . * * @param zf1 * first ZIP file. * @param zf2 * second ZIP file. * @param path1 * name of the first entry. * @param path2 * name of the second entry. * @return <code>true</code> if the contents of the entries were same. */ private static boolean doEntryEquals(ZipFile zf1, ZipFile zf2, String path1, String path2) throws IOException { InputStream is1 = null; InputStream is2 = null; try { ZipEntry e1 = zf1.getEntry(path1); ZipEntry e2 = zf2.getEntry(path2); if (e1 == null && e2 == null) { return true; } if (e1 == null || e2 == null) { return false; } is1 = zf1.getInputStream(e1); is2 = zf2.getInputStream(e2); if (is1 == null && is2 == null) { return true; } if (is1 == null || is2 == null) { return false; } return IOUtils.contentEquals(is1, is2); } finally { IOUtils.closeQuietly(is1); IOUtils.closeQuietly(is2); } } /** * Closes the ZIP file while ignoring any errors. * * @param zf * ZIP file to be closed. */ public static void closeQuietly(ZipFile zf) { try { if (zf != null) { zf.close(); } } catch (IOException e) { } } /** * Simple helper to make inplace operation easier * * @author shelajev */ private abstract static class InPlaceAction { /** * @return true if something has been changed during the action. */ abstract boolean act(File tmpFile); } /** * * This method provides a general infrastructure for in-place operations. * It creates temp file as a destination, then invokes the action on source and destination. * Then it copies the result back into src file. * * @param src - source zip file we want to modify * @param action - action which actually modifies the archives * * @return result of the action */ private static boolean operateInPlace(File src, InPlaceAction action) { File tmp = null; try { tmp = File.createTempFile("zt-zip-tmp", ".zip"); boolean result = action.act(tmp); if (result) { // else nothing changes FileUtils.forceDelete(src); FileUtils.moveFile(tmp, src); } return result; } catch (IOException e) { throw ZipExceptionUtil.rethrow(e); } finally { FileUtils.deleteQuietly(tmp); } } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_68_0
crossvul-java_data_good_4612_5
package org.jooby.issues; import org.jooby.test.ServerFeature; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertTrue; public class Issue1639 extends ServerFeature { { Path dir = Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "assets"); assertTrue(Files.exists(dir)); assets("/static/**", dir); } @Test public void shouldNotFallbackToArbitraryClasspathResources() throws Exception { request() .get("/static/WEB-INF/web2.xml") .expect(404); request() .get("/static/../WEB-INF/web2.xml") .expect(404); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4612_5
crossvul-java_data_bad_4612_0
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 Edgar Espina * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooby; import com.google.common.base.Joiner; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.escape.Escaper; import com.google.common.html.HtmlEscapers; import com.google.common.net.UrlEscapers; import com.google.common.util.concurrent.MoreExecutors; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.Stage; import com.google.inject.TypeLiteral; import com.google.inject.internal.ProviderMethodsModule; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.google.inject.util.Types; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import static com.typesafe.config.ConfigValueFactory.fromAnyRef; import static java.util.Objects.requireNonNull; import static org.jooby.Route.CONNECT; import static org.jooby.Route.DELETE; import org.jooby.Route.Definition; import static org.jooby.Route.GET; import static org.jooby.Route.HEAD; import org.jooby.Route.Mapper; import static org.jooby.Route.OPTIONS; import static org.jooby.Route.PATCH; import static org.jooby.Route.POST; import static org.jooby.Route.PUT; import static org.jooby.Route.TRACE; import org.jooby.Session.Store; import org.jooby.funzy.Throwing; import org.jooby.funzy.Try; import org.jooby.handlers.AssetHandler; import org.jooby.internal.AppPrinter; import org.jooby.internal.BuiltinParser; import org.jooby.internal.BuiltinRenderer; import org.jooby.internal.CookieSessionManager; import org.jooby.internal.DefaulErrRenderer; import org.jooby.internal.HttpHandlerImpl; import org.jooby.internal.JvmInfo; import org.jooby.internal.LocaleUtils; import org.jooby.internal.ParameterNameProvider; import org.jooby.internal.RequestScope; import org.jooby.internal.RouteMetadata; import org.jooby.internal.ServerExecutorProvider; import org.jooby.internal.ServerLookup; import org.jooby.internal.ServerSessionManager; import org.jooby.internal.SessionManager; import org.jooby.internal.SourceProvider; import org.jooby.internal.TypeConverters; import org.jooby.internal.handlers.HeadHandler; import org.jooby.internal.handlers.OptionsHandler; import org.jooby.internal.handlers.TraceHandler; import org.jooby.internal.mvc.MvcRoutes; import org.jooby.internal.mvc.MvcWebSocket; import org.jooby.internal.parser.BeanParser; import org.jooby.internal.parser.DateParser; import org.jooby.internal.parser.LocalDateParser; import org.jooby.internal.parser.LocaleParser; import org.jooby.internal.parser.ParserExecutor; import org.jooby.internal.parser.StaticMethodParser; import org.jooby.internal.parser.StringConstructorParser; import org.jooby.internal.parser.ZonedDateTimeParser; import org.jooby.internal.ssl.SslContextProvider; import org.jooby.mvc.Consumes; import org.jooby.mvc.Produces; import org.jooby.scope.Providers; import org.jooby.scope.RequestScoped; import org.jooby.spi.HttpHandler; import org.jooby.spi.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Singleton; import javax.net.ssl.SSLContext; import java.io.File; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.NumberFormat; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; /** * <h1>jooby</h1> * <h2>getting started</h2> * * <pre> * public class MyApp extends Jooby { * * { * use(new Jackson()); // 1. JSON serializer. * * // 2. Define a route * get("/", req {@literal ->} { * Map{@literal <}String, Object{@literal >} model = ...; * return model; * } * } * * public static void main(String[] args) { * run(MyApp::new, args); // 3. Done! * } * } * </pre> * * <h2>application.conf</h2> * <p> * Jooby delegate configuration management to <a * href="https://github.com/typesafehub/config">TypeSafe Config</a>. * </p> * * <p> * By default Jooby looks for an <code>application.conf</code>. If * you want to specify a different file or location, you can do it with {@link #conf(String)}. * </p> * * <p> * <a href="https://github.com/typesafehub/config">TypeSafe Config</a> uses a hierarchical model to * define and override properties. * </p> * <p> * A {@link Jooby.Module} might provides his own set of properties through the * {@link Jooby.Module#config()} method. By default, this method returns an empty config object. * </p> * For example: * * <pre> * use(new M1()); * use(new M2()); * use(new M3()); * </pre> * * Previous example had the following order (first-listed are higher priority): * <ul> * <li>arguments properties</li> * <li>System properties</li> * <li>application.conf</li> * <li>M3 properties</li> * <li>M2 properties</li> * <li>M1 properties</li> * </ul> * <p> * Command line argmuents or system properties takes precedence over any application specific * property. * </p> * * <h2>env</h2> * <p> * Jooby defines one mode or environment: <strong>dev</strong>. In Jooby, <strong>dev</strong> * is special and some modules could apply special settings while running in <strong>dev</strong>. * Any other env is usually considered a <code>prod</code> like env. But that depends on module * implementor. * </p> * <p> * An <code>environment</code> can be defined in your <code>.conf</code> file using the * <code>application.env</code> property. If missing, Jooby set the <code>env</code> for you to * <strong>dev</strong>. * </p> * <p> * There is more at {@link Env} please read the {@link Env} javadoc. * </p> * * <h2>modules: the jump to full-stack framework</h2> * <p> * {@link Jooby.Module Modules} are quite similar to a Guice modules except that the configure * callback has been complementing with {@link Env} and {@link Config}. * </p> * * <pre> * public class MyModule implements Jooby.Module { * public void configure(Env env, Config config, Binder binder) { * } * } * </pre> * * From the configure callback you can bind your services as you usually do in a Guice app. * <p> * There is more at {@link Jooby.Module} so please read the {@link Jooby.Module} javadoc. * </p> * * <h2>path patterns</h2> * <p> * Jooby supports Ant-style path patterns: * </p> * <p> * Some examples: * </p> * <ul> * <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.html} or * {@code com/txst.html}</li> * <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li> * <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath the * {@code com} path</li> * <li>{@code **}/{@code *} - matches any path at any level.</li> * <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li> * </ul> * * <h3>variables</h3> * <p> * Jooby supports path parameters too: * </p> * <p> * Some examples: * </p> * <ul> * <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric * <code>id</code> var.</li> * </ul> * * <h2>routes</h2> * <p> * Routes perform actions in response to a server HTTP request. * </p> * <p> * Routes are executed in the order they are defined, for example: * </p> * * <pre> * get("/", (req, rsp) {@literal ->} { * log.info("first"); // start here and go to second * }); * * get("/", (req, rsp) {@literal ->} { * log.info("second"); // execute after first and go to final * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * Previous example can be rewritten using {@link Route.Filter}: * * <pre> * get("/", (req, rsp, chain) {@literal ->} { * log.info("first"); // start here and go to second * chain.next(req, rsp); * }); * * get("/", (req, rsp, chain) {@literal ->} { * log.info("second"); // execute after first and go to final * chain.next(req, rsp); * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * Due to the use of lambdas a route is a singleton and you should NOT use global variables. For * example this is a bad practice: * * <pre> * List{@literal <}String{@literal >} names = new ArrayList{@literal <}{@literal >}(); // names produces side effects * get("/", (req, rsp) {@literal ->} { * names.add(req.param("name").value(); * // response will be different between calls. * rsp.send(names); * }); * </pre> * * <h3>mvc routes</h3> * <p> * A Mvc route use annotations to define routes: * </p> * * <pre> * use(MyRoute.class); * ... * * // MyRoute.java * {@literal @}Path("/") * public class MyRoute { * * {@literal @}GET * public String hello() { * return "Hello Jooby"; * } * } * </pre> * <p> * Programming model is quite similar to JAX-RS/Jersey with some minor differences and/or * simplifications. * </p> * * <p> * To learn more about Mvc Routes, please check {@link org.jooby.mvc.Path}, * {@link org.jooby.mvc.Produces} {@link org.jooby.mvc.Consumes} javadoc. * </p> * * <h2>static files</h2> * <p> * Static files, like: *.js, *.css, ..., etc... can be served with: * </p> * * <pre> * assets("assets/**"); * </pre> * <p> * Classpath resources under the <code>/assets</code> folder will be accessible from client/browser. * </p> * * <h2>lifecyle</h2> * <p> * We do provide {@link #onStart(Throwing.Consumer)} and {@link #onStop(Throwing.Consumer)} callbacks. * These callbacks are executed are application startup or shutdown time: * </p> * * <pre>{@code * { * onStart(() -> { * log.info("Welcome!"); * }); * * onStop(() -> { * log.info("Bye!"); * }); * } * }</pre> * * <p> * From life cycle callbacks you can access to application services: * </p> * * <pre>{@code * { * onStart(registry -> { * MyDatabase db = registry.require(MyDatabase.class); * // do something with databse: * }); * } * }</pre> * * @author edgar * @see Jooby.Module * @since 0.1.0 */ public class Jooby implements Router, LifeCycle, Registry { /** * <pre>{@code * { * on("dev", () -> { * // run something on dev * }).orElse(() -> { * // run something on prod * }); * } * }</pre> */ public interface EnvPredicate { /** * <pre>{@code * { * on("dev", () -> { * // run something on dev * }).orElse(() -> { * // run something on prod * }); * } * }</pre> * * @param callback Env callback. */ default void orElse(final Runnable callback) { orElse(conf -> callback.run()); } /** * <pre>{@code * { * on("dev", () -> { * // run something on dev * }).orElse(conf -> { * // run something on prod * }); * } * }</pre> * * @param callback Env callback. */ void orElse(Consumer<Config> callback); } /** * A module can publish or produces: {@link Route.Definition routes}, {@link Parser}, * {@link Renderer}, and any other application specific service or contract of your choice. * <p> * It is similar to {@link com.google.inject.Module} except for the callback method receives a * {@link Env}, {@link Config} and {@link Binder}. * </p> * * <p> * A module can provide his own set of properties through the {@link #config()} method. By * default, this method returns an empty config object. * </p> * For example: * * <pre> * use(new M1()); * use(new M2()); * use(new M3()); * </pre> * * Previous example had the following order (first-listed are higher priority): * <ul> * <li>System properties</li> * <li>application.conf</li> * <li>M3 properties</li> * <li>M2 properties</li> * <li>M1 properties</li> * </ul> * * <p> * A module can provide start/stop methods in order to start or close resources. * </p> * * @author edgar * @see Jooby#use(Jooby.Module) * @since 0.1.0 */ public interface Module { /** * @return Produces a module config object (when need it). By default a module doesn't produce * any configuration object. */ @Nonnull default Config config() { return ConfigFactory.empty(); } /** * Configure and produces bindings for the underlying application. A module can optimize or * customize a service by checking current the {@link Env application env} and/or the current * application properties available from {@link Config}. * * @param env The current application's env. Not null. * @param conf The current config object. Not null. * @param binder A guice binder. Not null. * @throws Throwable If something goes wrong. */ void configure(Env env, Config conf, Binder binder) throws Throwable; } static class MvcClass implements Route.Props<MvcClass> { Class<?> routeClass; String path; ImmutableMap.Builder<String, Object> attrs = ImmutableMap.builder(); private List<MediaType> consumes; private String name; private List<MediaType> produces; private List<String> excludes; private Mapper<?> mapper; private String prefix; private String renderer; public MvcClass(final Class<?> routeClass, final String path, final String prefix) { this.routeClass = routeClass; this.path = path; this.prefix = prefix; } @Override public MvcClass attr(final String name, final Object value) { attrs.put(name, value); return this; } @Override public MvcClass name(final String name) { this.name = name; return this; } @Override public MvcClass consumes(final List<MediaType> consumes) { this.consumes = consumes; return this; } @Override public MvcClass produces(final List<MediaType> produces) { this.produces = produces; return this; } @Override public MvcClass excludes(final List<String> excludes) { this.excludes = excludes; return this; } @Override public MvcClass map(final Mapper<?> mapper) { this.mapper = mapper; return this; } @Override public String renderer() { return renderer; } @Override public MvcClass renderer(final String name) { this.renderer = name; return this; } public Route.Definition apply(final Route.Definition route) { attrs.build().forEach(route::attr); if (name != null) { route.name(name); } if (prefix != null) { route.name(prefix + "/" + route.name()); } if (consumes != null) { route.consumes(consumes); } if (produces != null) { route.produces(produces); } if (excludes != null) { route.excludes(excludes); } if (mapper != null) { route.map(mapper); } if (renderer != null) { route.renderer(renderer); } return route; } } private static class EnvDep { Predicate<String> predicate; Consumer<Config> callback; public EnvDep(final Predicate<String> predicate, final Consumer<Config> callback) { this.predicate = predicate; this.callback = callback; } } static { // set pid as system property String pid = System.getProperty("pid", JvmInfo.pid() + ""); System.setProperty("pid", pid); } /** * Keep track of routes. */ private transient Set<Object> bag = new LinkedHashSet<>(); /** * The override config. Optional. */ private transient Config srcconf; private final transient AtomicBoolean started = new AtomicBoolean(false); /** Keep the global injector instance. */ private transient Injector injector; /** Session store. */ private transient Session.Definition session = new Session.Definition(Session.Mem.class); /** Env builder. */ private transient Env.Builder env = Env.DEFAULT; /** Route's prefix. */ private transient String prefix; /** startup callback . */ private transient List<Throwing.Consumer<Registry>> onStart = new ArrayList<>(); private transient List<Throwing.Consumer<Registry>> onStarted = new ArrayList<>(); /** stop callback . */ private transient List<Throwing.Consumer<Registry>> onStop = new ArrayList<>(); /** Mappers . */ @SuppressWarnings("rawtypes") private transient Mapper mapper; /** Don't add same mapper twice . */ private transient Set<String> mappers = new HashSet<>(); /** Bean parser . */ private transient Optional<Parser> beanParser = Optional.empty(); private transient ServerLookup server = new ServerLookup(); private transient String dateFormat; private transient Charset charset; private transient String[] languages; private transient ZoneId zoneId; private transient Integer port; private transient Integer securePort; private transient String numberFormat; private transient boolean http2; private transient List<Consumer<Binder>> executors = new ArrayList<>(); private transient boolean defaultExecSet; private boolean throwBootstrapException; /** * creates the injector */ private transient BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory = Guice::createInjector; private transient List<Jooby> apprefs; private transient LinkedList<String> path = new LinkedList<>(); private transient String confname; private transient boolean caseSensitiveRouting = true; private transient String classname; /** * Creates a new {@link Jooby} application. */ public Jooby() { this(null); } /** * Creates a new application and prefix all the names of the routes with the given prefix. Useful, * for dynamic/advanced routing. See {@link Route.Chain#next(String, Request, Response)}. * * @param prefix Route name prefix. */ public Jooby(final String prefix) { this.prefix = prefix; use(server); this.classname = classname(getClass().getName()); } @Override public Route.Collection path(String path, Runnable action) { this.path.addLast(Route.normalize(path)); Route.Collection collection = with(action); this.path.removeLast(); return collection; } @Override public Jooby use(final Jooby app) { return use(prefixPath(null), app); } private Optional<String> prefixPath(@Nullable String tail) { return path.size() == 0 ? tail == null ? Optional.empty() : Optional.of(Route.normalize(tail)) : Optional.of(path.stream() .collect(Collectors.joining("", "", tail == null ? "" : Route.normalize(tail)))); } @Override public Jooby use(final String path, final Jooby app) { return use(prefixPath(path), app); } /** * Use the provided HTTP server. * * @param server Server. * @return This jooby instance. */ public Jooby server(final Class<? extends Server> server) { requireNonNull(server, "Server required."); // remove server lookup List<Object> tmp = bag.stream() .skip(1) .collect(Collectors.toList()); tmp.add(0, (Module) (env, conf, binder) -> binder.bind(Server.class).to(server).asEagerSingleton()); bag.clear(); bag.addAll(tmp); return this; } private Jooby use(final Optional<String> path, final Jooby app) { requireNonNull(app, "App is required."); Function<Route.Definition, Route.Definition> rewrite = r -> { return path.map(p -> { Route.Definition result = new Route.Definition(r.method(), p + r.pattern(), r.filter()); result.consumes(r.consumes()); result.produces(r.produces()); result.excludes(r.excludes()); return result; }).orElse(r); }; app.bag.forEach(it -> { if (it instanceof Route.Definition) { this.bag.add(rewrite.apply((Definition) it)); } else if (it instanceof MvcClass) { Object routes = path.<Object>map(p -> new MvcClass(((MvcClass) it).routeClass, p, prefix)) .orElse(it); this.bag.add(routes); } else { // everything else this.bag.add(it); } }); // start/stop callback app.onStart.forEach(this.onStart::add); app.onStarted.forEach(this.onStarted::add); app.onStop.forEach(this.onStop::add); // mapper if (app.mapper != null) { this.map(app.mapper); } if (apprefs == null) { apprefs = new ArrayList<>(); } apprefs.add(app); return this; } /** * Set a custom {@link Env.Builder} to use. * * @param env A custom env builder. * @return This jooby instance. */ public Jooby env(final Env.Builder env) { this.env = requireNonNull(env, "Env builder is required."); return this; } @Override public Jooby onStart(final Throwing.Runnable callback) { LifeCycle.super.onStart(callback); return this; } @Override public Jooby onStart(final Throwing.Consumer<Registry> callback) { requireNonNull(callback, "Callback is required."); onStart.add(callback); return this; } @Override public Jooby onStarted(final Throwing.Runnable callback) { LifeCycle.super.onStarted(callback); return this; } @Override public Jooby onStarted(final Throwing.Consumer<Registry> callback) { requireNonNull(callback, "Callback is required."); onStarted.add(callback); return this; } @Override public Jooby onStop(final Throwing.Runnable callback) { LifeCycle.super.onStop(callback); return this; } @Override public Jooby onStop(final Throwing.Consumer<Registry> callback) { requireNonNull(callback, "Callback is required."); onStop.add(callback); return this; } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on("dev", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * There is an else clause which is the opposite version of the env predicate: * * <pre> * { * on("dev", () {@literal ->} { * use(new DevModule()); * }).orElse(() {@literal ->} { * use(new RealModule()); * }); * } * </pre> * * @param env Environment where we want to run the callback. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final String env, final Runnable callback) { requireNonNull(env, "Env is required."); return on(envpredicate(env), callback); } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on("dev", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * There is an else clause which is the opposite version of the env predicate: * * <pre> * { * on("dev", conf {@literal ->} { * use(new DevModule()); * }).orElse(conf {@literal ->} { * use(new RealModule()); * }); * } * </pre> * * @param env Environment where we want to run the callback. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final String env, final Consumer<Config> callback) { requireNonNull(env, "Env is required."); return on(envpredicate(env), callback); } /** * Run the given callback if and only if, application runs in the given envirobment. * * <pre> * { * on("dev", "test", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * There is an else clause which is the opposite version of the env predicate: * * <pre> * { * on(env {@literal ->} env.equals("dev"), () {@literal ->} { * use(new DevModule()); * }).orElse(() {@literal ->} { * use(new RealModule()); * }); * } * </pre> * * @param predicate Predicate to check the environment. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final Predicate<String> predicate, final Runnable callback) { requireNonNull(predicate, "Predicate is required."); requireNonNull(callback, "Callback is required."); return on(predicate, conf -> callback.run()); } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on(env {@literal ->} env.equals("dev"), conf {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * @param predicate Predicate to check the environment. * @param callback An env callback. * @return This jooby instance. */ public EnvPredicate on(final Predicate<String> predicate, final Consumer<Config> callback) { requireNonNull(predicate, "Predicate is required."); requireNonNull(callback, "Callback is required."); this.bag.add(new EnvDep(predicate, callback)); return otherwise -> this.bag.add(new EnvDep(predicate.negate(), otherwise)); } /** * Run the given callback if and only if, application runs in the given environment. * * <pre> * { * on("dev", "test", "mock", () {@literal ->} { * use(new DevModule()); * }); * } * </pre> * * @param env1 Environment where we want to run the callback. * @param env2 Environment where we want to run the callback. * @param env3 Environment where we want to run the callback. * @param callback An env callback. * @return This jooby instance. */ public Jooby on(final String env1, final String env2, final String env3, final Runnable callback) { on(envpredicate(env1).or(envpredicate(env2)).or(envpredicate(env3)), callback); return this; } @Override public <T> T require(final Key<T> type) { checkState(injector != null, "Registry is not ready. Require calls are available at application startup time, see http://jooby.org/doc/#application-life-cycle"); try { return injector.getInstance(type); } catch (ProvisionException x) { Throwable cause = x.getCause(); if (cause instanceof Err) { throw (Err) cause; } throw x; } } @Override public Route.OneArgHandler promise(final Deferred.Initializer initializer) { return req -> { return new Deferred(initializer); }; } @Override public Route.OneArgHandler promise(final String executor, final Deferred.Initializer initializer) { return req -> new Deferred(executor, initializer); } @Override public Route.OneArgHandler promise(final Deferred.Initializer0 initializer) { return req -> { return new Deferred(initializer); }; } @Override public Route.OneArgHandler promise(final String executor, final Deferred.Initializer0 initializer) { return req -> new Deferred(executor, initializer); } /** * Setup a session store to use. Useful if you want/need to persist sessions between shutdowns, * apply timeout policies, etc... * * Jooby comes with a dozen of {@link Session.Store}, checkout the * <a href="http://jooby.org/doc/session">session modules</a>. * * This method returns a {@link Session.Definition} objects that let you customize the session * cookie. * * @param store A session store. * @return A session store definition. */ public Session.Definition session(final Class<? extends Session.Store> store) { this.session = new Session.Definition(requireNonNull(store, "A session store is required.")); return this.session; } /** * Setup a session store that saves data in a the session cookie. It makes the application * stateless, which help to scale easily. Keep in mind that a cookie has a limited size (up to * 4kb) so you must pay attention to what you put in the session object (don't use as cache). * * Cookie session signed data using the <code>application.secret</code> property, so you must * provide an <code>application.secret</code> value. On dev environment you can set it in your * <code>.conf</code> file. In prod is probably better to provide as command line argument and/or * environment variable. Just make sure to keep it private. * * Please note {@link Session#id()}, {@link Session#accessedAt()}, etc.. make no sense for cookie * sessions, just the {@link Session#attributes()}. * * This method returns a {@link Session.Definition} objects that let you customize the session * cookie. * * @return A session definition/configuration object. */ public Session.Definition cookieSession() { this.session = new Session.Definition(); return this.session; } /** * Setup a session store to use. Useful if you want/need to persist sessions between shutdowns, * apply timeout policies, etc... * * Jooby comes with a dozen of {@link Session.Store}, checkout the * <a href="http://jooby.org/doc/session">session modules</a>. * * This method returns a {@link Session.Definition} objects that let you customize the session * cookie. * * @param store A session store. * @return A session store definition. */ public Session.Definition session(final Session.Store store) { this.session = new Session.Definition(requireNonNull(store, "A session store is required.")); return this.session; } /** * Register a new param/body converter. See {@link Parser} for more details. * * @param parser A parser. * @return This jooby instance. */ public Jooby parser(final Parser parser) { if (parser instanceof BeanParser) { beanParser = Optional.of(parser); } else { bag.add(requireNonNull(parser, "A parser is required.")); } return this; } /** * Append a response {@link Renderer} for write HTTP messages. * * @param renderer A renderer renderer. * @return This jooby instance. */ public Jooby renderer(final Renderer renderer) { this.bag.add(requireNonNull(renderer, "A renderer is required.")); return this; } @Override public Route.Definition before(final String method, final String pattern, final Route.Before handler) { return appendDefinition(method, pattern, handler); } @Override public Route.Definition after(final String method, final String pattern, final Route.After handler) { return appendDefinition(method, pattern, handler); } @Override public Route.Definition complete(final String method, final String pattern, final Route.Complete handler) { return appendDefinition(method, pattern, handler); } @Override public Route.Definition use(final String path, final Route.Filter filter) { return appendDefinition("*", path, filter); } @Override public Route.Definition use(final String verb, final String path, final Route.Filter filter) { return appendDefinition(verb, path, filter); } @Override public Route.Definition use(final String verb, final String path, final Route.Handler handler) { return appendDefinition(verb, path, handler); } @Override public Route.Definition use(final String path, final Route.Handler handler) { return appendDefinition("*", path, handler); } @Override public Route.Definition use(final String path, final Route.OneArgHandler handler) { return appendDefinition("*", path, handler); } @Override public Route.Definition get(final String path, final Route.Handler handler) { return appendDefinition(GET, path, handler); } @Override public Route.Collection get(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler)}); } @Override public Route.Definition get(final String path, final Route.OneArgHandler handler) { return appendDefinition(GET, path, handler); } @Override public Route.Collection get(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler)}); } @Override public Route.Definition get(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(GET, path, handler); } @Override public Route.Collection get(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{get(path1, handler), get(path2, handler), get(path3, handler)}); } @Override public Route.Definition get(final String path, final Route.Filter filter) { return appendDefinition(GET, path, filter); } @Override public Route.Collection get(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection(new Route.Definition[]{get(path1, filter), get(path2, filter)}); } @Override public Route.Collection get(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{get(path1, filter), get(path2, filter), get(path3, filter)}); } @Override public Route.Definition post(final String path, final Route.Handler handler) { return appendDefinition(POST, path, handler); } @Override public Route.Collection post(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler)}); } @Override public Route.Definition post(final String path, final Route.OneArgHandler handler) { return appendDefinition(POST, path, handler); } @Override public Route.Collection post(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler)}); } @Override public Route.Definition post(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(POST, path, handler); } @Override public Route.Collection post(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{post(path1, handler), post(path2, handler), post(path3, handler)}); } @Override public Route.Definition post(final String path, final Route.Filter filter) { return appendDefinition(POST, path, filter); } @Override public Route.Collection post(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{post(path1, filter), post(path2, filter)}); } @Override public Route.Collection post(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{post(path1, filter), post(path2, filter), post(path3, filter)}); } @Override public Route.Definition head(final String path, final Route.Handler handler) { return appendDefinition(HEAD, path, handler); } @Override public Route.Definition head(final String path, final Route.OneArgHandler handler) { return appendDefinition(HEAD, path, handler); } @Override public Route.Definition head(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(HEAD, path, handler); } @Override public Route.Definition head(final String path, final Route.Filter filter) { return appendDefinition(HEAD, path, filter); } @Override public Route.Definition head() { return appendDefinition(HEAD, "*", filter(HeadHandler.class)).name("*.head"); } @Override public Route.Definition options(final String path, final Route.Handler handler) { return appendDefinition(OPTIONS, path, handler); } @Override public Route.Definition options(final String path, final Route.OneArgHandler handler) { return appendDefinition(OPTIONS, path, handler); } @Override public Route.Definition options(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(OPTIONS, path, handler); } @Override public Route.Definition options(final String path, final Route.Filter filter) { return appendDefinition(OPTIONS, path, filter); } @Override public Route.Definition options() { return appendDefinition(OPTIONS, "*", handler(OptionsHandler.class)).name("*.options"); } @Override public Route.Definition put(final String path, final Route.Handler handler) { return appendDefinition(PUT, path, handler); } @Override public Route.Collection put(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler)}); } @Override public Route.Definition put(final String path, final Route.OneArgHandler handler) { return appendDefinition(PUT, path, handler); } @Override public Route.Collection put(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler)}); } @Override public Route.Definition put(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(PUT, path, handler); } @Override public Route.Collection put(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{put(path1, handler), put(path2, handler), put(path3, handler)}); } @Override public Route.Definition put(final String path, final Route.Filter filter) { return appendDefinition(PUT, path, filter); } @Override public Route.Collection put(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{put(path1, filter), put(path2, filter)}); } @Override public Route.Collection put(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{put(path1, filter), put(path2, filter), put(path3, filter)}); } @Override public Route.Definition patch(final String path, final Route.Handler handler) { return appendDefinition(PATCH, path, handler); } @Override public Route.Collection patch(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler), patch(path3, handler)}); } @Override public Route.Definition patch(final String path, final Route.OneArgHandler handler) { return appendDefinition(PATCH, path, handler); } @Override public Route.Collection patch(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler), patch(path3, handler)}); } @Override public Route.Definition patch(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(PATCH, path, handler); } @Override public Route.Collection patch(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{patch(path1, handler), patch(path2, handler), patch(path3, handler)}); } @Override public Route.Definition patch(final String path, final Route.Filter filter) { return appendDefinition(PATCH, path, filter); } @Override public Route.Collection patch(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{patch(path1, filter), patch(path2, filter)}); } @Override public Route.Collection patch(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{patch(path1, filter), patch(path2, filter), patch(path3, filter)}); } @Override public Route.Definition delete(final String path, final Route.Handler handler) { return appendDefinition(DELETE, path, handler); } @Override public Route.Collection delete(final String path1, final String path2, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.Handler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler), delete(path3, handler)}); } @Override public Route.Definition delete(final String path, final Route.OneArgHandler handler) { return appendDefinition(DELETE, path, handler); } @Override public Route.Collection delete(final String path1, final String path2, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.OneArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler), delete(path3, handler)}); } @Override public Route.Definition delete(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(DELETE, path, handler); } @Override public Route.Collection delete(final String path1, final String path2, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.ZeroArgHandler handler) { return new Route.Collection( new Route.Definition[]{delete(path1, handler), delete(path2, handler), delete(path3, handler)}); } @Override public Route.Definition delete(final String path, final Route.Filter filter) { return appendDefinition(DELETE, path, filter); } @Override public Route.Collection delete(final String path1, final String path2, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{delete(path1, filter), delete(path2, filter)}); } @Override public Route.Collection delete(final String path1, final String path2, final String path3, final Route.Filter filter) { return new Route.Collection( new Route.Definition[]{delete(path1, filter), delete(path2, filter), delete(path3, filter)}); } @Override public Route.Definition trace(final String path, final Route.Handler handler) { return appendDefinition(TRACE, path, handler); } @Override public Route.Definition trace(final String path, final Route.OneArgHandler handler) { return appendDefinition(TRACE, path, handler); } @Override public Route.Definition trace(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(TRACE, path, handler); } @Override public Route.Definition trace(final String path, final Route.Filter filter) { return appendDefinition(TRACE, path, filter); } @Override public Route.Definition trace() { return appendDefinition(TRACE, "*", handler(TraceHandler.class)).name("*.trace"); } @Override public Route.Definition connect(final String path, final Route.Handler handler) { return appendDefinition(CONNECT, path, handler); } @Override public Route.Definition connect(final String path, final Route.OneArgHandler handler) { return appendDefinition(CONNECT, path, handler); } @Override public Route.Definition connect(final String path, final Route.ZeroArgHandler handler) { return appendDefinition(CONNECT, path, handler); } @Override public Route.Definition connect(final String path, final Route.Filter filter) { return appendDefinition(CONNECT, path, filter); } /** * Creates a new {@link Route.Handler} that delegate the execution to the given handler. This is * useful when the target handler requires some dependencies. * * <pre> * public class MyHandler implements Route.Handler { * &#64;Inject * public MyHandler(Dependency d) { * } * * public void handle(Request req, Response rsp) throws Exception { * // do something * } * } * ... * // external route * get("/", handler(MyHandler.class)); * * // inline version route * get("/", (req, rsp) {@literal ->} { * Dependency d = req.getInstance(Dependency.class); * // do something * }); * </pre> * * You can access to a dependency from a in-line route too, so the use of external route it is * more or less a matter of taste. * * @param handler The external handler class. * @return A new inline route handler. */ private Route.Handler handler(final Class<? extends Route.Handler> handler) { requireNonNull(handler, "Route handler is required."); return (req, rsp) -> req.require(handler).handle(req, rsp); } /** * Creates a new {@link Route.Filter} that delegate the execution to the given filter. This is * useful when the target handler requires some dependencies. * * <pre> * public class MyFilter implements Filter { * &#64;Inject * public MyFilter(Dependency d) { * } * * public void handle(Request req, Response rsp, Route.Chain chain) throws Exception { * // do something * } * } * ... * // external filter * get("/", filter(MyFilter.class)); * * // inline version route * get("/", (req, rsp, chain) {@literal ->} { * Dependency d = req.getInstance(Dependency.class); * // do something * }); * </pre> * * You can access to a dependency from a in-line route too, so the use of external filter it is * more or less a matter of taste. * * @param filter The external filter class. * @return A new inline route. */ private Route.Filter filter(final Class<? extends Route.Filter> filter) { requireNonNull(filter, "Filter is required."); return (req, rsp, chain) -> req.require(filter).handle(req, rsp, chain); } @Override public Route.AssetDefinition assets(final String path, final Path basedir) { return assets(path, new AssetHandler(basedir)); } @Override public Route.AssetDefinition assets(final String path, final String location) { return assets(path, new AssetHandler(location)); } @Override public Route.AssetDefinition assets(final String path, final AssetHandler handler) { Route.AssetDefinition route = appendDefinition(GET, path, handler, Route.AssetDefinition::new); return configureAssetHandler(route); } @Override public Route.Collection use(final Class<?> routeClass) { return use("", routeClass); } @Override public Route.Collection use(final String path, final Class<?> routeClass) { requireNonNull(routeClass, "Route class is required."); requireNonNull(path, "Path is required"); MvcClass mvc = new MvcClass(routeClass, path, prefix); bag.add(mvc); return new Route.Collection(mvc); } /** * Keep track of routes in the order user define them. * * @param method Route method. * @param pattern Route pattern. * @param filter Route filter. * @return The same route definition. */ private Route.Definition appendDefinition(String method, String pattern, Route.Filter filter) { return appendDefinition(method, pattern, filter, Route.Definition::new); } /** * Keep track of routes in the order user define them. * * @param method Route method. * @param pattern Route pattern. * @param filter Route filter. * @param creator Route creator. * @return The same route definition. */ private <T extends Route.Definition> T appendDefinition(String method, String pattern, Route.Filter filter, Throwing.Function4<String, String, Route.Filter, Boolean, T> creator) { String pathPattern = prefixPath(pattern).orElse(pattern); T route = creator.apply(method, pathPattern, filter, caseSensitiveRouting); if (prefix != null) { route.prefix = prefix; // reset name will update the name if prefix != null route.name(route.name()); } bag.add(route); return route; } /** * Import an application {@link Module}. * * @param module The module to import. * @return This jooby instance. * @see Jooby.Module */ public Jooby use(final Jooby.Module module) { requireNonNull(module, "A module is required."); bag.add(module); return this; } /** * Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code> * file. * * @param path Classpath location. * @return This jooby instance. */ public Jooby conf(final String path) { this.confname = path; use(ConfigFactory.parseResources(path)); return this; } /** * Set/specify a custom .conf file, useful when you don't want a <code>application.conf</code> * file. * * @param path File system location. * @return This jooby instance. */ public Jooby conf(final File path) { this.confname = path.getName(); use(ConfigFactory.parseFile(path)); return this; } /** * Set the application configuration object. You must call this method when the default file * name: <code>application.conf</code> doesn't work for you or when you need/want to register two * or more files. * * @param config The application configuration object. * @return This jooby instance. * @see Config */ public Jooby use(final Config config) { this.srcconf = requireNonNull(config, "Config required."); return this; } @Override public Jooby err(final Err.Handler err) { this.bag.add(requireNonNull(err, "An err handler is required.")); return this; } @Override public WebSocket.Definition ws(final String path, final WebSocket.OnOpen handler) { WebSocket.Definition ws = new WebSocket.Definition(path, handler); checkArgument(bag.add(ws), "Duplicated path: '%s'", path); return ws; } @Override public <T> WebSocket.Definition ws(final String path, final Class<? extends WebSocket.OnMessage<T>> handler) { String fpath = Optional.ofNullable(handler.getAnnotation(org.jooby.mvc.Path.class)) .map(it -> path + "/" + it.value()[0]) .orElse(path); WebSocket.Definition ws = ws(fpath, MvcWebSocket.newWebSocket(handler)); Optional.ofNullable(handler.getAnnotation(Consumes.class)) .ifPresent(consumes -> Arrays.asList(consumes.value()).forEach(ws::consumes)); Optional.ofNullable(handler.getAnnotation(Produces.class)) .ifPresent(produces -> Arrays.asList(produces.value()).forEach(ws::produces)); return ws; } @Override public Route.Definition sse(final String path, final Sse.Handler handler) { return appendDefinition(GET, path, handler).consumes(MediaType.sse); } @Override public Route.Definition sse(final String path, final Sse.Handler1 handler) { return appendDefinition(GET, path, handler).consumes(MediaType.sse); } @SuppressWarnings("rawtypes") @Override public Route.Collection with(final Runnable callback) { // hacky way of doing what we want... but we do simplify developer life int size = this.bag.size(); callback.run(); // collect latest routes and apply route props List<Route.Props> local = this.bag.stream() .skip(size) .filter(Route.Props.class::isInstance) .map(Route.Props.class::cast) .collect(Collectors.toList()); return new Route.Collection(local.toArray(new Route.Props[local.size()])); } /** * Prepare and startup a {@link Jooby} application. * * @param app Application supplier. * @param args Application arguments. */ public static void run(final Supplier<? extends Jooby> app, final String... args) { Config conf = ConfigFactory.systemProperties() .withFallback(args(args)); System.setProperty("logback.configurationFile", logback(conf)); app.get().start(args); } /** * Prepare and startup a {@link Jooby} application. * * @param app Application supplier. * @param args Application arguments. */ public static void run(final Class<? extends Jooby> app, final String... args) { run(() -> Try.apply(() -> app.newInstance()).get(), args); } /** * Export configuration from an application. Useful for tooling, testing, debugging, etc... * * @param app Application to extract/collect configuration. * @return Application conf or <code>empty</code> conf on error. */ public static Config exportConf(final Jooby app) { AtomicReference<Config> conf = new AtomicReference<>(ConfigFactory.empty()); app.on("*", c -> { conf.set(c); }); exportRoutes(app); return conf.get(); } /** * Export routes from an application. Useful for route analysis, testing, debugging, etc... * * @param app Application to extract/collect routes. * @return Application routes. */ public static List<Definition> exportRoutes(final Jooby app) { @SuppressWarnings("serial") class Success extends RuntimeException { List<Definition> routes; Success(final List<Route.Definition> routes) { this.routes = routes; } } List<Definition> routes = Collections.emptyList(); try { app.start(new String[0], r -> { throw new Success(r); }); } catch (Success success) { routes = success.routes; } catch (Throwable x) { logger(app).debug("Failed bootstrap: {}", app, x); } return routes; } /** * Start an application. Fire the {@link #onStart(Throwing.Runnable)} event and the * {@link #onStarted(Throwing.Runnable)} events. */ public void start() { start(new String[0]); } /** * Start an application. Fire the {@link #onStart(Throwing.Runnable)} event and the * {@link #onStarted(Throwing.Runnable)} events. * * @param args Application arguments. */ public void start(final String... args) { try { start(args, null); } catch (Throwable x) { stop(); String msg = "An error occurred while starting the application:"; if (throwBootstrapException) { throw new Err(Status.SERVICE_UNAVAILABLE, msg, x); } else { logger(this).error(msg, x); } } } @SuppressWarnings("unchecked") private void start(final String[] args, final Consumer<List<Route.Definition>> routes) throws Throwable { long start = System.currentTimeMillis(); started.set(true); this.injector = bootstrap(args(args), routes); // shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); Config conf = injector.getInstance(Config.class); Logger log = logger(this); // inject class injector.injectMembers(this); // onStart callbacks via .conf if (conf.hasPath("jooby.internal.onStart")) { ClassLoader loader = getClass().getClassLoader(); Object internalOnStart = loader.loadClass(conf.getString("jooby.internal.onStart")) .newInstance(); onStart.add((Throwing.Consumer<Registry>) internalOnStart); } // start services for (Throwing.Consumer<Registry> onStart : this.onStart) { onStart.accept(this); } // route mapper Set<Route.Definition> routeDefs = injector.getInstance(Route.KEY); Set<WebSocket.Definition> sockets = injector.getInstance(WebSocket.KEY); if (mapper != null) { routeDefs.forEach(it -> it.map(mapper)); } AppPrinter printer = new AppPrinter(routeDefs, sockets, conf); printer.printConf(log, conf); // Start server Server server = injector.getInstance(Server.class); String serverName = server.getClass().getSimpleName().replace("Server", "").toLowerCase(); server.start(); long end = System.currentTimeMillis(); log.info("[{}@{}]: Server started in {}ms\n\n{}\n", conf.getString("application.env"), serverName, end - start, printer); // started services for (Throwing.Consumer<Registry> onStarted : this.onStarted) { onStarted.accept(this); } boolean join = conf.hasPath("server.join") ? conf.getBoolean("server.join") : true; if (join) { server.join(); } } @Override @SuppressWarnings("unchecked") public Jooby map(final Mapper<?> mapper) { requireNonNull(mapper, "Mapper is required."); if (mappers.add(mapper.name())) { this.mapper = Optional.ofNullable(this.mapper) .map(next -> Route.Mapper.chain(mapper, next)) .orElse((Mapper<Object>) mapper); } return this; } /** * Use the injection provider to create the Guice injector * * @param injectorFactory the injection provider * @return this instance. */ public Jooby injector( final BiFunction<Stage, com.google.inject.Module, Injector> injectorFactory) { this.injectorFactory = injectorFactory; return this; } /** * Bind the provided abstract type to the given implementation: * * <pre> * { * bind(MyInterface.class, MyImplementation.class); * } * </pre> * * @param type Service interface. * @param implementation Service implementation. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type, final Class<? extends T> implementation) { use((env, conf, binder) -> { binder.bind(type).to(implementation); }); return this; } /** * Bind the provided abstract type to the given implementation: * * <pre> * { * bind(MyInterface.class, MyImplementation::new); * } * </pre> * * @param type Service interface. * @param implementation Service implementation. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type, final Supplier<T> implementation) { use((env, conf, binder) -> { binder.bind(type).toInstance(implementation.get()); }); return this; } /** * Bind the provided type: * * <pre> * { * bind(MyInterface.class); * } * </pre> * * @param type Service interface. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type) { use((env, conf, binder) -> { binder.bind(type); }); return this; } /** * Bind the provided type: * * <pre> * { * bind(new MyService()); * } * </pre> * * @param service Service. * @return This instance. */ @SuppressWarnings({"rawtypes", "unchecked"}) public Jooby bind(final Object service) { use((env, conf, binder) -> { Class type = service.getClass(); binder.bind(type).toInstance(service); }); return this; } /** * Bind the provided type and object that requires some type of configuration: * * <pre>{@code * { * bind(MyService.class, conf -> new MyService(conf.getString("service.url"))); * } * }</pre> * * @param type Service type. * @param provider Service provider. * @param <T> Service type. * @return This instance. */ public <T> Jooby bind(final Class<T> type, final Function<Config, ? extends T> provider) { use((env, conf, binder) -> { T service = provider.apply(conf); binder.bind(type).toInstance(service); }); return this; } /** * Bind the provided type and object that requires some type of configuration: * * <pre>{@code * { * bind(conf -> new MyService(conf.getString("service.url"))); * } * }</pre> * * @param provider Service provider. * @param <T> Service type. * @return This instance. */ @SuppressWarnings({"unchecked", "rawtypes"}) public <T> Jooby bind(final Function<Config, T> provider) { use((env, conf, binder) -> { Object service = provider.apply(conf); Class type = service.getClass(); binder.bind(type).toInstance(service); }); return this; } /** * Set application date format. * * @param dateFormat A date format. * @return This instance. */ public Jooby dateFormat(final String dateFormat) { this.dateFormat = requireNonNull(dateFormat, "DateFormat required."); return this; } /** * Set application number format. * * @param numberFormat A number format. * @return This instance. */ public Jooby numberFormat(final String numberFormat) { this.numberFormat = requireNonNull(numberFormat, "NumberFormat required."); return this; } /** * Set application/default charset. * * @param charset A charset. * @return This instance. */ public Jooby charset(final Charset charset) { this.charset = requireNonNull(charset, "Charset required."); return this; } /** * Set application locale (first listed are higher priority). * * @param languages List of locale using the language tag format. * @return This instance. */ public Jooby lang(final String... languages) { this.languages = languages; return this; } /** * Set application time zone. * * @param zoneId ZoneId. * @return This instance. */ public Jooby timezone(final ZoneId zoneId) { this.zoneId = requireNonNull(zoneId, "ZoneId required."); return this; } /** * Set the HTTP port. * * <p> * Keep in mind this work as a default port and can be reset via <code>application.port</code> * property. * </p> * * @param port HTTP port. * @return This instance. */ public Jooby port(final int port) { this.port = port; return this; } /** * <p> * Set the HTTPS port to use. * </p> * * <p> * Keep in mind this work as a default port and can be reset via <code>application.port</code> * property. * </p> * * <h2>HTTPS</h2> * <p> * Jooby comes with a self-signed certificate, useful for development and test. But of course, you * should NEVER use it in the real world. * </p> * * <p> * In order to setup HTTPS with a secure certificate, you need to set these properties: * </p> * * <ul> * <li> * <code>ssl.keystore.cert</code>: An X.509 certificate chain file in PEM format. It can be an * absolute path or a classpath resource. * </li> * <li> * <code>ssl.keystore.key</code>: A PKCS#8 private key file in PEM format. It can be an absolute * path or a classpath resource. * </li> * </ul> * * <p> * Optionally, you can set these too: * </p> * * <ul> * <li> * <code>ssl.keystore.password</code>: Password of the keystore.key (if any). Default is: * null/empty. * </li> * <li> * <code>ssl.trust.cert</code>: Trusted certificates for verifying the remote endpoint’s * certificate. The file should contain an X.509 certificate chain in PEM format. Default uses the * system default. * </li> * <li> * <code>ssl.session.cacheSize</code>: Set the size of the cache used for storing SSL session * objects. 0 to use the default value. * </li> * <li> * <code>ssl.session.timeout</code>: Timeout for the cached SSL session objects, in seconds. 0 to * use the default value. * </li> * </ul> * * <p> * As you can see setup is very simple. All you need is your <code>.crt</code> and * <code>.key</code> files. * </p> * * @param port HTTPS port. * @return This instance. */ public Jooby securePort(final int port) { this.securePort = port; return this; } /** * <p> * Enable <code>HTTP/2</code> protocol. Some servers require special configuration, others just * works. It is a good idea to check the server documentation about * <a href="http://jooby.org/doc/servers">HTTP/2</a>. * </p> * * <p> * In order to use HTTP/2 from a browser you must configure HTTPS, see {@link #securePort(int)} * documentation. * </p> * * <p> * If HTTP/2 clear text is supported then you may skip the HTTPS setup, but of course you won't be * able to use HTTP/2 with browsers. * </p> * * @return This instance. */ public Jooby http2() { this.http2 = true; return this; } /** * Set the default executor to use from {@link Deferred Deferred API}. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final ExecutorService executor) { executor((Executor) executor); onStop(r -> executor.shutdown()); return this; } /** * Set the default executor to use from {@link Deferred Deferred API}. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final Executor executor) { this.defaultExecSet = true; this.executors.add(binder -> { binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance("deferred"); binder.bind(Key.get(Executor.class, Names.named("deferred"))).toInstance(executor); }); return this; } /** * Set a named executor to use from {@link Deferred Deferred API}. Useful for override the * default/global executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param name Name of the executor. * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final String name, final ExecutorService executor) { executor(name, (Executor) executor); onStop(r -> executor.shutdown()); return this; } /** * Set a named executor to use from {@link Deferred Deferred API}. Useful for override the * default/global executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * The {@link ExecutorService} will automatically shutdown. * * @param name Name of the executor. * @param executor Executor to use. * @return This jooby instance. */ public Jooby executor(final String name, final Executor executor) { this.executors.add(binder -> { binder.bind(Key.get(Executor.class, Names.named(name))).toInstance(executor); }); return this; } /** * Set the default executor to use from {@link Deferred Deferred API}. This works as reference to * an executor, application directly or via module must provide an named executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * @param name Executor to use. * @return This jooby instance. */ public Jooby executor(final String name) { defaultExecSet = true; this.executors.add(binder -> { binder.bind(Key.get(String.class, Names.named("deferred"))).toInstance(name); }); return this; } /** * Set a named executor to use from {@link Deferred Deferred API}. Useful for override the * default/global executor. * * Default executor runs each task in the thread that invokes {@link Executor#execute execute}, * that's a Jooby worker thread. A worker thread in Jooby can block. * * @param name Name of the executor. * @param provider Provider for the executor. * @return This jooby instance. */ private Jooby executor(final String name, final Class<? extends Provider<Executor>> provider) { this.executors.add(binder -> { binder.bind(Key.get(Executor.class, Names.named(name))).toProvider(provider) .in(Singleton.class); }); return this; } /** * If the application fails to start all the services are shutdown. Also, the exception is logged * and usually the application is going to exit. * * This options turn off logging and rethrow the exception as {@link Err}. Here is an example: * * <pre> * public class App extends Jooby { * { * throwBootstrapException(); * ... * } * } * * App app = new App(); * * try { * app.start(); * } catch (Err err) { * Throwable cause = err.getCause(); * } * </pre> * * @return This instance. */ public Jooby throwBootstrapException() { this.throwBootstrapException = true; return this; } /** * Configure case for routing algorithm. Default is <code>case sensitive</code>. * * @param enabled True for case sensitive, false otherwise. * @return This instance. */ public Jooby caseSensitiveRouting(boolean enabled) { this.caseSensitiveRouting = enabled; return this; } private static List<Object> normalize(final List<Object> services, final Env env, final RouteMetadata classInfo, final boolean caseSensitiveRouting) { List<Object> result = new ArrayList<>(); List<Object> snapshot = services; /** modules, routes, parsers, renderers and websockets */ snapshot.forEach(candidate -> { if (candidate instanceof Route.Definition) { result.add(candidate); } else if (candidate instanceof MvcClass) { MvcClass mvcRoute = ((MvcClass) candidate); Class<?> mvcClass = mvcRoute.routeClass; String path = ((MvcClass) candidate).path; MvcRoutes.routes(env, classInfo, path, caseSensitiveRouting, mvcClass) .forEach(route -> result.add(mvcRoute.apply(route))); } else { result.add(candidate); } }); return result; } private static List<Object> processEnvDep(final Set<Object> src, final Env env) { List<Object> result = new ArrayList<>(); List<Object> bag = new ArrayList<>(src); bag.forEach(it -> { if (it instanceof EnvDep) { EnvDep envdep = (EnvDep) it; if (envdep.predicate.test(env.name())) { int from = src.size(); envdep.callback.accept(env.config()); int to = src.size(); result.addAll(new ArrayList<>(src).subList(from, to)); } } else { result.add(it); } }); return result; } private Injector bootstrap(final Config args, final Consumer<List<Route.Definition>> rcallback) throws Throwable { Config initconf = Optional.ofNullable(srcconf) .orElseGet(() -> ConfigFactory.parseResources("application.conf")); List<Config> modconf = modconf(this.bag); Config conf = buildConfig(initconf, args, modconf); final List<Locale> locales = LocaleUtils.parse(conf.getString("application.lang")); Env env = this.env.build(conf, this, locales.get(0)); String envname = env.name(); final Charset charset = Charset.forName(conf.getString("application.charset")); String dateFormat = conf.getString("application.dateFormat"); ZoneId zoneId = ZoneId.of(conf.getString("application.tz")); DateTimeFormatter dateTimeFormatter = DateTimeFormatter .ofPattern(dateFormat, locales.get(0)) .withZone(zoneId); DateTimeFormatter zonedDateTimeFormat = DateTimeFormatter .ofPattern(conf.getString("application.zonedDateTimeFormat")); DecimalFormat numberFormat = new DecimalFormat(conf.getString("application.numberFormat")); // Guice Stage Stage stage = "dev".equals(envname) ? Stage.DEVELOPMENT : Stage.PRODUCTION; // expand and normalize bag RouteMetadata rm = new RouteMetadata(env); List<Object> realbag = processEnvDep(this.bag, env); List<Config> realmodconf = modconf(realbag); List<Object> bag = normalize(realbag, env, rm, caseSensitiveRouting); // collect routes and fire route callback if (rcallback != null) { List<Route.Definition> routes = bag.stream() .filter(it -> it instanceof Route.Definition) .map(it -> (Route.Definition) it) .collect(Collectors.<Route.Definition>toList()); rcallback.accept(routes); } // final config ? if we add a mod that depends on env Config finalConfig; Env finalEnv; if (modconf.size() != realmodconf.size()) { finalConfig = buildConfig(initconf, args, realmodconf); finalEnv = this.env.build(finalConfig, this, locales.get(0)); } else { finalConfig = conf; finalEnv = env; } boolean cookieSession = session.store() == null; if (cookieSession && !finalConfig.hasPath("application.secret")) { throw new IllegalStateException("Required property 'application.secret' is missing"); } /** executors: */ if (!defaultExecSet) { // default executor executor(MoreExecutors.directExecutor()); } executor("direct", MoreExecutors.directExecutor()); executor("server", ServerExecutorProvider.class); /** Some basic xss functions. */ xss(finalEnv); /** dependency injection */ @SuppressWarnings("unchecked") com.google.inject.Module joobyModule = binder -> { /** type converters */ new TypeConverters().configure(binder); /** bind config */ bindConfig(binder, finalConfig); /** bind env */ binder.bind(Env.class).toInstance(finalEnv); /** bind charset */ binder.bind(Charset.class).toInstance(charset); /** bind locale */ binder.bind(Locale.class).toInstance(locales.get(0)); TypeLiteral<List<Locale>> localeType = (TypeLiteral<List<Locale>>) TypeLiteral .get(Types.listOf(Locale.class)); binder.bind(localeType).toInstance(locales); /** bind time zone */ binder.bind(ZoneId.class).toInstance(zoneId); binder.bind(TimeZone.class).toInstance(TimeZone.getTimeZone(zoneId)); /** bind date format */ binder.bind(DateTimeFormatter.class).toInstance(dateTimeFormatter); /** bind number format */ binder.bind(NumberFormat.class).toInstance(numberFormat); binder.bind(DecimalFormat.class).toInstance(numberFormat); /** bind ssl provider. */ binder.bind(SSLContext.class).toProvider(SslContextProvider.class); /** routes */ Multibinder<Definition> definitions = Multibinder .newSetBinder(binder, Definition.class); /** web sockets */ Multibinder<WebSocket.Definition> sockets = Multibinder .newSetBinder(binder, WebSocket.Definition.class); /** tmp dir */ File tmpdir = new File(finalConfig.getString("application.tmpdir")); tmpdir.mkdirs(); binder.bind(File.class).annotatedWith(Names.named("application.tmpdir")) .toInstance(tmpdir); binder.bind(ParameterNameProvider.class).toInstance(rm); /** err handler */ Multibinder<Err.Handler> ehandlers = Multibinder .newSetBinder(binder, Err.Handler.class); /** parsers & renderers */ Multibinder<Parser> parsers = Multibinder .newSetBinder(binder, Parser.class); Multibinder<Renderer> renderers = Multibinder .newSetBinder(binder, Renderer.class); /** basic parser */ parsers.addBinding().toInstance(BuiltinParser.Basic); parsers.addBinding().toInstance(BuiltinParser.Collection); parsers.addBinding().toInstance(BuiltinParser.Optional); parsers.addBinding().toInstance(BuiltinParser.Enum); parsers.addBinding().toInstance(BuiltinParser.Bytes); /** basic render */ renderers.addBinding().toInstance(BuiltinRenderer.asset); renderers.addBinding().toInstance(BuiltinRenderer.bytes); renderers.addBinding().toInstance(BuiltinRenderer.byteBuffer); renderers.addBinding().toInstance(BuiltinRenderer.file); renderers.addBinding().toInstance(BuiltinRenderer.charBuffer); renderers.addBinding().toInstance(BuiltinRenderer.stream); renderers.addBinding().toInstance(BuiltinRenderer.reader); renderers.addBinding().toInstance(BuiltinRenderer.fileChannel); /** modules, routes, parsers, renderers and websockets */ Set<Object> routeClasses = new HashSet<>(); for (Object it : bag) { Try.run(() -> bindService( logger(this), this.bag, finalConfig, finalEnv, rm, binder, definitions, sockets, ehandlers, parsers, renderers, routeClasses, caseSensitiveRouting) .accept(it)) .throwException(); } parsers.addBinding().toInstance(new DateParser(dateFormat)); parsers.addBinding().toInstance(new LocalDateParser(dateTimeFormatter)); parsers.addBinding().toInstance(new ZonedDateTimeParser(zonedDateTimeFormat)); parsers.addBinding().toInstance(new LocaleParser()); parsers.addBinding().toInstance(new StaticMethodParser("valueOf")); parsers.addBinding().toInstance(new StaticMethodParser("fromString")); parsers.addBinding().toInstance(new StaticMethodParser("forName")); parsers.addBinding().toInstance(new StringConstructorParser()); parsers.addBinding().toInstance(beanParser.orElseGet(() -> new BeanParser(false))); binder.bind(ParserExecutor.class).in(Singleton.class); /** override(able) renderer */ renderers.addBinding().toInstance(new DefaulErrRenderer()); renderers.addBinding().toInstance(BuiltinRenderer.text); binder.bind(HttpHandler.class).to(HttpHandlerImpl.class).in(Singleton.class); RequestScope requestScope = new RequestScope(); binder.bind(RequestScope.class).toInstance(requestScope); binder.bindScope(RequestScoped.class, requestScope); /** session manager */ binder.bind(Session.Definition.class) .toProvider(session(finalConfig.getConfig("session"), session)) .asEagerSingleton(); Object sstore = session.store(); if (cookieSession) { binder.bind(SessionManager.class).to(CookieSessionManager.class) .asEagerSingleton(); } else { binder.bind(SessionManager.class).to(ServerSessionManager.class).asEagerSingleton(); if (sstore instanceof Class) { binder.bind(Store.class).to((Class<? extends Store>) sstore) .asEagerSingleton(); } else { binder.bind(Store.class).toInstance((Store) sstore); } } binder.bind(Request.class).toProvider(Providers.outOfScope(Request.class)) .in(RequestScoped.class); binder.bind(Route.Chain.class).toProvider(Providers.outOfScope(Route.Chain.class)) .in(RequestScoped.class); binder.bind(Response.class).toProvider(Providers.outOfScope(Response.class)) .in(RequestScoped.class); /** server sent event */ binder.bind(Sse.class).toProvider(Providers.outOfScope(Sse.class)) .in(RequestScoped.class); binder.bind(Session.class).toProvider(Providers.outOfScope(Session.class)) .in(RequestScoped.class); /** def err */ ehandlers.addBinding().toInstance(new Err.DefHandler()); /** executors. */ executors.forEach(it -> it.accept(binder)); }; Injector injector = injectorFactory.apply(stage, joobyModule); if (apprefs != null) { apprefs.forEach(app -> app.injector = injector); apprefs.clear(); apprefs = null; } onStart.addAll(0, finalEnv.startTasks()); onStarted.addAll(0, finalEnv.startedTasks()); onStop.addAll(finalEnv.stopTasks()); // clear bag and freeze it this.bag.clear(); this.bag = ImmutableSet.of(); this.executors.clear(); this.executors = ImmutableList.of(); return injector; } private void xss(final Env env) { Escaper ufe = UrlEscapers.urlFragmentEscaper(); Escaper fpe = UrlEscapers.urlFormParameterEscaper(); Escaper pse = UrlEscapers.urlPathSegmentEscaper(); Escaper html = HtmlEscapers.htmlEscaper(); env.xss("urlFragment", ufe::escape) .xss("formParam", fpe::escape) .xss("pathSegment", pse::escape) .xss("html", html::escape); } private static Provider<Session.Definition> session(final Config $session, final Session.Definition session) { return () -> { // save interval session.saveInterval(session.saveInterval() .orElse($session.getDuration("saveInterval", TimeUnit.MILLISECONDS))); // build cookie Cookie.Definition source = session.cookie(); source.name(source.name() .orElse($session.getString("cookie.name"))); if (!source.comment().isPresent() && $session.hasPath("cookie.comment")) { source.comment($session.getString("cookie.comment")); } if (!source.domain().isPresent() && $session.hasPath("cookie.domain")) { source.domain($session.getString("cookie.domain")); } source.httpOnly(source.httpOnly() .orElse($session.getBoolean("cookie.httpOnly"))); Object maxAge = $session.getAnyRef("cookie.maxAge"); if (maxAge instanceof String) { maxAge = $session.getDuration("cookie.maxAge", TimeUnit.SECONDS); } source.maxAge(source.maxAge() .orElse(((Number) maxAge).intValue())); source.path(source.path() .orElse($session.getString("cookie.path"))); source.secure(source.secure() .orElse($session.getBoolean("cookie.secure"))); return session; }; } private static Throwing.Consumer<? super Object> bindService(Logger log, final Set<Object> src, final Config conf, final Env env, final RouteMetadata rm, final Binder binder, final Multibinder<Route.Definition> definitions, final Multibinder<WebSocket.Definition> sockets, final Multibinder<Err.Handler> ehandlers, final Multibinder<Parser> parsers, final Multibinder<Renderer> renderers, final Set<Object> routeClasses, final boolean caseSensitiveRouting) { return it -> { if (it instanceof Jooby.Module) { int from = src.size(); install(log, (Jooby.Module) it, env, conf, binder); int to = src.size(); // collect any route a module might add if (to > from) { List<Object> elements = normalize(new ArrayList<>(src).subList(from, to), env, rm, caseSensitiveRouting); for (Object e : elements) { bindService(log, src, conf, env, rm, binder, definitions, sockets, ehandlers, parsers, renderers, routeClasses, caseSensitiveRouting).accept(e); } } } else if (it instanceof Route.Definition) { Route.Definition rdef = (Definition) it; Route.Filter h = rdef.filter(); if (h instanceof Route.MethodHandler) { Class<?> routeClass = ((Route.MethodHandler) h).implementingClass(); if (routeClasses.add(routeClass)) { binder.bind(routeClass); } definitions.addBinding().toInstance(rdef); } else { definitions.addBinding().toInstance(rdef); } } else if (it instanceof WebSocket.Definition) { sockets.addBinding().toInstance((WebSocket.Definition) it); } else if (it instanceof Parser) { parsers.addBinding().toInstance((Parser) it); } else if (it instanceof Renderer) { renderers.addBinding().toInstance((Renderer) it); } else { ehandlers.addBinding().toInstance((Err.Handler) it); } }; } private static List<Config> modconf(final Collection<Object> bag) { return bag.stream() .filter(it -> it instanceof Jooby.Module) .map(it -> ((Jooby.Module) it).config()) .filter(c -> !c.isEmpty()) .collect(Collectors.toList()); } /** * Test if the application is up and running. * * @return True if the application is up and running. */ public boolean isStarted() { return started.get(); } /** * Stop the application, fire the {@link #onStop(Throwing.Runnable)} event and shutdown the * web server. * * Stop listeners run in the order they were added: * * <pre>{@code * { * * onStop(() -> System.out.println("first")); * * onStop(() -> System.out.println("second")); * * ... * } * }</pre> * * */ public void stop() { if (started.compareAndSet(true, false)) { Logger log = logger(this); fireStop(this, log, onStop); if (injector != null) { try { injector.getInstance(Server.class).stop(); } catch (Throwable ex) { log.debug("server.stop() resulted in exception", ex); } } injector = null; log.info("Stopped"); } } private static void fireStop(final Jooby app, final Logger log, final List<Throwing.Consumer<Registry>> onStop) { // stop services onStop.forEach(c -> Try.run(() -> c.accept(app)) .onFailure(x -> log.error("shutdown of {} resulted in error", c, x))); } /** * Build configuration properties, it configure system, app and modules properties. * * @param source Source config to use. * @param args Args conf. * @param modules List of modules. * @return A configuration properties ready to use. */ private Config buildConfig(final Config source, final Config args, final List<Config> modules) { // normalize tmpdir Config system = ConfigFactory.systemProperties(); Config tmpdir = source.hasPath("java.io.tmpdir") ? source : system; // system properties system = system // file encoding got corrupted sometimes, override it. .withValue("file.encoding", fromAnyRef(System.getProperty("file.encoding"))) .withValue("java.io.tmpdir", fromAnyRef(Paths.get(tmpdir.getString("java.io.tmpdir")).normalize().toString())); // set module config Config moduleStack = ConfigFactory.empty(); for (Config module : ImmutableList.copyOf(modules).reverse()) { moduleStack = moduleStack.withFallback(module); } String env = Arrays.asList(system, args, source).stream() .filter(it -> it.hasPath("application.env")) .findFirst() .map(c -> c.getString("application.env")) .orElse("dev"); String cpath = Arrays.asList(system, args, source).stream() .filter(it -> it.hasPath("application.path")) .findFirst() .map(c -> c.getString("application.path")) .orElse("/"); Config envconf = envConf(source, env); // application.[env].conf -> application.conf Config conf = envconf.withFallback(source); return system .withFallback(args) .withFallback(conf) .withFallback(moduleStack) .withFallback(MediaType.types) .withFallback(defaultConfig(conf, Route.normalize(cpath))) .resolve(); } /** * Build a conf from arguments. * * @param args Application arguments. * @return A conf. */ static Config args(final String[] args) { if (args == null || args.length == 0) { return ConfigFactory.empty(); } Map<String, String> conf = new HashMap<>(); for (String arg : args) { String[] values = arg.split("="); String name; String value; if (values.length == 2) { name = values[0]; value = values[1]; } else { name = "application.env"; value = values[0]; } if (name.indexOf(".") == -1) { conf.put("application." + name, value); } conf.put(name, value); } return ConfigFactory.parseMap(conf, "args"); } /** * Build a env config: <code>[application].[env].[conf]</code>. * Stack looks like * * <pre> * (file://[origin].[env].[conf])? * (cp://[origin].[env].[conf])? * file://application.[env].[conf] * /application.[env].[conf] * </pre> * * @param source App source to use. * @param env Application env. * @return A config env. */ private Config envConf(final Config source, final String env) { String name = Optional.ofNullable(this.confname).orElse(source.origin().resource()); Config result = ConfigFactory.empty(); if (name != null) { // load [resource].[env].[ext] int dot = name.lastIndexOf('.'); name = name.substring(0, dot); } else { name = "application"; } String envconfname = name + "." + env + ".conf"; Config envconf = fileConfig(envconfname); Config appconf = fileConfig(name + ".conf"); return result // file system: .withFallback(envconf) .withFallback(appconf) // classpath: .withFallback(ConfigFactory.parseResources(envconfname)); } /** * Config from file system. * * @param fname A file name. * @return A config for the file name. */ static Config fileConfig(final String fname) { // TODO: sanitization of arguments File dir = new File(System.getProperty("user.dir")); // TODO: sanitization of arguments File froot = new File(dir, fname); if (froot.exists()) { return ConfigFactory.parseFile(froot); } else { // TODO: sanitization of arguments File fconfig = new File(new File(dir, "conf"), fname); if (fconfig.exists()) { return ConfigFactory.parseFile(fconfig); } } return ConfigFactory.empty(); } /** * Build default application.* properties. * * @param conf A source config. * @param cpath Application path. * @return default properties. */ private Config defaultConfig(final Config conf, final String cpath) { String ns = Optional.ofNullable(getClass().getPackage()) .map(Package::getName) .orElse("default." + getClass().getName()); String[] parts = ns.split("\\."); String appname = parts[parts.length - 1]; // locale final List<Locale> locales; if (!conf.hasPath("application.lang")) { locales = Optional.ofNullable(this.languages) .map(langs -> LocaleUtils.parse(Joiner.on(",").join(langs))) .orElse(ImmutableList.of(Locale.getDefault())); } else { locales = LocaleUtils.parse(conf.getString("application.lang")); } Locale locale = locales.iterator().next(); String lang = locale.toLanguageTag(); // time zone final String tz; if (!conf.hasPath("application.tz")) { tz = Optional.ofNullable(zoneId).orElse(ZoneId.systemDefault()).getId(); } else { tz = conf.getString("application.tz"); } // number format final String nf; if (!conf.hasPath("application.numberFormat")) { nf = Optional.ofNullable(numberFormat) .orElseGet(() -> ((DecimalFormat) DecimalFormat.getInstance(locale)).toPattern()); } else { nf = conf.getString("application.numberFormat"); } int processors = Runtime.getRuntime().availableProcessors(); String version = Optional.ofNullable(getClass().getPackage()) .map(Package::getImplementationVersion) .filter(Objects::nonNull) .orElse("0.0.0"); Config defs = ConfigFactory.parseResources(Jooby.class, "jooby.conf") .withValue("contextPath", fromAnyRef(cpath.equals("/") ? "" : cpath)) .withValue("application.name", fromAnyRef(appname)) .withValue("application.version", fromAnyRef(version)) .withValue("application.class", fromAnyRef(classname)) .withValue("application.ns", fromAnyRef(ns)) .withValue("application.lang", fromAnyRef(lang)) .withValue("application.tz", fromAnyRef(tz)) .withValue("application.numberFormat", fromAnyRef(nf)) .withValue("server.http2.enabled", fromAnyRef(http2)) .withValue("runtime.processors", fromAnyRef(processors)) .withValue("runtime.processors-plus1", fromAnyRef(processors + 1)) .withValue("runtime.processors-plus2", fromAnyRef(processors + 2)) .withValue("runtime.processors-x2", fromAnyRef(processors * 2)) .withValue("runtime.processors-x4", fromAnyRef(processors * 4)) .withValue("runtime.processors-x8", fromAnyRef(processors * 8)) .withValue("runtime.concurrencyLevel", fromAnyRef(Math.max(4, processors))) .withValue("server.threads.Min", fromAnyRef(Math.max(4, processors))) .withValue("server.threads.Max", fromAnyRef(Math.max(32, processors * 8))); if (charset != null) { defs = defs.withValue("application.charset", fromAnyRef(charset.name())); } if (port != null) { defs = defs.withValue("application.port", fromAnyRef(port)); } if (securePort != null) { defs = defs.withValue("application.securePort", fromAnyRef(securePort)); } if (dateFormat != null) { defs = defs.withValue("application.dateFormat", fromAnyRef(dateFormat)); } return defs; } /** * Install a {@link Jooby.Module}. * * @param log Logger. * @param module The module to install. * @param env Application env. * @param config The configuration object. * @param binder A Guice binder. * @throws Throwable If module bootstrap fails. */ private static void install(final Logger log, final Jooby.Module module, final Env env, final Config config, final Binder binder) throws Throwable { module.configure(env, config, binder); try { binder.install(ProviderMethodsModule.forObject(module)); } catch (NoClassDefFoundError x) { // Allow dynamic linking of optional dependencies (required by micrometer module), we ignore // missing classes here, if there is a missing class Jooby is going to fails early (not here) log.debug("ignoring class not found from guice provider method", x); } } /** * Bind a {@link Config} and make it available for injection. Each property of the config is also * binded it and ready to be injected with {@link javax.inject.Named}. * * @param binder Guice binder. * @param config App config. */ @SuppressWarnings("unchecked") private void bindConfig(final Binder binder, final Config config) { // root nodes traverse(binder, "", config.root()); // terminal nodes for (Entry<String, ConfigValue> entry : config.entrySet()) { String name = entry.getKey(); Named named = Names.named(name); Object value = entry.getValue().unwrapped(); if (value instanceof List) { List<Object> values = (List<Object>) value; Type listType = values.size() == 0 ? String.class : Types.listOf(values.iterator().next().getClass()); Key<Object> key = (Key<Object>) Key.get(listType, Names.named(name)); binder.bind(key).toInstance(values); } else { binder.bindConstant().annotatedWith(named).to(value.toString()); } } // bind config binder.bind(Config.class).toInstance(config); } private static void traverse(final Binder binder, final String p, final ConfigObject root) { root.forEach((n, v) -> { if (v instanceof ConfigObject) { ConfigObject child = (ConfigObject) v; String path = p + n; Named named = Names.named(path); binder.bind(Config.class).annotatedWith(named).toInstance(child.toConfig()); traverse(binder, path + ".", child); } }); } private static Predicate<String> envpredicate(final String candidate) { return env -> env.equalsIgnoreCase(candidate) || candidate.equals("*"); } static String logback(final Config conf) { // Avoid warning message from logback when multiples files are present String logback; if (conf.hasPath("logback.configurationFile")) { logback = conf.getString("logback.configurationFile"); } else { String env = conf.hasPath("application.env") ? conf.getString("application.env") : null; ImmutableList.Builder<File> files = ImmutableList.builder(); // TODO: sanitization of arguments File userdir = new File(System.getProperty("user.dir")); File confdir = new File(userdir, "conf"); if (env != null) { files.add(new File(userdir, "logback." + env + ".xml")); files.add(new File(confdir, "logback." + env + ".xml")); } files.add(new File(userdir, "logback.xml")); files.add(new File(confdir, "logback.xml")); logback = files.build() .stream() .filter(File::exists) .map(File::getAbsolutePath) .findFirst() .orElseGet(() -> { return Optional.ofNullable(Jooby.class.getResource("/logback." + env + ".xml")) .map(Objects::toString) .orElse("logback.xml"); }); } return logback; } private static Logger logger(final Jooby app) { return LoggerFactory.getLogger(app.getClass()); } private Route.AssetDefinition configureAssetHandler(final Route.AssetDefinition handler) { onStart(r -> { Config conf = r.require(Config.class); handler .cdn(conf.getString("assets.cdn")) .lastModified(conf.getBoolean("assets.lastModified")) .etag(conf.getBoolean("assets.etag")) .maxAge(conf.getString("assets.cache.maxAge")); }); return handler; } /** * Class name is this, except for script bootstrap. * * @param name Default classname. * @return Classname. */ private String classname(String name) { if (name.equals(Jooby.class.getName()) || name.equals("org.jooby.Kooby")) { return SourceProvider.INSTANCE.get() .map(StackTraceElement::getClassName) .orElse(name); } return name; } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_4612_0
crossvul-java_data_good_1884_3
package eu.hinsch.spring.boot.actuator.logview; import org.apache.catalina.ssi.ByteArrayServletOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import javax.servlet.http.HttpServletResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @SuppressWarnings("unchecked") public class LogViewEndpointTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private HttpServletResponse response; private LogViewEndpoint logViewEndpoint; private Model model; private long now; @Before public void setUp() { MockitoAnnotations.initMocks(this); logViewEndpoint = new LogViewEndpoint(temporaryFolder.getRoot().getAbsolutePath(), new LogViewEndpointAutoconfig.EndpointConfiguration().getStylesheets()); model = new ExtendedModelMap(); now = new Date().getTime(); } @Test public void shouldReturnEmptyFileListForEmptyDirectory() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.containsAttribute("files"), is(true)); assertThat(getFileEntries(), hasSize(0)); } @Test public void shouldListSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileNames(), contains("A.log", "B.log", "C.log")); } @Test public void shouldListReverseSortedByFilename() throws Exception { // given createFile("B.log", "x", now); createFile("A.log", "x", now); createFile("C.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, true, null); // then assertThat(getFileNames(), contains("C.log", "B.log", "A.log")); } @Test public void shouldListSortedBySize() throws Exception { // given createFile("A.log", "xx", now); createFile("B.log", "x", now); createFile("C.log", "xxx", now); // when logViewEndpoint.list(model, SortBy.SIZE, false, null); // then assertThat(getFileNames(), contains("B.log", "A.log", "C.log")); assertThat(getFileSizes(), contains(1L, 2L, 3L)); } @Test public void shouldListSortedByDate() throws Exception { // given // TODO java 8 date api createFile("A.log", "x", now); createFile("B.log", "x", now - 10 * 60 * 1000); createFile("C.log", "x", now - 5 * 60 * 1000); // when logViewEndpoint.list(model, SortBy.MODIFIED, false, null); // then assertThat(getFileNames(), contains("B.log", "C.log", "A.log")); assertThat(getFilePrettyTimes(), contains("10 minutes ago", "5 minutes ago", "moments ago")); } @Test public void shouldSetFileTypeForFile() throws Exception { // given createFile("A.log", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.FILE)); } @Test public void shouldSetFileTypeForArchive() throws Exception { // given createFile("A.log.tar.gz", "x", now); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(getFileEntries().get(0).getFileType(), is(FileType.ARCHIVE)); } @Test public void shouldContainEmptyParentLinkInBaseFolder() throws Exception { // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder"); // then assertThat(model.asMap().get("parent"), is("")); } @Test public void shouldContainEmptyParentLinkInNestedSubfolder() throws Exception { // given temporaryFolder.newFolder("subfolder"); temporaryFolder.newFolder("subfolder", "nested"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder/nested"); // then assertThat(model.asMap().get("parent"), is("/subfolder")); } @Test public void shouldIncludeSubfolderEntry() throws Exception { // given temporaryFolder.newFolder("subfolder"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, null); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFileType(), is(FileType.DIRECTORY)); assertThat(fileEntry.getFilename(), is("subfolder")); } @Test public void shouldListZipContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.zip"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewZipFileContent() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.zip", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } private void createZipArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(temporaryFolder.getRoot(), archiveFileName)))) { ZipEntry zipEntry = new ZipEntry(contentFileName); zos.putNextEntry(zipEntry); IOUtils.write(content, zos); } } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForZip() throws Exception { // given createZipArchive("file.zip", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.zip", 1, response); // then -> exception } @Test public void shouldListTarGzContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.list(model, SortBy.FILENAME, false, "file.tar.gz"); // then List<FileEntry> fileEntries = getFileEntries(); assertThat(fileEntries, hasSize(1)); FileEntry fileEntry = fileEntries.get(0); assertThat(fileEntry.getFilename(), is("A.log")); } @Test public void shouldViewTarGzFileContent() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("A.log", "file.tar.gz", null, response); // then assertThat(new String(outputStream.toByteArray()), is("content")); } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionWhenCallingTailForTarGz() throws Exception { // given createTarGzArchive("file.tar.gz", "A.log", "content"); // when logViewEndpoint.view("A.log", "file.tar.gz", 1, response); // then -> exception } private void createTarGzArchive(String archiveFileName, String contentFileName, String content) throws Exception { try(TarArchiveOutputStream tos = new TarArchiveOutputStream(new GZIPOutputStream( new BufferedOutputStream(new FileOutputStream( new File(temporaryFolder.getRoot(), archiveFileName)))))) { tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry archiveEntry = new TarArchiveEntry(contentFileName); archiveEntry.setSize(content.length()); tos.putArchiveEntry(archiveEntry); IOUtils.write(content, tos); tos.closeArchiveEntry(); } } @Test public void shouldRedirectWithoutTrainingSlash() throws IOException { // when logViewEndpoint.redirect(response); // then verify(response).sendRedirect("log/"); } @Test public void shouldEndpointBeSensitive() { assertThat(logViewEndpoint.isSensitive(), is(true)); } @Test public void shouldReturnContextPath() { assertThat(logViewEndpoint.getPath(), is("/log")); } @Test public void shouldReturnNullEndpointType() { assertThat(logViewEndpoint.getEndpointType(), is(nullValue())); } @Test public void shouldNotAllowToListFileOutsideRoot() throws Exception { // given expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("may not be located outside base path")); // when logViewEndpoint.view("../somefile", null, null, null); } @Test public void shouldNotAllowToListWithBaseOutsideRoot() throws Exception { // given expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("may not be located outside base path")); // when logViewEndpoint.view("somefile", "../otherdir", null, null); } @Test public void shouldViewFile() throws Exception { // given createFile("file.log", "abc", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, null, response); // then assertThat(new String(outputStream.toByteArray()), is("abc")); } @Test public void shouldTailViewOnlyLastLine() throws Exception { // given createFile("file.log", "line1" + System.lineSeparator() + "line2" + System.lineSeparator(), now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.view("file.log", null, 1, response); // then assertThat(new String(outputStream.toByteArray()), not(containsString("line1"))); assertThat(new String(outputStream.toByteArray()), containsString("line2")); } @Test public void shouldSearchInFiles() throws Exception { // given String sep = System.lineSeparator(); createFile("A.log", "A-line1" + sep + "A-line2" + sep + "A-line3", now - 1); createFile("B.log", "B-line1" + sep + "B-line2" + sep + "B-line3", now); ByteArrayServletOutputStream outputStream = mockResponseOutputStream(); // when logViewEndpoint.search("line2", response); // then String output = new String(outputStream.toByteArray()); assertThat(output, containsString("[A.log] A-line2")); assertThat(output, containsString("[B.log] B-line2")); assertThat(output, not(containsString("line1"))); assertThat(output, not(containsString("line3"))); } private ByteArrayServletOutputStream mockResponseOutputStream() throws Exception { ByteArrayServletOutputStream outputStream = new ByteArrayServletOutputStream(); when(response.getOutputStream()).thenReturn(outputStream); return outputStream; } private List<String> getFileNames() { return getFileEntries() .stream() .map(FileEntry::getFilename) .collect(toList()); } private List<Long> getFileSizes() { return getFileEntries() .stream() .map(FileEntry::getSize) .collect(toList()); } private List<String> getFilePrettyTimes() { return getFileEntries() .stream() .map(FileEntry::getModifiedPretty) .collect(toList()); } private List<FileEntry> getFileEntries() { return (List<FileEntry>) model.asMap().get("files"); } private void createFile(String filename, String content, long modified) throws Exception { File file = new File(temporaryFolder.getRoot(), filename); FileUtils.write(file, content); assertThat(file.setLastModified(modified), is(true)); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_1884_3
crossvul-java_data_bad_688_2
/* * Copyright 2011- Per Wendel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package spark.examples.staticresources; import static spark.Spark.get; import static spark.Spark.staticFileLocation; /** * Example showing how serve static resources. */ public class StaticResources { public static void main(String[] args) { // Will serve all static file are under "/public" in classpath if the route isn't consumed by others routes. staticFileLocation("/public"); get("/hello", (request, response) -> { return "Hello World!"; }); } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_688_2
crossvul-java_data_good_4612_3
package org.jooby.internal; import com.google.common.base.Strings; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; public interface AssetSource { URL getResource(String name); static AssetSource fromClassPath(ClassLoader loader, String source) { if (Strings.isNullOrEmpty(source) || "/".equals(source.trim())) { throw new IllegalArgumentException( "For security reasons root classpath access is not allowed: " + source); } return path -> { URL resource = loader.getResource(path); if (resource == null) { return null; } String realPath = resource.getPath(); if (realPath.startsWith(source)) { return resource; } return null; }; } static AssetSource fromFileSystem(Path basedir) { return name -> { Path path = basedir.resolve(name).normalize(); if (Files.exists(path) && path.startsWith(basedir)) { try { return path.toUri().toURL(); } catch (MalformedURLException x) { // shh } } return null; }; } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4612_3
crossvul-java_data_good_489_0
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.common.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * Zip-related utilities. */ public class ZipUtil { /** * Magic number for ZIP files (4 bytes: <tt>0x04034b50</tt>). */ private final static byte MAGIC_NUMBER[] = { (byte)0x50, (byte)0x4B, (byte)0x03, (byte)0x04 }; /** * Test if an input stream is a zip input stream by checking the "magic number" * * @param in input stream * @return true if start of input stream matches magic number * @throws IOException */ public static boolean isZipStream(InputStream in) throws IOException { in.mark(MAGIC_NUMBER.length); byte[] fileHeader = IOUtil.readBytes(in, MAGIC_NUMBER.length); in.reset(); return Arrays.equals(MAGIC_NUMBER, fileHeader); } /** * Extract the contents of a zipfile to a directory. * * @param zipFile * the zip file to extract * @param destDir * the destination directory * @throws IOException * when something untoward happens during the extraction process */ public static void extract(File zipFile, File destDir) throws IOException { try (ZipFile zf = new ZipFile(zipFile)) { extract(zf, destDir); } } /** * Extract the contents of a zipfile to a directory. * * @param zipFile * the zip file to extract * @param destDir * the destination directory * @throws IOException * when something untoward happens during the extraction process */ public static void extract(ZipFile zipFile, File destDir) throws IOException { assert destDir.isDirectory(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); writeEntry(zipFile, entry, destDir); } } /** * Write an entry to a zip file. * * @param zipFile * the zip file to read from * @param entry * the entry to process * @param destDir * the file to write to * @throws IOException * if the entry could not be processed */ public static void writeEntry(ZipFile zipFile, ZipEntry entry, File destDir) throws IOException { File outFile = new File(destDir, entry.getName()); if (! outFile.getCanonicalFile().toPath().startsWith(destDir.toPath())) { throw new IOException("Zip entry outside destination directory: " + entry.getName()); } if (entry.isDirectory()) { outFile.mkdirs(); } else { outFile.getParentFile().mkdirs(); try (InputStream in = zipFile.getInputStream(entry)) { IOUtil.writeStream(in, outFile); } } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_489_0
crossvul-java_data_good_4101_0
/** * This file is part of the Goobi viewer - a content presentation and management application for digitized objects. * * Visit these websites for more information. * - http://www.intranda.com * - http://digiverso.com * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.goobi.viewer.controller; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.unigoettingen.sub.commons.contentlib.exceptions.ContentLibException; import de.unigoettingen.sub.commons.contentlib.exceptions.ContentNotFoundException; import de.unigoettingen.sub.commons.contentlib.exceptions.ServiceNotAllowedException; import io.goobi.viewer.api.rest.AbstractApiUrlManager; import io.goobi.viewer.api.rest.resourcebuilders.TextResourceBuilder; import io.goobi.viewer.exceptions.AccessDeniedException; import io.goobi.viewer.exceptions.DAOException; import io.goobi.viewer.exceptions.HTTPException; import io.goobi.viewer.exceptions.IndexUnreachableException; import io.goobi.viewer.exceptions.PresentationException; import io.goobi.viewer.exceptions.ViewerConfigurationException; import io.goobi.viewer.managedbeans.utils.BeanUtils; /** * Utility class for retrieving data folders, data files and source files. * */ public class DataFileTools { private static final Logger logger = LoggerFactory.getLogger(DataFileTools.class); /** * Retrieves the path to viewer home or repositories root, depending on the record. Used to generate a specific task client query parameter. * * @param pi Record identifier * @return The root folder path of the data repositories; viewer home if none are used * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static String getDataRepositoryPathForRecord(String pi) throws PresentationException, IndexUnreachableException { String dataRepositoryPath = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return getDataRepositoryPath(dataRepositoryPath); } /** * Returns the absolute path to the data repository with the given name (including a slash at the end). Package private to discourage direct usage * by clients. * * @param dataRepositoryPath Data repository name or absolute path * @return * @should return correct path for empty data repository * @should return correct path for data repository name * @should return correct path for absolute data repository path */ static String getDataRepositoryPath(String dataRepositoryPath) { if (StringUtils.isBlank(dataRepositoryPath)) { return DataManager.getInstance().getConfiguration().getViewerHome(); } if (Paths.get(FileTools.adaptPathForWindows(dataRepositoryPath)).isAbsolute()) { return dataRepositoryPath + '/'; } return DataManager.getInstance().getConfiguration().getDataRepositoriesHome() + dataRepositoryPath + '/'; } /** * Constructs the media folder path for the given pi, either directly in viewer-home or within a data repository * * @param pi The work PI. This is both the actual name of the folder and the identifier used to look up data repository in solr * @return A Path to the media folder for the given PI * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getMediaFolder(String pi) throws PresentationException, IndexUnreachableException { return getDataFolder(pi, DataManager.getInstance().getConfiguration().getMediaFolder()); } /** * Returns a map of Paths for each data folder name passed as an argument. * * @param pi The record identifier. This is both the actual name of the folder and the identifier used to look up data repository in Solr * @return HashMap<dataFolderName,Path> * @should return all requested data folders * @param dataFolderNames a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Map<String, Path> getDataFolders(String pi, String... dataFolderNames) throws PresentationException, IndexUnreachableException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } if (dataFolderNames == null) { throw new IllegalArgumentException("dataFolderNames may not be null"); } String dataRepositoryName = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); Map<String, Path> ret = new HashMap<>(dataFolderNames.length); for (String dataFolderName : dataFolderNames) { ret.put(dataFolderName, getDataFolder(pi, dataFolderName, dataRepositoryName)); } return ret; } /** * Constructs the folder path for data of the given pi, either directly in viewer-home or within a data repository. * * @param pi The record identifier. This is both the actual name of the folder and the identifier used to look up data repository in Solr * @param dataFolderName the data folder within the repository; e.g 'media' or 'alto' * @return A Path to the data folder for the given PI * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getDataFolder(String pi, String dataFolderName) throws PresentationException, IndexUnreachableException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return getDataFolder(pi, dataFolderName, dataRepository); } /** * Returns the data folder path for the given record identifier. To be used in clients that already possess the data repository name. * * @param pi a {@link java.lang.String} object. * @param dataFolderName a {@link java.lang.String} object. * @param dataRepositoryFolder Absolute path to the data repository folder or just the folder name * @should return correct folder if no data repository used * @should return correct folder if data repository used * @return a {@link java.nio.file.Path} object. */ public static Path getDataFolder(String pi, String dataFolderName, String dataRepositoryFolder) { Path repository; // TODO Find a way to use absolute repo paths in unit tests if (StringUtils.isBlank(dataRepositoryFolder)) { repository = Paths.get(DataManager.getInstance().getConfiguration().getViewerHome()); } else if (Paths.get(FileTools.adaptPathForWindows(dataRepositoryFolder)).isAbsolute()) { repository = Paths.get(dataRepositoryFolder); } else { repository = Paths.get(DataManager.getInstance().getConfiguration().getDataRepositoriesHome(), dataRepositoryFolder); } Path folder = repository.resolve(dataFolderName).resolve(pi); return folder; } /** * <p> * getDataFilePath. * </p> * * @param pi Record identifier * @param dataFolderName Name of the data folder (e.g. 'alto') - first choice * @param altDataFolderName Name of the data folder - second choice * @param fileName Name of the content file * @return Path to the requested file * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getDataFilePath(String pi, String dataFolderName, String altDataFolderName, String fileName) throws PresentationException, IndexUnreachableException { //make sure fileName is a pure filename and not a path fileName = Paths.get(fileName).getFileName().toString(); java.nio.file.Path dataFolderPath = getDataFolder(pi, dataFolderName); if (StringUtils.isNotBlank(fileName)) { dataFolderPath = dataFolderPath.resolve(fileName); } if (StringUtils.isNotBlank(altDataFolderName) && !Files.exists(dataFolderPath)) { return getDataFilePath(pi, altDataFolderName, null, fileName); } return dataFolderPath; } /** * <p> * getDataFilePath. * </p> * * @param pi Record identifier * @param relativeFilePath File path relative to data repositories root * @return File represented by the relative file path * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getDataFilePath(String pi, String relativeFilePath) throws PresentationException, IndexUnreachableException { if (pi == null) { throw new IllegalArgumentException("pi may not be null"); } String dataRepositoryName = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); String dataRepositoryPath = getDataRepositoryPath(dataRepositoryName); return Paths.get(dataRepositoryPath, relativeFilePath); } /** * Returns the absolute path to the source (METS/LIDO) file with the given file name. * * @param fileName a {@link java.lang.String} object. * @param format a {@link java.lang.String} object. * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static String getSourceFilePath(String fileName, String format) throws PresentationException, IndexUnreachableException { String pi = FilenameUtils.getBaseName(fileName); String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); return getSourceFilePath(fileName, dataRepository, format); } /** * Returns the absolute path to the source (METS/LIDO/DENKXWEB/DUBLINCORE) file with the given file name. * * @param fileName a {@link java.lang.String} object. * @param dataRepository a {@link java.lang.String} object. * @param format a {@link java.lang.String} object. * @should construct METS file path correctly * @should construct LIDO file path correctly * @should construct DenkXweb file path correctly * @should throw IllegalArgumentException if fileName is null * @should throw IllegalArgumentException if format is unknown * @return a {@link java.lang.String} object. */ public static String getSourceFilePath(String fileName, String dataRepository, String format) { if (StringUtils.isEmpty(fileName)) { throw new IllegalArgumentException("fileName may not be null or empty"); } if (StringUtils.isEmpty(format)) { throw new IllegalArgumentException("format may not be null or empty"); } switch (format) { case SolrConstants._METS: case SolrConstants._LIDO: case SolrConstants._DENKXWEB: case SolrConstants._WORLDVIEWS: case SolrConstants._DUBLINCORE: break; default: throw new IllegalArgumentException("format must be: METS | LIDO | DENKXWEB | DUBLINCORE | WORLDVIEWS"); } StringBuilder sb = new StringBuilder(getDataRepositoryPath(dataRepository)); switch (format) { case SolrConstants._METS: sb.append(DataManager.getInstance().getConfiguration().getIndexedMetsFolder()); break; case SolrConstants._LIDO: sb.append(DataManager.getInstance().getConfiguration().getIndexedLidoFolder()); break; case SolrConstants._DENKXWEB: sb.append(DataManager.getInstance().getConfiguration().getIndexedDenkxwebFolder()); break; case SolrConstants._DUBLINCORE: sb.append(DataManager.getInstance().getConfiguration().getIndexedDublinCoreFolder()); break; case SolrConstants._WORLDVIEWS: sb.append(DataManager.getInstance().getConfiguration().getIndexedMetsFolder()); break; } sb.append('/').append(fileName); return sb.toString(); } /** * <p> * getTextFilePath. * </p> * * @param pi a {@link java.lang.String} object. * @param fileName a {@link java.lang.String} object. * @param format a {@link java.lang.String} object. * @should return correct path * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static String getTextFilePath(String pi, String fileName, String format) throws PresentationException, IndexUnreachableException { if (StringUtils.isEmpty(fileName)) { throw new IllegalArgumentException("fileName may not be null or empty"); } if (StringUtils.isEmpty(format)) { throw new IllegalArgumentException("format may not be null or empty"); } String dataFolderName = null; switch (format) { case SolrConstants.FILENAME_ALTO: dataFolderName = DataManager.getInstance().getConfiguration().getAltoFolder(); break; case SolrConstants.FILENAME_FULLTEXT: dataFolderName = DataManager.getInstance().getConfiguration().getFulltextFolder(); break; case SolrConstants.FILENAME_TEI: dataFolderName = DataManager.getInstance().getConfiguration().getTeiFolder(); break; } return getDataFilePath(pi, dataFolderName, null, fileName).toAbsolutePath().toString(); } /** * <p> * getTextFilePath. * </p> * * @param pi a {@link java.lang.String} object. * @param relativeFilePath ALTO/text file path relative to the data folder * @return a {@link java.nio.file.Path} object. * @throws io.goobi.viewer.exceptions.PresentationException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. */ public static Path getTextFilePath(String pi, String relativeFilePath) throws PresentationException, IndexUnreachableException { if (StringUtils.isBlank(relativeFilePath)) { return null; } String dataRepository = DataManager.getInstance().getSearchIndex().findDataRepositoryName(pi); Path filePath = Paths.get(getDataRepositoryPath(dataRepository), relativeFilePath); return filePath; } /** * Loads plain full-text via the REST service. ALTO is preferred (and converted to plain text, with a plain text fallback. * * @param altoFilePath ALTO file path relative to the repository root (e.g. "alto/PPN123/00000001.xml") * @param fulltextFilePath plain full-text file path relative to the repository root (e.g. "fulltext/PPN123/00000001.xml") * @param mergeLineBreakWords a boolean. * @param request a {@link javax.servlet.http.HttpServletRequest} object. * @should load fulltext from alto correctly * @should load fulltext from plain text correctly * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.AccessDeniedException if any. * @throws java.io.FileNotFoundException if any. * @throws java.io.IOException if any. * @throws io.goobi.viewer.exceptions.IndexUnreachableException if any. * @throws io.goobi.viewer.exceptions.DAOException if any. * @throws io.goobi.viewer.exceptions.ViewerConfigurationException if any. */ public static String loadFulltext(String altoFilePath, String fulltextFilePath, boolean mergeLineBreakWords, HttpServletRequest request) throws AccessDeniedException, FileNotFoundException, IOException, IndexUnreachableException, DAOException, ViewerConfigurationException { TextResourceBuilder builder = new TextResourceBuilder(BeanUtils.getRequest(), null); if (altoFilePath != null) { // ALTO file try { String alto = builder.getAltoDocument(FileTools.getBottomFolderFromPathString(altoFilePath), FileTools.getFilenameFromPathString(altoFilePath)); if (alto != null) { return ALTOTools.getFullText(alto, mergeLineBreakWords, request); } } catch (ContentNotFoundException e) { throw new FileNotFoundException(e.getMessage()); } catch (ServiceNotAllowedException e) { throw new AccessDeniedException("fulltextAccessDenied"); } catch (PresentationException e) { logger.error(e.getMessage()); } } if (fulltextFilePath != null) { // Plain full-text file try { String fulltext = builder.getFulltext(FileTools.getBottomFolderFromPathString(fulltextFilePath), FileTools.getFilenameFromPathString(fulltextFilePath)); if (fulltext != null) { return fulltext; } } catch (ContentNotFoundException e) { throw new FileNotFoundException(e.getMessage()); } catch (ServiceNotAllowedException e) { throw new AccessDeniedException("fulltextAccessDenied"); } catch (PresentationException e) { logger.error(e.getMessage()); } } return null; } public static String loadAlto(String altoFilePath) throws ContentNotFoundException, AccessDeniedException, IndexUnreachableException, DAOException, PresentationException { TextResourceBuilder builder = new TextResourceBuilder(BeanUtils.getRequest(), null); if (altoFilePath != null) { // ALTO file try { String alto = builder.getAltoDocument(FileTools.getBottomFolderFromPathString(altoFilePath), FileTools.getFilenameFromPathString(altoFilePath)); return alto; } catch (ServiceNotAllowedException e) { throw new AccessDeniedException("fulltextAccessDenied"); } } else throw new ContentNotFoundException("Alto file " + altoFilePath + " not found"); } /** * <p> * loadTei. * </p> * * @param pi a {@link java.lang.String} object. * @param language a {@link java.lang.String} object. * @return a {@link java.lang.String} object. * @throws io.goobi.viewer.exceptions.AccessDeniedException if any. * @throws java.io.FileNotFoundException if any. * @throws java.io.IOException if any. * @throws io.goobi.viewer.exceptions.ViewerConfigurationException if any. */ public static String loadTei(String pi, String language) throws AccessDeniedException, FileNotFoundException, IOException, ViewerConfigurationException { logger.trace("loadTei: {}/{}", pi, language); if (pi == null) { return null; } TextResourceBuilder builder = new TextResourceBuilder(BeanUtils.getRequest(), null); try { return builder.getTeiDocument(pi, language); } catch (PresentationException | IndexUnreachableException | DAOException | ContentLibException e) { logger.error(e.toString()); return null; } } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4101_0
crossvul-java_data_good_4612_1
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright 2014 Edgar Espina * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooby; import com.google.common.base.CaseFormat; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.primitives.Primitives; import com.google.inject.Key; import com.google.inject.TypeLiteral; import static java.util.Objects.requireNonNull; import org.jooby.funzy.Throwing; import org.jooby.handlers.AssetHandler; import org.jooby.internal.RouteImpl; import org.jooby.internal.RouteMatcher; import org.jooby.internal.RoutePattern; import org.jooby.internal.RouteSourceImpl; import org.jooby.internal.SourceProvider; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; /** * Routes are a key concept in Jooby. Routes are executed in the same order they are defined. * * <h1>handlers</h1> * <p> * There are few type of handlers: {@link Route.Handler}, {@link Route.OneArgHandler} * {@link Route.ZeroArgHandler} and {@link Route.Filter}. They behave very similar, except that a * {@link Route.Filter} can decide if the next route handler can be executed or not. For example: * </p> * * <pre> * get("/filter", (req, rsp, chain) {@literal ->} { * if (someCondition) { * chain.next(req, rsp); * } else { * // respond, throw err, etc... * } * }); * </pre> * * While a {@link Route.Handler} always execute the next handler: * * <pre> * get("/path", (req, rsp) {@literal ->} { * rsp.send("handler"); * }); * * // filter version * get("/path", (req, rsp, chain) {@literal ->} { * rsp.send("handler"); * chain.next(req, rsp); * }); * </pre> * * The {@link Route.OneArgHandler} and {@link Route.ZeroArgHandler} offers a functional version of * generating a response: * * <pre>{@code * { * get("/path", req -> "handler"); * * get("/path", () -> "handler"); * } * }</pre> * * There is no need to call {@link Response#send(Object)}. * * <h1>path patterns</h1> * <p> * Jooby supports Ant-style path patterns: * </p> * <p> * Some examples: * </p> * <ul> * <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.jsp} or * {@code com/txst.html}</li> * <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li> * <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath the * {@code com} path</li> * <li>{@code **}/{@code *} - matches any path at any level.</li> * <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li> * </ul> * * <h2>variables</h2> * <p> * Jooby supports path parameters too: * </p> * <p> * Some examples: * </p> * <ul> * <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric * <code>id</code> var.</li> * </ul> * * <h1>routes semantic</h1> * <p> * Routes are executed in the order they are defined, for example: * </p> * * <pre> * get("/", (req, rsp) {@literal ->} { * log.info("first"); // start here and go to second * }); * * get("/", (req, rsp) {@literal ->} { * log.info("second"); // execute after first and go to final * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * Please note first and second routes are converted to a filter, so previous example is the same * as: * * <pre> * get("/", (req, rsp, chain) {@literal ->} { * log.info("first"); // start here and go to second * chain.next(req, rsp); * }); * * get("/", (req, rsp, chain) {@literal ->} { * log.info("second"); // execute after first and go to final * chain.next(req, rsp); * }); * * get("/", (req, rsp) {@literal ->} { * rsp.send("final"); // done! * }); * </pre> * * <h2>script route</h2> * <p> * A script route can be defined using Lambda expressions, like: * </p> * * <pre> * get("/", (request, response) {@literal ->} { * response.send("Hello Jooby"); * }); * </pre> * * Due to the use of lambdas a route is a singleton and you should NOT use global variables. * For example this is a bad practice: * * <pre> * List{@literal <}String{@literal >} names = new ArrayList{@literal <>}(); // names produces side effects * get("/", (req, rsp) {@literal ->} { * names.add(req.param("name").value(); * // response will be different between calls. * rsp.send(names); * }); * </pre> * * <h2>mvc Route</h2> * <p> * A Mvc Route use annotations to define routes: * </p> * * <pre> * { * use(MyRoute.class); * } * </pre> * * MyRoute.java: * <pre> * {@literal @}Path("/") * public class MyRoute { * * {@literal @}GET * public String hello() { * return "Hello Jooby"; * } * } * </pre> * <p> * Programming model is quite similar to JAX-RS/Jersey with some minor differences and/or * simplifications. * </p> * * <p> * To learn more about Mvc Routes, please check {@link org.jooby.mvc.Path}, * {@link org.jooby.mvc.Produces} {@link org.jooby.mvc.Consumes}. * </p> * * @author edgar * @since 0.1.0 */ public interface Route { /** * Provides useful information about where the route was defined. * * See {@link Definition#source()} and {@link Route#source()}. * * @author edgar * @since 1.0.0.CR4 */ interface Source { /** * There is no source information. */ Source BUILTIN = new Source() { @Override public int line() { return -1; } @Override public Optional<String> declaringClass() { return Optional.empty(); } @Override public String toString() { return "~builtin"; } }; /** * @return Line number where the route was defined or <code>-1</code> when not available. */ int line(); /** * @return Class where the route */ @Nonnull Optional<String> declaringClass(); } /** * Converts a route output to something else, see {@link Router#map(Mapper)}. * * <pre>{@code * { * // we got bar.. not foo * get("/foo", () -> "foo") * .map(value -> "bar"); * * // we got foo.. not bar * get("/bar", () -> "bar") * .map(value -> "foo"); * } * }</pre> * * If you want to apply a single map to several routes: * * <pre>{@code * { * with(() -> { * get("/foo", () -> "foo"); * * get("/bar", () -> "bar"); * * }).map(v -> "foo or bar"); * } * }</pre> * * You can apply a {@link Mapper} to specific return type: * * <pre>{@code * { * with(() -> { * get("/str", () -> "str"); * * get("/int", () -> 1); * * }).map(String v -> "{" + v + "}"); * } * }</pre> * * A call to <code>/str</code> produces <code>{str}</code>, while <code>/int</code> just * <code>1</code>. * * <strong>NOTE</strong>: You can apply the map operator to routes that produces an output. * * For example, the map operator will be silently ignored here: * * <pre>{@code * { * get("/", (req, rsp) -> { * rsp.send(...); * }).map(v -> ..); * } * }</pre> * * @author edgar * @param <T> Type to map. */ interface Mapper<T> { /** * Produces a new mapper by combining the two mapper into one. * * @param it The first mapper to apply. * @param next The second mapper to apply. * @return A new mapper. */ @SuppressWarnings({"rawtypes", "unchecked"}) @Nonnull static Mapper<Object> chain(final Mapper it, final Mapper next) { return create(it.name() + ">" + next.name(), v -> next.map(it.map(v))); } /** * Creates a new named mapper (just syntax suggar for creating a new mapper). * * @param name Mapper's name. * @param fn Map function. * @param <T> Value type. * @return A new mapper. */ @Nonnull static <T> Mapper<T> create(final String name, final Throwing.Function<T, Object> fn) { return new Route.Mapper<T>() { @Override public String name() { return name; } @Override public Object map(final T value) throws Throwable { return fn.apply(value); } @Override public String toString() { return name(); } }; } /** * @return Mapper's name. */ @Nonnull default String name() { String name = Optional.ofNullable(Strings.emptyToNull(getClass().getSimpleName())) .orElseGet(() -> { String classname = getClass().getName(); return classname.substring(classname.lastIndexOf('.') + 1); }); return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name); } /** * Map the type to something else. * * @param value Value to map. * @return Mapped value. * @throws Throwable If mapping fails. */ @Nonnull Object map(T value) throws Throwable; } /** * Common route properties, like static and global metadata via attributes, path exclusion, * produces and consumes types. * * @author edgar * @since 1.0.0.CR * @param <T> Attribute subtype. */ interface Props<T extends Props<T>> { /** * Set route attribute. Only primitives, string, class, enum or array of previous types are * allowed as attributes values. * * @param name Attribute's name. * @param value Attribute's value. * @return This instance. */ @Nonnull T attr(String name, Object value); /** * Tell jooby what renderer should use to render the output. * * @param name A renderer's name. * @return This instance. */ @Nonnull T renderer(final String name); /** * Explicit renderer to use or <code>null</code>. * * @return Explicit renderer to use or <code>null</code>. */ @Nullable String renderer(); /** * Set the route name. Route's name, helpful for debugging but also to implement dynamic and * advanced routing. See {@link Route.Chain#next(String, Request, Response)} * * * @param name A route's name. * @return This instance. */ @Nonnull T name(final String name); /** * Set the media types the route can consume. * * @param consumes The media types to test for. * @return This instance. */ @Nonnull default T consumes(final MediaType... consumes) { return consumes(Arrays.asList(consumes)); } /** * Set the media types the route can consume. * * @param consumes The media types to test for. * @return This instance. */ @Nonnull default T consumes(final String... consumes) { return consumes(MediaType.valueOf(consumes)); } /** * Set the media types the route can consume. * * @param consumes The media types to test for. * @return This instance. */ @Nonnull T consumes(final List<MediaType> consumes); /** * Set the media types the route can produces. * * @param produces The media types to test for. * @return This instance. */ @Nonnull default T produces(final MediaType... produces) { return produces(Arrays.asList(produces)); } /** * Set the media types the route can produces. * * @param produces The media types to test for. * @return This instance. */ @Nonnull default T produces(final String... produces) { return produces(MediaType.valueOf(produces)); } /** * Set the media types the route can produces. * * @param produces The media types to test for. * @return This instance. */ @Nonnull T produces(final List<MediaType> produces); /** * Excludes one or more path pattern from this route, useful for filter: * * <pre> * { * use("*", req {@literal ->} { * ... * }).excludes("/logout"); * } * </pre> * * @param excludes A path pattern. * @return This instance. */ @Nonnull default T excludes(final String... excludes) { return excludes(Arrays.asList(excludes)); } /** * Excludes one or more path pattern from this route, useful for filter: * * <pre> * { * use("*", req {@literal ->} { * ... * }).excludes("/logout"); * } * </pre> * * @param excludes A path pattern. * @return This instance. */ @Nonnull T excludes(final List<String> excludes); @Nonnull T map(Mapper<?> mapper); } /** * Collection of {@link Route.Props} useful for registering/setting route options at once. * * See {@link Router#get(String, String, String, OneArgHandler)} and variants. * * @author edgar * @since 0.5.0 */ @SuppressWarnings({"unchecked", "rawtypes"}) class Collection implements Props<Collection> { /** List of definitions. */ private final Route.Props[] routes; /** * Creates a new collection of route definitions. * * @param definitions Collection of route definitions. */ public Collection(final Route.Props... definitions) { this.routes = requireNonNull(definitions, "Route definitions are required."); } @Override public Collection name(final String name) { for (Props definition : routes) { definition.name(name); } return this; } @Override public String renderer() { return routes[0].renderer(); } @Override public Collection renderer(final String name) { for (Props definition : routes) { definition.renderer(name); } return this; } @Override public Collection consumes(final List<MediaType> types) { for (Props definition : routes) { definition.consumes(types); } return this; } @Override public Collection produces(final List<MediaType> types) { for (Props definition : routes) { definition.produces(types); } return this; } @Override public Collection attr(final String name, final Object value) { for (Props definition : routes) { definition.attr(name, value); } return this; } @Override public Collection excludes(final List<String> excludes) { for (Props definition : routes) { definition.excludes(excludes); } return this; } @Override public Collection map(final Mapper<?> mapper) { for (Props route : routes) { route.map(mapper); } return this; } } /** * DSL for customize routes. * * <p> * Some examples: * </p> * * <pre> * public class MyApp extends Jooby { * { * get("/", () {@literal ->} "GET"); * * post("/", req {@literal ->} "POST"); * * put("/", (req, rsp) {@literal ->} rsp.send("PUT")); * } * } * </pre> * * <h1>Setting what a route can consumes</h1> * * <pre> * public class MyApp extends Jooby { * { * post("/", (req, resp) {@literal ->} resp.send("POST")) * .consumes(MediaType.json); * } * } * </pre> * * <h1>Setting what a route can produces</h1> * * <pre> * public class MyApp extends Jooby { * { * post("/", (req, resp) {@literal ->} resp.send("POST")) * .produces(MediaType.json); * } * } * </pre> * * <h1>Adding a name</h1> * * <pre> * public class MyApp extends Jooby { * { * post("/", (req, resp) {@literal ->} resp.send("POST")) * .name("My Root"); * } * } * </pre> * * @author edgar * @since 0.1.0 */ class Definition implements Props<Definition> { /** * Route's name. */ private String name = "/anonymous"; /** * A route pattern. */ private RoutePattern cpattern; /** * The target route. */ private Filter filter; /** * Defines the media types that the methods of a resource class or can accept. Default is: * {@code *}/{@code *}. */ private List<MediaType> consumes = MediaType.ALL; /** * Defines the media types that the methods of a resource class or can produces. Default is: * {@code *}/{@code *}. */ private List<MediaType> produces = MediaType.ALL; /** * A HTTP verb or <code>*</code>. */ private String method; /** * A path pattern. */ private String pattern; private List<RoutePattern> excludes = Collections.emptyList(); private Map<String, Object> attributes = ImmutableMap.of(); private Mapper<?> mapper; private int line; private String declaringClass; String prefix; private String renderer; /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. */ public Definition(final String verb, final String pattern, final Route.Handler handler) { this(verb, pattern, (Route.Filter) handler); } /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. * @param caseSensitiveRouting Configure case for routing algorithm. */ public Definition(final String verb, final String pattern, final Route.Handler handler, boolean caseSensitiveRouting) { this(verb, pattern, (Route.Filter) handler, caseSensitiveRouting); } /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. */ public Definition(final String verb, final String pattern, final Route.OneArgHandler handler) { this(verb, pattern, (Route.Filter) handler); } /** * Creates a new route definition. * * @param verb A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A route handler. */ public Definition(final String verb, final String pattern, final Route.ZeroArgHandler handler) { this(verb, pattern, (Route.Filter) handler); } /** * Creates a new route definition. * * @param method A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param filter A callback to execute. */ public Definition(final String method, final String pattern, final Filter filter) { this(method, pattern, filter, true); } /** * Creates a new route definition. * * @param method A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param filter A callback to execute. * @param caseSensitiveRouting Configure case for routing algorithm. */ public Definition(final String method, final String pattern, final Filter filter, boolean caseSensitiveRouting) { requireNonNull(pattern, "A route path is required."); requireNonNull(filter, "A filter is required."); this.method = method.toUpperCase(); this.cpattern = new RoutePattern(method, pattern, !caseSensitiveRouting); // normalized pattern this.pattern = cpattern.pattern(); this.filter = filter; SourceProvider.INSTANCE.get().ifPresent(source -> { this.line = source.getLineNumber(); this.declaringClass = source.getClassName(); }); } /** * <h1>Path Patterns</h1> * <p> * Jooby supports Ant-style path patterns: * </p> * <p> * Some examples: * </p> * <ul> * <li>{@code com/t?st.html} - matches {@code com/test.html} but also {@code com/tast.jsp} or * {@code com/txst.html}</li> * <li>{@code com/*.html} - matches all {@code .html} files in the {@code com} directory</li> * <li><code>com/{@literal **}/test.html</code> - matches all {@code test.html} files underneath * the {@code com} path</li> * <li>{@code **}/{@code *} - matches any path at any level.</li> * <li>{@code *} - matches any path at any level, shorthand for {@code **}/{@code *}.</li> * </ul> * * <h2>Variables</h2> * <p> * Jooby supports path parameters too: * </p> * <p> * Some examples: * </p> * <ul> * <li><code> /user/{id}</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/:id</code> - /user/* and give you access to the <code>id</code> var.</li> * <li><code> /user/{id:\\d+}</code> - /user/[digits] and give you access to the numeric * <code>id</code> var.</li> * </ul> * * @return A path pattern. */ @Nonnull public String pattern() { return pattern; } @Nullable public String renderer() { return renderer; } @Override public Definition renderer(final String name) { this.renderer = name; return this; } /** * @return List of path variables (if any). */ @Nonnull public List<String> vars() { return cpattern.vars(); } /** * Indicates if the {@link #pattern()} contains a glob charecter, like <code>?</code>, * <code>*</code> or <code>**</code>. * * @return Indicates if the {@link #pattern()} contains a glob charecter, like <code>?</code>, * <code>*</code> or <code>**</code>. */ @Nonnull public boolean glob() { return cpattern.glob(); } /** * Source information (where the route was defined). * * @return Source information (where the route was defined). */ @Nonnull public Route.Source source() { return new RouteSourceImpl(declaringClass, line); } /** * Recreate a route path and apply the given variables. * * @param vars Path variables. * @return A route pattern. */ @Nonnull public String reverse(final Map<String, Object> vars) { return cpattern.reverse(vars); } /** * Recreate a route path and apply the given variables. * * @param values Path variable values. * @return A route pattern. */ @Nonnull public String reverse(final Object... values) { return cpattern.reverse(values); } @Override @Nonnull public Definition attr(final String name, final Object value) { requireNonNull(name, "Attribute name is required."); requireNonNull(value, "Attribute value is required."); if (valid(value)) { attributes = ImmutableMap.<String, Object>builder() .putAll(attributes) .put(name, value) .build(); } return this; } private boolean valid(final Object value) { if (Primitives.isWrapperType(Primitives.wrap(value.getClass()))) { return true; } if (value instanceof String || value instanceof Enum || value instanceof Class) { return true; } if (value.getClass().isArray() && Array.getLength(value) > 0) { return valid(Array.get(value, 0)); } if (value instanceof Map && ((Map) value).size() > 0) { Map.Entry e = (Map.Entry) ((Map) value).entrySet().iterator().next(); return valid(e.getKey()) && valid(e.getValue()); } return false; } /** * Get an attribute by name. * * @param name Attribute's name. * @param <T> Attribute's type. * @return Attribute's value or <code>null</code>. */ @SuppressWarnings("unchecked") @Nonnull public <T> T attr(final String name) { return (T) attributes.get(name); } /** * @return A read only view of attributes. */ @Nonnull public Map<String, Object> attributes() { return attributes; } /** * Test if the route matches the given verb, path, content type and accept header. * * @param method A HTTP verb. * @param path Current HTTP path. * @param contentType The <code>Content-Type</code> header. * @param accept The <code>Accept</code> header. * @return A route or an empty optional. */ @Nonnull public Optional<Route> matches(final String method, final String path, final MediaType contentType, final List<MediaType> accept) { String fpath = method + path; if (excludes.size() > 0 && excludes(fpath)) { return Optional.empty(); } RouteMatcher matcher = cpattern.matcher(fpath); if (matcher.matches()) { List<MediaType> result = MediaType.matcher(accept).filter(this.produces); if (result.size() > 0 && canConsume(contentType)) { // keep accept when */* List<MediaType> produces = result.size() == 1 && result.get(0).name().equals("*/*") ? accept : this.produces; return Optional .of(asRoute(method, matcher, produces, new RouteSourceImpl(declaringClass, line))); } } return Optional.empty(); } /** * @return HTTP method or <code>*</code>. */ @Nonnull public String method() { return method; } /** * @return Handler behind this route. */ @Nonnull public Route.Filter filter() { return filter; } /** * Route's name, helpful for debugging but also to implement dynamic and advanced routing. See * {@link Route.Chain#next(String, Request, Response)} * * @return Route name. Default is: <code>anonymous</code>. */ @Nonnull public String name() { return name; } /** * Set the route name. Route's name, helpful for debugging but also to implement dynamic and * advanced routing. See {@link Route.Chain#next(String, Request, Response)} * * * @param name A route's name. * @return This definition. */ @Override @Nonnull public Definition name(final String name) { checkArgument(!Strings.isNullOrEmpty(name), "A route's name is required."); this.name = normalize(prefix != null ? prefix + "/" + name : name); return this; } /** * Test if the route definition can consume a media type. * * @param type A media type to test. * @return True, if the route can consume the given media type. */ public boolean canConsume(final MediaType type) { return MediaType.matcher(Arrays.asList(type)).matches(consumes); } /** * Test if the route definition can consume a media type. * * @param type A media type to test. * @return True, if the route can consume the given media type. */ public boolean canConsume(final String type) { return MediaType.matcher(MediaType.valueOf(type)).matches(consumes); } /** * Test if the route definition can consume a media type. * * @param types A media types to test. * @return True, if the route can produces the given media type. */ public boolean canProduce(final List<MediaType> types) { return MediaType.matcher(types).matches(produces); } /** * Test if the route definition can consume a media type. * * @param types A media types to test. * @return True, if the route can produces the given media type. */ public boolean canProduce(final MediaType... types) { return canProduce(Arrays.asList(types)); } /** * Test if the route definition can consume a media type. * * @param types A media types to test. * @return True, if the route can produces the given media type. */ public boolean canProduce(final String... types) { return canProduce(MediaType.valueOf(types)); } @Override public Definition consumes(final List<MediaType> types) { checkArgument(types != null && types.size() > 0, "Consumes types are required"); if (types.size() > 1) { this.consumes = Lists.newLinkedList(types); Collections.sort(this.consumes); } else { this.consumes = ImmutableList.of(types.get(0)); } return this; } @Override public Definition produces(final List<MediaType> types) { checkArgument(types != null && types.size() > 0, "Produces types are required"); if (types.size() > 1) { this.produces = Lists.newLinkedList(types); Collections.sort(this.produces); } else { this.produces = ImmutableList.of(types.get(0)); } return this; } @Override public Definition excludes(final List<String> excludes) { this.excludes = excludes.stream() .map(it -> new RoutePattern(method, it)) .collect(Collectors.toList()); return this; } /** * @return List of exclusion filters (if any). */ @Nonnull public List<String> excludes() { return excludes.stream().map(r -> r.pattern()).collect(Collectors.toList()); } private boolean excludes(final String path) { for (RoutePattern pattern : excludes) { if (pattern.matcher(path).matches()) { return true; } } return false; } /** * @return All the types this route can consumes. */ @Nonnull public List<MediaType> consumes() { return Collections.unmodifiableList(this.consumes); } /** * @return All the types this route can produces. */ @Nonnull public List<MediaType> produces() { return Collections.unmodifiableList(this.produces); } @Override @Nonnull public Definition map(final Mapper<?> mapper) { this.mapper = requireNonNull(mapper, "Mapper is required."); return this; } /** * Set the line where this route is defined. * * @param line Line number. * @return This instance. */ @Nonnull public Definition line(final int line) { this.line = line; return this; } /** * Set the class where this route is defined. * * @param declaringClass A source class. * @return This instance. */ @Nonnull public Definition declaringClass(final String declaringClass) { this.declaringClass = declaringClass; return this; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(method()).append(" ").append(pattern()).append("\n"); buffer.append(" name: ").append(name()).append("\n"); buffer.append(" excludes: ").append(excludes).append("\n"); buffer.append(" consumes: ").append(consumes()).append("\n"); buffer.append(" produces: ").append(produces()).append("\n"); return buffer.toString(); } /** * Creates a new route. * * @param method A HTTP verb. * @param matcher A route matcher. * @param produces List of produces types. * @param source Route source. * @return A new route. */ private Route asRoute(final String method, final RouteMatcher matcher, final List<MediaType> produces, final Route.Source source) { return new RouteImpl(filter, this, method, matcher.path(), produces, matcher.vars(), mapper, source); } } /** * A forwarding route. * * @author edgar * @since 0.1.0 */ class Forwarding implements Route { /** * Target route. */ private final Route route; /** * Creates a new {@link Forwarding} route. * * @param route A target route. */ public Forwarding(final Route route) { this.route = route; } @Override public String renderer() { return route.renderer(); } @Override public String path() { return route.path(); } @Override public String method() { return route.method(); } @Override public String pattern() { return route.pattern(); } @Override public String name() { return route.name(); } @Override public Map<Object, String> vars() { return route.vars(); } @Override public List<MediaType> consumes() { return route.consumes(); } @Override public List<MediaType> produces() { return route.produces(); } @Override public Map<String, Object> attributes() { return route.attributes(); } @Override public <T> T attr(final String name) { return route.attr(name); } @Override public boolean glob() { return route.glob(); } @Override public String reverse(final Map<String, Object> vars) { return route.reverse(vars); } @Override public String reverse(final Object... values) { return route.reverse(values); } @Override public Source source() { return route.source(); } @Override public String print() { return route.print(); } @Override public String print(final int indent) { return route.print(indent); } @Override public String toString() { return route.toString(); } /** * Find a target route. * * @param route A route to check. * @return A target route. */ public static Route unwrap(final Route route) { Route root = route; while (root instanceof Forwarding) { root = ((Forwarding) root).route; } return root; } } /** * The most advanced route handler which let you decided if the next route handler in the chain * can be executed or not. Example of filters are: * * <p> * Auth handler example: * </p> * * <pre> * String token = req.header("token").value(); * if (token != null) { * // validate token... * if (valid(token)) { * chain.next(req, rsp); * } * } else { * rsp.status(403); * } * </pre> * * <p> * Logging/Around handler example: * </p> * * <pre> * long start = System.currentTimeMillis(); * chain.next(req, rsp); * long end = System.currentTimeMillis(); * log.info("Request: {} took {}ms", req.path(), end - start); * </pre> * * NOTE: Don't forget to call {@link Route.Chain#next(Request, Response)} if next route handler * need to be executed. * * @author edgar * @since 0.1.0 */ public interface Filter { /** * The <code>handle</code> method of the Filter is called by the server each time a * request/response pair is passed through the chain due to a client request for a resource at * the end of the chain. * The {@link Route.Chain} passed in to this method allows the Filter to pass on the request and * response to the next entity in the chain. * * <p> * A typical implementation of this method would follow the following pattern: * </p> * <ul> * <li>Examine the request</li> * <li>Optionally wrap the request object with a custom implementation to filter content or * headers for input filtering</li> * <li>Optionally wrap the response object with a custom implementation to filter content or * headers for output filtering</li> * <li> * <ul> * <li><strong>Either</strong> invoke the next entity in the chain using the {@link Route.Chain} * object (<code>chain.next(req, rsp)</code>),</li> * <li><strong>or</strong> not pass on the request/response pair to the next entity in the * filter chain to block the request processing</li> * </ul> * <li>Directly set headers on the response after invocation of the next entity in the filter * chain.</li> * </ul> * * @param req A HTTP request. * @param rsp A HTTP response. * @param chain A route chain. * @throws Throwable If something goes wrong. */ void handle(Request req, Response rsp, Route.Chain chain) throws Throwable; } /** * Allow to customize an asset handler. * * @author edgar */ class AssetDefinition extends Definition { private Boolean etag; private String cdn; private Object maxAge; private Boolean lastModifiedSince; private Integer statusCode; /** * Creates a new route definition. * * @param method A HTTP verb or <code>*</code>. * @param pattern A path pattern. * @param handler A callback to execute. * @param caseSensitiveRouting Configure case for routing algorithm. */ public AssetDefinition(final String method, final String pattern, final Route.Filter handler, boolean caseSensitiveRouting) { super(method, pattern, handler, caseSensitiveRouting); filter().setRoute(this); } @Nonnull @Override public AssetHandler filter() { return (AssetHandler) super.filter(); } /** * Indicates what to do when an asset is missing (not resolved). Default action is to resolve them * as <code>404 (NOT FOUND)</code> request. * * If you specify a status code &lt;= 0, missing assets are ignored and the next handler on pipeline * will be executed. * * @param statusCode HTTP code or 0. * @return This route definition. */ public AssetDefinition onMissing(final int statusCode) { if (this.statusCode == null) { filter().onMissing(statusCode); this.statusCode = statusCode; } return this; } /** * @param etag Turn on/off etag support. * @return This route definition. */ public AssetDefinition etag(final boolean etag) { if (this.etag == null) { filter().etag(etag); this.etag = etag; } return this; } /** * @param enabled Turn on/off last modified support. * @return This route definition. */ public AssetDefinition lastModified(final boolean enabled) { if (this.lastModifiedSince == null) { filter().lastModified(enabled); this.lastModifiedSince = enabled; } return this; } /** * @param cdn If set, every resolved asset will be serve from it. * @return This route definition. */ public AssetDefinition cdn(final String cdn) { if (this.cdn == null) { filter().cdn(cdn); this.cdn = cdn; } return this; } /** * @param maxAge Set the cache header max-age value. * @return This route definition. */ public AssetDefinition maxAge(final Duration maxAge) { if (this.maxAge == null) { filter().maxAge(maxAge); this.maxAge = maxAge; } return this; } /** * @param maxAge Set the cache header max-age value in seconds. * @return This route definition. */ public AssetDefinition maxAge(final long maxAge) { if (this.maxAge == null) { filter().maxAge(maxAge); this.maxAge = maxAge; } return this; } /** * Parse value as {@link Duration}. If the value is already a number then it uses as seconds. * Otherwise, it parse expressions like: 8m, 1h, 365d, etc... * * @param maxAge Set the cache header max-age value in seconds. * @return This route definition. */ public AssetDefinition maxAge(final String maxAge) { if (this.maxAge == null) { filter().maxAge(maxAge); this.maxAge = maxAge; } return this; } } /** * A route handler that always call {@link Chain#next(Request, Response)}. * * <pre> * public class MyApp extends Jooby { * { * get("/", (req, rsp) {@literal ->} rsp.send("Hello")); * } * } * </pre> * * @author edgar * @since 0.1.0 */ interface Handler extends Filter { @Override default void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { handle(req, rsp); chain.next(req, rsp); } /** * Callback method for a HTTP request. * * @param req A HTTP request. * @param rsp A HTTP response. * @throws Throwable If something goes wrong. The exception will processed by Jooby. */ void handle(Request req, Response rsp) throws Throwable; } /** * A handler for a MVC route, it extends {@link Handler} by adding a reference to the method * and class behind this route. * * @author edgar * @since 0.6.2 */ interface MethodHandler extends Handler { /** * Target method. * * @return Target method. */ @Nonnull Method method(); /** * Target class. * * @return Target class. */ @Nonnull Class<?> implementingClass(); } /** * A functional route handler that use the return value as HTTP response. * * <pre> * { * get("/",(req {@literal ->} "Hello"); * } * </pre> * * @author edgar * @since 0.1.1 */ interface OneArgHandler extends Filter { @Override default void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { Object result = handle(req); rsp.send(result); chain.next(req, rsp); } /** * Callback method for a HTTP request. * * @param req A HTTP request. * @return Message to send. * @throws Throwable If something goes wrong. The exception will processed by Jooby. */ Object handle(Request req) throws Throwable; } /** * A functional handler that use the return value as HTTP response. * * <pre> * public class MyApp extends Jooby { * { * get("/", () {@literal ->} "Hello"); * } * } * </pre> * * @author edgar * @since 0.1.1 */ interface ZeroArgHandler extends Filter { @Override default void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { Object result = handle(); rsp.send(result); chain.next(req, rsp); } /** * Callback method for a HTTP request. * * @return Message to send. * @throws Throwable If something goes wrong. The exception will processed by Jooby. */ Object handle() throws Throwable; } /** * <h2>before</h2> * * Allows for customized handler execution chains. It will be invoked before the actual handler. * * <pre>{@code * { * before((req, rsp) -> { * // your code goes here * }); * } * }</pre> * * You are allowed to modify the request and response objects. * * Please note that the <code>before</code> handler is just syntax sugar for {@link Route.Filter}. * For example, the <code>before</code> handler was implemented as: * * <pre>{@code * { * use("*", "*", (req, rsp, chain) -> { * before(req, rsp); * // your code goes here * chain.next(req, rsp); * }); * } * }</pre> * * A <code>before</code> handler must to be registered before the actual handler you want to * intercept. * * <pre>{@code * { * before((req, rsp) -> { * // your code goes here * }); * * get("/path", req -> { * // your code goes here * return ...; * }); * } * }</pre> * * If you reverse the order then it won't work. * * <p> * <strong>Remember</strong>: routes are executed in the order they are defined and the pipeline * is executed as long you don't generate a response. * </p> * * @author edgar * @since 1.0.0.CR */ interface Before extends Route.Filter { @Override default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { handle(req, rsp); chain.next(req, rsp); } /** * Allows for customized handler execution chains. It will be invoked before the actual handler. * * @param req Request. * @param rsp Response * @throws Throwable If something goes wrong. */ void handle(Request req, Response rsp) throws Throwable; } /** * <h2>after</h2> * * Allows for customized response before send it. It will be invoked at the time a response need * to be send. * * <pre>{@code * { * after("GET", "*", (req, rsp, result) -> { * // your code goes here * return result; * }); * } * }</pre> * * You are allowed to modify the request, response and result objects. The handler returns a * {@link Result} which can be the same or an entirely new {@link Result}. * * Please note that the <code>after</code> handler is just syntax sugar for * {@link Route.Filter}. * For example, the <code>after</code> handler was implemented as: * * <pre>{@code * { * use("GET", "*", (req, rsp, chain) -> { * chain.next(req, new Response.Forwarding(rsp) { * public void send(Result result) { * rsp.send(after(req, rsp, result); * } * }); * }); * } * }</pre> * * Due <code>after</code> is implemented by wrapping the {@link Response} object. A * <code>after</code> handler must to be registered before the actual handler you want to * intercept. * * <pre>{@code * { * after("GET", "/path", (req, rsp, result) -> { * // your code goes here * return result; * }); * * get("/path", req -> { * return "hello"; * }); * } * }</pre> * * If you reverse the order then it won't work. * * <p> * <strong>Remember</strong>: routes are executed in the order they are defined and the pipeline * is executed as long you don't generate a response. * </p> * * @author edgar * @since 1.0.0.CR */ interface After extends Filter { @Override default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { rsp.after(this); chain.next(req, rsp); } /** * Allows for customized response before send it. It will be invoked at the time a response need * to be send. * * @param req Request. * @param rsp Response * @param result Result. * @return Same or new result. * @throws Exception If something goes wrong. */ Result handle(Request req, Response rsp, Result result) throws Exception; } /** * <h2>complete</h2> * * Allows for log and cleanup a request. It will be invoked after we send a response. * * <pre>{@code * { * complete((req, rsp, cause) -> { * // your code goes here * }); * } * }</pre> * * You are NOT allowed to modify the request and response objects. The <code>cause</code> is an * {@link Optional} with a {@link Throwable} useful to identify problems. * * The goal of the <code>complete</code> handler is to probably cleanup request object and log * responses. * * Please note that the <code>complete</code> handler is just syntax sugar for * {@link Route.Filter}. * For example, the <code>complete</code> handler was implemented as: * * <pre>{@code * { * use("*", "*", (req, rsp, chain) -> { * Optional<Throwable> err = Optional.empty(); * try { * chain.next(req, rsp); * } catch (Throwable cause) { * err = Optional.of(cause); * } finally { * complete(req, rsp, err); * } * }); * } * }</pre> * * An <code>complete</code> handler must to be registered before the actual handler you want to * intercept. * * <pre>{@code * { * complete((req, rsp, cause) -> { * // your code goes here * }); * * get(req -> { * return "hello"; * }); * } * }</pre> * * If you reverse the order then it won't work. * * <p> * <strong>Remember</strong>: routes are executed in the order they are defined and the pipeline * is executed as long you don't generate a response. * </p> * * <h2>example</h2> * <p> * Suppose you have a transactional resource, like a database connection. The next example shows * you how to implement a simple and effective <code>transaction-per-request</code> pattern: * </p> * * <pre>{@code * { * // start transaction * before((req, rsp) -> { * DataSource ds = req.require(DataSource.class); * Connection connection = ds.getConnection(); * Transaction trx = connection.getTransaction(); * trx.begin(); * req.set("connection", connection); * return true; * }); * * // commit/rollback transaction * complete((req, rsp, cause) -> { * // unbind connection from request * try(Connection connection = req.unset("connection").get()) { * Transaction trx = connection.getTransaction(); * if (cause.ifPresent()) { * trx.rollback(); * } else { * trx.commit(); * } * } * }); * * // your transactional routes goes here * get("/api/something", req -> { * Connection connection = req.get("connection"); * // work with connection * }); * } * }</pre> * * @author edgar * @since 1.0.0.CR */ interface Complete extends Filter { @Override default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable { rsp.complete(this); chain.next(req, rsp); } /** * Allows for log and cleanup a request. It will be invoked after we send a response. * * @param req Request. * @param rsp Response * @param cause Empty optional on success. Otherwise, it contains the exception. */ void handle(Request req, Response rsp, Optional<Throwable> cause); } /** * Chain of routes to be executed. It invokes the next route in the chain. * * @author edgar * @since 0.1.0 */ interface Chain { /** * Invokes the next route in the chain where {@link Route#name()} starts with the given prefix. * * @param prefix Iterates over the route chain and keep routes that start with the given prefix. * @param req A HTTP request. * @param rsp A HTTP response. * @throws Throwable If invocation goes wrong. */ void next(@Nullable String prefix, Request req, Response rsp) throws Throwable; /** * Invokes the next route in the chain. * * @param req A HTTP request. * @param rsp A HTTP response. * @throws Throwable If invocation goes wrong. */ default void next(final Request req, final Response rsp) throws Throwable { next(null, req, rsp); } /** * All the pending/next routes from pipeline. Example: * * <pre>{@code * use("*", (req, rsp, chain) -> { * List<Route> routes = chain.routes(); * assertEquals(2, routes.size()); * assertEquals("/r2", routes.get(0).name()); * assertEquals("/r3", routes.get(1).name()); * assertEquals("/786/:id", routes.get(routes.size() - 1).pattern()); * * chain.next(req, rsp); * }).name("r1"); * * use("/786/**", (req, rsp, chain) -> { * List<Route> routes = chain.routes(); * assertEquals(1, routes.size()); * assertEquals("/r3", routes.get(0).name()); * assertEquals("/786/:id", routes.get(routes.size() - 1).pattern()); * chain.next(req, rsp); * }).name("r2"); * * get("/786/:id", req -> { * return req.param("id").value(); * }).name("r3"); * }</pre> * * @return Next routes in the pipeline or empty list. */ List<Route> routes(); } /** Route key. */ Key<Set<Route.Definition>> KEY = Key.get(new TypeLiteral<Set<Route.Definition>>() { }); char OUT_OF_PATH = '\u200B'; String GET = "GET"; String POST = "POST"; String PUT = "PUT"; String DELETE = "DELETE"; String PATCH = "PATCH"; String HEAD = "HEAD"; String CONNECT = "CONNECT"; String OPTIONS = "OPTIONS"; String TRACE = "TRACE"; /** * Well known HTTP methods. */ List<String> METHODS = ImmutableList.<String>builder() .add(GET, POST, PUT, DELETE, PATCH, HEAD, CONNECT, OPTIONS, TRACE) .build(); /** * @return Current request path. */ @Nonnull String path(); /** * @return Current HTTP method. */ @Nonnull String method(); /** * @return The currently matched pattern. */ @Nonnull String pattern(); /** * Route's name, helpful for debugging but also to implement dynamic and advanced routing. See * {@link Route.Chain#next(String, Request, Response)} * * @return Route name, defaults to <code>"anonymous"</code> */ @Nonnull String name(); /** * Path variables, either named or by index (capturing group). * * <pre> * /path/:var * </pre> * * Variable <code>var</code> is accessible by name: <code>var</code> or index: <code>0</code>. * * @return The currently matched path variables (if any). */ @Nonnull Map<Object, String> vars(); /** * @return List all the types this route can consumes, defaults is: {@code * / *}. */ @Nonnull List<MediaType> consumes(); /** * @return List all the types this route can produces, defaults is: {@code * / *}. */ @Nonnull List<MediaType> produces(); /** * True, when route's name starts with the given prefix. Useful for dynamic routing. See * {@link Route.Chain#next(String, Request, Response)} * * @param prefix Prefix to check for. * @return True, when route's name starts with the given prefix. */ default boolean apply(final String prefix) { return name().startsWith(prefix); } /** * @return All the available attributes in the execution chain. */ @Nonnull Map<String, Object> attributes(); /** * Attribute by name. * * @param name Attribute's name. * @param <T> Attribute's type. * @return Attribute value. */ @SuppressWarnings("unchecked") @Nonnull default <T> T attr(final String name) { return (T) attributes().get(name); } /** * Explicit renderer to use or <code>null</code>. * * @return Explicit renderer to use or <code>null</code>. */ @Nonnull String renderer(); /** * Indicates if the {@link #pattern()} contains a glob character, like <code>?</code>, * <code>*</code> or <code>**</code>. * * @return Indicates if the {@link #pattern()} contains a glob charecter, like <code>?</code>, * <code>*</code> or <code>**</code>. */ boolean glob(); /** * Recreate a route path and apply the given variables. * * @param vars Path variables. * @return A route pattern. */ @Nonnull String reverse(final Map<String, Object> vars); /** * Recreate a route path and apply the given variables. * * @param values Path variable values. * @return A route pattern. */ @Nonnull String reverse(final Object... values); /** * Normalize a path by removing double or trailing slashes. * * @param path A path to normalize. * @return A normalized path. */ @Nonnull static String normalize(final String path) { return RoutePattern.normalize(path); } /** * Remove invalid path mark when present. * * @param path Path. * @return Original path. */ @Nonnull static String unerrpath(final String path) { if (path.charAt(0) == OUT_OF_PATH) { return path.substring(1); } return path; } /** * Mark a path as invalid. * * @param path Path. * @return Invalid path. */ @Nonnull static String errpath(final String path) { return OUT_OF_PATH + path; } /** * Source information (where the route was defined). * * @return Source information (where the route was defined). */ @Nonnull Route.Source source(); /** * Print route information like: method, path, source, etc... Useful for debugging. * * @param indent Indent level * @return Output. */ @Nonnull default String print(final int indent) { StringBuilder buff = new StringBuilder(); String[] header = {"Method", "Path", "Source", "Name", "Pattern", "Consumes", "Produces"}; String[] values = {method(), path(), source().toString(), name(), pattern(), consumes().toString(), produces().toString()}; BiConsumer<Function<Integer, String>, Character> format = (v, s) -> { buff.append(Strings.padEnd("", indent, ' ')) .append("|").append(s); for (int i = 0; i < header.length; i++) { buff .append(Strings.padEnd(v.apply(i), Math.max(header[i].length(), values[i].length()), s)) .append(s).append("|").append(s); } buff.setLength(buff.length() - 1); }; format.accept(i -> header[i], ' '); buff.append("\n"); format.accept(i -> "-", '-'); buff.append("\n"); format.accept(i -> values[i], ' '); return buff.toString(); } /** * Print route information like: method, path, source, etc... Useful for debugging. * * @return Output. */ @Nonnull default String print() { return print(0); } }
./CrossVul/dataset_final_sorted/CWE-22/java/good_4612_1
crossvul-java_data_bad_2092_0
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.cli; import hudson.model.ModifiableItemGroup; import hudson.model.TopLevelItem; import jenkins.model.Jenkins; import hudson.Extension; import hudson.model.Item; import jenkins.model.ModifiableTopLevelItemGroup; import org.kohsuke.args4j.Argument; /** * Creates a new job by reading stdin as a configuration XML file. * * @author Kohsuke Kawaguchi */ @Extension public class CreateJobCommand extends CLICommand { @Override public String getShortDescription() { return Messages.CreateJobCommand_ShortDescription(); } @Argument(metaVar="NAME",usage="Name of the job to create",required=true) public String name; protected int run() throws Exception { Jenkins h = Jenkins.getInstance(); h.checkPermission(Item.CREATE); if (h.getItemByFullName(name)!=null) { stderr.println("Job '"+name+"' already exists"); return -1; } ModifiableTopLevelItemGroup ig = h; int i = name.lastIndexOf('/'); if (i > 0) { String group = name.substring(0, i); Item item = h.getItemByFullName(group); if (item == null) { throw new IllegalArgumentException("Unknown ItemGroup " + group); } if (item instanceof ModifiableTopLevelItemGroup) { ig = (ModifiableTopLevelItemGroup) item; } else { throw new IllegalArgumentException("Can't create job from CLI in " + group); } name = name.substring(i + 1); } ig.createProjectFromXML(name, stdin); return 0; } }
./CrossVul/dataset_final_sorted/CWE-22/java/bad_2092_0
crossvul-java_data_good_854_1
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.ShortStack; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** * TCompactProtocol2 is the Java implementation of the compact protocol specified in THRIFT-110. The * fundamental approach to reducing the overhead of structures is a) use variable-length integers * all over the place and b) make use of unused bits wherever possible. Your savings will obviously * vary based on the specific makeup of your structs, but in general, the more fields, nested * structures, short strings and collections, and low-value i32 and i64 fields you have, the more * benefit you'll see. */ public class TCompactProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(""); private static final TField TSTOP = new TField("", TType.STOP, (short) 0); private static final byte[] ttypeToCompactType = new byte[20]; static { ttypeToCompactType[TType.STOP] = TType.STOP; ttypeToCompactType[TType.BOOL] = Types.BOOLEAN_TRUE; ttypeToCompactType[TType.BYTE] = Types.BYTE; ttypeToCompactType[TType.I16] = Types.I16; ttypeToCompactType[TType.I32] = Types.I32; ttypeToCompactType[TType.I64] = Types.I64; ttypeToCompactType[TType.DOUBLE] = Types.DOUBLE; ttypeToCompactType[TType.STRING] = Types.BINARY; ttypeToCompactType[TType.LIST] = Types.LIST; ttypeToCompactType[TType.SET] = Types.SET; ttypeToCompactType[TType.MAP] = Types.MAP; ttypeToCompactType[TType.STRUCT] = Types.STRUCT; ttypeToCompactType[TType.FLOAT] = Types.FLOAT; } /** TProtocolFactory that produces TCompactProtocols. */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { private final long maxNetworkBytes_; public Factory() { maxNetworkBytes_ = -1; } public Factory(int maxNetworkBytes) { maxNetworkBytes_ = maxNetworkBytes; } public TProtocol getProtocol(TTransport trans) { return new TCompactProtocol(trans, maxNetworkBytes_); } } public static final byte PROTOCOL_ID = (byte) 0x82; public static final byte VERSION = 2; public static final byte VERSION_LOW = 1; public static final byte VERSION_DOUBLE_BE = 2; public static final byte VERSION_MASK = 0x1f; // 0001 1111 public static final byte TYPE_MASK = (byte) 0xE0; // 1110 0000 public static final int TYPE_SHIFT_AMOUNT = 5; /** All of the on-wire type codes. */ private static class Types { public static final byte BOOLEAN_TRUE = 0x01; public static final byte BOOLEAN_FALSE = 0x02; public static final byte BYTE = 0x03; public static final byte I16 = 0x04; public static final byte I32 = 0x05; public static final byte I64 = 0x06; public static final byte DOUBLE = 0x07; public static final byte BINARY = 0x08; public static final byte LIST = 0x09; public static final byte SET = 0x0A; public static final byte MAP = 0x0B; public static final byte STRUCT = 0x0C; public static final byte FLOAT = 0x0D; } /** * Used to keep track of the last field for the current and previous structs, so we can do the * delta stuff. */ private ShortStack lastField_ = new ShortStack(15); private short lastFieldId_ = 0; private byte version_ = VERSION; /** * If we encounter a boolean field begin, save the TField here so it can have the value * incorporated. */ private TField booleanField_ = null; /** * If we read a field header, and it's a boolean field, save the boolean value here so that * readBool can use it. */ private Boolean boolValue_ = null; /** * The maximum number of bytes to read from the network for variable-length fields (such as * strings or binary) or -1 for unlimited. */ private final long maxNetworkBytes_; /** Temporary buffer to avoid allocations */ private final byte[] buffer = new byte[10]; /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. * @param maxNetworkBytes the maximum number of bytes to read for variable-length fields. */ public TCompactProtocol(TTransport transport, long maxNetworkBytes) { super(transport); maxNetworkBytes_ = maxNetworkBytes; } /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. */ public TCompactProtocol(TTransport transport) { this(transport, -1); } public void reset() { lastField_.clear(); lastFieldId_ = 0; } // // Public Writing methods. // /** * Write a message header to the wire. Compact Protocol messages contain the protocol version so * we can migrate forwards in the future if need be. */ public void writeMessageBegin(TMessage message) throws TException { writeByteDirect(PROTOCOL_ID); writeByteDirect((VERSION & VERSION_MASK) | ((message.type << TYPE_SHIFT_AMOUNT) & TYPE_MASK)); writeVarint32(message.seqid); writeString(message.name); } /** * Write a struct begin. This doesn't actually put anything on the wire. We use it as an * opportunity to put special placeholder markers on the field stack so we can get the field id * deltas correct. */ public void writeStructBegin(TStruct struct) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; } /** * Write a struct end. This doesn't actually put anything on the wire. We use this as an * opportunity to pop the last field from the current struct off of the field stack. */ public void writeStructEnd() throws TException { lastFieldId_ = lastField_.pop(); } /** * Write a field header containing the field id and field type. If the difference between the * current field id and the last one is small (< 15), then the field id will be encoded in the 4 * MSB as a delta. Otherwise, the field id will follow the type header as a zigzag varint. */ public void writeFieldBegin(TField field) throws TException { if (field.type == TType.BOOL) { // we want to possibly include the value, so we'll wait. booleanField_ = field; } else { writeFieldBeginInternal(field, (byte) -1); } } /** * The workhorse of writeFieldBegin. It has the option of doing a 'type override' of the type * header. This is used specifically in the boolean field case. */ private void writeFieldBeginInternal(TField field, byte typeOverride) throws TException { // short lastField = lastField_.pop(); // if there's a type override, use that. byte typeToWrite = typeOverride == -1 ? getCompactType(field.type) : typeOverride; // check if we can use delta encoding for the field id if (field.id > lastFieldId_ && field.id - lastFieldId_ <= 15) { // write them together writeByteDirect((field.id - lastFieldId_) << 4 | typeToWrite); } else { // write them separate writeByteDirect(typeToWrite); writeI16(field.id); } lastFieldId_ = field.id; // lastField_.push(field.id); } /** Write the STOP symbol so we know there are no more fields in this struct. */ public void writeFieldStop() throws TException { writeByteDirect(TType.STOP); } /** * Write a map header. If the map is empty, omit the key and value type headers, as we don't need * any additional information to skip it. */ public void writeMapBegin(TMap map) throws TException { if (map.size == 0) { writeByteDirect(0); } else { writeVarint32(map.size); writeByteDirect(getCompactType(map.keyType) << 4 | getCompactType(map.valueType)); } } /** Write a list header. */ public void writeListBegin(TList list) throws TException { writeCollectionBegin(list.elemType, list.size); } /** Write a set header. */ public void writeSetBegin(TSet set) throws TException { writeCollectionBegin(set.elemType, set.size); } /** * Write a boolean value. Potentially, this could be a boolean field, in which case the field * header info isn't written yet. If so, decide what the right type header is for the value and * then write the field header. Otherwise, write a single byte. */ public void writeBool(boolean b) throws TException { if (booleanField_ != null) { // we haven't written the field header yet writeFieldBeginInternal(booleanField_, b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); booleanField_ = null; } else { // we're not part of a field, so just write the value. writeByteDirect(b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); } } /** Write a byte. Nothing to see here! */ public void writeByte(byte b) throws TException { writeByteDirect(b); } /** Write an I16 as a zigzag varint. */ public void writeI16(short i16) throws TException { writeVarint32(intToZigZag(i16)); } /** Write an i32 as a zigzag varint. */ public void writeI32(int i32) throws TException { writeVarint32(intToZigZag(i32)); } /** Write an i64 as a zigzag varint. */ public void writeI64(long i64) throws TException { writeVarint64(longToZigzag(i64)); } /** Write a double to the wire as 8 bytes. */ public void writeDouble(double dub) throws TException { fixedLongToBytes(Double.doubleToLongBits(dub), buffer, 0); trans_.write(buffer, 0, 8); } /** Write a float to the wire as 4 bytes. */ public void writeFloat(float flt) throws TException { fixedIntToBytes(Float.floatToIntBits(flt), buffer, 0); trans_.write(buffer, 0, 4); } /** Write a string to the wire with a varint size preceding. */ public void writeString(String str) throws TException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); writeBinary(bytes, 0, bytes.length); } /** Write a byte array, using a varint for the size. */ public void writeBinary(byte[] buf) throws TException { writeBinary(buf, 0, buf.length); } private void writeBinary(byte[] buf, int offset, int length) throws TException { writeVarint32(length); trans_.write(buf, offset, length); } // // These methods are called by structs, but don't actually have any wire // output or purpose. // public void writeMessageEnd() throws TException {} public void writeMapEnd() throws TException {} public void writeListEnd() throws TException {} public void writeSetEnd() throws TException {} public void writeFieldEnd() throws TException {} // // Internal writing methods // /** * Abstract method for writing the start of lists and sets. List and sets on the wire differ only * by the type indicator. */ protected void writeCollectionBegin(byte elemType, int size) throws TException { if (size <= 14) { writeByteDirect(size << 4 | getCompactType(elemType)); } else { writeByteDirect(0xf0 | getCompactType(elemType)); writeVarint32(size); } } /** Write an i32 as a varint. Results in 1-5 bytes on the wire. */ private void writeVarint32(int n) throws TException { int idx = 0; while (true) { if ((n & ~0x7F) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = (byte) ((n & 0x7F) | 0x80); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** Write an i64 as a varint. Results in 1-10 bytes on the wire. */ private void writeVarint64(long n) throws TException { int idx = 0; while (true) { if ((n & ~0x7FL) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = ((byte) ((n & 0x7F) | 0x80)); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** * Convert l into a zigzag long. This allows negative numbers to be represented compactly as a * varint. */ private long longToZigzag(long l) { return (l << 1) ^ (l >> 63); } /** * Convert n into a zigzag int. This allows negative numbers to be represented compactly as a * varint. */ private int intToZigZag(int n) { return (n << 1) ^ (n >> 31); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedLongToBytes(long n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 56) & 0xff); buf[off + 1] = (byte) ((n >> 48) & 0xff); buf[off + 2] = (byte) ((n >> 40) & 0xff); buf[off + 3] = (byte) ((n >> 32) & 0xff); buf[off + 4] = (byte) ((n >> 24) & 0xff); buf[off + 5] = (byte) ((n >> 16) & 0xff); buf[off + 6] = (byte) ((n >> 8) & 0xff); buf[off + 7] = (byte) (n & 0xff); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedIntToBytes(int n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 24) & 0xff); buf[off + 1] = (byte) ((n >> 16) & 0xff); buf[off + 2] = (byte) ((n >> 8) & 0xff); buf[off + 3] = (byte) (n & 0xff); } /** * Writes a byte without any possiblity of all that field header nonsense. Used internally by * other writing methods that know they need to write a byte. */ private void writeByteDirect(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } /** Writes a byte without any possiblity of all that field header nonsense. */ private void writeByteDirect(int n) throws TException { writeByteDirect((byte) n); } // // Reading methods. // /** Read a message header. */ public TMessage readMessageBegin() throws TException { byte protocolId = readByte(); if (protocolId != PROTOCOL_ID) { throw new TProtocolException( "Expected protocol id " + Integer.toHexString(PROTOCOL_ID) + " but got " + Integer.toHexString(protocolId)); } byte versionAndType = readByte(); version_ = (byte) (versionAndType & VERSION_MASK); if (!(version_ <= VERSION && version_ >= VERSION_LOW)) { throw new TProtocolException("Expected version " + VERSION + " but got " + version_); } byte type = (byte) ((versionAndType >> TYPE_SHIFT_AMOUNT) & 0x03); int seqid = readVarint32(); String messageName = readString(); return new TMessage(messageName, type, seqid); } /** * Read a struct begin. There's nothing on the wire for this, but it is our opportunity to push a * new struct begin marker onto the field stack. */ public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; return ANONYMOUS_STRUCT; } /** * Doesn't actually consume any wire data, just removes the last field for this struct from the * field stack. */ public void readStructEnd() throws TException { // consume the last field we read off the wire. lastFieldId_ = lastField_.pop(); } /** Read a field header off the wire. */ public TField readFieldBegin() throws TException { byte type = readByte(); // if it's a stop, then we can return immediately, as the struct is over. if (type == TType.STOP) { return TSTOP; } short fieldId; // mask off the 4 MSB of the type header. it could contain a field id delta. short modifier = (short) ((type & 0xf0) >> 4); if (modifier == 0) { // not a delta. look ahead for the zigzag varint field id. fieldId = readI16(); } else { // has a delta. add the delta to the last read field id. fieldId = (short) (lastFieldId_ + modifier); } TField field = new TField("", getTType((byte) (type & 0x0f)), fieldId); // if this happens to be a boolean field, the value is encoded in the type if (isBoolType(type)) { // save the boolean value in a special instance variable. boolValue_ = (byte) (type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; } // push the new field onto the field stack so we can keep the deltas going. lastFieldId_ = field.id; return field; } /** * Read a map header off the wire. If the size is zero, skip reading the key and value type. This * means that 0-length maps will yield TMaps without the "correct" types. */ public TMap readMapBegin() throws TException { int size = readVarint32(); byte keyAndValueType = size == 0 ? 0 : readByte(); byte keyType = getTType((byte) (keyAndValueType >> 4)); byte valueType = getTType((byte) (keyAndValueType & 0xf)); if (size > 0) { ensureMapHasEnough(size, keyType, valueType); } return new TMap(keyType, valueType, size); } /** * Read a list header off the wire. If the list size is 0-14, the size will be packed into the * element type header. If it's a longer list, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TList readListBegin() throws TException { byte size_and_type = readByte(); int size = (size_and_type >> 4) & 0x0f; if (size == 15) { size = readVarint32(); } byte type = getTType(size_and_type); ensureContainerHasEnough(size, type); return new TList(type, size); } /** * Read a set header off the wire. If the set size is 0-14, the size will be packed into the * element type header. If it's a longer set, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TSet readSetBegin() throws TException { return new TSet(readListBegin()); } /** * Read a boolean off the wire. If this is a boolean field, the value should already have been * read during readFieldBegin, so we'll just consume the pre-stored value. Otherwise, read a byte. */ public boolean readBool() throws TException { if (boolValue_ != null) { boolean result = boolValue_.booleanValue(); boolValue_ = null; return result; } return readByte() == Types.BOOLEAN_TRUE; } /** Read a single byte off the wire. Nothing interesting here. */ public byte readByte() throws TException { byte b; if (trans_.getBytesRemainingInBuffer() > 0) { b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); } else { trans_.readAll(buffer, 0, 1); b = buffer[0]; } return b; } /** Read an i16 from the wire as a zigzag varint. */ public short readI16() throws TException { return (short) zigzagToInt(readVarint32()); } /** Read an i32 from the wire as a zigzag varint. */ public int readI32() throws TException { return zigzagToInt(readVarint32()); } /** Read an i64 from the wire as a zigzag varint. */ public long readI64() throws TException { return zigzagToLong(readVarint64()); } /** No magic here - just read a double off the wire. */ public double readDouble() throws TException { trans_.readAll(buffer, 0, 8); long value; if (version_ >= VERSION_DOUBLE_BE) { value = bytesToLong(buffer); } else { value = bytesToLongLE(buffer); } return Double.longBitsToDouble(value); } /** No magic here - just read a float off the wire. */ public float readFloat() throws TException { trans_.readAll(buffer, 0, 4); int value = bytesToInt(buffer); return Float.intBitsToFloat(value); } /** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */ public String readString() throws TException { int length = readVarint32(); checkReadLength(length); if (length == 0) { return ""; } if (trans_.getBytesRemainingInBuffer() >= length) { String str = new String( trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8); trans_.consumeBuffer(length); return str; } else { return new String(readBinary(length), StandardCharsets.UTF_8); } } /** Read a byte[] from the wire. */ public byte[] readBinary() throws TException { int length = readVarint32(); checkReadLength(length); return readBinary(length); } private byte[] readBinary(int length) throws TException { if (length == 0) { return new byte[0]; } byte[] buf = new byte[length]; trans_.readAll(buf, 0, length); return buf; } private void checkReadLength(int length) throws TProtocolException { if (length < 0) { throw new TProtocolException("Negative length: " + length); } if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) { throw new TProtocolException("Length exceeded max allowed: " + length); } } // // These methods are here for the struct to call, but don't have any wire // encoding. // public void readMessageEnd() throws TException {} public void readFieldEnd() throws TException {} public void readMapEnd() throws TException {} public void readListEnd() throws TException {} public void readSetEnd() throws TException {} // // Internal reading methods // /** * Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to * follow. This can read up to 5 bytes. */ private int readVarint32() throws TException { int result = 0; int shift = 0; if (trans_.getBytesRemainingInBuffer() >= 5) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } /** * Read an i64 from the wire as a proper varint. The MSB of each byte is set if there is another * byte to follow. This can read up to 10 bytes. */ private long readVarint64() throws TException { int shift = 0; long result = 0; if (trans_.getBytesRemainingInBuffer() >= 10) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } // // encoding helpers // /** Convert from zigzag int to int. */ private int zigzagToInt(int n) { return (n >>> 1) ^ -(n & 1); } /** Convert from zigzag long to long. */ private long zigzagToLong(long n) { return (n >>> 1) ^ -(n & 1); } /** * Note that it's important that the mask bytes are long literals, otherwise they'll default to * ints, and when you shift an int left 56 bits, you just get a messed up int. */ private long bytesToLong(byte[] bytes) { return ((bytes[0] & 0xffL) << 56) | ((bytes[1] & 0xffL) << 48) | ((bytes[2] & 0xffL) << 40) | ((bytes[3] & 0xffL) << 32) | ((bytes[4] & 0xffL) << 24) | ((bytes[5] & 0xffL) << 16) | ((bytes[6] & 0xffL) << 8) | ((bytes[7] & 0xffL)); } /* Little endian version of the above */ private long bytesToLongLE(byte[] bytes) { return ((bytes[7] & 0xffL) << 56) | ((bytes[6] & 0xffL) << 48) | ((bytes[5] & 0xffL) << 40) | ((bytes[4] & 0xffL) << 32) | ((bytes[3] & 0xffL) << 24) | ((bytes[2] & 0xffL) << 16) | ((bytes[1] & 0xffL) << 8) | ((bytes[0] & 0xffL)); } private int bytesToInt(byte[] bytes) { return ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | ((bytes[3] & 0xff)); } // // type testing and converting // private boolean isBoolType(byte b) { int lowerNibble = b & 0x0f; return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE; } /** Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. */ private byte getTType(byte type) throws TProtocolException { switch ((byte) (type & 0x0f)) { case TType.STOP: return TType.STOP; case Types.BOOLEAN_FALSE: case Types.BOOLEAN_TRUE: return TType.BOOL; case Types.BYTE: return TType.BYTE; case Types.I16: return TType.I16; case Types.I32: return TType.I32; case Types.I64: return TType.I64; case Types.DOUBLE: return TType.DOUBLE; case Types.FLOAT: return TType.FLOAT; case Types.BINARY: return TType.STRING; case Types.LIST: return TType.LIST; case Types.SET: return TType.SET; case Types.MAP: return TType.MAP; case Types.STRUCT: return TType.STRUCT; default: throw new TProtocolException("don't know what type: " + (byte) (type & 0x0f)); } } /** Given a TType value, find the appropriate TCompactProtocol.Types constant. */ private byte getCompactType(byte ttype) { return ttypeToCompactType[ttype]; } @Override protected int typeMinimumSize(byte type) { switch (type & 0x0f) { case TType.BOOL: case TType.BYTE: case TType.I16: // because of variable length encoding case TType.I32: // because of variable length encoding case TType.I64: // because of variable length encoding return 1; case TType.FLOAT: return 4; case TType.DOUBLE: return 8; case TType.STRING: case TType.STRUCT: case TType.MAP: case TType.SET: case TType.LIST: case TType.ENUM: return 1; default: throw new TProtocolException( TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f)); } } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_854_1
crossvul-java_data_good_854_3
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.meta_data.FieldMetaData; import java.util.Map; /** * <code>TProtocolDecorator</code> forwards all requests to an enclosed <code>TProtocol</code> * instance, providing a way to author concise concrete decorator subclasses. While it has no * abstract methods, it is marked abstract as a reminder that by itself, it does not modify the * behaviour of the enclosed <code>TProtocol</code>. * * <p> * * <p>See p.175 of Design Patterns (by Gamma et al.) * * @see org.apache.thrift.protocol.TMultiplexedProtocol */ public abstract class TProtocolDecorator extends TProtocol { private final TProtocol concreteProtocol; /** * Encloses the specified protocol. * * @param protocol All operations will be forward to this protocol. Must be non-null. */ public TProtocolDecorator(TProtocol protocol) { super(protocol.getTransport()); concreteProtocol = protocol; } public void writeMessageBegin(TMessage tMessage) throws TException { concreteProtocol.writeMessageBegin(tMessage); } public void writeMessageEnd() throws TException { concreteProtocol.writeMessageEnd(); } public void writeStructBegin(TStruct tStruct) throws TException { concreteProtocol.writeStructBegin(tStruct); } public void writeStructEnd() throws TException { concreteProtocol.writeStructEnd(); } public void writeFieldBegin(TField tField) throws TException { concreteProtocol.writeFieldBegin(tField); } public void writeFieldEnd() throws TException { concreteProtocol.writeFieldEnd(); } public void writeFieldStop() throws TException { concreteProtocol.writeFieldStop(); } public void writeMapBegin(TMap tMap) throws TException { concreteProtocol.writeMapBegin(tMap); } public void writeMapEnd() throws TException { concreteProtocol.writeMapEnd(); } public void writeListBegin(TList tList) throws TException { concreteProtocol.writeListBegin(tList); } public void writeListEnd() throws TException { concreteProtocol.writeListEnd(); } public void writeSetBegin(TSet tSet) throws TException { concreteProtocol.writeSetBegin(tSet); } public void writeSetEnd() throws TException { concreteProtocol.writeSetEnd(); } public void writeBool(boolean b) throws TException { concreteProtocol.writeBool(b); } public void writeByte(byte b) throws TException { concreteProtocol.writeByte(b); } public void writeI16(short i) throws TException { concreteProtocol.writeI16(i); } public void writeI32(int i) throws TException { concreteProtocol.writeI32(i); } public void writeI64(long l) throws TException { concreteProtocol.writeI64(l); } public void writeFloat(float v) throws TException { concreteProtocol.writeFloat(v); } public void writeDouble(double v) throws TException { concreteProtocol.writeDouble(v); } public void writeString(String s) throws TException { concreteProtocol.writeString(s); } public void writeBinary(byte[] buf) throws TException { concreteProtocol.writeBinary(buf); } public TMessage readMessageBegin() throws TException { return concreteProtocol.readMessageBegin(); } public void readMessageEnd() throws TException { concreteProtocol.readMessageEnd(); } public TStruct readStructBegin(Map<Integer, FieldMetaData> m) throws TException { return concreteProtocol.readStructBegin(m); } public void readStructEnd() throws TException { concreteProtocol.readStructEnd(); } public TField readFieldBegin() throws TException { return concreteProtocol.readFieldBegin(); } public void readFieldEnd() throws TException { concreteProtocol.readFieldEnd(); } public TMap readMapBegin() throws TException { return concreteProtocol.readMapBegin(); } public void readMapEnd() throws TException { concreteProtocol.readMapEnd(); } public TList readListBegin() throws TException { return concreteProtocol.readListBegin(); } public void readListEnd() throws TException { concreteProtocol.readListEnd(); } public TSet readSetBegin() throws TException { return concreteProtocol.readSetBegin(); } public void readSetEnd() throws TException { concreteProtocol.readSetEnd(); } public boolean readBool() throws TException { return concreteProtocol.readBool(); } public byte readByte() throws TException { return concreteProtocol.readByte(); } public short readI16() throws TException { return concreteProtocol.readI16(); } public int readI32() throws TException { return concreteProtocol.readI32(); } public long readI64() throws TException { return concreteProtocol.readI64(); } public float readFloat() throws TException { return concreteProtocol.readFloat(); } public double readDouble() throws TException { return concreteProtocol.readDouble(); } public String readString() throws TException { return concreteProtocol.readString(); } public byte[] readBinary() throws TException { return concreteProtocol.readBinary(); } @Override protected int typeMinimumSize(byte type) { return concreteProtocol.typeMinimumSize(type); } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_854_3
crossvul-java_data_good_853_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** Binary protocol implementation for thrift. */ public class TBinaryProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(); public static final int VERSION_MASK = 0xffff0000; public static final int VERSION_1 = 0x80010000; protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; protected boolean checkReadLength_; private final byte[] buffer = new byte[8]; /** Factory */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; public Factory() { this(false, true); } public Factory(boolean strictRead, boolean strictWrite) { this(strictRead, strictWrite, 0); } public Factory(boolean strictRead, boolean strictWrite, int readLength) { strictRead_ = strictRead; strictWrite_ = strictWrite; readLength_ = readLength; } public TProtocol getProtocol(TTransport trans) { TBinaryProtocol proto = new TBinaryProtocol(trans, strictRead_, strictWrite_); if (readLength_ != 0) { proto.setReadLength(readLength_); } return proto; } } /** Constructor */ public TBinaryProtocol(TTransport trans) { this(trans, false, true); } public TBinaryProtocol(TTransport trans, boolean strictRead, boolean strictWrite) { super(trans); strictRead_ = strictRead; strictWrite_ = strictWrite; checkReadLength_ = false; } public void writeMessageBegin(TMessage message) throws TException { if (message == null) { throw new TException("Can't write 'null' message"); } if (strictWrite_) { int version = VERSION_1 | message.type; writeI32(version); writeString(message.name); writeI32(message.seqid); } else { writeString(message.name); writeByte(message.type); writeI32(message.seqid); } } public void writeMessageEnd() {} public void writeStructBegin(TStruct struct) {} public void writeStructEnd() {} public void writeFieldBegin(TField field) throws TException { writeByte(field.type); writeI16(field.id); } public void writeFieldEnd() {} public void writeFieldStop() throws TException { writeByte(TType.STOP); } public void writeMapBegin(TMap map) throws TException { writeByte(map.keyType); writeByte(map.valueType); writeI32(map.size); } public void writeMapEnd() {} public void writeListBegin(TList list) throws TException { writeByte(list.elemType); writeI32(list.size); } public void writeListEnd() {} public void writeSetBegin(TSet set) throws TException { writeByte(set.elemType); writeI32(set.size); } public void writeSetEnd() {} public void writeBool(boolean b) throws TException { writeByte(b ? (byte) 1 : (byte) 0); } public void writeByte(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } public void writeI16(short i16) throws TException { buffer[0] = (byte) (0xff & (i16 >> 8)); buffer[1] = (byte) (0xff & (i16)); trans_.write(buffer, 0, 2); } public void writeI32(int i32) throws TException { buffer[0] = (byte) (0xff & (i32 >> 24)); buffer[1] = (byte) (0xff & (i32 >> 16)); buffer[2] = (byte) (0xff & (i32 >> 8)); buffer[3] = (byte) (0xff & (i32)); trans_.write(buffer, 0, 4); } public void writeI64(long i64) throws TException { buffer[0] = (byte) (0xff & (i64 >> 56)); buffer[1] = (byte) (0xff & (i64 >> 48)); buffer[2] = (byte) (0xff & (i64 >> 40)); buffer[3] = (byte) (0xff & (i64 >> 32)); buffer[4] = (byte) (0xff & (i64 >> 24)); buffer[5] = (byte) (0xff & (i64 >> 16)); buffer[6] = (byte) (0xff & (i64 >> 8)); buffer[7] = (byte) (0xff & (i64)); trans_.write(buffer, 0, 8); } public void writeDouble(double dub) throws TException { writeI64(Double.doubleToLongBits(dub)); } public void writeFloat(float flt) throws TException { writeI32(Float.floatToIntBits(flt)); } public void writeString(String str) throws TException { byte[] dat = str.getBytes(StandardCharsets.UTF_8); writeI32(dat.length); trans_.write(dat, 0, dat.length); } public void writeBinary(byte[] bin) throws TException { writeI32(bin.length); trans_.write(bin, 0, bin.length); } /** Reading methods. */ public TMessage readMessageBegin() throws TException { int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } return new TMessage(readString(), (byte) (size & 0x000000ff), readI32()); } else { if (strictRead_) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } return new TMessage(readStringBody(size), readByte(), readI32()); } } public void readMessageEnd() {} public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) { return ANONYMOUS_STRUCT; } public void readStructEnd() {} public TField readFieldBegin() throws TException { byte type = readByte(); short id = type == TType.STOP ? 0 : readI16(); return new TField("", type, id); } public void readFieldEnd() {} public TMap readMapBegin() throws TException { byte keyType = readByte(); byte valueType = readByte(); int size = readI32(); ensureMapHasEnough(size, keyType, valueType); return new TMap(keyType, valueType, size); } public void readMapEnd() {} public TList readListBegin() throws TException { byte type = readByte(); int size = readI32(); ensureContainerHasEnough(size, type); return new TList(type, size); } public void readListEnd() {} public TSet readSetBegin() throws TException { byte type = readByte(); int size = readI32(); ensureContainerHasEnough(size, type); return new TSet(type, size); } public void readSetEnd() {} public boolean readBool() throws TException { return (readByte() == 1); } public byte readByte() throws TException { if (trans_.getBytesRemainingInBuffer() >= 1) { byte b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); return b; } readAll(buffer, 0, 1); return buffer[0]; } public short readI16() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 2) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(2); } else { readAll(buffer, 0, 2); } return (short) (((buf[off] & 0xff) << 8) | ((buf[off + 1] & 0xff))); } public int readI32() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 4) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(4); } else { readAll(buffer, 0, 4); } return ((buf[off] & 0xff) << 24) | ((buf[off + 1] & 0xff) << 16) | ((buf[off + 2] & 0xff) << 8) | ((buf[off + 3] & 0xff)); } public long readI64() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 8) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(8); } else { readAll(buffer, 0, 8); } return ((long) (buf[off] & 0xff) << 56) | ((long) (buf[off + 1] & 0xff) << 48) | ((long) (buf[off + 2] & 0xff) << 40) | ((long) (buf[off + 3] & 0xff) << 32) | ((long) (buf[off + 4] & 0xff) << 24) | ((long) (buf[off + 5] & 0xff) << 16) | ((long) (buf[off + 6] & 0xff) << 8) | ((long) (buf[off + 7] & 0xff)); } public double readDouble() throws TException { return Double.longBitsToDouble(readI64()); } public float readFloat() throws TException { return Float.intBitsToFloat(readI32()); } public String readString() throws TException { int size = readI32(); checkReadLength(size); if (trans_.getBytesRemainingInBuffer() >= size) { String s = new String(trans_.getBuffer(), trans_.getBufferPosition(), size, StandardCharsets.UTF_8); trans_.consumeBuffer(size); return s; } return readStringBody(size); } public String readStringBody(int size) throws TException { ensureContainerHasEnough(size, TType.BYTE); checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return new String(buf, StandardCharsets.UTF_8); } public byte[] readBinary() throws TException { int size = readI32(); ensureContainerHasEnough(size, TType.BYTE); checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return buf; } private int readAll(byte[] buf, int off, int len) throws TException { checkReadLength(len); return trans_.readAll(buf, off, len); } public void setReadLength(int readLength) { readLength_ = readLength; checkReadLength_ = true; } protected void checkReadLength(int length) throws TException { if (length < 0) { throw new TException("Negative length: " + length); } if (checkReadLength_) { readLength_ -= length; if (readLength_ < 0) { throw new TException("Message length exceeded: " + length); } } } @Override protected int typeMinimumSize(byte type) { switch (type & 0x0f) { case TType.BOOL: case TType.BYTE: return 1; case TType.I16: return 2; case TType.I32: case TType.FLOAT: return 4; case TType.DOUBLE: case TType.I64: return 8; case TType.STRING: return 4; case TType.LIST: case TType.SET: // type (1 byte) + size (4 bytes) return 1 + 4; case TType.MAP: // key type (1 byte) + value type (1 byte) + size (4 bytes) return 1 + 1 + 4; case TType.STRUCT: return 1; default: throw new TProtocolException( TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f)); } } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_853_0
crossvul-java_data_good_853_1
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.ShortStack; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** * TCompactProtocol2 is the Java implementation of the compact protocol specified in THRIFT-110. The * fundamental approach to reducing the overhead of structures is a) use variable-length integers * all over the place and b) make use of unused bits wherever possible. Your savings will obviously * vary based on the specific makeup of your structs, but in general, the more fields, nested * structures, short strings and collections, and low-value i32 and i64 fields you have, the more * benefit you'll see. */ public class TCompactProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(""); private static final TField TSTOP = new TField("", TType.STOP, (short) 0); private static final byte[] ttypeToCompactType = new byte[20]; static { ttypeToCompactType[TType.STOP] = TType.STOP; ttypeToCompactType[TType.BOOL] = Types.BOOLEAN_TRUE; ttypeToCompactType[TType.BYTE] = Types.BYTE; ttypeToCompactType[TType.I16] = Types.I16; ttypeToCompactType[TType.I32] = Types.I32; ttypeToCompactType[TType.I64] = Types.I64; ttypeToCompactType[TType.DOUBLE] = Types.DOUBLE; ttypeToCompactType[TType.STRING] = Types.BINARY; ttypeToCompactType[TType.LIST] = Types.LIST; ttypeToCompactType[TType.SET] = Types.SET; ttypeToCompactType[TType.MAP] = Types.MAP; ttypeToCompactType[TType.STRUCT] = Types.STRUCT; ttypeToCompactType[TType.FLOAT] = Types.FLOAT; } /** TProtocolFactory that produces TCompactProtocols. */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { private final long maxNetworkBytes_; public Factory() { maxNetworkBytes_ = -1; } public Factory(int maxNetworkBytes) { maxNetworkBytes_ = maxNetworkBytes; } public TProtocol getProtocol(TTransport trans) { return new TCompactProtocol(trans, maxNetworkBytes_); } } public static final byte PROTOCOL_ID = (byte) 0x82; public static final byte VERSION = 2; public static final byte VERSION_LOW = 1; public static final byte VERSION_DOUBLE_BE = 2; public static final byte VERSION_MASK = 0x1f; // 0001 1111 public static final byte TYPE_MASK = (byte) 0xE0; // 1110 0000 public static final int TYPE_SHIFT_AMOUNT = 5; /** All of the on-wire type codes. */ private static class Types { public static final byte BOOLEAN_TRUE = 0x01; public static final byte BOOLEAN_FALSE = 0x02; public static final byte BYTE = 0x03; public static final byte I16 = 0x04; public static final byte I32 = 0x05; public static final byte I64 = 0x06; public static final byte DOUBLE = 0x07; public static final byte BINARY = 0x08; public static final byte LIST = 0x09; public static final byte SET = 0x0A; public static final byte MAP = 0x0B; public static final byte STRUCT = 0x0C; public static final byte FLOAT = 0x0D; } /** * Used to keep track of the last field for the current and previous structs, so we can do the * delta stuff. */ private ShortStack lastField_ = new ShortStack(15); private short lastFieldId_ = 0; private byte version_ = VERSION; /** * If we encounter a boolean field begin, save the TField here so it can have the value * incorporated. */ private TField booleanField_ = null; /** * If we read a field header, and it's a boolean field, save the boolean value here so that * readBool can use it. */ private Boolean boolValue_ = null; /** * The maximum number of bytes to read from the network for variable-length fields (such as * strings or binary) or -1 for unlimited. */ private final long maxNetworkBytes_; /** Temporary buffer to avoid allocations */ private final byte[] buffer = new byte[10]; /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. * @param maxNetworkBytes the maximum number of bytes to read for variable-length fields. */ public TCompactProtocol(TTransport transport, long maxNetworkBytes) { super(transport); maxNetworkBytes_ = maxNetworkBytes; } /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. */ public TCompactProtocol(TTransport transport) { this(transport, -1); } public void reset() { lastField_.clear(); lastFieldId_ = 0; } // // Public Writing methods. // /** * Write a message header to the wire. Compact Protocol messages contain the protocol version so * we can migrate forwards in the future if need be. */ public void writeMessageBegin(TMessage message) throws TException { writeByteDirect(PROTOCOL_ID); writeByteDirect((VERSION & VERSION_MASK) | ((message.type << TYPE_SHIFT_AMOUNT) & TYPE_MASK)); writeVarint32(message.seqid); writeString(message.name); } /** * Write a struct begin. This doesn't actually put anything on the wire. We use it as an * opportunity to put special placeholder markers on the field stack so we can get the field id * deltas correct. */ public void writeStructBegin(TStruct struct) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; } /** * Write a struct end. This doesn't actually put anything on the wire. We use this as an * opportunity to pop the last field from the current struct off of the field stack. */ public void writeStructEnd() throws TException { lastFieldId_ = lastField_.pop(); } /** * Write a field header containing the field id and field type. If the difference between the * current field id and the last one is small (< 15), then the field id will be encoded in the 4 * MSB as a delta. Otherwise, the field id will follow the type header as a zigzag varint. */ public void writeFieldBegin(TField field) throws TException { if (field.type == TType.BOOL) { // we want to possibly include the value, so we'll wait. booleanField_ = field; } else { writeFieldBeginInternal(field, (byte) -1); } } /** * The workhorse of writeFieldBegin. It has the option of doing a 'type override' of the type * header. This is used specifically in the boolean field case. */ private void writeFieldBeginInternal(TField field, byte typeOverride) throws TException { // short lastField = lastField_.pop(); // if there's a type override, use that. byte typeToWrite = typeOverride == -1 ? getCompactType(field.type) : typeOverride; // check if we can use delta encoding for the field id if (field.id > lastFieldId_ && field.id - lastFieldId_ <= 15) { // write them together writeByteDirect((field.id - lastFieldId_) << 4 | typeToWrite); } else { // write them separate writeByteDirect(typeToWrite); writeI16(field.id); } lastFieldId_ = field.id; // lastField_.push(field.id); } /** Write the STOP symbol so we know there are no more fields in this struct. */ public void writeFieldStop() throws TException { writeByteDirect(TType.STOP); } /** * Write a map header. If the map is empty, omit the key and value type headers, as we don't need * any additional information to skip it. */ public void writeMapBegin(TMap map) throws TException { if (map.size == 0) { writeByteDirect(0); } else { writeVarint32(map.size); writeByteDirect(getCompactType(map.keyType) << 4 | getCompactType(map.valueType)); } } /** Write a list header. */ public void writeListBegin(TList list) throws TException { writeCollectionBegin(list.elemType, list.size); } /** Write a set header. */ public void writeSetBegin(TSet set) throws TException { writeCollectionBegin(set.elemType, set.size); } /** * Write a boolean value. Potentially, this could be a boolean field, in which case the field * header info isn't written yet. If so, decide what the right type header is for the value and * then write the field header. Otherwise, write a single byte. */ public void writeBool(boolean b) throws TException { if (booleanField_ != null) { // we haven't written the field header yet writeFieldBeginInternal(booleanField_, b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); booleanField_ = null; } else { // we're not part of a field, so just write the value. writeByteDirect(b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); } } /** Write a byte. Nothing to see here! */ public void writeByte(byte b) throws TException { writeByteDirect(b); } /** Write an I16 as a zigzag varint. */ public void writeI16(short i16) throws TException { writeVarint32(intToZigZag(i16)); } /** Write an i32 as a zigzag varint. */ public void writeI32(int i32) throws TException { writeVarint32(intToZigZag(i32)); } /** Write an i64 as a zigzag varint. */ public void writeI64(long i64) throws TException { writeVarint64(longToZigzag(i64)); } /** Write a double to the wire as 8 bytes. */ public void writeDouble(double dub) throws TException { fixedLongToBytes(Double.doubleToLongBits(dub), buffer, 0); trans_.write(buffer, 0, 8); } /** Write a float to the wire as 4 bytes. */ public void writeFloat(float flt) throws TException { fixedIntToBytes(Float.floatToIntBits(flt), buffer, 0); trans_.write(buffer, 0, 4); } /** Write a string to the wire with a varint size preceding. */ public void writeString(String str) throws TException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); writeBinary(bytes, 0, bytes.length); } /** Write a byte array, using a varint for the size. */ public void writeBinary(byte[] buf) throws TException { writeBinary(buf, 0, buf.length); } private void writeBinary(byte[] buf, int offset, int length) throws TException { writeVarint32(length); trans_.write(buf, offset, length); } // // These methods are called by structs, but don't actually have any wire // output or purpose. // public void writeMessageEnd() throws TException {} public void writeMapEnd() throws TException {} public void writeListEnd() throws TException {} public void writeSetEnd() throws TException {} public void writeFieldEnd() throws TException {} // // Internal writing methods // /** * Abstract method for writing the start of lists and sets. List and sets on the wire differ only * by the type indicator. */ protected void writeCollectionBegin(byte elemType, int size) throws TException { if (size <= 14) { writeByteDirect(size << 4 | getCompactType(elemType)); } else { writeByteDirect(0xf0 | getCompactType(elemType)); writeVarint32(size); } } /** Write an i32 as a varint. Results in 1-5 bytes on the wire. */ private void writeVarint32(int n) throws TException { int idx = 0; while (true) { if ((n & ~0x7F) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = (byte) ((n & 0x7F) | 0x80); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** Write an i64 as a varint. Results in 1-10 bytes on the wire. */ private void writeVarint64(long n) throws TException { int idx = 0; while (true) { if ((n & ~0x7FL) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = ((byte) ((n & 0x7F) | 0x80)); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** * Convert l into a zigzag long. This allows negative numbers to be represented compactly as a * varint. */ private long longToZigzag(long l) { return (l << 1) ^ (l >> 63); } /** * Convert n into a zigzag int. This allows negative numbers to be represented compactly as a * varint. */ private int intToZigZag(int n) { return (n << 1) ^ (n >> 31); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedLongToBytes(long n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 56) & 0xff); buf[off + 1] = (byte) ((n >> 48) & 0xff); buf[off + 2] = (byte) ((n >> 40) & 0xff); buf[off + 3] = (byte) ((n >> 32) & 0xff); buf[off + 4] = (byte) ((n >> 24) & 0xff); buf[off + 5] = (byte) ((n >> 16) & 0xff); buf[off + 6] = (byte) ((n >> 8) & 0xff); buf[off + 7] = (byte) (n & 0xff); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedIntToBytes(int n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 24) & 0xff); buf[off + 1] = (byte) ((n >> 16) & 0xff); buf[off + 2] = (byte) ((n >> 8) & 0xff); buf[off + 3] = (byte) (n & 0xff); } /** * Writes a byte without any possiblity of all that field header nonsense. Used internally by * other writing methods that know they need to write a byte. */ private void writeByteDirect(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } /** Writes a byte without any possiblity of all that field header nonsense. */ private void writeByteDirect(int n) throws TException { writeByteDirect((byte) n); } // // Reading methods. // /** Read a message header. */ public TMessage readMessageBegin() throws TException { byte protocolId = readByte(); if (protocolId != PROTOCOL_ID) { throw new TProtocolException( "Expected protocol id " + Integer.toHexString(PROTOCOL_ID) + " but got " + Integer.toHexString(protocolId)); } byte versionAndType = readByte(); version_ = (byte) (versionAndType & VERSION_MASK); if (!(version_ <= VERSION && version_ >= VERSION_LOW)) { throw new TProtocolException("Expected version " + VERSION + " but got " + version_); } byte type = (byte) ((versionAndType >> TYPE_SHIFT_AMOUNT) & 0x03); int seqid = readVarint32(); String messageName = readString(); return new TMessage(messageName, type, seqid); } /** * Read a struct begin. There's nothing on the wire for this, but it is our opportunity to push a * new struct begin marker onto the field stack. */ public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; return ANONYMOUS_STRUCT; } /** * Doesn't actually consume any wire data, just removes the last field for this struct from the * field stack. */ public void readStructEnd() throws TException { // consume the last field we read off the wire. lastFieldId_ = lastField_.pop(); } /** Read a field header off the wire. */ public TField readFieldBegin() throws TException { byte type = readByte(); // if it's a stop, then we can return immediately, as the struct is over. if (type == TType.STOP) { return TSTOP; } short fieldId; // mask off the 4 MSB of the type header. it could contain a field id delta. short modifier = (short) ((type & 0xf0) >> 4); if (modifier == 0) { // not a delta. look ahead for the zigzag varint field id. fieldId = readI16(); } else { // has a delta. add the delta to the last read field id. fieldId = (short) (lastFieldId_ + modifier); } TField field = new TField("", getTType((byte) (type & 0x0f)), fieldId); // if this happens to be a boolean field, the value is encoded in the type if (isBoolType(type)) { // save the boolean value in a special instance variable. boolValue_ = (byte) (type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; } // push the new field onto the field stack so we can keep the deltas going. lastFieldId_ = field.id; return field; } /** * Read a map header off the wire. If the size is zero, skip reading the key and value type. This * means that 0-length maps will yield TMaps without the "correct" types. */ public TMap readMapBegin() throws TException { int size = readVarint32(); byte keyAndValueType = size == 0 ? 0 : readByte(); byte keyType = getTType((byte) (keyAndValueType >> 4)); byte valueType = getTType((byte) (keyAndValueType & 0xf)); if (size > 0) { ensureMapHasEnough(size, keyType, valueType); } return new TMap(keyType, valueType, size); } /** * Read a list header off the wire. If the list size is 0-14, the size will be packed into the * element type header. If it's a longer list, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TList readListBegin() throws TException { byte size_and_type = readByte(); int size = (size_and_type >> 4) & 0x0f; if (size == 15) { size = readVarint32(); } byte type = getTType(size_and_type); ensureContainerHasEnough(size, type); return new TList(type, size); } /** * Read a set header off the wire. If the set size is 0-14, the size will be packed into the * element type header. If it's a longer set, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TSet readSetBegin() throws TException { return new TSet(readListBegin()); } /** * Read a boolean off the wire. If this is a boolean field, the value should already have been * read during readFieldBegin, so we'll just consume the pre-stored value. Otherwise, read a byte. */ public boolean readBool() throws TException { if (boolValue_ != null) { boolean result = boolValue_.booleanValue(); boolValue_ = null; return result; } return readByte() == Types.BOOLEAN_TRUE; } /** Read a single byte off the wire. Nothing interesting here. */ public byte readByte() throws TException { byte b; if (trans_.getBytesRemainingInBuffer() > 0) { b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); } else { trans_.readAll(buffer, 0, 1); b = buffer[0]; } return b; } /** Read an i16 from the wire as a zigzag varint. */ public short readI16() throws TException { return (short) zigzagToInt(readVarint32()); } /** Read an i32 from the wire as a zigzag varint. */ public int readI32() throws TException { return zigzagToInt(readVarint32()); } /** Read an i64 from the wire as a zigzag varint. */ public long readI64() throws TException { return zigzagToLong(readVarint64()); } /** No magic here - just read a double off the wire. */ public double readDouble() throws TException { trans_.readAll(buffer, 0, 8); long value; if (version_ >= VERSION_DOUBLE_BE) { value = bytesToLong(buffer); } else { value = bytesToLongLE(buffer); } return Double.longBitsToDouble(value); } /** No magic here - just read a float off the wire. */ public float readFloat() throws TException { trans_.readAll(buffer, 0, 4); int value = bytesToInt(buffer); return Float.intBitsToFloat(value); } /** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */ public String readString() throws TException { int length = readVarint32(); checkReadLength(length); if (length == 0) { return ""; } if (trans_.getBytesRemainingInBuffer() >= length) { String str = new String( trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8); trans_.consumeBuffer(length); return str; } else { return new String(readBinary(length), StandardCharsets.UTF_8); } } /** Read a byte[] from the wire. */ public byte[] readBinary() throws TException { int length = readVarint32(); checkReadLength(length); return readBinary(length); } private byte[] readBinary(int length) throws TException { if (length == 0) { return new byte[0]; } ensureContainerHasEnough(length, TType.BYTE); byte[] buf = new byte[length]; trans_.readAll(buf, 0, length); return buf; } private void checkReadLength(int length) throws TProtocolException { if (length < 0) { throw new TProtocolException("Negative length: " + length); } if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) { throw new TProtocolException("Length exceeded max allowed: " + length); } } // // These methods are here for the struct to call, but don't have any wire // encoding. // public void readMessageEnd() throws TException {} public void readFieldEnd() throws TException {} public void readMapEnd() throws TException {} public void readListEnd() throws TException {} public void readSetEnd() throws TException {} // // Internal reading methods // /** * Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to * follow. This can read up to 5 bytes. */ private int readVarint32() throws TException { int result = 0; int shift = 0; if (trans_.getBytesRemainingInBuffer() >= 5) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } /** * Read an i64 from the wire as a proper varint. The MSB of each byte is set if there is another * byte to follow. This can read up to 10 bytes. */ private long readVarint64() throws TException { int shift = 0; long result = 0; if (trans_.getBytesRemainingInBuffer() >= 10) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } // // encoding helpers // /** Convert from zigzag int to int. */ private int zigzagToInt(int n) { return (n >>> 1) ^ -(n & 1); } /** Convert from zigzag long to long. */ private long zigzagToLong(long n) { return (n >>> 1) ^ -(n & 1); } /** * Note that it's important that the mask bytes are long literals, otherwise they'll default to * ints, and when you shift an int left 56 bits, you just get a messed up int. */ private long bytesToLong(byte[] bytes) { return ((bytes[0] & 0xffL) << 56) | ((bytes[1] & 0xffL) << 48) | ((bytes[2] & 0xffL) << 40) | ((bytes[3] & 0xffL) << 32) | ((bytes[4] & 0xffL) << 24) | ((bytes[5] & 0xffL) << 16) | ((bytes[6] & 0xffL) << 8) | ((bytes[7] & 0xffL)); } /* Little endian version of the above */ private long bytesToLongLE(byte[] bytes) { return ((bytes[7] & 0xffL) << 56) | ((bytes[6] & 0xffL) << 48) | ((bytes[5] & 0xffL) << 40) | ((bytes[4] & 0xffL) << 32) | ((bytes[3] & 0xffL) << 24) | ((bytes[2] & 0xffL) << 16) | ((bytes[1] & 0xffL) << 8) | ((bytes[0] & 0xffL)); } private int bytesToInt(byte[] bytes) { return ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | ((bytes[3] & 0xff)); } // // type testing and converting // private boolean isBoolType(byte b) { int lowerNibble = b & 0x0f; return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE; } /** Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. */ private byte getTType(byte type) throws TProtocolException { switch ((byte) (type & 0x0f)) { case TType.STOP: return TType.STOP; case Types.BOOLEAN_FALSE: case Types.BOOLEAN_TRUE: return TType.BOOL; case Types.BYTE: return TType.BYTE; case Types.I16: return TType.I16; case Types.I32: return TType.I32; case Types.I64: return TType.I64; case Types.DOUBLE: return TType.DOUBLE; case Types.FLOAT: return TType.FLOAT; case Types.BINARY: return TType.STRING; case Types.LIST: return TType.LIST; case Types.SET: return TType.SET; case Types.MAP: return TType.MAP; case Types.STRUCT: return TType.STRUCT; default: throw new TProtocolException("don't know what type: " + (byte) (type & 0x0f)); } } /** Given a TType value, find the appropriate TCompactProtocol.Types constant. */ private byte getCompactType(byte ttype) { return ttypeToCompactType[ttype]; } @Override protected int typeMinimumSize(byte type) { switch (type & 0x0f) { case TType.BOOL: case TType.BYTE: case TType.I16: // because of variable length encoding case TType.I32: // because of variable length encoding case TType.I64: // because of variable length encoding return 1; case TType.FLOAT: return 4; case TType.DOUBLE: return 8; case TType.STRING: case TType.STRUCT: case TType.MAP: case TType.SET: case TType.LIST: case TType.ENUM: return 1; default: throw new TProtocolException( TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f)); } } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_853_1
crossvul-java_data_bad_854_3
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.meta_data.FieldMetaData; import java.util.Map; /** * <code>TProtocolDecorator</code> forwards all requests to an enclosed <code>TProtocol</code> * instance, providing a way to author concise concrete decorator subclasses. While it has no * abstract methods, it is marked abstract as a reminder that by itself, it does not modify the * behaviour of the enclosed <code>TProtocol</code>. * * <p> * * <p>See p.175 of Design Patterns (by Gamma et al.) * * @see org.apache.thrift.protocol.TMultiplexedProtocol */ public abstract class TProtocolDecorator extends TProtocol { private final TProtocol concreteProtocol; /** * Encloses the specified protocol. * * @param protocol All operations will be forward to this protocol. Must be non-null. */ public TProtocolDecorator(TProtocol protocol) { super(protocol.getTransport()); concreteProtocol = protocol; } public void writeMessageBegin(TMessage tMessage) throws TException { concreteProtocol.writeMessageBegin(tMessage); } public void writeMessageEnd() throws TException { concreteProtocol.writeMessageEnd(); } public void writeStructBegin(TStruct tStruct) throws TException { concreteProtocol.writeStructBegin(tStruct); } public void writeStructEnd() throws TException { concreteProtocol.writeStructEnd(); } public void writeFieldBegin(TField tField) throws TException { concreteProtocol.writeFieldBegin(tField); } public void writeFieldEnd() throws TException { concreteProtocol.writeFieldEnd(); } public void writeFieldStop() throws TException { concreteProtocol.writeFieldStop(); } public void writeMapBegin(TMap tMap) throws TException { concreteProtocol.writeMapBegin(tMap); } public void writeMapEnd() throws TException { concreteProtocol.writeMapEnd(); } public void writeListBegin(TList tList) throws TException { concreteProtocol.writeListBegin(tList); } public void writeListEnd() throws TException { concreteProtocol.writeListEnd(); } public void writeSetBegin(TSet tSet) throws TException { concreteProtocol.writeSetBegin(tSet); } public void writeSetEnd() throws TException { concreteProtocol.writeSetEnd(); } public void writeBool(boolean b) throws TException { concreteProtocol.writeBool(b); } public void writeByte(byte b) throws TException { concreteProtocol.writeByte(b); } public void writeI16(short i) throws TException { concreteProtocol.writeI16(i); } public void writeI32(int i) throws TException { concreteProtocol.writeI32(i); } public void writeI64(long l) throws TException { concreteProtocol.writeI64(l); } public void writeFloat(float v) throws TException { concreteProtocol.writeFloat(v); } public void writeDouble(double v) throws TException { concreteProtocol.writeDouble(v); } public void writeString(String s) throws TException { concreteProtocol.writeString(s); } public void writeBinary(byte[] buf) throws TException { concreteProtocol.writeBinary(buf); } public TMessage readMessageBegin() throws TException { return concreteProtocol.readMessageBegin(); } public void readMessageEnd() throws TException { concreteProtocol.readMessageEnd(); } public TStruct readStructBegin(Map<Integer, FieldMetaData> m) throws TException { return concreteProtocol.readStructBegin(m); } public void readStructEnd() throws TException { concreteProtocol.readStructEnd(); } public TField readFieldBegin() throws TException { return concreteProtocol.readFieldBegin(); } public void readFieldEnd() throws TException { concreteProtocol.readFieldEnd(); } public TMap readMapBegin() throws TException { return concreteProtocol.readMapBegin(); } public void readMapEnd() throws TException { concreteProtocol.readMapEnd(); } public TList readListBegin() throws TException { return concreteProtocol.readListBegin(); } public void readListEnd() throws TException { concreteProtocol.readListEnd(); } public TSet readSetBegin() throws TException { return concreteProtocol.readSetBegin(); } public void readSetEnd() throws TException { concreteProtocol.readSetEnd(); } public boolean readBool() throws TException { return concreteProtocol.readBool(); } public byte readByte() throws TException { return concreteProtocol.readByte(); } public short readI16() throws TException { return concreteProtocol.readI16(); } public int readI32() throws TException { return concreteProtocol.readI32(); } public long readI64() throws TException { return concreteProtocol.readI64(); } public float readFloat() throws TException { return concreteProtocol.readFloat(); } public double readDouble() throws TException { return concreteProtocol.readDouble(); } public String readString() throws TException { return concreteProtocol.readString(); } public byte[] readBinary() throws TException { return concreteProtocol.readBinary(); } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_854_3
crossvul-java_data_good_853_3
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift; import com.facebook.thrift.java.test.MyListStruct; import com.facebook.thrift.java.test.MyMapStruct; import com.facebook.thrift.java.test.MySetStruct; import com.facebook.thrift.java.test.MyStringStruct; import com.facebook.thrift.protocol.TBinaryProtocol; import com.facebook.thrift.protocol.TCompactProtocol; import com.facebook.thrift.protocol.TProtocol; import com.facebook.thrift.protocol.TProtocolException; import com.facebook.thrift.protocol.TType; import com.facebook.thrift.transport.TMemoryInputTransport; import org.junit.Test; public class TruncatedFrameTest extends junit.framework.TestCase { private static final byte[] kBinaryListEncoding = { TType.LIST, // Field Type = List (byte) 0x00, (byte) 0x01, // Field id = 1 TType.I64, // List type = i64 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, // List length (255 > 3!) (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 1L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, // value = 2L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, // value = 3L (byte) 0x00, // Stop }; private static final byte[] kCompactListEncoding = { (byte) 0b00011001, // field id delta (0001) + type (1001) = List (byte) 0b11100110, // list size (0111) and 7>3 + list type (0110) = i64 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; private static final byte[] kCompactListEncoding2 = { (byte) 0b00011001, // field id delta (0001) + type (1001) = List (byte) 0b11110110, // list size magic marker (1111) + list type (0110) = i64 (byte) 0x64, // list actual size (varint of 1 byte here) = 100 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; public static void testTruncated(TBase struct, TProtocol iprot) throws Exception { try { struct.read(iprot); assertTrue("Not reachable", false); } catch (TProtocolException ex) { assertEquals( "Not enough bytes to read the entire message, the data appears to be truncated", ex.getMessage()); } } @Test public static void testListBinary() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryListEncoding); TProtocol iprot = new TBinaryProtocol(buf); testTruncated(new MyListStruct(), iprot); } @Test public static void testListCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MyListStruct(), iprot); } @Test public static void testLongListCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding2); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MyListStruct(), iprot); } private static final byte[] kBinarySetEncoding = { TType.SET, // Field Type = Set (byte) 0x00, (byte) 0x01, // Field id = 1 TType.I64, // Set type = i64 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, // Set length (255 > 3!) (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 1L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, // value = 2L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, // value = 3L (byte) 0x00, // Stop }; private static final byte[] kCompactSetEncoding = { (byte) 0b00011010, // field id delta (0001) + type (1010) = Set (byte) 0b01110110, // set size (0111) and 7>3 + set type (0110) = i64 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; private static final byte[] kCompactSetEncoding2 = { (byte) 0b00011010, // field id delta (0001) + type (1010) = Set (byte) 0b11110110, // set size magic marker (1111) + set type (0110) = i64 (byte) 0x64, // set actual size (varint of 1 byte here) = 100 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; @Test public static void testSetBinary() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kBinarySetEncoding); TProtocol iprot = new TBinaryProtocol(buf); testTruncated(new MySetStruct(), iprot); } @Test public static void testSetCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MySetStruct(), iprot); } @Test public static void testLongSetCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding2); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MySetStruct(), iprot); } private static final byte[] kBinaryMapEncoding = { TType.MAP, // field type = Map (byte) 0x00, (byte) 0x01, // field id = 1 TType.I64, // key type = i64 TType.STRING, // value type = string (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // size = 0x00FFFFFF (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, // key = 0 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // string size = 1 (byte) 0x30, // string value = "0" (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // key = 1 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // string size = 1 (byte) 0x31, // string value = "1" (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, // key = 2 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // string size = 1 (byte) 0x32, // string value = "2" (byte) 0x00, // Stop }; private static final byte[] kCompactMapEncoding = { (byte) 0b00011011, // field id delta (0001) + type (1011) = Map (byte) 0x64, // map size (varint = 100) (byte) 0b01101000, // key type (0110) i64, value type (1000) string (byte) 0x00, // key value = 0 (byte) 0x01, // value: string size = 1 (byte) 0x30, // string content = "0" (byte) 0x02, // key value = 1 (zigzag encoded) (byte) 0x01, // value: string size = 1 (byte) 0x31, // string content = "1" (byte) 0x04, // key value = 2 (zigzag encoded) (byte) 0x01, // value: string size = 1 (byte) 0x32, // string content = "2" (byte) 0x00, // Stop }; @Test public static void testMapBinary() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryMapEncoding); TProtocol iprot = new TBinaryProtocol(buf); testTruncated(new MyMapStruct(), iprot); } @Test public static void testMapCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactMapEncoding); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MyMapStruct(), iprot); } private static final byte[] kBinaryStringEncoding = { TType.STRING, // Field Type = string (byte) 0x00, (byte) 0x01, // Field id = 1 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, // string length (255!) (byte) 0x48, (byte) 0x65, (byte) 0x6C, (byte) 0x6C, (byte) 0x6F, (byte) 0x2C, (byte) 0x20, (byte) 0x57, (byte) 0x6F, (byte) 0x72, (byte) 0x6C, (byte) 0x64, (byte) 0x21, // string chars: "Hello, World!" (byte) 0x00, // Stop }; private static final byte[] kCompactStringEncoding = { (byte) 0b00011000, // field id delta (0001) + type (1000) = Binary (byte) 0xFF, (byte) 0x0F, // string size (varint) = 0x0FFF (4095) (byte) 0x48, (byte) 0x65, (byte) 0x6C, (byte) 0x6C, (byte) 0x6F, (byte) 0x2C, (byte) 0x20, (byte) 0x57, (byte) 0x6F, (byte) 0x72, (byte) 0x6C, (byte) 0x64, (byte) 0x21, // string chars: "Hello, World!" (byte) 0x00, // Stop }; @Test public void testStringBinary() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryStringEncoding); TProtocol iprot = new TBinaryProtocol(buf); testTruncated(new MyStringStruct(), iprot); } @Test public void testStringCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactStringEncoding); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MyStringStruct(), iprot); } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_853_3
crossvul-java_data_bad_854_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** Binary protocol implementation for thrift. */ public class TBinaryProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(); public static final int VERSION_MASK = 0xffff0000; public static final int VERSION_1 = 0x80010000; protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; protected boolean checkReadLength_; private final byte[] buffer = new byte[8]; /** Factory */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; public Factory() { this(false, true); } public Factory(boolean strictRead, boolean strictWrite) { this(strictRead, strictWrite, 0); } public Factory(boolean strictRead, boolean strictWrite, int readLength) { strictRead_ = strictRead; strictWrite_ = strictWrite; readLength_ = readLength; } public TProtocol getProtocol(TTransport trans) { TBinaryProtocol proto = new TBinaryProtocol(trans, strictRead_, strictWrite_); if (readLength_ != 0) { proto.setReadLength(readLength_); } return proto; } } /** Constructor */ public TBinaryProtocol(TTransport trans) { this(trans, false, true); } public TBinaryProtocol(TTransport trans, boolean strictRead, boolean strictWrite) { super(trans); strictRead_ = strictRead; strictWrite_ = strictWrite; checkReadLength_ = false; } public void writeMessageBegin(TMessage message) throws TException { if (message == null) { throw new TException("Can't write 'null' message"); } if (strictWrite_) { int version = VERSION_1 | message.type; writeI32(version); writeString(message.name); writeI32(message.seqid); } else { writeString(message.name); writeByte(message.type); writeI32(message.seqid); } } public void writeMessageEnd() {} public void writeStructBegin(TStruct struct) {} public void writeStructEnd() {} public void writeFieldBegin(TField field) throws TException { writeByte(field.type); writeI16(field.id); } public void writeFieldEnd() {} public void writeFieldStop() throws TException { writeByte(TType.STOP); } public void writeMapBegin(TMap map) throws TException { writeByte(map.keyType); writeByte(map.valueType); writeI32(map.size); } public void writeMapEnd() {} public void writeListBegin(TList list) throws TException { writeByte(list.elemType); writeI32(list.size); } public void writeListEnd() {} public void writeSetBegin(TSet set) throws TException { writeByte(set.elemType); writeI32(set.size); } public void writeSetEnd() {} public void writeBool(boolean b) throws TException { writeByte(b ? (byte) 1 : (byte) 0); } public void writeByte(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } public void writeI16(short i16) throws TException { buffer[0] = (byte) (0xff & (i16 >> 8)); buffer[1] = (byte) (0xff & (i16)); trans_.write(buffer, 0, 2); } public void writeI32(int i32) throws TException { buffer[0] = (byte) (0xff & (i32 >> 24)); buffer[1] = (byte) (0xff & (i32 >> 16)); buffer[2] = (byte) (0xff & (i32 >> 8)); buffer[3] = (byte) (0xff & (i32)); trans_.write(buffer, 0, 4); } public void writeI64(long i64) throws TException { buffer[0] = (byte) (0xff & (i64 >> 56)); buffer[1] = (byte) (0xff & (i64 >> 48)); buffer[2] = (byte) (0xff & (i64 >> 40)); buffer[3] = (byte) (0xff & (i64 >> 32)); buffer[4] = (byte) (0xff & (i64 >> 24)); buffer[5] = (byte) (0xff & (i64 >> 16)); buffer[6] = (byte) (0xff & (i64 >> 8)); buffer[7] = (byte) (0xff & (i64)); trans_.write(buffer, 0, 8); } public void writeDouble(double dub) throws TException { writeI64(Double.doubleToLongBits(dub)); } public void writeFloat(float flt) throws TException { writeI32(Float.floatToIntBits(flt)); } public void writeString(String str) throws TException { byte[] dat = str.getBytes(StandardCharsets.UTF_8); writeI32(dat.length); trans_.write(dat, 0, dat.length); } public void writeBinary(byte[] bin) throws TException { writeI32(bin.length); trans_.write(bin, 0, bin.length); } /** Reading methods. */ public TMessage readMessageBegin() throws TException { int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } return new TMessage(readString(), (byte) (size & 0x000000ff), readI32()); } else { if (strictRead_) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } return new TMessage(readStringBody(size), readByte(), readI32()); } } public void readMessageEnd() {} public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) { return ANONYMOUS_STRUCT; } public void readStructEnd() {} public TField readFieldBegin() throws TException { byte type = readByte(); short id = type == TType.STOP ? 0 : readI16(); return new TField("", type, id); } public void readFieldEnd() {} public TMap readMapBegin() throws TException { return new TMap(readByte(), readByte(), readI32()); } public void readMapEnd() {} public TList readListBegin() throws TException { return new TList(readByte(), readI32()); } public void readListEnd() {} public TSet readSetBegin() throws TException { return new TSet(readByte(), readI32()); } public void readSetEnd() {} public boolean readBool() throws TException { return (readByte() == 1); } public byte readByte() throws TException { if (trans_.getBytesRemainingInBuffer() >= 1) { byte b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); return b; } readAll(buffer, 0, 1); return buffer[0]; } public short readI16() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 2) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(2); } else { readAll(buffer, 0, 2); } return (short) (((buf[off] & 0xff) << 8) | ((buf[off + 1] & 0xff))); } public int readI32() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 4) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(4); } else { readAll(buffer, 0, 4); } return ((buf[off] & 0xff) << 24) | ((buf[off + 1] & 0xff) << 16) | ((buf[off + 2] & 0xff) << 8) | ((buf[off + 3] & 0xff)); } public long readI64() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 8) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(8); } else { readAll(buffer, 0, 8); } return ((long) (buf[off] & 0xff) << 56) | ((long) (buf[off + 1] & 0xff) << 48) | ((long) (buf[off + 2] & 0xff) << 40) | ((long) (buf[off + 3] & 0xff) << 32) | ((long) (buf[off + 4] & 0xff) << 24) | ((long) (buf[off + 5] & 0xff) << 16) | ((long) (buf[off + 6] & 0xff) << 8) | ((long) (buf[off + 7] & 0xff)); } public double readDouble() throws TException { return Double.longBitsToDouble(readI64()); } public float readFloat() throws TException { return Float.intBitsToFloat(readI32()); } public String readString() throws TException { int size = readI32(); checkReadLength(size); if (trans_.getBytesRemainingInBuffer() >= size) { String s = new String(trans_.getBuffer(), trans_.getBufferPosition(), size, StandardCharsets.UTF_8); trans_.consumeBuffer(size); return s; } return readStringBody(size); } public String readStringBody(int size) throws TException { checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return new String(buf, StandardCharsets.UTF_8); } public byte[] readBinary() throws TException { int size = readI32(); checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return buf; } private int readAll(byte[] buf, int off, int len) throws TException { checkReadLength(len); return trans_.readAll(buf, off, len); } public void setReadLength(int readLength) { readLength_ = readLength; checkReadLength_ = true; } protected void checkReadLength(int length) throws TException { if (length < 0) { throw new TException("Negative length: " + length); } if (checkReadLength_) { readLength_ -= length; if (readLength_ < 0) { throw new TException("Message length exceeded: " + length); } } } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_854_0
crossvul-java_data_good_854_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** Binary protocol implementation for thrift. */ public class TBinaryProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(); public static final int VERSION_MASK = 0xffff0000; public static final int VERSION_1 = 0x80010000; protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; protected boolean checkReadLength_; private final byte[] buffer = new byte[8]; /** Factory */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; public Factory() { this(false, true); } public Factory(boolean strictRead, boolean strictWrite) { this(strictRead, strictWrite, 0); } public Factory(boolean strictRead, boolean strictWrite, int readLength) { strictRead_ = strictRead; strictWrite_ = strictWrite; readLength_ = readLength; } public TProtocol getProtocol(TTransport trans) { TBinaryProtocol proto = new TBinaryProtocol(trans, strictRead_, strictWrite_); if (readLength_ != 0) { proto.setReadLength(readLength_); } return proto; } } /** Constructor */ public TBinaryProtocol(TTransport trans) { this(trans, false, true); } public TBinaryProtocol(TTransport trans, boolean strictRead, boolean strictWrite) { super(trans); strictRead_ = strictRead; strictWrite_ = strictWrite; checkReadLength_ = false; } public void writeMessageBegin(TMessage message) throws TException { if (message == null) { throw new TException("Can't write 'null' message"); } if (strictWrite_) { int version = VERSION_1 | message.type; writeI32(version); writeString(message.name); writeI32(message.seqid); } else { writeString(message.name); writeByte(message.type); writeI32(message.seqid); } } public void writeMessageEnd() {} public void writeStructBegin(TStruct struct) {} public void writeStructEnd() {} public void writeFieldBegin(TField field) throws TException { writeByte(field.type); writeI16(field.id); } public void writeFieldEnd() {} public void writeFieldStop() throws TException { writeByte(TType.STOP); } public void writeMapBegin(TMap map) throws TException { writeByte(map.keyType); writeByte(map.valueType); writeI32(map.size); } public void writeMapEnd() {} public void writeListBegin(TList list) throws TException { writeByte(list.elemType); writeI32(list.size); } public void writeListEnd() {} public void writeSetBegin(TSet set) throws TException { writeByte(set.elemType); writeI32(set.size); } public void writeSetEnd() {} public void writeBool(boolean b) throws TException { writeByte(b ? (byte) 1 : (byte) 0); } public void writeByte(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } public void writeI16(short i16) throws TException { buffer[0] = (byte) (0xff & (i16 >> 8)); buffer[1] = (byte) (0xff & (i16)); trans_.write(buffer, 0, 2); } public void writeI32(int i32) throws TException { buffer[0] = (byte) (0xff & (i32 >> 24)); buffer[1] = (byte) (0xff & (i32 >> 16)); buffer[2] = (byte) (0xff & (i32 >> 8)); buffer[3] = (byte) (0xff & (i32)); trans_.write(buffer, 0, 4); } public void writeI64(long i64) throws TException { buffer[0] = (byte) (0xff & (i64 >> 56)); buffer[1] = (byte) (0xff & (i64 >> 48)); buffer[2] = (byte) (0xff & (i64 >> 40)); buffer[3] = (byte) (0xff & (i64 >> 32)); buffer[4] = (byte) (0xff & (i64 >> 24)); buffer[5] = (byte) (0xff & (i64 >> 16)); buffer[6] = (byte) (0xff & (i64 >> 8)); buffer[7] = (byte) (0xff & (i64)); trans_.write(buffer, 0, 8); } public void writeDouble(double dub) throws TException { writeI64(Double.doubleToLongBits(dub)); } public void writeFloat(float flt) throws TException { writeI32(Float.floatToIntBits(flt)); } public void writeString(String str) throws TException { byte[] dat = str.getBytes(StandardCharsets.UTF_8); writeI32(dat.length); trans_.write(dat, 0, dat.length); } public void writeBinary(byte[] bin) throws TException { writeI32(bin.length); trans_.write(bin, 0, bin.length); } /** Reading methods. */ public TMessage readMessageBegin() throws TException { int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } return new TMessage(readString(), (byte) (size & 0x000000ff), readI32()); } else { if (strictRead_) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } return new TMessage(readStringBody(size), readByte(), readI32()); } } public void readMessageEnd() {} public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) { return ANONYMOUS_STRUCT; } public void readStructEnd() {} public TField readFieldBegin() throws TException { byte type = readByte(); short id = type == TType.STOP ? 0 : readI16(); return new TField("", type, id); } public void readFieldEnd() {} public TMap readMapBegin() throws TException { byte keyType = readByte(); byte valueType = readByte(); int size = readI32(); ensureMapHasEnough(size, keyType, valueType); return new TMap(keyType, valueType, size); } public void readMapEnd() {} public TList readListBegin() throws TException { byte type = readByte(); int size = readI32(); ensureContainerHasEnough(size, type); return new TList(type, size); } public void readListEnd() {} public TSet readSetBegin() throws TException { byte type = readByte(); int size = readI32(); ensureContainerHasEnough(size, type); return new TSet(type, size); } public void readSetEnd() {} public boolean readBool() throws TException { return (readByte() == 1); } public byte readByte() throws TException { if (trans_.getBytesRemainingInBuffer() >= 1) { byte b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); return b; } readAll(buffer, 0, 1); return buffer[0]; } public short readI16() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 2) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(2); } else { readAll(buffer, 0, 2); } return (short) (((buf[off] & 0xff) << 8) | ((buf[off + 1] & 0xff))); } public int readI32() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 4) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(4); } else { readAll(buffer, 0, 4); } return ((buf[off] & 0xff) << 24) | ((buf[off + 1] & 0xff) << 16) | ((buf[off + 2] & 0xff) << 8) | ((buf[off + 3] & 0xff)); } public long readI64() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 8) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(8); } else { readAll(buffer, 0, 8); } return ((long) (buf[off] & 0xff) << 56) | ((long) (buf[off + 1] & 0xff) << 48) | ((long) (buf[off + 2] & 0xff) << 40) | ((long) (buf[off + 3] & 0xff) << 32) | ((long) (buf[off + 4] & 0xff) << 24) | ((long) (buf[off + 5] & 0xff) << 16) | ((long) (buf[off + 6] & 0xff) << 8) | ((long) (buf[off + 7] & 0xff)); } public double readDouble() throws TException { return Double.longBitsToDouble(readI64()); } public float readFloat() throws TException { return Float.intBitsToFloat(readI32()); } public String readString() throws TException { int size = readI32(); checkReadLength(size); if (trans_.getBytesRemainingInBuffer() >= size) { String s = new String(trans_.getBuffer(), trans_.getBufferPosition(), size, StandardCharsets.UTF_8); trans_.consumeBuffer(size); return s; } return readStringBody(size); } public String readStringBody(int size) throws TException { checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return new String(buf, StandardCharsets.UTF_8); } public byte[] readBinary() throws TException { int size = readI32(); checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return buf; } private int readAll(byte[] buf, int off, int len) throws TException { checkReadLength(len); return trans_.readAll(buf, off, len); } public void setReadLength(int readLength) { readLength_ = readLength; checkReadLength_ = true; } protected void checkReadLength(int length) throws TException { if (length < 0) { throw new TException("Negative length: " + length); } if (checkReadLength_) { readLength_ -= length; if (readLength_ < 0) { throw new TException("Message length exceeded: " + length); } } } @Override protected int typeMinimumSize(byte type) { switch (type & 0x0f) { case TType.BOOL: case TType.BYTE: return 1; case TType.I16: return 2; case TType.I32: case TType.FLOAT: return 4; case TType.DOUBLE: case TType.I64: return 8; case TType.STRING: return 4; case TType.LIST: case TType.SET: // type (1 byte) + size (4 bytes) return 1 + 4; case TType.MAP: // key type (1 byte) + value type (1 byte) + size (4 bytes) return 1 + 1 + 4; case TType.STRUCT: return 1; default: throw new TProtocolException( TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f)); } } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_854_0
crossvul-java_data_bad_853_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** Binary protocol implementation for thrift. */ public class TBinaryProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(); public static final int VERSION_MASK = 0xffff0000; public static final int VERSION_1 = 0x80010000; protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; protected boolean checkReadLength_; private final byte[] buffer = new byte[8]; /** Factory */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { protected final boolean strictRead_; protected final boolean strictWrite_; protected int readLength_; public Factory() { this(false, true); } public Factory(boolean strictRead, boolean strictWrite) { this(strictRead, strictWrite, 0); } public Factory(boolean strictRead, boolean strictWrite, int readLength) { strictRead_ = strictRead; strictWrite_ = strictWrite; readLength_ = readLength; } public TProtocol getProtocol(TTransport trans) { TBinaryProtocol proto = new TBinaryProtocol(trans, strictRead_, strictWrite_); if (readLength_ != 0) { proto.setReadLength(readLength_); } return proto; } } /** Constructor */ public TBinaryProtocol(TTransport trans) { this(trans, false, true); } public TBinaryProtocol(TTransport trans, boolean strictRead, boolean strictWrite) { super(trans); strictRead_ = strictRead; strictWrite_ = strictWrite; checkReadLength_ = false; } public void writeMessageBegin(TMessage message) throws TException { if (message == null) { throw new TException("Can't write 'null' message"); } if (strictWrite_) { int version = VERSION_1 | message.type; writeI32(version); writeString(message.name); writeI32(message.seqid); } else { writeString(message.name); writeByte(message.type); writeI32(message.seqid); } } public void writeMessageEnd() {} public void writeStructBegin(TStruct struct) {} public void writeStructEnd() {} public void writeFieldBegin(TField field) throws TException { writeByte(field.type); writeI16(field.id); } public void writeFieldEnd() {} public void writeFieldStop() throws TException { writeByte(TType.STOP); } public void writeMapBegin(TMap map) throws TException { writeByte(map.keyType); writeByte(map.valueType); writeI32(map.size); } public void writeMapEnd() {} public void writeListBegin(TList list) throws TException { writeByte(list.elemType); writeI32(list.size); } public void writeListEnd() {} public void writeSetBegin(TSet set) throws TException { writeByte(set.elemType); writeI32(set.size); } public void writeSetEnd() {} public void writeBool(boolean b) throws TException { writeByte(b ? (byte) 1 : (byte) 0); } public void writeByte(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } public void writeI16(short i16) throws TException { buffer[0] = (byte) (0xff & (i16 >> 8)); buffer[1] = (byte) (0xff & (i16)); trans_.write(buffer, 0, 2); } public void writeI32(int i32) throws TException { buffer[0] = (byte) (0xff & (i32 >> 24)); buffer[1] = (byte) (0xff & (i32 >> 16)); buffer[2] = (byte) (0xff & (i32 >> 8)); buffer[3] = (byte) (0xff & (i32)); trans_.write(buffer, 0, 4); } public void writeI64(long i64) throws TException { buffer[0] = (byte) (0xff & (i64 >> 56)); buffer[1] = (byte) (0xff & (i64 >> 48)); buffer[2] = (byte) (0xff & (i64 >> 40)); buffer[3] = (byte) (0xff & (i64 >> 32)); buffer[4] = (byte) (0xff & (i64 >> 24)); buffer[5] = (byte) (0xff & (i64 >> 16)); buffer[6] = (byte) (0xff & (i64 >> 8)); buffer[7] = (byte) (0xff & (i64)); trans_.write(buffer, 0, 8); } public void writeDouble(double dub) throws TException { writeI64(Double.doubleToLongBits(dub)); } public void writeFloat(float flt) throws TException { writeI32(Float.floatToIntBits(flt)); } public void writeString(String str) throws TException { byte[] dat = str.getBytes(StandardCharsets.UTF_8); writeI32(dat.length); trans_.write(dat, 0, dat.length); } public void writeBinary(byte[] bin) throws TException { writeI32(bin.length); trans_.write(bin, 0, bin.length); } /** Reading methods. */ public TMessage readMessageBegin() throws TException { int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } return new TMessage(readString(), (byte) (size & 0x000000ff), readI32()); } else { if (strictRead_) { throw new TProtocolException( TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } return new TMessage(readStringBody(size), readByte(), readI32()); } } public void readMessageEnd() {} public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) { return ANONYMOUS_STRUCT; } public void readStructEnd() {} public TField readFieldBegin() throws TException { byte type = readByte(); short id = type == TType.STOP ? 0 : readI16(); return new TField("", type, id); } public void readFieldEnd() {} public TMap readMapBegin() throws TException { byte keyType = readByte(); byte valueType = readByte(); int size = readI32(); ensureMapHasEnough(size, keyType, valueType); return new TMap(keyType, valueType, size); } public void readMapEnd() {} public TList readListBegin() throws TException { byte type = readByte(); int size = readI32(); ensureContainerHasEnough(size, type); return new TList(type, size); } public void readListEnd() {} public TSet readSetBegin() throws TException { byte type = readByte(); int size = readI32(); ensureContainerHasEnough(size, type); return new TSet(type, size); } public void readSetEnd() {} public boolean readBool() throws TException { return (readByte() == 1); } public byte readByte() throws TException { if (trans_.getBytesRemainingInBuffer() >= 1) { byte b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); return b; } readAll(buffer, 0, 1); return buffer[0]; } public short readI16() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 2) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(2); } else { readAll(buffer, 0, 2); } return (short) (((buf[off] & 0xff) << 8) | ((buf[off + 1] & 0xff))); } public int readI32() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 4) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(4); } else { readAll(buffer, 0, 4); } return ((buf[off] & 0xff) << 24) | ((buf[off + 1] & 0xff) << 16) | ((buf[off + 2] & 0xff) << 8) | ((buf[off + 3] & 0xff)); } public long readI64() throws TException { byte[] buf = buffer; int off = 0; if (trans_.getBytesRemainingInBuffer() >= 8) { buf = trans_.getBuffer(); off = trans_.getBufferPosition(); trans_.consumeBuffer(8); } else { readAll(buffer, 0, 8); } return ((long) (buf[off] & 0xff) << 56) | ((long) (buf[off + 1] & 0xff) << 48) | ((long) (buf[off + 2] & 0xff) << 40) | ((long) (buf[off + 3] & 0xff) << 32) | ((long) (buf[off + 4] & 0xff) << 24) | ((long) (buf[off + 5] & 0xff) << 16) | ((long) (buf[off + 6] & 0xff) << 8) | ((long) (buf[off + 7] & 0xff)); } public double readDouble() throws TException { return Double.longBitsToDouble(readI64()); } public float readFloat() throws TException { return Float.intBitsToFloat(readI32()); } public String readString() throws TException { int size = readI32(); checkReadLength(size); if (trans_.getBytesRemainingInBuffer() >= size) { String s = new String(trans_.getBuffer(), trans_.getBufferPosition(), size, StandardCharsets.UTF_8); trans_.consumeBuffer(size); return s; } return readStringBody(size); } public String readStringBody(int size) throws TException { checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return new String(buf, StandardCharsets.UTF_8); } public byte[] readBinary() throws TException { int size = readI32(); checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return buf; } private int readAll(byte[] buf, int off, int len) throws TException { checkReadLength(len); return trans_.readAll(buf, off, len); } public void setReadLength(int readLength) { readLength_ = readLength; checkReadLength_ = true; } protected void checkReadLength(int length) throws TException { if (length < 0) { throw new TException("Negative length: " + length); } if (checkReadLength_) { readLength_ -= length; if (readLength_ < 0) { throw new TException("Message length exceeded: " + length); } } } @Override protected int typeMinimumSize(byte type) { switch (type & 0x0f) { case TType.BOOL: case TType.BYTE: return 1; case TType.I16: return 2; case TType.I32: case TType.FLOAT: return 4; case TType.DOUBLE: case TType.I64: return 8; case TType.STRING: return 4; case TType.LIST: case TType.SET: // type (1 byte) + size (4 bytes) return 1 + 4; case TType.MAP: // key type (1 byte) + value type (1 byte) + size (4 bytes) return 1 + 1 + 4; case TType.STRUCT: return 1; default: throw new TProtocolException( TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f)); } } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_853_0
crossvul-java_data_good_854_2
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.meta_data.FieldMetaData; import com.facebook.thrift.scheme.IScheme; import com.facebook.thrift.scheme.StandardScheme; import com.facebook.thrift.transport.TTransport; import java.util.Collections; import java.util.Map; /** Protocol interface definition. */ public abstract class TProtocol { /** Prevent direct instantiation */ @SuppressWarnings("unused") private TProtocol() {} /** Transport */ protected TTransport trans_; /** Constructor */ protected TProtocol(TTransport trans) { trans_ = trans; } /** Transport accessor */ public TTransport getTransport() { return trans_; } /** Writing methods. */ public abstract void writeMessageBegin(TMessage message) throws TException; public abstract void writeMessageEnd() throws TException; public abstract void writeStructBegin(TStruct struct) throws TException; public abstract void writeStructEnd() throws TException; public abstract void writeFieldBegin(TField field) throws TException; public abstract void writeFieldEnd() throws TException; public abstract void writeFieldStop() throws TException; public abstract void writeMapBegin(TMap map) throws TException; public abstract void writeMapEnd() throws TException; public abstract void writeListBegin(TList list) throws TException; public abstract void writeListEnd() throws TException; public abstract void writeSetBegin(TSet set) throws TException; public abstract void writeSetEnd() throws TException; public abstract void writeBool(boolean b) throws TException; public abstract void writeByte(byte b) throws TException; public abstract void writeI16(short i16) throws TException; public abstract void writeI32(int i32) throws TException; public abstract void writeI64(long i64) throws TException; public abstract void writeDouble(double dub) throws TException; public abstract void writeFloat(float flt) throws TException; public abstract void writeString(String str) throws TException; public abstract void writeBinary(byte[] bin) throws TException; /** Reading methods. */ public abstract TMessage readMessageBegin() throws TException; public abstract void readMessageEnd() throws TException; /** * Protocol may have elements listed by name, and needs a mapping to determine their ids, as * required of readFieldBegin method. */ public abstract TStruct readStructBegin(Map<Integer, FieldMetaData> metaDataMap) throws TException; /** * Code generated by older compiler doesn't pass metadata map parameter to readStructBegin. It * won't be able to employ protocols that rely on it, but will work with pre-existing protocols. */ public TStruct readStructBegin() throws TException { return readStructBegin(Collections.<Integer, FieldMetaData>emptyMap()); } public abstract void readStructEnd() throws TException; public abstract TField readFieldBegin() throws TException; public abstract void readFieldEnd() throws TException; /** * Returned TMap may have size of -1, expecting the user to peek into the map, one element at a * time, with peekMap method. */ public abstract TMap readMapBegin() throws TException; public boolean peekMap() throws TException { throw new TException("Peeking into a map not supported, likely because it's sized"); } public abstract void readMapEnd() throws TException; /** * Returned TList may have size of -1, expecting the user to peek into the list, one element at a * time, with peekList method. */ public abstract TList readListBegin() throws TException; public boolean peekList() throws TException { throw new TException("Peeking into a list not supported, likely because it's sized"); } public abstract void readListEnd() throws TException; /** * Returned TSet may have size of -1, expecting the user to peek into the set, one element at a * time, with peekSet method. */ public abstract TSet readSetBegin() throws TException; public boolean peekSet() throws TException { throw new TException("Peeking into a set not supported, likely because it's sized"); } public abstract void readSetEnd() throws TException; public abstract boolean readBool() throws TException; public abstract byte readByte() throws TException; public abstract short readI16() throws TException; public abstract int readI32() throws TException; public abstract long readI64() throws TException; public abstract double readDouble() throws TException; public abstract float readFloat() throws TException; public abstract String readString() throws TException; public abstract byte[] readBinary() throws TException; /** * Reset any internal state back to a blank slate. This method only needs to be implemented for * stateful protocols. */ public void reset() {} /** Scheme accessor */ public Class<? extends IScheme> getScheme() { return StandardScheme.class; } /** Return the minimum size of a type */ protected int typeMinimumSize(byte type) { return 1; } protected void ensureContainerHasEnough(int size, byte type) { int minimumExpected = size * typeMinimumSize(type); ensureHasEnoughBytes(minimumExpected); } protected void ensureMapHasEnough(int size, byte keyType, byte valueType) { int minimumExpected = size * (typeMinimumSize(keyType) + typeMinimumSize(valueType)); ensureHasEnoughBytes(minimumExpected); } private void ensureHasEnoughBytes(int minimumExpected) { int remaining = trans_.getBytesRemainingInBuffer(); if (remaining < 0) { return; // Some transport are not buffered } if (remaining < minimumExpected) { throw new TProtocolException( TProtocolException.INVALID_DATA, "Not enough bytes to read the entire message, the data appears to be truncated"); } } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_854_2
crossvul-java_data_bad_853_1
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.ShortStack; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** * TCompactProtocol2 is the Java implementation of the compact protocol specified in THRIFT-110. The * fundamental approach to reducing the overhead of structures is a) use variable-length integers * all over the place and b) make use of unused bits wherever possible. Your savings will obviously * vary based on the specific makeup of your structs, but in general, the more fields, nested * structures, short strings and collections, and low-value i32 and i64 fields you have, the more * benefit you'll see. */ public class TCompactProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(""); private static final TField TSTOP = new TField("", TType.STOP, (short) 0); private static final byte[] ttypeToCompactType = new byte[20]; static { ttypeToCompactType[TType.STOP] = TType.STOP; ttypeToCompactType[TType.BOOL] = Types.BOOLEAN_TRUE; ttypeToCompactType[TType.BYTE] = Types.BYTE; ttypeToCompactType[TType.I16] = Types.I16; ttypeToCompactType[TType.I32] = Types.I32; ttypeToCompactType[TType.I64] = Types.I64; ttypeToCompactType[TType.DOUBLE] = Types.DOUBLE; ttypeToCompactType[TType.STRING] = Types.BINARY; ttypeToCompactType[TType.LIST] = Types.LIST; ttypeToCompactType[TType.SET] = Types.SET; ttypeToCompactType[TType.MAP] = Types.MAP; ttypeToCompactType[TType.STRUCT] = Types.STRUCT; ttypeToCompactType[TType.FLOAT] = Types.FLOAT; } /** TProtocolFactory that produces TCompactProtocols. */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { private final long maxNetworkBytes_; public Factory() { maxNetworkBytes_ = -1; } public Factory(int maxNetworkBytes) { maxNetworkBytes_ = maxNetworkBytes; } public TProtocol getProtocol(TTransport trans) { return new TCompactProtocol(trans, maxNetworkBytes_); } } public static final byte PROTOCOL_ID = (byte) 0x82; public static final byte VERSION = 2; public static final byte VERSION_LOW = 1; public static final byte VERSION_DOUBLE_BE = 2; public static final byte VERSION_MASK = 0x1f; // 0001 1111 public static final byte TYPE_MASK = (byte) 0xE0; // 1110 0000 public static final int TYPE_SHIFT_AMOUNT = 5; /** All of the on-wire type codes. */ private static class Types { public static final byte BOOLEAN_TRUE = 0x01; public static final byte BOOLEAN_FALSE = 0x02; public static final byte BYTE = 0x03; public static final byte I16 = 0x04; public static final byte I32 = 0x05; public static final byte I64 = 0x06; public static final byte DOUBLE = 0x07; public static final byte BINARY = 0x08; public static final byte LIST = 0x09; public static final byte SET = 0x0A; public static final byte MAP = 0x0B; public static final byte STRUCT = 0x0C; public static final byte FLOAT = 0x0D; } /** * Used to keep track of the last field for the current and previous structs, so we can do the * delta stuff. */ private ShortStack lastField_ = new ShortStack(15); private short lastFieldId_ = 0; private byte version_ = VERSION; /** * If we encounter a boolean field begin, save the TField here so it can have the value * incorporated. */ private TField booleanField_ = null; /** * If we read a field header, and it's a boolean field, save the boolean value here so that * readBool can use it. */ private Boolean boolValue_ = null; /** * The maximum number of bytes to read from the network for variable-length fields (such as * strings or binary) or -1 for unlimited. */ private final long maxNetworkBytes_; /** Temporary buffer to avoid allocations */ private final byte[] buffer = new byte[10]; /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. * @param maxNetworkBytes the maximum number of bytes to read for variable-length fields. */ public TCompactProtocol(TTransport transport, long maxNetworkBytes) { super(transport); maxNetworkBytes_ = maxNetworkBytes; } /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. */ public TCompactProtocol(TTransport transport) { this(transport, -1); } public void reset() { lastField_.clear(); lastFieldId_ = 0; } // // Public Writing methods. // /** * Write a message header to the wire. Compact Protocol messages contain the protocol version so * we can migrate forwards in the future if need be. */ public void writeMessageBegin(TMessage message) throws TException { writeByteDirect(PROTOCOL_ID); writeByteDirect((VERSION & VERSION_MASK) | ((message.type << TYPE_SHIFT_AMOUNT) & TYPE_MASK)); writeVarint32(message.seqid); writeString(message.name); } /** * Write a struct begin. This doesn't actually put anything on the wire. We use it as an * opportunity to put special placeholder markers on the field stack so we can get the field id * deltas correct. */ public void writeStructBegin(TStruct struct) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; } /** * Write a struct end. This doesn't actually put anything on the wire. We use this as an * opportunity to pop the last field from the current struct off of the field stack. */ public void writeStructEnd() throws TException { lastFieldId_ = lastField_.pop(); } /** * Write a field header containing the field id and field type. If the difference between the * current field id and the last one is small (< 15), then the field id will be encoded in the 4 * MSB as a delta. Otherwise, the field id will follow the type header as a zigzag varint. */ public void writeFieldBegin(TField field) throws TException { if (field.type == TType.BOOL) { // we want to possibly include the value, so we'll wait. booleanField_ = field; } else { writeFieldBeginInternal(field, (byte) -1); } } /** * The workhorse of writeFieldBegin. It has the option of doing a 'type override' of the type * header. This is used specifically in the boolean field case. */ private void writeFieldBeginInternal(TField field, byte typeOverride) throws TException { // short lastField = lastField_.pop(); // if there's a type override, use that. byte typeToWrite = typeOverride == -1 ? getCompactType(field.type) : typeOverride; // check if we can use delta encoding for the field id if (field.id > lastFieldId_ && field.id - lastFieldId_ <= 15) { // write them together writeByteDirect((field.id - lastFieldId_) << 4 | typeToWrite); } else { // write them separate writeByteDirect(typeToWrite); writeI16(field.id); } lastFieldId_ = field.id; // lastField_.push(field.id); } /** Write the STOP symbol so we know there are no more fields in this struct. */ public void writeFieldStop() throws TException { writeByteDirect(TType.STOP); } /** * Write a map header. If the map is empty, omit the key and value type headers, as we don't need * any additional information to skip it. */ public void writeMapBegin(TMap map) throws TException { if (map.size == 0) { writeByteDirect(0); } else { writeVarint32(map.size); writeByteDirect(getCompactType(map.keyType) << 4 | getCompactType(map.valueType)); } } /** Write a list header. */ public void writeListBegin(TList list) throws TException { writeCollectionBegin(list.elemType, list.size); } /** Write a set header. */ public void writeSetBegin(TSet set) throws TException { writeCollectionBegin(set.elemType, set.size); } /** * Write a boolean value. Potentially, this could be a boolean field, in which case the field * header info isn't written yet. If so, decide what the right type header is for the value and * then write the field header. Otherwise, write a single byte. */ public void writeBool(boolean b) throws TException { if (booleanField_ != null) { // we haven't written the field header yet writeFieldBeginInternal(booleanField_, b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); booleanField_ = null; } else { // we're not part of a field, so just write the value. writeByteDirect(b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); } } /** Write a byte. Nothing to see here! */ public void writeByte(byte b) throws TException { writeByteDirect(b); } /** Write an I16 as a zigzag varint. */ public void writeI16(short i16) throws TException { writeVarint32(intToZigZag(i16)); } /** Write an i32 as a zigzag varint. */ public void writeI32(int i32) throws TException { writeVarint32(intToZigZag(i32)); } /** Write an i64 as a zigzag varint. */ public void writeI64(long i64) throws TException { writeVarint64(longToZigzag(i64)); } /** Write a double to the wire as 8 bytes. */ public void writeDouble(double dub) throws TException { fixedLongToBytes(Double.doubleToLongBits(dub), buffer, 0); trans_.write(buffer, 0, 8); } /** Write a float to the wire as 4 bytes. */ public void writeFloat(float flt) throws TException { fixedIntToBytes(Float.floatToIntBits(flt), buffer, 0); trans_.write(buffer, 0, 4); } /** Write a string to the wire with a varint size preceding. */ public void writeString(String str) throws TException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); writeBinary(bytes, 0, bytes.length); } /** Write a byte array, using a varint for the size. */ public void writeBinary(byte[] buf) throws TException { writeBinary(buf, 0, buf.length); } private void writeBinary(byte[] buf, int offset, int length) throws TException { writeVarint32(length); trans_.write(buf, offset, length); } // // These methods are called by structs, but don't actually have any wire // output or purpose. // public void writeMessageEnd() throws TException {} public void writeMapEnd() throws TException {} public void writeListEnd() throws TException {} public void writeSetEnd() throws TException {} public void writeFieldEnd() throws TException {} // // Internal writing methods // /** * Abstract method for writing the start of lists and sets. List and sets on the wire differ only * by the type indicator. */ protected void writeCollectionBegin(byte elemType, int size) throws TException { if (size <= 14) { writeByteDirect(size << 4 | getCompactType(elemType)); } else { writeByteDirect(0xf0 | getCompactType(elemType)); writeVarint32(size); } } /** Write an i32 as a varint. Results in 1-5 bytes on the wire. */ private void writeVarint32(int n) throws TException { int idx = 0; while (true) { if ((n & ~0x7F) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = (byte) ((n & 0x7F) | 0x80); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** Write an i64 as a varint. Results in 1-10 bytes on the wire. */ private void writeVarint64(long n) throws TException { int idx = 0; while (true) { if ((n & ~0x7FL) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = ((byte) ((n & 0x7F) | 0x80)); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** * Convert l into a zigzag long. This allows negative numbers to be represented compactly as a * varint. */ private long longToZigzag(long l) { return (l << 1) ^ (l >> 63); } /** * Convert n into a zigzag int. This allows negative numbers to be represented compactly as a * varint. */ private int intToZigZag(int n) { return (n << 1) ^ (n >> 31); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedLongToBytes(long n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 56) & 0xff); buf[off + 1] = (byte) ((n >> 48) & 0xff); buf[off + 2] = (byte) ((n >> 40) & 0xff); buf[off + 3] = (byte) ((n >> 32) & 0xff); buf[off + 4] = (byte) ((n >> 24) & 0xff); buf[off + 5] = (byte) ((n >> 16) & 0xff); buf[off + 6] = (byte) ((n >> 8) & 0xff); buf[off + 7] = (byte) (n & 0xff); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedIntToBytes(int n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 24) & 0xff); buf[off + 1] = (byte) ((n >> 16) & 0xff); buf[off + 2] = (byte) ((n >> 8) & 0xff); buf[off + 3] = (byte) (n & 0xff); } /** * Writes a byte without any possiblity of all that field header nonsense. Used internally by * other writing methods that know they need to write a byte. */ private void writeByteDirect(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } /** Writes a byte without any possiblity of all that field header nonsense. */ private void writeByteDirect(int n) throws TException { writeByteDirect((byte) n); } // // Reading methods. // /** Read a message header. */ public TMessage readMessageBegin() throws TException { byte protocolId = readByte(); if (protocolId != PROTOCOL_ID) { throw new TProtocolException( "Expected protocol id " + Integer.toHexString(PROTOCOL_ID) + " but got " + Integer.toHexString(protocolId)); } byte versionAndType = readByte(); version_ = (byte) (versionAndType & VERSION_MASK); if (!(version_ <= VERSION && version_ >= VERSION_LOW)) { throw new TProtocolException("Expected version " + VERSION + " but got " + version_); } byte type = (byte) ((versionAndType >> TYPE_SHIFT_AMOUNT) & 0x03); int seqid = readVarint32(); String messageName = readString(); return new TMessage(messageName, type, seqid); } /** * Read a struct begin. There's nothing on the wire for this, but it is our opportunity to push a * new struct begin marker onto the field stack. */ public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; return ANONYMOUS_STRUCT; } /** * Doesn't actually consume any wire data, just removes the last field for this struct from the * field stack. */ public void readStructEnd() throws TException { // consume the last field we read off the wire. lastFieldId_ = lastField_.pop(); } /** Read a field header off the wire. */ public TField readFieldBegin() throws TException { byte type = readByte(); // if it's a stop, then we can return immediately, as the struct is over. if (type == TType.STOP) { return TSTOP; } short fieldId; // mask off the 4 MSB of the type header. it could contain a field id delta. short modifier = (short) ((type & 0xf0) >> 4); if (modifier == 0) { // not a delta. look ahead for the zigzag varint field id. fieldId = readI16(); } else { // has a delta. add the delta to the last read field id. fieldId = (short) (lastFieldId_ + modifier); } TField field = new TField("", getTType((byte) (type & 0x0f)), fieldId); // if this happens to be a boolean field, the value is encoded in the type if (isBoolType(type)) { // save the boolean value in a special instance variable. boolValue_ = (byte) (type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; } // push the new field onto the field stack so we can keep the deltas going. lastFieldId_ = field.id; return field; } /** * Read a map header off the wire. If the size is zero, skip reading the key and value type. This * means that 0-length maps will yield TMaps without the "correct" types. */ public TMap readMapBegin() throws TException { int size = readVarint32(); byte keyAndValueType = size == 0 ? 0 : readByte(); byte keyType = getTType((byte) (keyAndValueType >> 4)); byte valueType = getTType((byte) (keyAndValueType & 0xf)); if (size > 0) { ensureMapHasEnough(size, keyType, valueType); } return new TMap(keyType, valueType, size); } /** * Read a list header off the wire. If the list size is 0-14, the size will be packed into the * element type header. If it's a longer list, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TList readListBegin() throws TException { byte size_and_type = readByte(); int size = (size_and_type >> 4) & 0x0f; if (size == 15) { size = readVarint32(); } byte type = getTType(size_and_type); ensureContainerHasEnough(size, type); return new TList(type, size); } /** * Read a set header off the wire. If the set size is 0-14, the size will be packed into the * element type header. If it's a longer set, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TSet readSetBegin() throws TException { return new TSet(readListBegin()); } /** * Read a boolean off the wire. If this is a boolean field, the value should already have been * read during readFieldBegin, so we'll just consume the pre-stored value. Otherwise, read a byte. */ public boolean readBool() throws TException { if (boolValue_ != null) { boolean result = boolValue_.booleanValue(); boolValue_ = null; return result; } return readByte() == Types.BOOLEAN_TRUE; } /** Read a single byte off the wire. Nothing interesting here. */ public byte readByte() throws TException { byte b; if (trans_.getBytesRemainingInBuffer() > 0) { b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); } else { trans_.readAll(buffer, 0, 1); b = buffer[0]; } return b; } /** Read an i16 from the wire as a zigzag varint. */ public short readI16() throws TException { return (short) zigzagToInt(readVarint32()); } /** Read an i32 from the wire as a zigzag varint. */ public int readI32() throws TException { return zigzagToInt(readVarint32()); } /** Read an i64 from the wire as a zigzag varint. */ public long readI64() throws TException { return zigzagToLong(readVarint64()); } /** No magic here - just read a double off the wire. */ public double readDouble() throws TException { trans_.readAll(buffer, 0, 8); long value; if (version_ >= VERSION_DOUBLE_BE) { value = bytesToLong(buffer); } else { value = bytesToLongLE(buffer); } return Double.longBitsToDouble(value); } /** No magic here - just read a float off the wire. */ public float readFloat() throws TException { trans_.readAll(buffer, 0, 4); int value = bytesToInt(buffer); return Float.intBitsToFloat(value); } /** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */ public String readString() throws TException { int length = readVarint32(); checkReadLength(length); if (length == 0) { return ""; } if (trans_.getBytesRemainingInBuffer() >= length) { String str = new String( trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8); trans_.consumeBuffer(length); return str; } else { return new String(readBinary(length), StandardCharsets.UTF_8); } } /** Read a byte[] from the wire. */ public byte[] readBinary() throws TException { int length = readVarint32(); checkReadLength(length); return readBinary(length); } private byte[] readBinary(int length) throws TException { if (length == 0) { return new byte[0]; } byte[] buf = new byte[length]; trans_.readAll(buf, 0, length); return buf; } private void checkReadLength(int length) throws TProtocolException { if (length < 0) { throw new TProtocolException("Negative length: " + length); } if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) { throw new TProtocolException("Length exceeded max allowed: " + length); } } // // These methods are here for the struct to call, but don't have any wire // encoding. // public void readMessageEnd() throws TException {} public void readFieldEnd() throws TException {} public void readMapEnd() throws TException {} public void readListEnd() throws TException {} public void readSetEnd() throws TException {} // // Internal reading methods // /** * Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to * follow. This can read up to 5 bytes. */ private int readVarint32() throws TException { int result = 0; int shift = 0; if (trans_.getBytesRemainingInBuffer() >= 5) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } /** * Read an i64 from the wire as a proper varint. The MSB of each byte is set if there is another * byte to follow. This can read up to 10 bytes. */ private long readVarint64() throws TException { int shift = 0; long result = 0; if (trans_.getBytesRemainingInBuffer() >= 10) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } // // encoding helpers // /** Convert from zigzag int to int. */ private int zigzagToInt(int n) { return (n >>> 1) ^ -(n & 1); } /** Convert from zigzag long to long. */ private long zigzagToLong(long n) { return (n >>> 1) ^ -(n & 1); } /** * Note that it's important that the mask bytes are long literals, otherwise they'll default to * ints, and when you shift an int left 56 bits, you just get a messed up int. */ private long bytesToLong(byte[] bytes) { return ((bytes[0] & 0xffL) << 56) | ((bytes[1] & 0xffL) << 48) | ((bytes[2] & 0xffL) << 40) | ((bytes[3] & 0xffL) << 32) | ((bytes[4] & 0xffL) << 24) | ((bytes[5] & 0xffL) << 16) | ((bytes[6] & 0xffL) << 8) | ((bytes[7] & 0xffL)); } /* Little endian version of the above */ private long bytesToLongLE(byte[] bytes) { return ((bytes[7] & 0xffL) << 56) | ((bytes[6] & 0xffL) << 48) | ((bytes[5] & 0xffL) << 40) | ((bytes[4] & 0xffL) << 32) | ((bytes[3] & 0xffL) << 24) | ((bytes[2] & 0xffL) << 16) | ((bytes[1] & 0xffL) << 8) | ((bytes[0] & 0xffL)); } private int bytesToInt(byte[] bytes) { return ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | ((bytes[3] & 0xff)); } // // type testing and converting // private boolean isBoolType(byte b) { int lowerNibble = b & 0x0f; return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE; } /** Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. */ private byte getTType(byte type) throws TProtocolException { switch ((byte) (type & 0x0f)) { case TType.STOP: return TType.STOP; case Types.BOOLEAN_FALSE: case Types.BOOLEAN_TRUE: return TType.BOOL; case Types.BYTE: return TType.BYTE; case Types.I16: return TType.I16; case Types.I32: return TType.I32; case Types.I64: return TType.I64; case Types.DOUBLE: return TType.DOUBLE; case Types.FLOAT: return TType.FLOAT; case Types.BINARY: return TType.STRING; case Types.LIST: return TType.LIST; case Types.SET: return TType.SET; case Types.MAP: return TType.MAP; case Types.STRUCT: return TType.STRUCT; default: throw new TProtocolException("don't know what type: " + (byte) (type & 0x0f)); } } /** Given a TType value, find the appropriate TCompactProtocol.Types constant. */ private byte getCompactType(byte ttype) { return ttypeToCompactType[ttype]; } @Override protected int typeMinimumSize(byte type) { switch (type & 0x0f) { case TType.BOOL: case TType.BYTE: case TType.I16: // because of variable length encoding case TType.I32: // because of variable length encoding case TType.I64: // because of variable length encoding return 1; case TType.FLOAT: return 4; case TType.DOUBLE: return 8; case TType.STRING: case TType.STRUCT: case TType.MAP: case TType.SET: case TType.LIST: case TType.ENUM: return 1; default: throw new TProtocolException( TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f)); } } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_853_1
crossvul-java_data_bad_853_3
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift; import com.facebook.thrift.java.test.MyListStruct; import com.facebook.thrift.java.test.MyMapStruct; import com.facebook.thrift.java.test.MySetStruct; import com.facebook.thrift.protocol.TBinaryProtocol; import com.facebook.thrift.protocol.TCompactProtocol; import com.facebook.thrift.protocol.TProtocol; import com.facebook.thrift.protocol.TProtocolException; import com.facebook.thrift.protocol.TType; import com.facebook.thrift.transport.TMemoryInputTransport; import org.junit.Test; public class TruncatedFrameTest extends junit.framework.TestCase { private static final byte[] kBinaryListEncoding = { TType.LIST, // Field Type = List (byte) 0x00, (byte) 0x01, // Field id = 1 TType.I64, // List type = i64 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, // List length (255 > 3!) (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 1L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 2L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 3L (byte) 0x00, // Stop }; private static final byte[] kCompactListEncoding = { (byte) 0b00011001, // field id delta (0001) + type (1001) = List (byte) 0b11100110, // list size (0111) and 7>3 + list type (0110) = i64 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; private static final byte[] kCompactListEncoding2 = { (byte) 0b00011001, // field id delta (0001) + type (1001) = List (byte) 0b11110110, // list size magic marker (1111) + list type (0110) = i64 (byte) 0x64, // list actual size (varint of 1 byte here) = 100 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; public static void testTruncated(TBase struct, TProtocol iprot) throws Exception { try { struct.read(iprot); assertTrue("Not reachable", false); } catch (TProtocolException ex) { assertEquals( "Not enough bytes to read the entire message, the data appears to be truncated", ex.getMessage()); } } @Test public static void testListBinary() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryListEncoding); TProtocol iprot = new TBinaryProtocol(buf); testTruncated(new MyListStruct(), iprot); } @Test public static void testListCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MyListStruct(), iprot); } @Test public static void testLongListCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding2); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MyListStruct(), iprot); } private static final byte[] kBinarySetEncoding = { TType.SET, // Field Type = Set (byte) 0x00, (byte) 0x01, // Field id = 1 TType.I64, // Set type = i64 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xFF, // Set length (255 > 3!) (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 1L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 2L (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // value = 3L (byte) 0x00, // Stop }; private static final byte[] kCompactSetEncoding = { (byte) 0b00011010, // field id delta (0001) + type (1010) = Set (byte) 0b01110110, // set size (0111) and 7>3 + set type (0110) = i64 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; private static final byte[] kCompactSetEncoding2 = { (byte) 0b00011010, // field id delta (0001) + type (1010) = Set (byte) 0b11110110, // set size magic marker (1111) + set type (0110) = i64 (byte) 0x64, // set actual size (varint of 1 byte here) = 100 (byte) 0x02, // value = 1 (zigzag encoded) (byte) 0x04, // value = 2 (zigzag encoded) (byte) 0x06, // value = 3 (zigzag encoded) (byte) 0x00, // Stop }; @Test public static void testSetBinary() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kBinarySetEncoding); TProtocol iprot = new TBinaryProtocol(buf); testTruncated(new MySetStruct(), iprot); } @Test public static void testSetCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MySetStruct(), iprot); } @Test public static void testLongSetCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding2); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MySetStruct(), iprot); } private static final byte[] kBinaryMapEncoding = { TType.MAP, // field type = Map (byte) 0x00, (byte) 0x01, // field id = 1 TType.I64, // key type = i64 TType.STRING, // value type = string (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, // size = 0x00FFFFFF (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, // key = 0 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // string size = 1 (byte) 0x30, // string value = "0" (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // key = 1 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // string size = 1 (byte) 0x31, // string value = "1" (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, // key = 2 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, // string size = 1 (byte) 0x32, // string value = "2" (byte) 0x00, // Stop }; private static final byte[] kCompactMapEncoding = { (byte) 0b00011011, // field id delta (0001) + type (1011) = Map (byte) 0x64, // map size (varint = 100) (byte) 0b01101000, // key type (0110) i64, value type (1000) string (byte) 0x00, // key value = 0 (byte) 0x01, // value: string size = 1 (byte) 0x30, // string content = "0" (byte) 0x02, // key value = 1 (zigzag encoded) (byte) 0x01, // value: string size = 1 (byte) 0x31, // string content = "1" (byte) 0x04, // key value = 2 (zigzag encoded) (byte) 0x01, // value: string size = 1 (byte) 0x32, // string content = "2" (byte) 0x00, // Stop }; @Test public static void testMapBinary() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryMapEncoding); TProtocol iprot = new TBinaryProtocol(buf); testTruncated(new MyMapStruct(), iprot); } @Test public static void testMapCompact() throws Exception { TMemoryInputTransport buf = new TMemoryInputTransport(kCompactMapEncoding); TProtocol iprot = new TCompactProtocol(buf); testTruncated(new MyMapStruct(), iprot); } private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); private static String bytesToHex(byte[] bytes, int length) { String out = ""; for (int j = 0; j < length; j++) { int v = bytes[j] & 0xFF; out += hexArray[v >>> 4]; out += hexArray[v & 0x0F]; out += " "; } return out; } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_853_3
crossvul-java_data_bad_854_2
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.meta_data.FieldMetaData; import com.facebook.thrift.scheme.IScheme; import com.facebook.thrift.scheme.StandardScheme; import com.facebook.thrift.transport.TTransport; import java.util.Collections; import java.util.Map; /** Protocol interface definition. */ public abstract class TProtocol { /** Prevent direct instantiation */ @SuppressWarnings("unused") private TProtocol() {} /** Transport */ protected TTransport trans_; /** Constructor */ protected TProtocol(TTransport trans) { trans_ = trans; } /** Transport accessor */ public TTransport getTransport() { return trans_; } /** Writing methods. */ public abstract void writeMessageBegin(TMessage message) throws TException; public abstract void writeMessageEnd() throws TException; public abstract void writeStructBegin(TStruct struct) throws TException; public abstract void writeStructEnd() throws TException; public abstract void writeFieldBegin(TField field) throws TException; public abstract void writeFieldEnd() throws TException; public abstract void writeFieldStop() throws TException; public abstract void writeMapBegin(TMap map) throws TException; public abstract void writeMapEnd() throws TException; public abstract void writeListBegin(TList list) throws TException; public abstract void writeListEnd() throws TException; public abstract void writeSetBegin(TSet set) throws TException; public abstract void writeSetEnd() throws TException; public abstract void writeBool(boolean b) throws TException; public abstract void writeByte(byte b) throws TException; public abstract void writeI16(short i16) throws TException; public abstract void writeI32(int i32) throws TException; public abstract void writeI64(long i64) throws TException; public abstract void writeDouble(double dub) throws TException; public abstract void writeFloat(float flt) throws TException; public abstract void writeString(String str) throws TException; public abstract void writeBinary(byte[] bin) throws TException; /** Reading methods. */ public abstract TMessage readMessageBegin() throws TException; public abstract void readMessageEnd() throws TException; /** * Protocol may have elements listed by name, and needs a mapping to determine their ids, as * required of readFieldBegin method. */ public abstract TStruct readStructBegin(Map<Integer, FieldMetaData> metaDataMap) throws TException; /** * Code generated by older compiler doesn't pass metadata map parameter to readStructBegin. It * won't be able to employ protocols that rely on it, but will work with pre-existing protocols. */ public TStruct readStructBegin() throws TException { return readStructBegin(Collections.<Integer, FieldMetaData>emptyMap()); } public abstract void readStructEnd() throws TException; public abstract TField readFieldBegin() throws TException; public abstract void readFieldEnd() throws TException; /** * Returned TMap may have size of -1, expecting the user to peek into the map, one element at a * time, with peekMap method. */ public abstract TMap readMapBegin() throws TException; public boolean peekMap() throws TException { throw new TException("Peeking into a map not supported, likely because it's sized"); } public abstract void readMapEnd() throws TException; /** * Returned TList may have size of -1, expecting the user to peek into the list, one element at a * time, with peekList method. */ public abstract TList readListBegin() throws TException; public boolean peekList() throws TException { throw new TException("Peeking into a list not supported, likely because it's sized"); } public abstract void readListEnd() throws TException; /** * Returned TSet may have size of -1, expecting the user to peek into the set, one element at a * time, with peekSet method. */ public abstract TSet readSetBegin() throws TException; public boolean peekSet() throws TException { throw new TException("Peeking into a set not supported, likely because it's sized"); } public abstract void readSetEnd() throws TException; public abstract boolean readBool() throws TException; public abstract byte readByte() throws TException; public abstract short readI16() throws TException; public abstract int readI32() throws TException; public abstract long readI64() throws TException; public abstract double readDouble() throws TException; public abstract float readFloat() throws TException; public abstract String readString() throws TException; public abstract byte[] readBinary() throws TException; /** * Reset any internal state back to a blank slate. This method only needs to be implemented for * stateful protocols. */ public void reset() {} /** Scheme accessor */ public Class<? extends IScheme> getScheme() { return StandardScheme.class; } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_854_2
crossvul-java_data_bad_854_1
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift.protocol; import com.facebook.thrift.ShortStack; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import java.nio.charset.StandardCharsets; import java.util.Map; /** * TCompactProtocol2 is the Java implementation of the compact protocol specified in THRIFT-110. The * fundamental approach to reducing the overhead of structures is a) use variable-length integers * all over the place and b) make use of unused bits wherever possible. Your savings will obviously * vary based on the specific makeup of your structs, but in general, the more fields, nested * structures, short strings and collections, and low-value i32 and i64 fields you have, the more * benefit you'll see. */ public class TCompactProtocol extends TProtocol { private static final TStruct ANONYMOUS_STRUCT = new TStruct(""); private static final TField TSTOP = new TField("", TType.STOP, (short) 0); private static final byte[] ttypeToCompactType = new byte[20]; static { ttypeToCompactType[TType.STOP] = TType.STOP; ttypeToCompactType[TType.BOOL] = Types.BOOLEAN_TRUE; ttypeToCompactType[TType.BYTE] = Types.BYTE; ttypeToCompactType[TType.I16] = Types.I16; ttypeToCompactType[TType.I32] = Types.I32; ttypeToCompactType[TType.I64] = Types.I64; ttypeToCompactType[TType.DOUBLE] = Types.DOUBLE; ttypeToCompactType[TType.STRING] = Types.BINARY; ttypeToCompactType[TType.LIST] = Types.LIST; ttypeToCompactType[TType.SET] = Types.SET; ttypeToCompactType[TType.MAP] = Types.MAP; ttypeToCompactType[TType.STRUCT] = Types.STRUCT; ttypeToCompactType[TType.FLOAT] = Types.FLOAT; } /** TProtocolFactory that produces TCompactProtocols. */ @SuppressWarnings("serial") public static class Factory implements TProtocolFactory { private final long maxNetworkBytes_; public Factory() { maxNetworkBytes_ = -1; } public Factory(int maxNetworkBytes) { maxNetworkBytes_ = maxNetworkBytes; } public TProtocol getProtocol(TTransport trans) { return new TCompactProtocol(trans, maxNetworkBytes_); } } public static final byte PROTOCOL_ID = (byte) 0x82; public static final byte VERSION = 2; public static final byte VERSION_LOW = 1; public static final byte VERSION_DOUBLE_BE = 2; public static final byte VERSION_MASK = 0x1f; // 0001 1111 public static final byte TYPE_MASK = (byte) 0xE0; // 1110 0000 public static final int TYPE_SHIFT_AMOUNT = 5; /** All of the on-wire type codes. */ private static class Types { public static final byte BOOLEAN_TRUE = 0x01; public static final byte BOOLEAN_FALSE = 0x02; public static final byte BYTE = 0x03; public static final byte I16 = 0x04; public static final byte I32 = 0x05; public static final byte I64 = 0x06; public static final byte DOUBLE = 0x07; public static final byte BINARY = 0x08; public static final byte LIST = 0x09; public static final byte SET = 0x0A; public static final byte MAP = 0x0B; public static final byte STRUCT = 0x0C; public static final byte FLOAT = 0x0D; } /** * Used to keep track of the last field for the current and previous structs, so we can do the * delta stuff. */ private ShortStack lastField_ = new ShortStack(15); private short lastFieldId_ = 0; private byte version_ = VERSION; /** * If we encounter a boolean field begin, save the TField here so it can have the value * incorporated. */ private TField booleanField_ = null; /** * If we read a field header, and it's a boolean field, save the boolean value here so that * readBool can use it. */ private Boolean boolValue_ = null; /** * The maximum number of bytes to read from the network for variable-length fields (such as * strings or binary) or -1 for unlimited. */ private final long maxNetworkBytes_; /** Temporary buffer to avoid allocations */ private final byte[] buffer = new byte[10]; /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. * @param maxNetworkBytes the maximum number of bytes to read for variable-length fields. */ public TCompactProtocol(TTransport transport, long maxNetworkBytes) { super(transport); maxNetworkBytes_ = maxNetworkBytes; } /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. */ public TCompactProtocol(TTransport transport) { this(transport, -1); } public void reset() { lastField_.clear(); lastFieldId_ = 0; } // // Public Writing methods. // /** * Write a message header to the wire. Compact Protocol messages contain the protocol version so * we can migrate forwards in the future if need be. */ public void writeMessageBegin(TMessage message) throws TException { writeByteDirect(PROTOCOL_ID); writeByteDirect((VERSION & VERSION_MASK) | ((message.type << TYPE_SHIFT_AMOUNT) & TYPE_MASK)); writeVarint32(message.seqid); writeString(message.name); } /** * Write a struct begin. This doesn't actually put anything on the wire. We use it as an * opportunity to put special placeholder markers on the field stack so we can get the field id * deltas correct. */ public void writeStructBegin(TStruct struct) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; } /** * Write a struct end. This doesn't actually put anything on the wire. We use this as an * opportunity to pop the last field from the current struct off of the field stack. */ public void writeStructEnd() throws TException { lastFieldId_ = lastField_.pop(); } /** * Write a field header containing the field id and field type. If the difference between the * current field id and the last one is small (< 15), then the field id will be encoded in the 4 * MSB as a delta. Otherwise, the field id will follow the type header as a zigzag varint. */ public void writeFieldBegin(TField field) throws TException { if (field.type == TType.BOOL) { // we want to possibly include the value, so we'll wait. booleanField_ = field; } else { writeFieldBeginInternal(field, (byte) -1); } } /** * The workhorse of writeFieldBegin. It has the option of doing a 'type override' of the type * header. This is used specifically in the boolean field case. */ private void writeFieldBeginInternal(TField field, byte typeOverride) throws TException { // short lastField = lastField_.pop(); // if there's a type override, use that. byte typeToWrite = typeOverride == -1 ? getCompactType(field.type) : typeOverride; // check if we can use delta encoding for the field id if (field.id > lastFieldId_ && field.id - lastFieldId_ <= 15) { // write them together writeByteDirect((field.id - lastFieldId_) << 4 | typeToWrite); } else { // write them separate writeByteDirect(typeToWrite); writeI16(field.id); } lastFieldId_ = field.id; // lastField_.push(field.id); } /** Write the STOP symbol so we know there are no more fields in this struct. */ public void writeFieldStop() throws TException { writeByteDirect(TType.STOP); } /** * Write a map header. If the map is empty, omit the key and value type headers, as we don't need * any additional information to skip it. */ public void writeMapBegin(TMap map) throws TException { if (map.size == 0) { writeByteDirect(0); } else { writeVarint32(map.size); writeByteDirect(getCompactType(map.keyType) << 4 | getCompactType(map.valueType)); } } /** Write a list header. */ public void writeListBegin(TList list) throws TException { writeCollectionBegin(list.elemType, list.size); } /** Write a set header. */ public void writeSetBegin(TSet set) throws TException { writeCollectionBegin(set.elemType, set.size); } /** * Write a boolean value. Potentially, this could be a boolean field, in which case the field * header info isn't written yet. If so, decide what the right type header is for the value and * then write the field header. Otherwise, write a single byte. */ public void writeBool(boolean b) throws TException { if (booleanField_ != null) { // we haven't written the field header yet writeFieldBeginInternal(booleanField_, b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); booleanField_ = null; } else { // we're not part of a field, so just write the value. writeByteDirect(b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE); } } /** Write a byte. Nothing to see here! */ public void writeByte(byte b) throws TException { writeByteDirect(b); } /** Write an I16 as a zigzag varint. */ public void writeI16(short i16) throws TException { writeVarint32(intToZigZag(i16)); } /** Write an i32 as a zigzag varint. */ public void writeI32(int i32) throws TException { writeVarint32(intToZigZag(i32)); } /** Write an i64 as a zigzag varint. */ public void writeI64(long i64) throws TException { writeVarint64(longToZigzag(i64)); } /** Write a double to the wire as 8 bytes. */ public void writeDouble(double dub) throws TException { fixedLongToBytes(Double.doubleToLongBits(dub), buffer, 0); trans_.write(buffer, 0, 8); } /** Write a float to the wire as 4 bytes. */ public void writeFloat(float flt) throws TException { fixedIntToBytes(Float.floatToIntBits(flt), buffer, 0); trans_.write(buffer, 0, 4); } /** Write a string to the wire with a varint size preceding. */ public void writeString(String str) throws TException { byte[] bytes = str.getBytes(StandardCharsets.UTF_8); writeBinary(bytes, 0, bytes.length); } /** Write a byte array, using a varint for the size. */ public void writeBinary(byte[] buf) throws TException { writeBinary(buf, 0, buf.length); } private void writeBinary(byte[] buf, int offset, int length) throws TException { writeVarint32(length); trans_.write(buf, offset, length); } // // These methods are called by structs, but don't actually have any wire // output or purpose. // public void writeMessageEnd() throws TException {} public void writeMapEnd() throws TException {} public void writeListEnd() throws TException {} public void writeSetEnd() throws TException {} public void writeFieldEnd() throws TException {} // // Internal writing methods // /** * Abstract method for writing the start of lists and sets. List and sets on the wire differ only * by the type indicator. */ protected void writeCollectionBegin(byte elemType, int size) throws TException { if (size <= 14) { writeByteDirect(size << 4 | getCompactType(elemType)); } else { writeByteDirect(0xf0 | getCompactType(elemType)); writeVarint32(size); } } /** Write an i32 as a varint. Results in 1-5 bytes on the wire. */ private void writeVarint32(int n) throws TException { int idx = 0; while (true) { if ((n & ~0x7F) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = (byte) ((n & 0x7F) | 0x80); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** Write an i64 as a varint. Results in 1-10 bytes on the wire. */ private void writeVarint64(long n) throws TException { int idx = 0; while (true) { if ((n & ~0x7FL) == 0) { buffer[idx++] = (byte) n; break; } else { buffer[idx++] = ((byte) ((n & 0x7F) | 0x80)); n >>>= 7; } } trans_.write(buffer, 0, idx); } /** * Convert l into a zigzag long. This allows negative numbers to be represented compactly as a * varint. */ private long longToZigzag(long l) { return (l << 1) ^ (l >> 63); } /** * Convert n into a zigzag int. This allows negative numbers to be represented compactly as a * varint. */ private int intToZigZag(int n) { return (n << 1) ^ (n >> 31); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedLongToBytes(long n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 56) & 0xff); buf[off + 1] = (byte) ((n >> 48) & 0xff); buf[off + 2] = (byte) ((n >> 40) & 0xff); buf[off + 3] = (byte) ((n >> 32) & 0xff); buf[off + 4] = (byte) ((n >> 24) & 0xff); buf[off + 5] = (byte) ((n >> 16) & 0xff); buf[off + 6] = (byte) ((n >> 8) & 0xff); buf[off + 7] = (byte) (n & 0xff); } /** Convert a long into little-endian bytes in buf starting at off and going until off+7. */ private void fixedIntToBytes(int n, byte[] buf, int off) { buf[off + 0] = (byte) ((n >> 24) & 0xff); buf[off + 1] = (byte) ((n >> 16) & 0xff); buf[off + 2] = (byte) ((n >> 8) & 0xff); buf[off + 3] = (byte) (n & 0xff); } /** * Writes a byte without any possiblity of all that field header nonsense. Used internally by * other writing methods that know they need to write a byte. */ private void writeByteDirect(byte b) throws TException { buffer[0] = b; trans_.write(buffer, 0, 1); } /** Writes a byte without any possiblity of all that field header nonsense. */ private void writeByteDirect(int n) throws TException { writeByteDirect((byte) n); } // // Reading methods. // /** Read a message header. */ public TMessage readMessageBegin() throws TException { byte protocolId = readByte(); if (protocolId != PROTOCOL_ID) { throw new TProtocolException( "Expected protocol id " + Integer.toHexString(PROTOCOL_ID) + " but got " + Integer.toHexString(protocolId)); } byte versionAndType = readByte(); version_ = (byte) (versionAndType & VERSION_MASK); if (!(version_ <= VERSION && version_ >= VERSION_LOW)) { throw new TProtocolException("Expected version " + VERSION + " but got " + version_); } byte type = (byte) ((versionAndType >> TYPE_SHIFT_AMOUNT) & 0x03); int seqid = readVarint32(); String messageName = readString(); return new TMessage(messageName, type, seqid); } /** * Read a struct begin. There's nothing on the wire for this, but it is our opportunity to push a * new struct begin marker onto the field stack. */ public TStruct readStructBegin( Map<Integer, com.facebook.thrift.meta_data.FieldMetaData> metaDataMap) throws TException { lastField_.push(lastFieldId_); lastFieldId_ = 0; return ANONYMOUS_STRUCT; } /** * Doesn't actually consume any wire data, just removes the last field for this struct from the * field stack. */ public void readStructEnd() throws TException { // consume the last field we read off the wire. lastFieldId_ = lastField_.pop(); } /** Read a field header off the wire. */ public TField readFieldBegin() throws TException { byte type = readByte(); // if it's a stop, then we can return immediately, as the struct is over. if (type == TType.STOP) { return TSTOP; } short fieldId; // mask off the 4 MSB of the type header. it could contain a field id delta. short modifier = (short) ((type & 0xf0) >> 4); if (modifier == 0) { // not a delta. look ahead for the zigzag varint field id. fieldId = readI16(); } else { // has a delta. add the delta to the last read field id. fieldId = (short) (lastFieldId_ + modifier); } TField field = new TField("", getTType((byte) (type & 0x0f)), fieldId); // if this happens to be a boolean field, the value is encoded in the type if (isBoolType(type)) { // save the boolean value in a special instance variable. boolValue_ = (byte) (type & 0x0f) == Types.BOOLEAN_TRUE ? Boolean.TRUE : Boolean.FALSE; } // push the new field onto the field stack so we can keep the deltas going. lastFieldId_ = field.id; return field; } /** * Read a map header off the wire. If the size is zero, skip reading the key and value type. This * means that 0-length maps will yield TMaps without the "correct" types. */ public TMap readMapBegin() throws TException { int size = readVarint32(); byte keyAndValueType = size == 0 ? 0 : readByte(); return new TMap( getTType((byte) (keyAndValueType >> 4)), getTType((byte) (keyAndValueType & 0xf)), size); } /** * Read a list header off the wire. If the list size is 0-14, the size will be packed into the * element type header. If it's a longer list, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TList readListBegin() throws TException { byte size_and_type = readByte(); int size = (size_and_type >> 4) & 0x0f; if (size == 15) { size = readVarint32(); } byte type = getTType(size_and_type); return new TList(type, size); } /** * Read a set header off the wire. If the set size is 0-14, the size will be packed into the * element type header. If it's a longer set, the 4 MSB of the element type header will be 0xF, * and a varint will follow with the true size. */ public TSet readSetBegin() throws TException { return new TSet(readListBegin()); } /** * Read a boolean off the wire. If this is a boolean field, the value should already have been * read during readFieldBegin, so we'll just consume the pre-stored value. Otherwise, read a byte. */ public boolean readBool() throws TException { if (boolValue_ != null) { boolean result = boolValue_.booleanValue(); boolValue_ = null; return result; } return readByte() == Types.BOOLEAN_TRUE; } /** Read a single byte off the wire. Nothing interesting here. */ public byte readByte() throws TException { byte b; if (trans_.getBytesRemainingInBuffer() > 0) { b = trans_.getBuffer()[trans_.getBufferPosition()]; trans_.consumeBuffer(1); } else { trans_.readAll(buffer, 0, 1); b = buffer[0]; } return b; } /** Read an i16 from the wire as a zigzag varint. */ public short readI16() throws TException { return (short) zigzagToInt(readVarint32()); } /** Read an i32 from the wire as a zigzag varint. */ public int readI32() throws TException { return zigzagToInt(readVarint32()); } /** Read an i64 from the wire as a zigzag varint. */ public long readI64() throws TException { return zigzagToLong(readVarint64()); } /** No magic here - just read a double off the wire. */ public double readDouble() throws TException { trans_.readAll(buffer, 0, 8); long value; if (version_ >= VERSION_DOUBLE_BE) { value = bytesToLong(buffer); } else { value = bytesToLongLE(buffer); } return Double.longBitsToDouble(value); } /** No magic here - just read a float off the wire. */ public float readFloat() throws TException { trans_.readAll(buffer, 0, 4); int value = bytesToInt(buffer); return Float.intBitsToFloat(value); } /** Reads a byte[] (via readBinary), and then UTF-8 decodes it. */ public String readString() throws TException { int length = readVarint32(); checkReadLength(length); if (length == 0) { return ""; } if (trans_.getBytesRemainingInBuffer() >= length) { String str = new String( trans_.getBuffer(), trans_.getBufferPosition(), length, StandardCharsets.UTF_8); trans_.consumeBuffer(length); return str; } else { return new String(readBinary(length), StandardCharsets.UTF_8); } } /** Read a byte[] from the wire. */ public byte[] readBinary() throws TException { int length = readVarint32(); checkReadLength(length); return readBinary(length); } private byte[] readBinary(int length) throws TException { if (length == 0) { return new byte[0]; } byte[] buf = new byte[length]; trans_.readAll(buf, 0, length); return buf; } private void checkReadLength(int length) throws TProtocolException { if (length < 0) { throw new TProtocolException("Negative length: " + length); } if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) { throw new TProtocolException("Length exceeded max allowed: " + length); } } // // These methods are here for the struct to call, but don't have any wire // encoding. // public void readMessageEnd() throws TException {} public void readFieldEnd() throws TException {} public void readMapEnd() throws TException {} public void readListEnd() throws TException {} public void readSetEnd() throws TException {} // // Internal reading methods // /** * Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to * follow. This can read up to 5 bytes. */ private int readVarint32() throws TException { int result = 0; int shift = 0; if (trans_.getBytesRemainingInBuffer() >= 5) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (int) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } /** * Read an i64 from the wire as a proper varint. The MSB of each byte is set if there is another * byte to follow. This can read up to 10 bytes. */ private long readVarint64() throws TException { int shift = 0; long result = 0; if (trans_.getBytesRemainingInBuffer() >= 10) { byte[] buf = trans_.getBuffer(); int pos = trans_.getBufferPosition(); int off = 0; while (true) { byte b = buf[pos + off]; result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; off++; } trans_.consumeBuffer(off + 1); } else { while (true) { byte b = readByte(); result |= (long) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } } return result; } // // encoding helpers // /** Convert from zigzag int to int. */ private int zigzagToInt(int n) { return (n >>> 1) ^ -(n & 1); } /** Convert from zigzag long to long. */ private long zigzagToLong(long n) { return (n >>> 1) ^ -(n & 1); } /** * Note that it's important that the mask bytes are long literals, otherwise they'll default to * ints, and when you shift an int left 56 bits, you just get a messed up int. */ private long bytesToLong(byte[] bytes) { return ((bytes[0] & 0xffL) << 56) | ((bytes[1] & 0xffL) << 48) | ((bytes[2] & 0xffL) << 40) | ((bytes[3] & 0xffL) << 32) | ((bytes[4] & 0xffL) << 24) | ((bytes[5] & 0xffL) << 16) | ((bytes[6] & 0xffL) << 8) | ((bytes[7] & 0xffL)); } /* Little endian version of the above */ private long bytesToLongLE(byte[] bytes) { return ((bytes[7] & 0xffL) << 56) | ((bytes[6] & 0xffL) << 48) | ((bytes[5] & 0xffL) << 40) | ((bytes[4] & 0xffL) << 32) | ((bytes[3] & 0xffL) << 24) | ((bytes[2] & 0xffL) << 16) | ((bytes[1] & 0xffL) << 8) | ((bytes[0] & 0xffL)); } private int bytesToInt(byte[] bytes) { return ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | ((bytes[3] & 0xff)); } // // type testing and converting // private boolean isBoolType(byte b) { int lowerNibble = b & 0x0f; return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE; } /** Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. */ private byte getTType(byte type) throws TProtocolException { switch ((byte) (type & 0x0f)) { case TType.STOP: return TType.STOP; case Types.BOOLEAN_FALSE: case Types.BOOLEAN_TRUE: return TType.BOOL; case Types.BYTE: return TType.BYTE; case Types.I16: return TType.I16; case Types.I32: return TType.I32; case Types.I64: return TType.I64; case Types.DOUBLE: return TType.DOUBLE; case Types.FLOAT: return TType.FLOAT; case Types.BINARY: return TType.STRING; case Types.LIST: return TType.LIST; case Types.SET: return TType.SET; case Types.MAP: return TType.MAP; case Types.STRUCT: return TType.STRUCT; default: throw new TProtocolException("don't know what type: " + (byte) (type & 0x0f)); } } /** Given a TType value, find the appropriate TCompactProtocol.Types constant. */ private byte getCompactType(byte ttype) { return ttypeToCompactType[ttype]; } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_854_1
crossvul-java_data_good_854_5
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import com.facebook.thrift.java.test.BigEnum; import com.facebook.thrift.java.test.MySimpleStruct; import com.facebook.thrift.java.test.SmallEnum; import junit.framework.TestCase; import org.junit.Test; public class StructTest extends TestCase { @Test public void testStructHashcode() throws Exception { MySimpleStruct defaultStruct = new MySimpleStruct(); assertThat(defaultStruct.hashCode(), is(not(equalTo(0)))); MySimpleStruct struct1 = new MySimpleStruct(1, "Foo"); MySimpleStruct struct2 = new MySimpleStruct(2, "Bar"); assertThat(struct1.hashCode(), is(not(equalTo(0)))); assertThat(struct2.hashCode(), is(not(equalTo(0)))); assertThat(struct1.hashCode(), is(not(equalTo(struct2.hashCode())))); } @Test public void testSmallEnum() throws Exception { assertThat(SmallEnum.findByValue(SmallEnum.RED.getValue()), equalTo(SmallEnum.RED)); assertThat(SmallEnum.findByValue(Integer.MAX_VALUE), equalTo(null)); } @Test public void testBigEnum() throws Exception { assertThat(BigEnum.findByValue(BigEnum.ONE.getValue()), equalTo(BigEnum.ONE)); assertThat(BigEnum.findByValue(Integer.MAX_VALUE), equalTo(null)); } }
./CrossVul/dataset_final_sorted/CWE-770/java/good_854_5
crossvul-java_data_bad_854_5
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.thrift; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import com.facebook.thrift.test.BigEnum; import com.facebook.thrift.test.MySimpleStruct; import com.facebook.thrift.test.SmallEnum; import junit.framework.TestCase; import org.junit.Test; public class StructTest extends TestCase { @Test public void testStructHashcode() throws Exception { MySimpleStruct defaultStruct = new MySimpleStruct(); assertThat(defaultStruct.hashCode(), is(not(equalTo(0)))); MySimpleStruct struct1 = new MySimpleStruct(1, "Foo"); MySimpleStruct struct2 = new MySimpleStruct(2, "Bar"); assertThat(struct1.hashCode(), is(not(equalTo(0)))); assertThat(struct2.hashCode(), is(not(equalTo(0)))); assertThat(struct1.hashCode(), is(not(equalTo(struct2.hashCode())))); } @Test public void testSmallEnum() throws Exception { assertThat(SmallEnum.findByValue(SmallEnum.RED.getValue()), equalTo(SmallEnum.RED)); assertThat(SmallEnum.findByValue(Integer.MAX_VALUE), equalTo(null)); } @Test public void testBigEnum() throws Exception { assertThat(BigEnum.findByValue(BigEnum.ONE.getValue()), equalTo(BigEnum.ONE)); assertThat(BigEnum.findByValue(Integer.MAX_VALUE), equalTo(null)); } }
./CrossVul/dataset_final_sorted/CWE-770/java/bad_854_5
crossvul-java_data_good_1910_20
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.tellstick.internal.live; import java.math.BigDecimal; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.DefaultAsyncHttpClient; import org.asynchttpclient.DefaultAsyncHttpClientConfig; import org.asynchttpclient.DefaultAsyncHttpClientConfig.Builder; import org.asynchttpclient.Response; import org.asynchttpclient.oauth.ConsumerKey; import org.asynchttpclient.oauth.OAuthSignatureCalculator; import org.asynchttpclient.oauth.RequestToken; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.State; import org.openhab.binding.tellstick.internal.TelldusBindingException; import org.openhab.binding.tellstick.internal.handler.TelldusDeviceController; import org.openhab.binding.tellstick.internal.live.xml.TelldusLiveResponse; import org.openhab.binding.tellstick.internal.live.xml.TellstickNetDevice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tellstick.JNA; import org.tellstick.device.TellstickDevice; import org.tellstick.device.TellstickDeviceEvent; import org.tellstick.device.TellstickException; import org.tellstick.device.TellstickSensorEvent; import org.tellstick.device.iface.Device; import org.tellstick.device.iface.DeviceChangeListener; import org.tellstick.device.iface.SensorListener; import org.tellstick.device.iface.SwitchableDevice; /** * {@link TelldusLiveDeviceController} is the communication with Telldus Live service (Tellstick.NET and ZNET) * This controller uses XML based Rest API to communicate with Telldus Live. * * @author Jarle Hjortland - Initial contribution */ public class TelldusLiveDeviceController implements DeviceChangeListener, SensorListener, TelldusDeviceController { private final Logger logger = LoggerFactory.getLogger(TelldusLiveDeviceController.class); private long lastSend = 0; public static final long DEFAULT_INTERVAL_BETWEEN_SEND = 250; static final int REQUEST_TIMEOUT_MS = 5000; private AsyncHttpClient client; static final String HTTP_API_TELLDUS_COM_XML = "http://api.telldus.com/xml/"; static final String HTTP_TELLDUS_CLIENTS = HTTP_API_TELLDUS_COM_XML + "clients/list"; static final String HTTP_TELLDUS_DEVICES = HTTP_API_TELLDUS_COM_XML + "devices/list?supportedMethods=19"; static final String HTTP_TELLDUS_SENSORS = HTTP_API_TELLDUS_COM_XML + "sensors/list?includeValues=1&includeScale=1&includeUnit=1"; static final String HTTP_TELLDUS_SENSOR_INFO = HTTP_API_TELLDUS_COM_XML + "sensor/info"; static final String HTTP_TELLDUS_DEVICE_DIM = HTTP_API_TELLDUS_COM_XML + "device/dim?id=%d&level=%d"; static final String HTTP_TELLDUS_DEVICE_TURNOFF = HTTP_API_TELLDUS_COM_XML + "device/turnOff?id=%d"; static final String HTTP_TELLDUS_DEVICE_TURNON = HTTP_API_TELLDUS_COM_XML + "device/turnOn?id=%d"; private static final int MAX_RETRIES = 3; public TelldusLiveDeviceController() { } @Override public void dispose() { try { client.close(); } catch (Exception e) { logger.error("Failed to close client", e); } } void connectHttpClient(String publicKey, String privateKey, String token, String tokenSecret) { ConsumerKey consumer = new ConsumerKey(publicKey, privateKey); RequestToken user = new RequestToken(token, tokenSecret); OAuthSignatureCalculator calc = new OAuthSignatureCalculator(consumer, user); this.client = new DefaultAsyncHttpClient(createAsyncHttpClientConfig()); try { this.client.setSignatureCalculator(calc); Response response = client.prepareGet(HTTP_TELLDUS_CLIENTS).execute().get(); logger.debug("Response {} statusText {}", response.getResponseBody(), response.getStatusText()); } catch (InterruptedException | ExecutionException e) { logger.error("Failed to connect", e); } } private AsyncHttpClientConfig createAsyncHttpClientConfig() { Builder builder = new DefaultAsyncHttpClientConfig.Builder(); builder.setConnectTimeout(REQUEST_TIMEOUT_MS); return builder.build(); } @Override public void handleSendEvent(Device device, int resendCount, boolean isdimmer, Command command) throws TellstickException { logger.info("Send {} to {}", command, device); if (device instanceof TellstickNetDevice) { if (command == OnOffType.ON) { turnOn(device); } else if (command == OnOffType.OFF) { turnOff(device); } else if (command instanceof PercentType) { dim(device, (PercentType) command); } else if (command instanceof IncreaseDecreaseType) { increaseDecrease(device, ((IncreaseDecreaseType) command)); } } else if (device instanceof SwitchableDevice) { if (command == OnOffType.ON) { if (isdimmer) { logger.debug("Turn off first in case it is allready on"); turnOff(device); } turnOn(device); } else if (command == OnOffType.OFF) { turnOff(device); } } else { logger.warn("Cannot send to {}", device); } } private void increaseDecrease(Device dev, IncreaseDecreaseType increaseDecreaseType) throws TellstickException { String strValue = ((TellstickDevice) dev).getData(); double value = 0; if (strValue != null) { value = Double.valueOf(strValue); } int percent = (int) Math.round((value / 255) * 100); if (IncreaseDecreaseType.INCREASE == increaseDecreaseType) { percent = Math.min(percent + 10, 100); } else if (IncreaseDecreaseType.DECREASE == increaseDecreaseType) { percent = Math.max(percent - 10, 0); } dim(dev, new PercentType(percent)); } private void dim(Device dev, PercentType command) throws TellstickException { double value = command.doubleValue(); // 0 means OFF and 100 means ON if (value == 0 && dev instanceof TellstickNetDevice) { turnOff(dev); } else if (value == 100 && dev instanceof TellstickNetDevice) { turnOn(dev); } else if (dev instanceof TellstickNetDevice && (((TellstickNetDevice) dev).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) { long tdVal = Math.round((value / 100) * 255); TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_DIM, dev.getId(), tdVal), TelldusLiveResponse.class); handleResponse((TellstickNetDevice) dev, response); } else { throw new TelldusBindingException("Cannot send DIM to " + dev); } } private void turnOff(Device dev) throws TellstickException { if (dev instanceof TellstickNetDevice) { TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNOFF, dev.getId()), TelldusLiveResponse.class); handleResponse((TellstickNetDevice) dev, response); } else { throw new TelldusBindingException("Cannot send OFF to " + dev); } } private void handleResponse(TellstickNetDevice device, TelldusLiveResponse response) throws TellstickException { if (response == null || (response.status == null && response.error == null)) { throw new TelldusBindingException("No response " + response); } else if (response.error != null) { if (response.error.equals("The client for this device is currently offline")) { device.setOnline(false); device.setUpdated(true); } throw new TelldusBindingException("Error " + response.error); } else if (!response.status.trim().equals("success")) { throw new TelldusBindingException("Response " + response.status); } } private void turnOn(Device dev) throws TellstickException { if (dev instanceof TellstickNetDevice) { TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNON, dev.getId()), TelldusLiveResponse.class); handleResponse((TellstickNetDevice) dev, response); } else { throw new TelldusBindingException("Cannot send ON to " + dev); } } @Override public State calcState(Device dev) { TellstickNetDevice device = (TellstickNetDevice) dev; State st = null; if (device.getOnline()) { switch (device.getState()) { case JNA.CLibrary.TELLSTICK_TURNON: st = OnOffType.ON; break; case JNA.CLibrary.TELLSTICK_TURNOFF: st = OnOffType.OFF; break; case JNA.CLibrary.TELLSTICK_DIM: BigDecimal dimValue = new BigDecimal(device.getStatevalue()); if (dimValue.intValue() == 0) { st = OnOffType.OFF; } else if (dimValue.intValue() >= 255) { st = OnOffType.ON; } else { st = OnOffType.ON; } break; default: logger.warn("Could not handle {} for {}", device.getState(), device); } } return st; } @Override public BigDecimal calcDimValue(Device device) { BigDecimal dimValue = new BigDecimal(0); switch (((TellstickNetDevice) device).getState()) { case JNA.CLibrary.TELLSTICK_TURNON: dimValue = new BigDecimal(100); break; case JNA.CLibrary.TELLSTICK_TURNOFF: break; case JNA.CLibrary.TELLSTICK_DIM: dimValue = new BigDecimal(((TellstickNetDevice) device).getStatevalue()); dimValue = dimValue.multiply(new BigDecimal(100)); dimValue = dimValue.divide(new BigDecimal(255), 0, BigDecimal.ROUND_HALF_UP); break; default: logger.warn("Could not handle {} for {}", (((TellstickNetDevice) device).getState()), device); } return dimValue; } public long getLastSend() { return lastSend; } public void setLastSend(long currentTimeMillis) { lastSend = currentTimeMillis; } @Override public void onRequest(TellstickSensorEvent newDevices) { setLastSend(newDevices.getTimestamp()); } @Override public void onRequest(TellstickDeviceEvent newDevices) { setLastSend(newDevices.getTimestamp()); } <T> T callRestMethod(String uri, Class<T> response) throws TelldusLiveException { T resultObj = null; try { for (int i = 0; i < MAX_RETRIES; i++) { try { resultObj = innerCallRest(uri, response); break; } catch (TimeoutException e) { logger.warn("TimeoutException error in get", e); } catch (InterruptedException e) { logger.warn("InterruptedException error in get", e); } } } catch (JAXBException e) { logger.warn("Encoding error in get", e); logResponse(uri, e); throw new TelldusLiveException(e); } catch (XMLStreamException e) { logger.warn("Communication error in get", e); logResponse(uri, e); throw new TelldusLiveException(e); } catch (ExecutionException e) { logger.warn("ExecutionException error in get", e); throw new TelldusLiveException(e); } return resultObj; } private <T> T innerCallRest(String uri, Class<T> response) throws InterruptedException, ExecutionException, TimeoutException, JAXBException, FactoryConfigurationError, XMLStreamException { Future<Response> future = client.prepareGet(uri).execute(); Response resp = future.get(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS); // TelldusLiveHandler.logger.info("Devices" + resp.getResponseBody()); JAXBContext jc = JAXBContext.newInstance(response); XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xsr = xif.createXMLStreamReader(resp.getResponseBodyAsStream()); // xsr = new PropertyRenamerDelegate(xsr); @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xsr); if (logger.isTraceEnabled()) { logger.trace("Request [{}] Response:{}", uri, resp.getResponseBody()); } return obj; } private void logResponse(String uri, Exception e) { if (e != null) { logger.warn("Request [{}] Failure:{}", uri, e.getMessage()); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_20
crossvul-java_data_good_1969_1
// Copyright (C) 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.json; import static com.google.json.JsonSanitizer.DEFAULT_NESTING_DEPTH; import static com.google.json.JsonSanitizer.sanitize; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import junit.framework.TestCase; import org.junit.Test; @SuppressWarnings("javadoc") public final class JsonSanitizerTest extends TestCase { private static void assertSanitized(String golden, String input) { assertSanitized(golden, input, DEFAULT_NESTING_DEPTH); } private static void assertSanitized(String golden, String input, int maximumNestingDepth) { String actual = sanitize(input, maximumNestingDepth); assertEquals(input, golden, actual); if (actual.equals(input)) { assertSame(input, input, actual); } } private static void assertSanitized(String sanitary) { assertSanitized(sanitary, sanitary); } @Test public static final void testSanitize() { // On the left is the sanitized output, and on the right the input. // If there is a single string, then the input is fine as-is. assertSanitized("null", null); assertSanitized("null", ""); assertSanitized("null"); assertSanitized("false"); assertSanitized("true"); assertSanitized(" false "); assertSanitized(" false"); assertSanitized("false\n"); assertSanitized("false", "false,true"); assertSanitized("\"foo\""); assertSanitized("\"foo\"", "'foo'"); assertSanitized( "\"\\u003cscript>foo()\\u003c/script>\"", "\"<script>foo()</script>\""); assertSanitized("\"\\u003c/SCRIPT\\n>\"", "\"</SCRIPT\n>\""); assertSanitized("\"\\u003c/ScRIpT\"", "\"</ScRIpT\""); // \u0130 is a Turkish dotted upper-case 'I' so the lower case version of // the tag name is "script". assertSanitized("\"\\u003c/ScR\u0130pT\"", "\"</ScR\u0130pT\""); assertSanitized("\"<b>Hello</b>\""); assertSanitized("\"<s>Hello</s>\""); assertSanitized("\"<[[\\u005d]>\"", "'<[[]]>'"); assertSanitized("\"\\u005d]>\"", "']]>'"); assertSanitized("[[0]]", "[[0]]>"); assertSanitized("[1,-1,0.0,-0.5,1e2]", "[1,-1,0.0,-0.5,1e2,"); assertSanitized("[1,2,3]", "[1,2,3,]"); assertSanitized("[1,null,3]", "[1,,3,]"); assertSanitized("[1 ,2 ,3]", "[1 2 3]"); assertSanitized("{ \"foo\": \"bar\" }"); assertSanitized("{ \"foo\": \"bar\" }", "{ \"foo\": \"bar\", }"); assertSanitized("{\"foo\":\"bar\"}", "{\"foo\",\"bar\"}"); assertSanitized("{ \"foo\": \"bar\" }", "{ foo: \"bar\" }"); assertSanitized("{ \"foo\": \"bar\"}", "{ foo: 'bar"); assertSanitized("{ \"foo\": [\"bar\"]}", "{ foo: ['bar"); assertSanitized("false", "// comment\nfalse"); assertSanitized("false", "false// comment"); assertSanitized("false", "false// comment\n"); assertSanitized("false", "false/* comment */"); assertSanitized("false", "false/* comment *"); assertSanitized("false", "false/* comment "); assertSanitized("false", "/*/true**/false"); assertSanitized("1"); assertSanitized("-1"); assertSanitized("1.0"); assertSanitized("-1.0"); assertSanitized("1.05"); assertSanitized("427.0953333"); assertSanitized("6.0221412927e+23"); assertSanitized("6.0221412927e23"); assertSanitized("6.0221412927e0", "6.0221412927e"); assertSanitized("6.0221412927e-0", "6.0221412927e-"); assertSanitized("6.0221412927e+0", "6.0221412927e+"); assertSanitized("1.660538920287695E-24"); assertSanitized("-6.02e-23"); assertSanitized("1.0", "1."); assertSanitized("0.5", ".5"); assertSanitized("-0.5", "-.5"); assertSanitized("0.5", "+.5"); assertSanitized("0.5e2", "+.5e2"); assertSanitized("1.5e+2", "+1.5e+2"); assertSanitized("0.5e-2", "+.5e-2"); assertSanitized("{\"0\":0}", "{0:0}"); assertSanitized("{\"0\":0}", "{-0:0}"); assertSanitized("{\"0\":0}", "{+0:0}"); assertSanitized("{\"1\":0}", "{1.0:0}"); assertSanitized("{\"1\":0}", "{1.:0}"); assertSanitized("{\"0.5\":0}", "{.5:0}"); assertSanitized("{\"-0.5\":0}", "{-.5:0}"); assertSanitized("{\"0.5\":0}", "{+.5:0}"); assertSanitized("{\"50\":0}", "{+.5e2:0}"); assertSanitized("{\"150\":0}", "{+1.5e+2:0}"); assertSanitized("{\"0.1\":0}", "{+.1:0}"); assertSanitized("{\"0.01\":0}", "{+.01:0}"); assertSanitized("{\"0.005\":0}", "{+.5e-2:0}"); assertSanitized("{\"1e+101\":0}", "{10e100:0}"); assertSanitized("{\"1e-99\":0}", "{10e-100:0}"); assertSanitized("{\"1.05e-99\":0}", "{10.5e-100:0}"); assertSanitized("{\"1.05e-99\":0}", "{10.500e-100:0}"); assertSanitized("{\"1.234e+101\":0}", "{12.34e100:0}"); assertSanitized("{\"1.234e-102\":0}", "{.01234e-100:0}"); assertSanitized("{\"1.234e-102\":0}", "{.01234e-100:0}"); assertSanitized("{}"); // Remove grouping parentheses. assertSanitized("{}", "({})"); // Escape code-points and isolated surrogates which are not XML embeddable. assertSanitized("\"\\u0000\\u0008\\u001f\"", "'\u0000\u0008\u001f'"); assertSanitized("\"\ud800\udc00\\udc00\\ud800\"", "'\ud800\udc00\udc00\ud800'"); assertSanitized("\"\ufffd\\ufffe\\uffff\"", "'\ufffd\ufffe\uffff'"); // These control characters should be elided if they appear outside a string // literal. assertSanitized("42", "\uffef\u000042\u0008\ud800\uffff\udc00"); assertSanitized("null", "\uffef\u0000\u0008\ud800\uffff\udc00"); assertSanitized("[null]", "[,]"); assertSanitized("[null]", "[null,]"); assertSanitized("{\"a\":0,\"false\":\"x\",\"\":{\"\":-1}}", "{\"a\":0,false\"x\":{\"\":-1}}"); assertSanitized("[true ,false]", "[true false]"); assertSanitized("[\"\\u00a0\\u1234\"]"); assertSanitized("{\"a\\b\":\"c\"}", "{a\\b\"c"); assertSanitized("{\"a\":\"b\",\"c\":null}", "{\"a\":\"b\",\"c\":"); assertSanitized( "{\"1e0001234567890123456789123456789123456789\":0}", // Exponent way out of representable range in a JS double. "{1e0001234567890123456789123456789123456789:0}" ); // Our octal recoder interprets an octal-like literal that includes a digit '8' or '9' as // decimal. assertSanitized("-16923547559", "-016923547559"); } @Test public static final void testIssue3() { // These triggered index out of bounds and assertion errors. assertSanitized("[{\"\":{}}]", "[{{},\u00E4"); assertSanitized("[{\"\":{}}]", "[{{\u00E4\u00E4},\u00E4"); } @Test public static final void testIssue4() { // Make sure that bare words are quoted. assertSanitized("\"dev\"", "dev"); assertSanitized("\"eval\"", "eval"); assertSanitized("\"comment\"", "comment"); assertSanitized("\"fasle\"", "fasle"); assertSanitized("\"FALSE\"", "FALSE"); assertSanitized("\"dev/comment\"", "dev/comment"); assertSanitized("\"devcomment\"", "dev\\comment"); assertSanitized("\"dev\\ncomment\"", "dev\\ncomment"); assertSanitized("[\"dev\", \"comment\"]", "[dev\\, comment]"); } @Test public static final void testMaximumNestingLevel() { String nestedMaps = "{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"; String sanitizedNestedMaps = "{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"; boolean exceptionIfTooMuchNesting = false; try { assertSanitized(sanitizedNestedMaps, nestedMaps, DEFAULT_NESTING_DEPTH); } catch (ArrayIndexOutOfBoundsException e) { Logger.getAnonymousLogger().log(Level.FINEST, "Expected exception in testing maximum nesting level", e); exceptionIfTooMuchNesting = true; } assertTrue("Expecting failure for too nested JSON", exceptionIfTooMuchNesting); assertSanitized(sanitizedNestedMaps, nestedMaps, DEFAULT_NESTING_DEPTH + 1); } @Test public static final void testMaximumNestingLevelAssignment() { assertEquals(1, new JsonSanitizer("", Integer.MIN_VALUE).getMaximumNestingDepth()); assertEquals(JsonSanitizer.MAXIMUM_NESTING_DEPTH, new JsonSanitizer("", Integer.MAX_VALUE).getMaximumNestingDepth()); } @Test public static final void testUnopenedArray() { // Discovered by fuzzer with seed -Dfuzz.seed=df3b4778ce54d00a assertSanitized("-1742461140214282", "\ufeff-01742461140214282]"); } @Test public static final void testIssue13() { assertSanitized( "[ { \"description\": \"aa##############aa\" }, 1 ]", "[ { \"description\": \"aa##############aa\" }, 1 ]"); } @Test public static final void testHtmlParserStateChanges() { assertSanitized("\"\\u003cscript\"", "\"<script\""); assertSanitized("\"\\u003cScript\"", "\"<Script\""); // \u0130 is a Turkish dotted upper-case 'I' so the lower case version of // the tag name is "script". assertSanitized("\"\\u003cScR\u0130pT\"", "\"<ScR\u0130pT\""); assertSanitized("\"\\u003cSCRIPT\\n>\"", "\"<SCRIPT\n>\""); assertSanitized("\"script\"", "<script"); assertSanitized("\"\\u003c!--\"", "\"<!--\""); assertSanitized("-0", "<!--"); assertSanitized("\"--\\u003e\"", "\"-->\""); assertSanitized("-0", "-->"); assertSanitized("\"\\u003c!--\\u003cscript>\"", "\"<!--<script>\""); } @Test public static final void testLongOctalNumberWithBadDigits() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) assertEquals( "-888888888888888888888", JsonSanitizer.sanitize("-0888888888888888888888") ); } @Test public static final void testLongNumberInUnclosedInputWithU80() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) assertEquals( "{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"x80\":{\"\":{\"\":[-400557869725698078427]}}}}}}}}}", JsonSanitizer.sanitize("{{{{{{{\\x80{{([-053333333304233333333333") ); } @Test public static final void testSlashFour() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) assertEquals("\"y\\u0004\"", JsonSanitizer.sanitize("y\\4")); // "y\4" } @Test public static final void testUnterminatedObject() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) String input = "?\u0000\u0000\u0000{{\u0000\ufffd\u0003]ve{R]\u00000\ufffd\u0016&e{\u0003]\ufffda<!.b<!<!cc1x\u0000\u00005{281<\u0000.{t\u0001\ufffd5\ufffd{5\ufffd\ufffd0\ufffd15\r\ufffd\u0000\u0000\u0000~~-0081273222428822883223759,55\ufffd\u0000\ufffd\t\u0000\ufffd"; String got = JsonSanitizer.sanitize(input); String want = "{\"\":{},\"ve\":{\"R\":null},\"0\":\"e\",\"\":{},\"a<!.b<!<!cc1x\":5,\"\":{\"281\":0.0,\"\":{\"t\":5,\"\":{\"5\":0,\"15\"\r:-81273222428822883223759,\"55\"\t:null}}}}"; assertEquals(want, got); } @Test public static final void testCrash1() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) String input = "?\u0000\u0000\u0000{{\u0000\ufffd\u0003]ve{R]\u00000\ufffd\ufffd\u0016&e{\u0003]\ufffda<!.b<!<!c\u00005{281<\u0000.{t\u0001\ufffd5\ufffd{515\r[\u0000\u0000\u0000~~-008127322242\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd23759,551x\u0000\u00006{281<\u0000.{t\u0001\ufffd5\ufffd{5\ufffd\ufffd0\ufffd15\r[\u0000\u0000\u0000~~-0081273222428822883223759,\ufffd"; String want = "{\"\":{},\"ve\":{\"R\":null},\"0\":\"e\",\"\":{},\"a<!.b<!<!c\":5,\"\":{\"281\":0.0,\"\":{\"t\":5,\"\":{\"515\"\r:[-8127322242,23759,551,6,{\"281\":0.0,\"\":{\"t\":5,\"\":{\"5\":0,\"15\"\r:[-81273222428822883223759]}}}]}}}}"; String got = JsonSanitizer.sanitize(input); assertEquals(want, got); } @Test public static final void testDisallowedSubstrings() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) String[] inputs = { "x<\\script>", "x</\\script>", "x</sc\\ript>", "x<\\163cript>", "x</\\163cript>", "x<\\123cript>", "x</\\123cript>", "u\\u\\uu\ufffd\ufffd\\u7u\\u\\u\\u\ufffdu<\\script>5", "z\\<\\!--", "z\\<!\\--", "z\\<!-\\-", "z\\<\\!--", "\"\\]]\\>", }; for (String input : inputs) { String out = JsonSanitizer.sanitize(input).toLowerCase(Locale.ROOT); assertFalse(out, out.contains("<!--")); assertFalse(out, out.contains("-->")); assertFalse(out, out.contains("<script")); assertFalse(out, out.contains("</script")); assertFalse(out, out.contains("]]>")); assertFalse(out, out.contains("<![cdata[")); } } @Test public static final void testXssPayload() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) String input = "x</\\script>u\\u\\uu\ufffd\ufffd\\u7u\\u\\u\\u\ufffdu<\\script>5+alert(1)//"; assertEquals( "\"x\\u003c/script>uuuu\uFFFD\uFFFDu7uuuu\uFFFDu\\u003cscript>5+alert(1)//\"", JsonSanitizer.sanitize(input) ); } @Test public static final void testInvalidOutput() { // Found by Fabian Meumertzheim using CI Fuzz (https://www.code-intelligence.com) String input = "\u0010{'\u0000\u0000'\"\u0000\"{.\ufffd-0X29295909049550970,\n\n0"; String want = "{\"\\u0000\\u0000\":\"\\u0000\",\"\":{\"0\":-47455995597866469744,\n\n\"0\":null}}"; String got = JsonSanitizer.sanitize(input); assertEquals(want, got); } @Test public static final void testBadNumber() { String input = "¶0x.\\蹃4\\À906"; String want = "0.0"; String got = JsonSanitizer.sanitize(input); assertEquals(want, got); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1969_1
crossvul-java_data_bad_3279_1
/* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.designer.web.server; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.*; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import bpsim.impl.BpsimFactoryImpl; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.html.simpleparser.HTMLWorker; import com.lowagie.text.pdf.PdfWriter; import org.apache.batik.transcoder.SVGAbstractTranscoder; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.ImageTranscoder; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.commons.codec.binary.Base64; import org.eclipse.bpmn2.DataInputAssociation; import org.eclipse.bpmn2.Definitions; import org.eclipse.bpmn2.FlowElement; import org.eclipse.bpmn2.FlowElementsContainer; import org.eclipse.bpmn2.FlowNode; import org.eclipse.bpmn2.FormalExpression; import org.eclipse.bpmn2.Process; import org.eclipse.bpmn2.RootElement; import org.eclipse.bpmn2.SequenceFlow; import org.eclipse.bpmn2.Task; import org.eclipse.bpmn2.UserTask; import org.eclipse.bpmn2.di.BPMNDiagram; import org.eclipse.bpmn2.di.BPMNEdge; import org.eclipse.bpmn2.di.BPMNPlane; import org.eclipse.bpmn2.di.BPMNShape; import org.eclipse.bpmn2.di.BpmnDiFactory; import org.eclipse.dd.dc.Bounds; import org.eclipse.dd.dc.DcFactory; import org.eclipse.dd.dc.Point; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.util.FeatureMap; import org.jboss.drools.impl.DroolsFactoryImpl; import org.jbpm.designer.bpmn2.resource.JBPMBpmn2ResourceFactoryImpl; import org.jbpm.designer.bpmn2.resource.JBPMBpmn2ResourceImpl; import org.jbpm.designer.repository.Asset; import org.jbpm.designer.repository.AssetBuilderFactory; import org.jbpm.designer.repository.Repository; import org.jbpm.designer.repository.impl.AssetBuilder; import org.jbpm.designer.util.Utils; import org.jbpm.designer.web.profile.IDiagramProfile; import org.jbpm.designer.web.profile.IDiagramProfileService; import org.jbpm.designer.web.profile.impl.JbpmProfileImpl; import org.jbpm.migration.JbpmMigration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Transformer for svg process representation to * various formats. * * @author Tihomir Surdilovic */ public class TransformerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger _logger = LoggerFactory.getLogger(TransformerServlet.class); private static final String TO_PDF = "pdf"; private static final String TO_PNG = "png"; private static final String TO_SVG = "svg"; private static final String JPDL_TO_BPMN2 = "jpdl2bpmn2"; private static final String BPMN2_TO_JSON = "bpmn2json"; private static final String JSON_TO_BPMN2 = "json2bpmn2"; private static final String HTML_TO_PDF = "html2pdf"; private static final String RESPACTION_SHOWURL = "showurl"; private static final String SVG_WIDTH_PARAM = "svgwidth"; private static final String SVG_HEIGHT_PARAM = "svgheight"; private static final float DEFAULT_PDF_WIDTH = (float) 750.0; private static final float DEFAULT_PDF_HEIGHT = (float) 500.0; static { StringTokenizer html2pdfTagsSupported = new StringTokenizer("ol ul li a pre font span br p div body table td th tr i b u sub sup em strong s strike h1 h2 h3 h4 h5 h6"); HTMLWorker.tagsSupported.clear(); while(html2pdfTagsSupported.hasMoreTokens()) { HTMLWorker.tagsSupported.put(html2pdfTagsSupported.nextToken(), null); } } private IDiagramProfile profile; // For unit testing purpose only public void setProfile(IDiagramProfile profile) { this.profile = profile; } @Inject private IDiagramProfileService _profileService = null; @Override public void init(ServletConfig config) throws ServletException { super.init(config); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String formattedSvgEncoded = req.getParameter("fsvg"); String uuid = Utils.getUUID(req); String profileName = Utils.getDefaultProfileName(req.getParameter("profile")); String transformto = req.getParameter("transformto"); String jpdl = req.getParameter("jpdl"); String gpd = req.getParameter("gpd"); String bpmn2in = req.getParameter("bpmn2"); String jsonin = req.getParameter("json"); String preprocessingData = req.getParameter("pp"); String respaction = req.getParameter("respaction"); String pp = req.getParameter("pp"); String processid = req.getParameter("processid"); String sourceEnc = req.getParameter("enc"); String convertServiceTasks = req.getParameter("convertservicetasks"); String htmlSourceEnc = req.getParameter("htmlenc"); String formattedSvg = ( formattedSvgEncoded == null ? "" : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8") ); String htmlSource = ( htmlSourceEnc == null ? "" : new String(Base64.decodeBase64(htmlSourceEnc), "UTF-8") ); if(sourceEnc != null && sourceEnc.equals("true")) { bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8"); } if (profile == null) { profile = _profileService.findProfile(req, profileName); } DroolsFactoryImpl.init(); BpsimFactoryImpl.init(); Repository repository = profile.getRepository(); if (transformto != null && transformto.equals(TO_PDF)) { if(respaction != null && respaction.equals(RESPACTION_SHOWURL)) { try { ByteArrayOutputStream pdfBout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfBout); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); float widthHint = getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH); float heightHint = getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT); String objStyle = "style=\"width:" + widthHint + "px;height:" + heightHint + "px;\""; t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, widthHint); t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, heightHint); ByteArrayOutputStream imageBout = new ByteArrayOutputStream(); TranscoderInput input = new TranscoderInput(new StringReader( formattedSvg)); TranscoderOutput output = new TranscoderOutput(imageBout); t.transcode(input, output); Image processImage = Image.getInstance(imageBout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getWriter().write("<object type=\"application/pdf\" " + objStyle + " data=\"data:application/pdf;base64," + Base64.encodeBase64String(pdfBout.toByteArray()) + "\"></object>"); } catch(Exception e) { resp.sendError(500, e.getMessage()); } } else { storeInRepository(uuid, formattedSvg, transformto, processid, repository); try { resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/pdf"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\""); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream()); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); Image processImage = Image.getInstance(bout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); } catch(Exception e) { resp.sendError(500, e.getMessage()); } } } else if (transformto != null && transformto.equals(TO_PNG)) { try { if(respaction != null && respaction.equals(RESPACTION_SHOWURL)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); if(req.getParameter(SVG_WIDTH_PARAM) != null && req.getParameter(SVG_HEIGHT_PARAM) != null) { int widthHint = (int) getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH); int heightHint = (int) getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT); resp.getWriter().write("<img width=\"" + widthHint + "\" height=\"" + heightHint + "\" src=\"data:image/png;base64," + Base64.encodeBase64String(bout.toByteArray()) + "\">"); } else { resp.getWriter().write("<img src=\"data:image/png;base64," + Base64.encodeBase64String(bout.toByteArray()) + "\">"); } } else { storeInRepository(uuid, formattedSvg, transformto, processid, repository); resp.setContentType("image/png"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\""); } PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( formattedSvg)); TranscoderOutput output = new TranscoderOutput( resp.getOutputStream()); t.transcode(input, output); } } catch (TranscoderException e) { resp.sendError(500, e.getMessage()); } } else if (transformto != null && transformto.equals(TO_SVG)) { storeInRepository(uuid, formattedSvg, transformto, processid, repository); } else if (transformto != null && transformto.equals(JPDL_TO_BPMN2)) { try { String bpmn2 = JbpmMigration.transform(jpdl); Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2); // add bpmndi info to Definitions with help of gpd addBpmnDiInfo(def, gpd); // hack for now revisitSequenceFlows(def, bpmn2); // another hack if id == name revisitNodeNames(def); // get the xml from Definitions ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet.createResource(URI.createURI("virtual.bpmn2")); rSet.getResources().add(bpmn2resource); bpmn2resource.getContents().add(def); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bpmn2resource.save(outputStream, new HashMap<Object, Object>()); String fullXmlModel = outputStream.toString(); // convert to json and write response String json = profile.createUnmarshaller().parseModel(fullXmlModel, profile, pp); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); resp.getWriter().print(json); } catch(Exception e) { _logger.error(e.getMessage()); resp.setContentType("application/json"); resp.getWriter().print("{}"); } } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) { try { if(convertServiceTasks != null && convertServiceTasks.equals("true")) { bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\""); bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\""); } Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in); def.setTargetNamespace("http://www.omg.org/bpmn20"); if(convertServiceTasks != null && convertServiceTasks.equals("true")) { // fix the data input associations for converted tasks List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { updateTaskDataInputs((Process) root, def); } } } // get the xml from Definitions ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet.createResource(URI.createURI("virtual.bpmn2")); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8"); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, true); bpmn2resource.getDefaultLoadOptions().put( JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true ); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF, JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD); bpmn2resource.setEncoding("UTF-8"); rSet.getResources().add(bpmn2resource); bpmn2resource.getContents().add(def); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bpmn2resource.save(outputStream, new HashMap<Object, Object>()); String revisedXmlModel = outputStream.toString(); String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); resp.getWriter().print(json); } catch(Exception e) { e.printStackTrace(); _logger.error(e.getMessage()); resp.setContentType("application/json"); resp.getWriter().print("{}"); } } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) { try { DroolsFactoryImpl.init(); BpsimFactoryImpl.init(); if(preprocessingData == null) { preprocessingData = ""; } String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData); resp.setContentType("application/xml"); resp.getWriter().print(processXML); } catch(Exception e) { e.printStackTrace(); _logger.error(e.getMessage()); resp.setContentType("application/xml"); resp.getWriter().print(""); } } else if (transformto != null && transformto.equals(HTML_TO_PDF)) { try { resp.setContentType("application/pdf"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\""); } Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream()); pdfDoc.open(); pdfDoc.addCreator("jBPM Designer"); pdfDoc.addSubject("Business Process Documentation"); pdfDoc.addCreationDate(); pdfDoc.addTitle("Process Documentation"); HTMLWorker htmlWorker = new HTMLWorker(pdfDoc); htmlWorker.parse(new StringReader(htmlSource)); pdfDoc.close(); } catch(DocumentException e) { resp.sendError(500, e.getMessage()); } } } private void updateTaskDataInputs(FlowElementsContainer container, Definitions def) { List<FlowElement> flowElements = container.getFlowElements(); for(FlowElement fe : flowElements) { if(fe instanceof Task && !(fe instanceof UserTask)) { Task task = (Task) fe; boolean foundReadOnlyServiceTask = false; Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("taskName")) { if(entry.getValue().equals("ReadOnlyService")) { foundReadOnlyServiceTask = true; } } } if(foundReadOnlyServiceTask) { if(task.getDataInputAssociations() != null) { List<DataInputAssociation> dataInputAssociations = task.getDataInputAssociations(); for(DataInputAssociation dia : dataInputAssociations) { if(dia.getTargetRef().getId().endsWith("TaskNameInput")) { ((FormalExpression) dia.getAssignment().get(0).getFrom()).setBody("ReadOnlyService"); } } } } } else if(fe instanceof FlowElementsContainer) { updateTaskDataInputs((FlowElementsContainer) fe, def); } } } private void revisitNodeNames(Definitions def) { List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { Process process = (Process) root; List<FlowElement> flowElements = process.getFlowElements(); for(FlowElement fe : flowElements) { if(fe.getName() != null && fe.getId().equals(fe.getName())) { // change the name so they are not the same fe.setName("_" + fe.getName()); } } } } } private void revisitSequenceFlows(Definitions def, String orig) { try { Map<String, Map<String, String>> sequenceFlowMapping = new HashMap<String, Map<String,String>>(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(orig)); while(reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("sequenceFlow".equals(reader.getLocalName())) { String id = ""; String source = ""; String target = ""; for (int i = 0 ; i < reader.getAttributeCount() ; i++) { if ("id".equals(reader.getAttributeLocalName(i))) { id = reader.getAttributeValue(i); } if ("sourceRef".equals(reader.getAttributeLocalName(i))) { source = reader.getAttributeValue(i); } if ("targetRef".equals(reader.getAttributeLocalName(i))) { target = reader.getAttributeValue(i); } } Map<String, String> valueMap = new HashMap<String, String>(); valueMap.put("sourceRef", source); valueMap.put("targetRef", target); sequenceFlowMapping.put(id, valueMap); } } } List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { Process process = (Process) root; List<FlowElement> flowElements = process.getFlowElements(); for(FlowElement fe : flowElements) { if(fe instanceof SequenceFlow) { SequenceFlow sf = (SequenceFlow) fe; if(sequenceFlowMapping.containsKey(sf.getId())) { sf.setSourceRef(getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("sourceRef"))); sf.setTargetRef(getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("targetRef"))); } else { _logger.error("Could not find mapping for sequenceFlow: " + sf.getId()); } } } } } } catch (FactoryConfigurationError e) { _logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { _logger.error(e.getMessage()); e.printStackTrace(); } } private FlowNode getFlowNode(Definitions def, String nodeId) { List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { Process process = (Process) root; List<FlowElement> flowElements = process.getFlowElements(); for(FlowElement fe : flowElements) { if(fe instanceof FlowNode) { if(fe.getId().equals(nodeId)) { return (FlowNode) fe; } } } } } return null; } private void addBpmnDiInfo(Definitions def, String gpd) { try { Map<String, Bounds> _bounds = new HashMap<String, Bounds>(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(gpd)); while(reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("node".equals(reader.getLocalName())) { Bounds b = DcFactory.eINSTANCE.createBounds(); String nodeName = null; String nodeX = null; String nodeY = null; String nodeWidth = null; String nodeHeight = null; for (int i = 0 ; i < reader.getAttributeCount() ; i++) { if ("name".equals(reader.getAttributeLocalName(i))) { nodeName = reader.getAttributeValue(i); } else if("x".equals(reader.getAttributeLocalName(i))) { nodeX = reader.getAttributeValue(i); } else if("y".equals(reader.getAttributeLocalName(i))) { nodeY = reader.getAttributeValue(i); } else if("width".equals(reader.getAttributeLocalName(i))) { nodeWidth = reader.getAttributeValue(i); } else if("height".equals(reader.getAttributeLocalName(i))) { nodeHeight = reader.getAttributeValue(i); } } b.setX(new Float(nodeX).floatValue()); b.setY(new Float(nodeY).floatValue()); b.setWidth(new Float(nodeWidth).floatValue()); b.setHeight(new Float(nodeHeight).floatValue()); _bounds.put(nodeName, b); } } } for (RootElement rootElement: def.getRootElements()) { if (rootElement instanceof Process) { Process process = (Process) rootElement; BpmnDiFactory diFactory = BpmnDiFactory.eINSTANCE; BPMNDiagram diagram = diFactory.createBPMNDiagram(); BPMNPlane plane = diFactory.createBPMNPlane(); plane.setBpmnElement(process); diagram.setPlane(plane); for (FlowElement flowElement: process.getFlowElements()) { if (flowElement instanceof FlowNode) { Bounds b = _bounds.get(flowElement.getId()); if (b != null) { BPMNShape shape = diFactory.createBPMNShape(); shape.setBpmnElement(flowElement); shape.setBounds(b); plane.getPlaneElement().add(shape); } } else if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; BPMNEdge edge = diFactory.createBPMNEdge(); edge.setBpmnElement(flowElement); DcFactory dcFactory = DcFactory.eINSTANCE; Point point = dcFactory.createPoint(); if(sequenceFlow.getSourceRef() != null) { Bounds sourceBounds = _bounds.get(sequenceFlow.getSourceRef().getId()); point.setX(sourceBounds.getX() + (sourceBounds.getWidth()/2)); point.setY(sourceBounds.getY() + (sourceBounds.getHeight()/2)); } edge.getWaypoint().add(point); // List<Point> dockers = _dockers.get(sequenceFlow.getId()); // for (int i = 1; i < dockers.size() - 1; i++) { // edge.getWaypoint().add(dockers.get(i)); // } point = dcFactory.createPoint(); if(sequenceFlow.getTargetRef() != null) { Bounds targetBounds = _bounds.get(sequenceFlow.getTargetRef().getId()); point.setX(targetBounds.getX() + (targetBounds.getWidth()/2)); point.setY(targetBounds.getY() + (targetBounds.getHeight()/2)); } edge.getWaypoint().add(point); plane.getPlaneElement().add(edge); } } def.getDiagrams().add(diagram); } } } catch (FactoryConfigurationError e) { _logger.error("Exception adding bpmndi info: " + e.getMessage()); } catch (Exception e) { _logger.error("Exception adding bpmndi info: " + e.getMessage()); } } protected void storeInRepository(String uuid, String svg, String transformto, String processid, Repository repository) { String assetFullName = ""; try { if(processid != null) { Asset<byte[]> processAsset = repository.loadAsset(uuid); String assetExt = ""; String assetFileExt = ""; if(transformto.equals(TO_PDF)) { assetExt = "-pdf"; assetFileExt = ".pdf"; } if(transformto.equals(TO_PNG)) { assetExt = "-image"; assetFileExt = ".png"; } if(transformto.equals(TO_SVG)) { assetExt = "-svg"; assetFileExt = ".svg"; } if(processid.startsWith(".")) { processid = processid.substring(1, processid.length()); } assetFullName = processid + assetExt + assetFileExt; repository.deleteAssetFromPath(processAsset.getAssetLocation() + File.separator + assetFullName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (transformto.equals(TO_PDF)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, outputStream); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( svg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); Image processImage = Image.getInstance(bout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); } else if (transformto.equals(TO_PNG)) { PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( svg)); TranscoderOutput output = new TranscoderOutput(outputStream); try { t.transcode(input, output); } catch (Exception e) { // issue with batik here..do not make a big deal _logger.debug(e.getMessage()); } } else if(transformto.equals(TO_SVG)) { OutputStreamWriter outStreamWriter = new OutputStreamWriter(outputStream); outStreamWriter.write(svg); outStreamWriter.close(); } AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte); builder.name(processid + assetExt) .type(assetFileExt.substring(1)) .location(processAsset.getAssetLocation()) .version(processAsset.getVersion()) .content(outputStream.toByteArray()); Asset<byte[]> resourceAsset = builder.getAsset(); repository.createAsset(resourceAsset); } } catch (Exception e) { // just log that error happened if (e.getMessage() != null) { _logger.error(e.getMessage()); } else { _logger.error(e.getClass().toString() + " " + assetFullName); } e.printStackTrace(); } } private String getProcessContent(String uuid, Repository repository) { try { Asset<String> processAsset = repository.loadAsset(uuid); return processAsset.getAssetContent(); } catch (Exception e) { // we dont want to barf..just log that error happened _logger.error(e.getMessage()); return ""; } } private float getFloatParam(final HttpServletRequest req, final String paramName, final float defaultValue) { float value = defaultValue; String paramValue = req.getParameter(paramName); if (paramValue != null && !paramValue.isEmpty()) { try { value = Float.parseFloat(paramValue); } catch (NumberFormatException nfe) { value = defaultValue; } } return value; } public void scalePDFImage(Document document, Image image) { float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()) / image.getWidth()) * 100; image.scalePercent(scaler); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_3279_1
crossvul-java_data_bad_1910_12
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.hpprinter.internal.api; import java.io.IOException; import java.io.StringReader; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpMethod; import org.openhab.binding.hpprinter.internal.api.HPServerResult.RequestStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link HPWebServerClient} is responsible for handling reading of data from the HP Embedded Web Server. * * @author Stewart Cossey - Initial contribution */ @NonNullByDefault public class HPWebServerClient { public static final int REQUEST_TIMEOUT_SEC = 10; private final Logger logger = LoggerFactory.getLogger(HPWebServerClient.class); private final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); private final HttpClient httpClient; private final String serverAddress; /** * Creates a new HP Web Server Client object. * * @param httpClient {HttpClient} The HttpClient to use for HTTP requests. * @param address The address for the Embedded Web Server. */ public HPWebServerClient(HttpClient httpClient, String address) { this.httpClient = httpClient; serverAddress = "http://" + address; logger.debug("Create printer connection {}", serverAddress); } /** * Gets the Status information from the Embedded Web Server. * * @return The status information. */ public HPServerResult<HPStatus> getStatus() { return fetchData(serverAddress + HPStatus.ENDPOINT, (HPStatus::new)); } public HPServerResult<HPProductUsageFeatures> getProductFeatures() { return fetchData(serverAddress + HPProductUsageFeatures.ENDPOINT, (HPProductUsageFeatures::new)); } public HPServerResult<HPFeatures> getProductUsageFeatures() { return fetchData(serverAddress + HPFeatures.ENDPOINT, (HPFeatures::new)); } public HPServerResult<HPScannerStatusFeatures> getScannerFeatures() { return fetchData(serverAddress + HPScannerStatusFeatures.ENDPOINT, (HPScannerStatusFeatures::new)); } /** * Gets the Usage information from the Embedded Web Server. * * @return The usage information. */ public HPServerResult<HPUsage> getUsage() { return fetchData(serverAddress + HPUsage.ENDPOINT, (HPUsage::new)); } public HPServerResult<HPScannerStatus> getScannerStatus() { return fetchData(serverAddress + HPScannerStatus.ENDPOINT, (HPScannerStatus::new)); } public HPServerResult<HPProperties> getProperties() { return fetchData(serverAddress + HPProperties.ENDPOINT, (HPProperties::new)); } private <T> HPServerResult<T> fetchData(String endpoint, Function<Document, T> function) { try { logger.trace("HTTP Client Load {}", endpoint); ContentResponse cr = httpClient.newRequest(endpoint).method(HttpMethod.GET) .timeout(REQUEST_TIMEOUT_SEC, TimeUnit.SECONDS).send(); String contentAsString = cr.getContentAsString(); logger.trace("HTTP Client Result {} Size {}", cr.getStatus(), contentAsString.length()); return new HPServerResult<>(function.apply(getDocument(contentAsString))); } catch (TimeoutException ex) { logger.trace("HTTP Client Timeout Exception {}", ex.getMessage()); return new HPServerResult<>(RequestStatus.TIMEOUT, ex.getMessage()); } catch (InterruptedException | ExecutionException | ParserConfigurationException | SAXException | IOException ex) { logger.trace("HTTP Client Exception {}", ex.getMessage()); return new HPServerResult<>(RequestStatus.ERROR, ex.getMessage()); } } private synchronized Document getDocument(String contentAsString) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder builder = factory.newDocumentBuilder(); InputSource source = new InputSource(new StringReader(contentAsString)); return builder.parse(source); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_12
crossvul-java_data_bad_4290_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4290_3
crossvul-java_data_good_2449_13
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.accenture.examples.rest; import org.platformlambda.core.exception.AppException; import org.platformlambda.core.models.EventEnvelope; import org.platformlambda.core.models.Kv; import org.platformlambda.core.system.Platform; import org.platformlambda.core.system.PostOffice; import org.platformlambda.models.ObjectWithGenericType; import org.platformlambda.models.SamplePoJo; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.concurrent.TimeoutException; @Path("/hello") public class HelloPoJo { @GET @Path("/pojo/{id}") @Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_HTML}) public Object getPoJo(@PathParam("id") Integer id) throws TimeoutException, AppException, IOException { PostOffice po = PostOffice.getInstance(); EventEnvelope response = po.request("hello.pojo", 3000, new Kv("id", id)); // confirm that the PoJo object is transported correctly over the event stream system if (response.getBody() instanceof SamplePoJo) { return response.getBody(); } else { if (response.getBody() == null) { throw new AppException(500, "Invalid service response. Expect: " + SamplePoJo.class.getName() + ", actual: null"); } else { throw new AppException(500, "Invalid service response. Expect: " + SamplePoJo.class.getName() + ", actual: " + response.getBody().getClass().getName()); } } } @GET @Path("/generic/{id}") @Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_HTML}) public Object getGeneric(@PathParam("id") Integer id) throws TimeoutException, AppException, IOException { PostOffice po = PostOffice.getInstance(); EventEnvelope response = po.request("hello.generic", 3000, new Kv("id", id.toString())); // demonstrate error handling if (response.hasError()) { throw new AppException(response.getStatus(), response.getError()); } // confirm that the PoJo object is transported correctly over the event stream system if (response.getBody() instanceof ObjectWithGenericType) { ObjectWithGenericType result = (ObjectWithGenericType) response.getBody(); if (result.getContent() instanceof SamplePoJo) { return response.getBody(); } else { throw new AppException(500, "Invalid service response. Expect: " + SamplePoJo.class.getSimpleName() + " as a parametric type of " + ObjectWithGenericType.class.getName()+", actual: " + response.getBody().getClass().getName()); } } else { if (response.getBody() == null) { throw new AppException(500, "Invalid service response. Expect: " + ObjectWithGenericType.class.getName() + ", actual: null"); } else { throw new AppException(500, "Invalid service response. Expect: " + ObjectWithGenericType.class.getName() + ", actual: " + response.getBody().getClass().getName()); } } } @POST @Path("/echo") @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Object echoPojo(SamplePoJo pojo) { // this demonstrates that you can send a PoJo and receive a PoJo pojo.setOrigin(Platform.getInstance().getOrigin()); return pojo; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_2449_13
crossvul-java_data_bad_2449_13
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.accenture.examples.rest; import org.platformlambda.core.exception.AppException; import org.platformlambda.core.models.EventEnvelope; import org.platformlambda.core.models.Kv; import org.platformlambda.core.system.Platform; import org.platformlambda.core.system.PostOffice; import org.platformlambda.models.ObjectWithGenericType; import org.platformlambda.models.SamplePoJo; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.util.concurrent.TimeoutException; @Path("/hello") public class HelloPoJo { @GET @Path("/pojo/{id}") @Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_HTML}) public Object getPoJo(@PathParam("id") Integer id) throws TimeoutException, AppException, IOException { PostOffice po = PostOffice.getInstance(); EventEnvelope response = po.request("hello.pojo", 3000, new Kv("id", id)); // confirm that the PoJo object is transported correctly over the event stream system if (response.getBody() instanceof SamplePoJo) { return response.getBody(); } else { if (response.getBody() == null) { throw new AppException(500, "Invalid service response. Expect: " + SamplePoJo.class.getName() + ", actual: null"); } else { throw new AppException(500, "Invalid service response. Expect: " + SamplePoJo.class.getName() + ", actual: " + response.getBody().getClass().getName()); } } } @GET @Path("/generic/{id}") @Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_HTML}) public Object getGeneric(@PathParam("id") Integer id) throws TimeoutException, AppException, IOException { PostOffice po = PostOffice.getInstance(); EventEnvelope response = po.request("hello.generic", 3000, new Kv("id", id.toString())); // demonstrate error handling if (response.hasError()) { throw new AppException(response.getStatus(), response.getError()); } // confirm that the PoJo object is transported correctly over the event stream system if (response.getBody() instanceof ObjectWithGenericType) { ObjectWithGenericType result = (ObjectWithGenericType) response.getBody(); if (result.getContent() instanceof SamplePoJo) { return response.getBody(); } else { throw new AppException(500, "Invalid service response. Expect: " + SamplePoJo.class.getSimpleName() + " as a parametric type of " + ObjectWithGenericType.class.getName()+", actual: " + response.getBody().getClass().getName()); } } else { if (response.getBody() == null) { throw new AppException(500, "Invalid service response. Expect: " + ObjectWithGenericType.class.getName() + ", actual: null"); } else { throw new AppException(500, "Invalid service response. Expect: " + ObjectWithGenericType.class.getName() + ", actual: " + response.getBody().getClass().getName()); } } } @POST @Path("/echo") @Consumes(MediaType.APPLICATION_JSON) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Object echoPojo(SamplePoJo pojo) { // this demonstrates that you can send a PoJo and receive a PoJo pojo.setOrigin(Platform.getInstance().getOrigin()); return pojo; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_2449_13
crossvul-java_data_bad_1969_0
// Copyright (C) 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.json; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.Iterator; import java.util.Locale; import java.util.Random; import javax.annotation.Nullable; import junit.framework.TestCase; import org.junit.Test; /** * Tries a series of pseudo-random variants of a string of JSON to suss out * boundary conditions in the JSON parser. */ @SuppressWarnings("javadoc") public final class FuzzyTest extends TestCase { @Test public static final void testSanitizerLikesFuzzyWuzzyInputs() throws Throwable { int nRuns = 10000; long seed; { // Try to fetch a seed from a system property so that we can replay failed // tests. String seedString = System.getProperty("fuzz.seed", null); if (seedString != null) { seed = Long.parseLong(seedString, 16); } else { // Use java.util.Random's default constructor to generate a seed since // it does a pretty good job of making a good non-crypto-strong seed. seed = new Random().nextLong(); } } // Dump the seed so that failures can be reproduced with only this line // from the test log. System.err.println("Fuzzing with -Dfuzz.seed=" + Long.toHexString(seed)); System.err.flush(); Random rnd = new Random(seed); for (String fuzzyWuzzyString : new FuzzyStringGenerator(rnd)) { try { String sanitized0 = JsonSanitizer.sanitize(fuzzyWuzzyString); String sanitized1 = JsonSanitizer.sanitize(sanitized0); // Test idempotence. assertEquals(fuzzyWuzzyString + " => " + sanitized0, sanitized0, sanitized1); } catch (Throwable th) { System.err.println("Failed on `" + fuzzyWuzzyString + "`"); hexDump(fuzzyWuzzyString.getBytes("UTF16"), System.err); System.err.println(""); throw th; } if (--nRuns <= 0) { break; } } } private static void hexDump(byte[] bytes, Appendable app) throws IOException { for (int i = 0; i < bytes.length; ++i) { if ((i % 16) == 0) { if (i != 0) { app.append('\n'); } } else { app.append(' '); } byte b = bytes[i]; app.append("0123456789ABCDEF".charAt((b >>> 4) & 0xf)); app.append("0123456789ABCDEF".charAt((b >>> 0) & 0xf)); } } } final class FuzzyStringGenerator implements Iterable<String> { final Random rnd; FuzzyStringGenerator(Random rnd) { this.rnd = rnd; } @Override public Iterator<String> iterator() { return new Iterator<String>() { private @Nullable String basis; private @Nullable String pending; @Override public boolean hasNext() { return true; } @Override public String next() { if (pending == null) { fuzz(); } String s = pending; pending = null; if (0 == rnd.nextInt(16)) { basis = null; } return s; } @Override public void remove() { throw new UnsupportedOperationException(); } @SuppressWarnings("synthetic-access") private void fuzz() { if (basis == null) { pending = basis = makeRandomJson(); return; } pending = mutate(basis); } }; } private String makeRandomJson() { int maxDepth = 1 + rnd.nextInt(8); int maxBreadth = 4 + rnd.nextInt(16); StringBuilder sb = new StringBuilder(); appendWhitespace(sb); appendRandomJson(maxDepth, maxBreadth, sb); appendWhitespace(sb); return sb.toString(); } private static final String[] FLOAT_FORMAT_STRING = { "%g", "%G", "%e", "%E", "%f" }; private static final String[] INT_FORMAT_STRING = { "%x", "%X", "%d" }; private void appendRandomJson( int maxDepth, int maxBreadth, StringBuilder sb) { int r = rnd.nextInt(maxDepth > 0 ? 8 : 6); switch (r) { case 0: sb.append("null"); break; case 1: sb.append("true"); break; case 2: sb.append("false"); break; case 3: { String fmt = FLOAT_FORMAT_STRING [rnd.nextInt(FLOAT_FORMAT_STRING.length)]; sb.append(String.format(Locale.ROOT, fmt, 1.0 / rnd.nextGaussian())); break; } case 4: { switch (rnd.nextInt(3)) { case 0: break; case 1: sb.append('-'); break; case 2: sb.append('+'); break; } String fmt = INT_FORMAT_STRING [rnd.nextInt(INT_FORMAT_STRING.length)]; BigInteger num = new BigInteger(randomDecimalDigits(maxBreadth * 2)); sb.append(String.format(Locale.ROOT, fmt, num)); break; } case 5: appendRandomString(maxBreadth, sb); break; case 6: sb.append('['); appendWhitespace(sb); for (int i = rnd.nextInt(maxBreadth); --i >= 0;) { appendWhitespace(sb); appendRandomJson(maxDepth - 1, Math.max(1, maxBreadth - 1), sb); if (i != 1) { appendWhitespace(sb); sb.append(','); } } appendWhitespace(sb); sb.append(']'); break; case 7: sb.append('{'); appendWhitespace(sb); for (int i = rnd.nextInt(maxBreadth); --i >= 0;) { appendWhitespace(sb); appendRandomString(maxBreadth, sb); appendWhitespace(sb); sb.append(':'); appendWhitespace(sb); appendRandomJson(maxDepth - 1, Math.max(1, maxBreadth - 1), sb); if (i != 1) { appendWhitespace(sb); sb.append(','); } } appendWhitespace(sb); sb.append('}'); break; } } private void appendRandomString(int maxBreadth, StringBuilder sb) { sb.append('"'); appendRandomChars(rnd.nextInt(maxBreadth * 4), sb); sb.append('"'); } private void appendRandomChars(int nChars, StringBuilder sb) { for (int i = nChars; --i >= 0;) { appendRandomChar(sb); } } private void appendRandomChar(StringBuilder sb) { char delim = rnd.nextInt(8) == 0 ? '\'' : '"'; int cpMax; switch (rnd.nextInt(7)) { case 0: case 1: case 2: case 3: cpMax = 0x100; break; case 4: case 5: cpMax = 0x10000; break; default: cpMax = Character.MAX_CODE_POINT; break; } int cp = rnd.nextInt(cpMax); boolean encode = false; if (cp == delim || cp < 0x20 || cp == '\\') { encode = true; } if (!encode && 0 == rnd.nextInt(8)) { encode = true; } if (encode) { if (rnd.nextBoolean()) { for (char cu : Character.toChars(cp)) { sb.append("\\u").append(String.format("%04x", (int) cu)); } } else { sb.append('\\'); switch (cp) { case 0xa: sb.append('\n'); break; case 0xd: sb.append('\r'); break; default: sb.appendCodePoint(cp); break; } } } else { sb.appendCodePoint(cp); } } private void appendWhitespace(StringBuilder sb) { if (rnd.nextInt(4) == 0) { for (int i = rnd.nextInt(4); --i >= 0;) { sb.append(" \t\r\n".charAt(rnd.nextInt(4))); } } } private String randomDecimalDigits(int maxDigits) { int nDigits = Math.max(1, rnd.nextInt(maxDigits)); StringBuilder sb = new StringBuilder(nDigits); for (int i = nDigits; --i >= 0;) { sb.append((char) ('0' + rnd.nextInt(10))); } return sb.toString(); } private String mutate(String s) { int n = rnd.nextInt(16) + 1; // Number of changes. int len = s.length(); // Pick the places where we mutate, so we can sort, de-dupe, and then // derive s' in a left-to-right pass. int[] locations = new int[n]; for (int i = n; --i >= 0;) { locations[i] = rnd.nextInt(len); } Arrays.sort(locations); // Dedupe. { int k = 1; for (int i = 1; i < n; ++i) { if (locations[i] != locations[i - 1]) { locations[k++] = locations[i]; } } n = k; // Skip any duped ones. } // Walk left-to-right and perform modifications. int left = 0; StringBuilder delta = new StringBuilder(len); for (int i = 0; i < n; ++i) { int loc = locations[i]; int nextLoc = i + 1 == n ? len : locations[i + 1]; int size = nextLoc - loc; int rndSliceLen = 1; if (size > 1) { rndSliceLen = rnd.nextInt(size); } delta.append(s, left, loc); left = loc; switch (rnd.nextInt(3)) { case 0: // insert appendRandomChars(rndSliceLen, delta); break; case 1: // replace appendRandomChars(rndSliceLen, delta); left += rndSliceLen; break; case 2: // remove left += rndSliceLen; break; } } delta.append(s, left, len); return delta.toString(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1969_0
crossvul-java_data_bad_3875_1
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * <p> * <code>SAXHelper</code> contains some helper methods for working with SAX * and XMLReader objects. * </p> * * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a> * @version $Revision: 1.18 $ */ class SAXHelper { private static boolean loggedWarning = true; protected SAXHelper() { } public static boolean setParserProperty(XMLReader reader, String propertyName, Object value) { try { reader.setProperty(propertyName, value); return true; } catch (SAXNotSupportedException e) { // ignore } catch (SAXNotRecognizedException e) { // ignore } return false; } public static boolean setParserFeature(XMLReader reader, String featureName, boolean value) { try { reader.setFeature(featureName, value); return true; } catch (SAXNotSupportedException e) { // ignore } catch (SAXNotRecognizedException e) { // ignore } return false; } /** * Creats a default XMLReader via the org.xml.sax.driver system property or * JAXP if the system property is not set. * * @param validating * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ public static XMLReader createXMLReader(boolean validating) throws SAXException { XMLReader reader = null; if (reader == null) { reader = createXMLReaderViaJAXP(validating, true); } if (reader == null) { try { reader = XMLReaderFactory.createXMLReader(); } catch (Exception e) { if (isVerboseErrorReporting()) { // log all exceptions as warnings and carry // on as we have a default SAX parser we can use System.out.println("Warning: Caught exception attempting " + "to use SAX to load a SAX XMLReader "); System.out.println("Warning: Exception was: " + e); System.out .println("Warning: I will print the stack trace " + "then carry on using the default " + "SAX parser"); e.printStackTrace(); } throw new SAXException(e); } } if (reader == null) { throw new SAXException("Couldn't create SAX reader"); } // configure namespace support SAXHelper.setParserFeature(reader, "http://xml.org/sax/features/namespaces", true); SAXHelper.setParserFeature(reader, "http://xml.org/sax/features/namespace-prefixes", false); // external entites SAXHelper.setParserFeature(reader, "http://xml.org/sax/properties/external-general-entities", false); SAXHelper.setParserFeature(reader, "http://xml.org/sax/properties/external-parameter-entities", false); // external DTD SAXHelper.setParserFeature(reader,"http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // use Locator2 if possible SAXHelper.setParserFeature(reader,"http://xml.org/sax/features/use-locator2", true); return reader; } /** * This method attempts to use JAXP to locate the SAX2 XMLReader * implementation. This method uses reflection to avoid being dependent * directly on the JAXP classes. * * @param validating * DOCUMENT ME! * @param namespaceAware * DOCUMENT ME! * * @return DOCUMENT ME! */ protected static XMLReader createXMLReaderViaJAXP(boolean validating, boolean namespaceAware) { // try use JAXP to load the XMLReader... try { return JAXPHelper.createXMLReader(validating, namespaceAware); } catch (Throwable e) { if (!loggedWarning) { loggedWarning = true; if (isVerboseErrorReporting()) { // log all exceptions as warnings and carry // on as we have a default SAX parser we can use System.out.println("Warning: Caught exception attempting " + "to use JAXP to load a SAX XMLReader"); System.out.println("Warning: Exception was: " + e); e.printStackTrace(); } } } return null; } protected static boolean isVerboseErrorReporting() { try { String flag = System.getProperty("org.dom4j.verbose"); if ((flag != null) && flag.equalsIgnoreCase("true")) { return true; } } catch (Exception e) { // in case a security exception // happens in an applet or similar JVM } return true; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-611/java/bad_3875_1
crossvul-java_data_good_4033_1
/* * Copyright (c) 2003, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.core; import org.postgresql.PGConnection; import org.postgresql.PGProperty; import org.postgresql.jdbc.FieldMetadata; import org.postgresql.jdbc.TimestampUtils; import org.postgresql.util.LruCache; import org.postgresql.xml.PGXmlFactoryFactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.TimerTask; /** * Driver-internal connection interface. Application code should not use this interface. */ public interface BaseConnection extends PGConnection, Connection { /** * Cancel the current query executing on this connection. * * @throws SQLException if something goes wrong. */ void cancelQuery() throws SQLException; /** * Execute a SQL query that returns a single resultset. Never causes a new transaction to be * started regardless of the autocommit setting. * * @param s the query to execute * @return the (non-null) returned resultset * @throws SQLException if something goes wrong. */ ResultSet execSQLQuery(String s) throws SQLException; ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException; /** * Execute a SQL query that does not return results. Never causes a new transaction to be started * regardless of the autocommit setting. * * @param s the query to execute * @throws SQLException if something goes wrong. */ void execSQLUpdate(String s) throws SQLException; /** * Get the QueryExecutor implementation for this connection. * * @return the (non-null) executor */ QueryExecutor getQueryExecutor(); /** * Internal protocol for work with physical and logical replication. Physical replication available * only since PostgreSQL version 9.1. Logical replication available only since PostgreSQL version 9.4. * * @return not null replication protocol */ ReplicationProtocol getReplicationProtocol(); /** * <p>Construct and return an appropriate object for the given type and value. This only considers * the types registered via {@link org.postgresql.PGConnection#addDataType(String, Class)} and * {@link org.postgresql.PGConnection#addDataType(String, String)}.</p> * * <p>If no class is registered as handling the given type, then a generic * {@link org.postgresql.util.PGobject} instance is returned.</p> * * @param type the backend typename * @param value the type-specific string representation of the value * @param byteValue the type-specific binary representation of the value * @return an appropriate object; never null. * @throws SQLException if something goes wrong */ Object getObject(String type, String value, byte[] byteValue) throws SQLException; Encoding getEncoding() throws SQLException; TypeInfo getTypeInfo(); /** * <p>Check if we have at least a particular server version.</p> * * <p>The input version is of the form xxyyzz, matching a PostgreSQL version like xx.yy.zz. So 9.0.12 * is 90012.</p> * * @param ver the server version to check, of the form xxyyzz eg 90401 * @return true if the server version is at least "ver". */ boolean haveMinimumServerVersion(int ver); /** * <p>Check if we have at least a particular server version.</p> * * <p>The input version is of the form xxyyzz, matching a PostgreSQL version like xx.yy.zz. So 9.0.12 * is 90012.</p> * * @param ver the server version to check * @return true if the server version is at least "ver". */ boolean haveMinimumServerVersion(Version ver); /** * Encode a string using the database's client_encoding (usually UTF8, but can vary on older * server versions). This is used when constructing synthetic resultsets (for example, in metadata * methods). * * @param str the string to encode * @return an encoded representation of the string * @throws SQLException if something goes wrong. */ byte[] encodeString(String str) throws SQLException; /** * Escapes a string for use as string-literal within an SQL command. The method chooses the * applicable escaping rules based on the value of {@link #getStandardConformingStrings()}. * * @param str a string value * @return the escaped representation of the string * @throws SQLException if the string contains a {@code \0} character */ String escapeString(String str) throws SQLException; /** * Returns whether the server treats string-literals according to the SQL standard or if it uses * traditional PostgreSQL escaping rules. Versions up to 8.1 always treated backslashes as escape * characters in string-literals. Since 8.2, this depends on the value of the * {@code standard_conforming_strings} server variable. * * @return true if the server treats string literals according to the SQL standard * @see QueryExecutor#getStandardConformingStrings() */ boolean getStandardConformingStrings(); // Ew. Quick hack to give access to the connection-specific utils implementation. TimestampUtils getTimestampUtils(); // Get the per-connection logger. java.util.logging.Logger getLogger(); // Get the bind-string-as-varchar config flag boolean getStringVarcharFlag(); /** * Get the current transaction state of this connection. * * @return current transaction state of this connection */ TransactionState getTransactionState(); /** * Returns true if value for the given oid should be sent using binary transfer. False if value * should be sent using text transfer. * * @param oid The oid to check. * @return True for binary transfer, false for text transfer. */ boolean binaryTransferSend(int oid); /** * Return whether to disable column name sanitation. * * @return true column sanitizer is disabled */ boolean isColumnSanitiserDisabled(); /** * Schedule a TimerTask for later execution. The task will be scheduled with the shared Timer for * this connection. * * @param timerTask timer task to schedule * @param milliSeconds delay in milliseconds */ void addTimerTask(TimerTask timerTask, long milliSeconds); /** * Invoke purge() on the underlying shared Timer so that internal resources will be released. */ void purgeTimerTasks(); /** * Return metadata cache for given connection. * * @return metadata cache */ LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache(); CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized, String... columnNames) throws SQLException; /** * By default, the connection resets statement cache in case deallocate all/discard all * message is observed. * This API allows to disable that feature for testing purposes. * * @param flushCacheOnDeallocate true if statement cache should be reset when "deallocate/discard" message observed */ void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate); /** * Indicates if statements to backend should be hinted as read only. * * @return Indication if hints to backend (such as when transaction begins) * should be read only. * @see PGProperty#READ_ONLY_MODE */ boolean hintReadOnly(); /** * Retrieve the factory to instantiate XML processing factories. * * @return The factory to use to instantiate XML processing factories * @throws SQLException if the class cannot be found or instantiated. */ PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException; }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4033_1
crossvul-java_data_good_1969_0
// Copyright (C) 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.json; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.Iterator; import java.util.Locale; import java.util.Random; import javax.annotation.Nullable; import junit.framework.TestCase; import org.junit.Test; /** * Tries a series of pseudo-random variants of a string of JSON to suss out * boundary conditions in the JSON parser. */ @SuppressWarnings("javadoc") public final class FuzzyTest extends TestCase { @Test public static final void testSanitizerLikesFuzzyWuzzyInputs() throws Throwable { int nRuns = 10000; long seed; { // Try to fetch a seed from a system property so that we can replay failed // tests. String seedString = System.getProperty("fuzz.seed", null); if (seedString != null) { seed = Long.parseLong(seedString, 16); } else { // Use java.util.Random's default constructor to generate a seed since // it does a pretty good job of making a good non-crypto-strong seed. seed = new Random().nextLong(); } } // Dump the seed so that failures can be reproduced with only this line // from the test log. System.err.println("Fuzzing with -Dfuzz.seed=" + Long.toHexString(seed)); System.err.flush(); Random rnd = new Random(seed); for (String fuzzyWuzzyString : new FuzzyStringGenerator(rnd)) { try { String sanitized0 = JsonSanitizer.sanitize(fuzzyWuzzyString); String sanitized1 = JsonSanitizer.sanitize(sanitized0); // Test idempotence. if (!sanitized0.equals(sanitized1)) { int commonPrefixLen = 0; int minLength = Math.min(sanitized0.length(), sanitized1.length()); while (commonPrefixLen < minLength) { if (sanitized0.charAt(commonPrefixLen) != sanitized1.charAt(commonPrefixLen)) { break; } ++commonPrefixLen; } int right0 = sanitized0.length(); int right1 = sanitized1.length(); while (right0 > commonPrefixLen && right1 > commonPrefixLen) { if (sanitized0.charAt(right0 - 1) != sanitized1.charAt(right1 - 1)) { break; } --right0; --right1; } int commonSuffixLen = sanitized0.length() - right0; System.err.println("Difference at " + commonPrefixLen + " to -" + commonSuffixLen); System.err.println("Before: " + excerpt(sanitized0, commonPrefixLen, right0)); System.err.println("After: " + excerpt(sanitized0, commonPrefixLen, right1)); } assertEquals(fuzzyWuzzyString + " => " + sanitized0, sanitized0, sanitized1); } catch (Throwable th) { System.err.println("Failed on `" + fuzzyWuzzyString + "`"); hexDump(fuzzyWuzzyString.getBytes("UTF16"), System.err); System.err.println(""); throw th; } if (--nRuns <= 0) { break; } } } private static void hexDump(byte[] bytes, Appendable app) throws IOException { for (int i = 0; i < bytes.length; ++i) { if ((i % 16) == 0) { if (i != 0) { app.append('\n'); } } else { app.append(' '); } byte b = bytes[i]; app.append("0123456789ABCDEF".charAt((b >>> 4) & 0xf)); app.append("0123456789ABCDEF".charAt((b >>> 0) & 0xf)); } } private static String excerpt(String s, int left, int right) { int leftIncl = left - 10; boolean ellipseLeft = leftIncl > 0; if (!ellipseLeft) { leftIncl = 0; } int rightIncl = right + 10; boolean ellipseRight = s.length() > rightIncl; if (!ellipseRight) { rightIncl = s.length(); } return s.substring(leftIncl, rightIncl) .replace("\r", "\\r") .replace("\n", "\\n") .replace("\\", "\\\\"); } } final class FuzzyStringGenerator implements Iterable<String> { final Random rnd; FuzzyStringGenerator(Random rnd) { this.rnd = rnd; } @Override public Iterator<String> iterator() { return new Iterator<String>() { private @Nullable String basis; private @Nullable String pending; @Override public boolean hasNext() { return true; } @Override public String next() { if (pending == null) { fuzz(); } String s = pending; pending = null; if (0 == rnd.nextInt(16)) { basis = null; } return s; } @Override public void remove() { throw new UnsupportedOperationException(); } @SuppressWarnings("synthetic-access") private void fuzz() { if (basis == null) { pending = basis = makeRandomJson(); return; } pending = mutate(basis); } }; } private String makeRandomJson() { int maxDepth = 1 + rnd.nextInt(8); int maxBreadth = 4 + rnd.nextInt(16); StringBuilder sb = new StringBuilder(); appendWhitespace(sb); appendRandomJson(maxDepth, maxBreadth, sb); appendWhitespace(sb); return sb.toString(); } private static final String[] FLOAT_FORMAT_STRING = { "%g", "%G", "%e", "%E", "%f" }; private static final String[] INT_FORMAT_STRING = { "%x", "%X", "%d" }; private void appendRandomJson( int maxDepth, int maxBreadth, StringBuilder sb) { int r = rnd.nextInt(maxDepth > 0 ? 8 : 6); switch (r) { case 0: sb.append("null"); break; case 1: sb.append("true"); break; case 2: sb.append("false"); break; case 3: { String fmt = FLOAT_FORMAT_STRING [rnd.nextInt(FLOAT_FORMAT_STRING.length)]; sb.append(String.format(Locale.ROOT, fmt, 1.0 / rnd.nextGaussian())); break; } case 4: { switch (rnd.nextInt(3)) { case 0: break; case 1: sb.append('-'); break; case 2: sb.append('+'); break; } String fmt = INT_FORMAT_STRING [rnd.nextInt(INT_FORMAT_STRING.length)]; BigInteger num = new BigInteger(randomDecimalDigits(maxBreadth * 2)); sb.append(String.format(Locale.ROOT, fmt, num)); break; } case 5: appendRandomString(maxBreadth, sb); break; case 6: sb.append('['); appendWhitespace(sb); for (int i = rnd.nextInt(maxBreadth); --i >= 0;) { appendWhitespace(sb); appendRandomJson(maxDepth - 1, Math.max(1, maxBreadth - 1), sb); if (i != 1) { appendWhitespace(sb); sb.append(','); } } appendWhitespace(sb); sb.append(']'); break; case 7: sb.append('{'); appendWhitespace(sb); for (int i = rnd.nextInt(maxBreadth); --i >= 0;) { appendWhitespace(sb); appendRandomString(maxBreadth, sb); appendWhitespace(sb); sb.append(':'); appendWhitespace(sb); appendRandomJson(maxDepth - 1, Math.max(1, maxBreadth - 1), sb); if (i != 1) { appendWhitespace(sb); sb.append(','); } } appendWhitespace(sb); sb.append('}'); break; } } private void appendRandomString(int maxBreadth, StringBuilder sb) { sb.append('"'); appendRandomChars(rnd.nextInt(maxBreadth * 4), sb); sb.append('"'); } private void appendRandomChars(int nChars, StringBuilder sb) { for (int i = nChars; --i >= 0;) { appendRandomChar(sb); } } private void appendRandomChar(StringBuilder sb) { char delim = rnd.nextInt(8) == 0 ? '\'' : '"'; int cpMax; switch (rnd.nextInt(7)) { case 0: case 1: case 2: case 3: cpMax = 0x100; break; case 4: case 5: cpMax = 0x10000; break; default: cpMax = Character.MAX_CODE_POINT; break; } int cp = rnd.nextInt(cpMax); boolean encode = false; if (cp == delim || cp < 0x20 || cp == '\\') { encode = true; } if (!encode && 0 == rnd.nextInt(8)) { encode = true; } if (encode) { if (rnd.nextBoolean()) { for (char cu : Character.toChars(cp)) { sb.append("\\u").append(String.format("%04x", (int) cu)); } } else { sb.append('\\'); switch (cp) { case 0xa: sb.append('\n'); break; case 0xd: sb.append('\r'); break; default: sb.appendCodePoint(cp); break; } } } else { sb.appendCodePoint(cp); } } private void appendWhitespace(StringBuilder sb) { if (rnd.nextInt(4) == 0) { for (int i = rnd.nextInt(4); --i >= 0;) { sb.append(" \t\r\n".charAt(rnd.nextInt(4))); } } } private String randomDecimalDigits(int maxDigits) { int nDigits = Math.max(1, rnd.nextInt(maxDigits)); StringBuilder sb = new StringBuilder(nDigits); for (int i = nDigits; --i >= 0;) { sb.append((char) ('0' + rnd.nextInt(10))); } return sb.toString(); } private String mutate(String s) { int n = rnd.nextInt(16) + 1; // Number of changes. int len = s.length(); // Pick the places where we mutate, so we can sort, de-dupe, and then // derive s' in a left-to-right pass. int[] locations = new int[n]; for (int i = n; --i >= 0;) { locations[i] = rnd.nextInt(len); } Arrays.sort(locations); // Dedupe. { int k = 1; for (int i = 1; i < n; ++i) { if (locations[i] != locations[i - 1]) { locations[k++] = locations[i]; } } n = k; // Skip any duped ones. } // Walk left-to-right and perform modifications. int left = 0; StringBuilder delta = new StringBuilder(len); for (int i = 0; i < n; ++i) { int loc = locations[i]; int nextLoc = i + 1 == n ? len : locations[i + 1]; int size = nextLoc - loc; int rndSliceLen = 1; if (size > 1) { rndSliceLen = rnd.nextInt(size); } delta.append(s, left, loc); left = loc; switch (rnd.nextInt(3)) { case 0: // insert appendRandomChars(rndSliceLen, delta); break; case 1: // replace appendRandomChars(rndSliceLen, delta); left += rndSliceLen; break; case 2: // remove left += rndSliceLen; break; } } delta.append(s, left, len); return delta.toString(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1969_0
crossvul-java_data_bad_1736_0
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.milton.http.webdav; import io.milton.common.StreamUtils; import java.io.ByteArrayInputStream; import org.apache.commons.io.output.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashSet; import java.util.Set; import javax.xml.namespace.QName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * Simple implmentation which just parses the request body. If no xml is present * it will return an empty set. * * Note this generally shouldnt be used directly, but should be wrapped by * MSPropFindRequestFieldParser to support windows clients. * * @author brad */ public class DefaultPropFindRequestFieldParser implements PropFindRequestFieldParser { private static final Logger log = LoggerFactory.getLogger( DefaultPropFindRequestFieldParser.class ); public DefaultPropFindRequestFieldParser() { } @Override public PropertiesRequest getRequestedFields( InputStream in ) { final Set<QName> set = new LinkedHashSet<QName>(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); StreamUtils.readTo( in, bout, false, true ); byte[] arr = bout.toByteArray(); if( arr.length > 1 ) { ByteArrayInputStream bin = new ByteArrayInputStream( arr ); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); PropFindSaxHandler handler = new PropFindSaxHandler(); reader.setContentHandler( handler ); try { reader.parse( new InputSource( bin ) ); if( handler.isAllProp() ) { return new PropertiesRequest(); } else { set.addAll( handler.getAttributes().keySet() ); } } catch( IOException e ) { log.warn( "exception parsing request body", e ); // ignore } catch( SAXException e ) { log.warn( "exception parsing request body", e ); // ignore } } } catch( Exception ex ) { // There's a report of an exception being thrown here by IT Hit Webdav client // Perhaps we can just log the error and return an empty set. Usually this // class is wrapped by the MsPropFindRequestFieldParser which will use a default // set of properties if this returns an empty set log.warn("Exception parsing PROPFIND request fields. Returning empty property set", ex); //throw new RuntimeException( ex ); } return PropertiesRequest.toProperties(set); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1736_0
crossvul-java_data_bad_4033_3
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.jdbc; import org.postgresql.Driver; import org.postgresql.PGNotification; import org.postgresql.PGProperty; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; import org.postgresql.core.BaseStatement; import org.postgresql.core.CachedQuery; import org.postgresql.core.ConnectionFactory; import org.postgresql.core.Encoding; import org.postgresql.core.Oid; import org.postgresql.core.Provider; import org.postgresql.core.Query; import org.postgresql.core.QueryExecutor; import org.postgresql.core.ReplicationProtocol; import org.postgresql.core.ResultHandlerBase; import org.postgresql.core.ServerVersion; import org.postgresql.core.SqlCommand; import org.postgresql.core.TransactionState; import org.postgresql.core.TypeInfo; import org.postgresql.core.Utils; import org.postgresql.core.Version; import org.postgresql.fastpath.Fastpath; import org.postgresql.largeobject.LargeObjectManager; import org.postgresql.replication.PGReplicationConnection; import org.postgresql.replication.PGReplicationConnectionImpl; import org.postgresql.util.GT; import org.postgresql.util.HostSpec; import org.postgresql.util.LruCache; import org.postgresql.util.PGBinaryObject; import org.postgresql.util.PGobject; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import java.io.IOException; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.ClientInfoStatus; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLPermission; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.sql.Types; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; public class PgConnection implements BaseConnection { private static final Logger LOGGER = Logger.getLogger(PgConnection.class.getName()); private static final Set<Integer> SUPPORTED_BINARY_OIDS = getSupportedBinaryOids(); private static final SQLPermission SQL_PERMISSION_ABORT = new SQLPermission("callAbort"); private static final SQLPermission SQL_PERMISSION_NETWORK_TIMEOUT = new SQLPermission("setNetworkTimeout"); private enum ReadOnlyBehavior { ignore, transaction, always; } // // Data initialized on construction: // private final Properties clientInfo; /* URL we were created via */ private final String creatingURL; private final ReadOnlyBehavior readOnlyBehavior; private Throwable openStackTrace; /* Actual network handler */ private final QueryExecutor queryExecutor; /* Query that runs COMMIT */ private final Query commitQuery; /* Query that runs ROLLBACK */ private final Query rollbackQuery; private final CachedQuery setSessionReadOnly; private final CachedQuery setSessionNotReadOnly; private final TypeInfo typeCache; private boolean disableColumnSanitiser = false; // Default statement prepare threshold. protected int prepareThreshold; /** * Default fetch size for statement. * * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ protected int defaultFetchSize; // Default forcebinary option. protected boolean forcebinary = false; private int rsHoldability = ResultSet.CLOSE_CURSORS_AT_COMMIT; private int savepointId = 0; // Connection's autocommit state. private boolean autoCommit = true; // Connection's readonly state. private boolean readOnly = false; // Filter out database objects for which the current user has no privileges granted from the DatabaseMetaData private boolean hideUnprivilegedObjects ; // Bind String to UNSPECIFIED or VARCHAR? private final boolean bindStringAsVarchar; // Current warnings; there might be more on queryExecutor too. private SQLWarning firstWarning = null; // Timer for scheduling TimerTasks for this connection. // Only instantiated if a task is actually scheduled. private volatile Timer cancelTimer = null; private PreparedStatement checkConnectionQuery; /** * Replication protocol in current version postgresql(10devel) supports a limited number of * commands. */ private final boolean replicationConnection; private final LruCache<FieldMetadata.Key, FieldMetadata> fieldMetadataCache; final CachedQuery borrowQuery(String sql) throws SQLException { return queryExecutor.borrowQuery(sql); } final CachedQuery borrowCallableQuery(String sql) throws SQLException { return queryExecutor.borrowCallableQuery(sql); } private CachedQuery borrowReturningQuery(String sql, String[] columnNames) throws SQLException { return queryExecutor.borrowReturningQuery(sql, columnNames); } @Override public CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized, String... columnNames) throws SQLException { return queryExecutor.createQuery(sql, escapeProcessing, isParameterized, columnNames); } void releaseQuery(CachedQuery cachedQuery) { queryExecutor.releaseQuery(cachedQuery); } @Override public void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate) { queryExecutor.setFlushCacheOnDeallocate(flushCacheOnDeallocate); LOGGER.log(Level.FINE, " setFlushCacheOnDeallocate = {0}", flushCacheOnDeallocate); } // // Ctor. // public PgConnection(HostSpec[] hostSpecs, String user, String database, Properties info, String url) throws SQLException { // Print out the driver version number LOGGER.log(Level.FINE, org.postgresql.util.DriverInfo.DRIVER_FULL_NAME); this.creatingURL = url; this.readOnlyBehavior = getReadOnlyBehavior(PGProperty.READ_ONLY_MODE.get(info)); setDefaultFetchSize(PGProperty.DEFAULT_ROW_FETCH_SIZE.getInt(info)); setPrepareThreshold(PGProperty.PREPARE_THRESHOLD.getInt(info)); if (prepareThreshold == -1) { setForceBinary(true); } // Now make the initial connection and set up local state this.queryExecutor = ConnectionFactory.openConnection(hostSpecs, user, database, info); // WARNING for unsupported servers (8.1 and lower are not supported) if (LOGGER.isLoggable(Level.WARNING) && !haveMinimumServerVersion(ServerVersion.v8_2)) { LOGGER.log(Level.WARNING, "Unsupported Server Version: {0}", queryExecutor.getServerVersion()); } setSessionReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", false, true); setSessionNotReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", false, true); // Set read-only early if requested if (PGProperty.READ_ONLY.getBoolean(info)) { setReadOnly(true); } this.hideUnprivilegedObjects = PGProperty.HIDE_UNPRIVILEGED_OBJECTS.getBoolean(info); Set<Integer> binaryOids = getBinaryOids(info); // split for receive and send for better control Set<Integer> useBinarySendForOids = new HashSet<Integer>(binaryOids); Set<Integer> useBinaryReceiveForOids = new HashSet<Integer>(binaryOids); /* * Does not pass unit tests because unit tests expect setDate to have millisecond accuracy * whereas the binary transfer only supports date accuracy. */ useBinarySendForOids.remove(Oid.DATE); queryExecutor.setBinaryReceiveOids(useBinaryReceiveForOids); queryExecutor.setBinarySendOids(useBinarySendForOids); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, " types using binary send = {0}", oidsToString(useBinarySendForOids)); LOGGER.log(Level.FINEST, " types using binary receive = {0}", oidsToString(useBinaryReceiveForOids)); LOGGER.log(Level.FINEST, " integer date/time = {0}", queryExecutor.getIntegerDateTimes()); } // // String -> text or unknown? // String stringType = PGProperty.STRING_TYPE.get(info); if (stringType != null) { if (stringType.equalsIgnoreCase("unspecified")) { bindStringAsVarchar = false; } else if (stringType.equalsIgnoreCase("varchar")) { bindStringAsVarchar = true; } else { throw new PSQLException( GT.tr("Unsupported value for stringtype parameter: {0}", stringType), PSQLState.INVALID_PARAMETER_VALUE); } } else { bindStringAsVarchar = true; } // Initialize timestamp stuff timestampUtils = new TimestampUtils(!queryExecutor.getIntegerDateTimes(), new Provider<TimeZone>() { @Override public TimeZone get() { return queryExecutor.getTimeZone(); } }); // Initialize common queries. // isParameterized==true so full parse is performed and the engine knows the query // is not a compound query with ; inside, so it could use parse/bind/exec messages commitQuery = createQuery("COMMIT", false, true).query; rollbackQuery = createQuery("ROLLBACK", false, true).query; int unknownLength = PGProperty.UNKNOWN_LENGTH.getInt(info); // Initialize object handling typeCache = createTypeInfo(this, unknownLength); initObjectTypes(info); if (PGProperty.LOG_UNCLOSED_CONNECTIONS.getBoolean(info)) { openStackTrace = new Throwable("Connection was created at this point:"); } this.disableColumnSanitiser = PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(info); if (haveMinimumServerVersion(ServerVersion.v8_3)) { typeCache.addCoreType("uuid", Oid.UUID, Types.OTHER, "java.util.UUID", Oid.UUID_ARRAY); typeCache.addCoreType("xml", Oid.XML, Types.SQLXML, "java.sql.SQLXML", Oid.XML_ARRAY); } this.clientInfo = new Properties(); if (haveMinimumServerVersion(ServerVersion.v9_0)) { String appName = PGProperty.APPLICATION_NAME.get(info); if (appName == null) { appName = ""; } this.clientInfo.put("ApplicationName", appName); } fieldMetadataCache = new LruCache<FieldMetadata.Key, FieldMetadata>( Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS.getInt(info)), Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.getInt(info) * 1024 * 1024), false); replicationConnection = PGProperty.REPLICATION.get(info) != null; } private static ReadOnlyBehavior getReadOnlyBehavior(String property) { try { return ReadOnlyBehavior.valueOf(property); } catch (IllegalArgumentException e) { try { return ReadOnlyBehavior.valueOf(property.toLowerCase(Locale.US)); } catch (IllegalArgumentException e2) { return ReadOnlyBehavior.transaction; } } } private static Set<Integer> getSupportedBinaryOids() { return new HashSet<Integer>(Arrays.asList( Oid.BYTEA, Oid.INT2, Oid.INT4, Oid.INT8, Oid.FLOAT4, Oid.FLOAT8, Oid.TIME, Oid.DATE, Oid.TIMETZ, Oid.TIMESTAMP, Oid.TIMESTAMPTZ, Oid.INT2_ARRAY, Oid.INT4_ARRAY, Oid.INT8_ARRAY, Oid.FLOAT4_ARRAY, Oid.FLOAT8_ARRAY, Oid.VARCHAR_ARRAY, Oid.TEXT_ARRAY, Oid.POINT, Oid.BOX, Oid.UUID)); } private static Set<Integer> getBinaryOids(Properties info) throws PSQLException { boolean binaryTransfer = PGProperty.BINARY_TRANSFER.getBoolean(info); // Formats that currently have binary protocol support Set<Integer> binaryOids = new HashSet<Integer>(32); if (binaryTransfer) { binaryOids.addAll(SUPPORTED_BINARY_OIDS); } binaryOids.addAll(getOidSet(PGProperty.BINARY_TRANSFER_ENABLE.get(info))); binaryOids.removeAll(getOidSet(PGProperty.BINARY_TRANSFER_DISABLE.get(info))); binaryOids.retainAll(SUPPORTED_BINARY_OIDS); return binaryOids; } private static Set<Integer> getOidSet(String oidList) throws PSQLException { Set<Integer> oids = new HashSet<Integer>(); StringTokenizer tokenizer = new StringTokenizer(oidList, ","); while (tokenizer.hasMoreTokens()) { String oid = tokenizer.nextToken(); oids.add(Oid.valueOf(oid)); } return oids; } private String oidsToString(Set<Integer> oids) { StringBuilder sb = new StringBuilder(); for (Integer oid : oids) { sb.append(Oid.toString(oid)); sb.append(','); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } else { sb.append(" <none>"); } return sb.toString(); } private final TimestampUtils timestampUtils; public TimestampUtils getTimestampUtils() { return timestampUtils; } /** * The current type mappings. */ protected Map<String, Class<?>> typemap = new HashMap<String, Class<?>>(); @Override public Statement createStatement() throws SQLException { // We now follow the spec and default to TYPE_FORWARD_ONLY. return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return typemap; } public QueryExecutor getQueryExecutor() { return queryExecutor; } public ReplicationProtocol getReplicationProtocol() { return queryExecutor.getReplicationProtocol(); } /** * This adds a warning to the warning chain. * * @param warn warning to add */ public void addWarning(SQLWarning warn) { // Add the warning to the chain if (firstWarning != null) { firstWarning.setNextWarning(warn); } else { firstWarning = warn; } } @Override public ResultSet execSQLQuery(String s) throws SQLException { return execSQLQuery(s, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException { BaseStatement stat = (BaseStatement) createStatement(resultSetType, resultSetConcurrency); boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN); while (!hasResultSet && stat.getUpdateCount() != -1) { hasResultSet = stat.getMoreResults(); } if (!hasResultSet) { throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stat.getWarnings(); if (warnings != null) { addWarning(warnings); } return stat.getResultSet(); } @Override public void execSQLUpdate(String s) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } void execSQLUpdate(CachedQuery query) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(query, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } /** * <p>In SQL, a result table can be retrieved through a cursor that is named. The current row of a * result can be updated or deleted using a positioned update/delete statement that references the * cursor name.</p> * * <p>We do not support positioned update/delete, so this is a no-op.</p> * * @param cursor the cursor name * @throws SQLException if a database access error occurs */ public void setCursorName(String cursor) throws SQLException { checkClosed(); // No-op. } /** * getCursorName gets the cursor name. * * @return the current cursor name * @throws SQLException if a database access error occurs */ public String getCursorName() throws SQLException { checkClosed(); return null; } /** * <p>We are required to bring back certain information by the DatabaseMetaData class. These * functions do that.</p> * * <p>Method getURL() brings back the URL (good job we saved it)</p> * * @return the url * @throws SQLException just in case... */ public String getURL() throws SQLException { return creatingURL; } /** * Method getUserName() brings back the User Name (again, we saved it). * * @return the user name * @throws SQLException just in case... */ public String getUserName() throws SQLException { return queryExecutor.getUser(); } public Fastpath getFastpathAPI() throws SQLException { checkClosed(); if (fastpath == null) { fastpath = new Fastpath(this); } return fastpath; } // This holds a reference to the Fastpath API if already open private Fastpath fastpath = null; public LargeObjectManager getLargeObjectAPI() throws SQLException { checkClosed(); if (largeobject == null) { largeobject = new LargeObjectManager(this); } return largeobject; } // This holds a reference to the LargeObject API if already open private LargeObjectManager largeobject = null; /* * This method is used internally to return an object based around org.postgresql's more unique * data types. * * <p>It uses an internal HashMap to get the handling class. If the type is not supported, then an * instance of org.postgresql.util.PGobject is returned. * * You can use the getValue() or setValue() methods to handle the returned object. Custom objects * can have their own methods. * * @return PGobject for this type, and set to value * * @exception SQLException if value is not correct for this type */ @Override public Object getObject(String type, String value, byte[] byteValue) throws SQLException { if (typemap != null) { Class<?> c = typemap.get(type); if (c != null) { // Handle the type (requires SQLInput & SQLOutput classes to be implemented) throw new PSQLException(GT.tr("Custom type maps are not supported."), PSQLState.NOT_IMPLEMENTED); } } PGobject obj = null; if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Constructing object from type={0} value=<{1}>", new Object[]{type, value}); } try { Class<? extends PGobject> klass = typeCache.getPGobject(type); // If className is not null, then try to instantiate it, // It must be basetype PGobject // This is used to implement the org.postgresql unique types (like lseg, // point, etc). if (klass != null) { obj = klass.newInstance(); obj.setType(type); if (byteValue != null && obj instanceof PGBinaryObject) { PGBinaryObject binObj = (PGBinaryObject) obj; binObj.setByteValue(byteValue, 0); } else { obj.setValue(value); } } else { // If className is null, then the type is unknown. // so return a PGobject with the type set, and the value set obj = new PGobject(); obj.setType(type); obj.setValue(value); } return obj; } catch (SQLException sx) { // rethrow the exception. Done because we capture any others next throw sx; } catch (Exception ex) { throw new PSQLException(GT.tr("Failed to create object for: {0}.", type), PSQLState.CONNECTION_FAILURE, ex); } } protected TypeInfo createTypeInfo(BaseConnection conn, int unknownLength) { return new TypeInfoCache(conn, unknownLength); } public TypeInfo getTypeInfo() { return typeCache; } @Override public void addDataType(String type, String name) { try { addDataType(type, Class.forName(name).asSubclass(PGobject.class)); } catch (Exception e) { throw new RuntimeException("Cannot register new type: " + e); } } @Override public void addDataType(String type, Class<? extends PGobject> klass) throws SQLException { checkClosed(); typeCache.addDataType(type, klass); } // This initialises the objectTypes hash map private void initObjectTypes(Properties info) throws SQLException { // Add in the types that come packaged with the driver. // These can be overridden later if desired. addDataType("box", org.postgresql.geometric.PGbox.class); addDataType("circle", org.postgresql.geometric.PGcircle.class); addDataType("line", org.postgresql.geometric.PGline.class); addDataType("lseg", org.postgresql.geometric.PGlseg.class); addDataType("path", org.postgresql.geometric.PGpath.class); addDataType("point", org.postgresql.geometric.PGpoint.class); addDataType("polygon", org.postgresql.geometric.PGpolygon.class); addDataType("money", org.postgresql.util.PGmoney.class); addDataType("interval", org.postgresql.util.PGInterval.class); Enumeration<?> e = info.propertyNames(); while (e.hasMoreElements()) { String propertyName = (String) e.nextElement(); if (propertyName.startsWith("datatype.")) { String typeName = propertyName.substring(9); String className = info.getProperty(propertyName); Class<?> klass; try { klass = Class.forName(className); } catch (ClassNotFoundException cnfe) { throw new PSQLException( GT.tr("Unable to load the class {0} responsible for the datatype {1}", className, typeName), PSQLState.SYSTEM_ERROR, cnfe); } addDataType(typeName, klass.asSubclass(PGobject.class)); } } } /** * <B>Note:</B> even though {@code Statement} is automatically closed when it is garbage * collected, it is better to close it explicitly to lower resource consumption. * * {@inheritDoc} */ @Override public void close() throws SQLException { if (queryExecutor == null) { // This might happen in case constructor throws an exception (e.g. host being not available). // When that happens the connection is still registered in the finalizer queue, so it gets finalized return; } releaseTimer(); queryExecutor.close(); openStackTrace = null; } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); CachedQuery cachedQuery = queryExecutor.createQuery(sql, false, true); return cachedQuery.query.getNativeSql(); } @Override public synchronized SQLWarning getWarnings() throws SQLException { checkClosed(); SQLWarning newWarnings = queryExecutor.getWarnings(); // NB: also clears them. if (firstWarning == null) { firstWarning = newWarnings; } else { firstWarning.setNextWarning(newWarnings); // Chain them on. } return firstWarning; } @Override public synchronized void clearWarnings() throws SQLException { checkClosed(); queryExecutor.getWarnings(); // Clear and discard. firstWarning = null; } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction read-only property in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } if (readOnly != this.readOnly && autoCommit && this.readOnlyBehavior == ReadOnlyBehavior.always) { execSQLUpdate(readOnly ? setSessionReadOnly : setSessionNotReadOnly); } this.readOnly = readOnly; LOGGER.log(Level.FINE, " setReadOnly = {0}", readOnly); } @Override public boolean isReadOnly() throws SQLException { checkClosed(); return readOnly; } @Override public boolean hintReadOnly() { return readOnly && readOnlyBehavior != ReadOnlyBehavior.ignore; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); if (this.autoCommit == autoCommit) { return; } if (!this.autoCommit) { commit(); } // if the connection is read only, we need to make sure session settings are // correct when autocommit status changed if (this.readOnly && readOnlyBehavior == ReadOnlyBehavior.always) { // if we are turning on autocommit, we need to set session // to read only if (autoCommit) { this.autoCommit = true; execSQLUpdate(setSessionReadOnly); } else { // if we are turning auto commit off, we need to // disable session execSQLUpdate(setSessionNotReadOnly); } } this.autoCommit = autoCommit; LOGGER.log(Level.FINE, " setAutoCommit = {0}", autoCommit); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return this.autoCommit; } private void executeTransactionCommand(Query query) throws SQLException { int flags = QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN; if (prepareThreshold == 0) { flags |= QueryExecutor.QUERY_ONESHOT; } try { getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } catch (SQLException e) { // Don't retry composite queries as it might get partially executed if (query.getSubqueries() != null || !queryExecutor.willHealOnRetry(e)) { throw e; } query.close(); // retry getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } } @Override public void commit() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot commit when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(commitQuery); } } protected void checkClosed() throws SQLException { if (isClosed()) { throw new PSQLException(GT.tr("This connection has been closed."), PSQLState.CONNECTION_DOES_NOT_EXIST); } } @Override public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { // just log for debugging LOGGER.log(Level.FINE, "Rollback requested but no transaction in progress"); } } public TransactionState getTransactionState() { return queryExecutor.getTransactionState(); } public int getTransactionIsolation() throws SQLException { checkClosed(); String level = null; final ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered if (rs.next()) { level = rs.getString(1); } rs.close(); // TODO revisit: throw exception instead of silently eating the error in unknown cases? if (level == null) { return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } level = level.toUpperCase(Locale.US); if (level.equals("READ COMMITTED")) { return Connection.TRANSACTION_READ_COMMITTED; } if (level.equals("READ UNCOMMITTED")) { return Connection.TRANSACTION_READ_UNCOMMITTED; } if (level.equals("REPEATABLE READ")) { return Connection.TRANSACTION_REPEATABLE_READ; } if (level.equals("SERIALIZABLE")) { return Connection.TRANSACTION_SERIALIZABLE; } return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction isolation level in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } String isolationLevelName = getIsolationLevelName(level); if (isolationLevelName == null) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", level), PSQLState.NOT_IMPLEMENTED); } String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName; execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered LOGGER.log(Level.FINE, " setTransactionIsolation = {0}", isolationLevelName); } protected String getIsolationLevelName(int level) { switch (level) { case Connection.TRANSACTION_READ_COMMITTED: return "READ COMMITTED"; case Connection.TRANSACTION_SERIALIZABLE: return "SERIALIZABLE"; case Connection.TRANSACTION_READ_UNCOMMITTED: return "READ UNCOMMITTED"; case Connection.TRANSACTION_REPEATABLE_READ: return "REPEATABLE READ"; default: return null; } } public void setCatalog(String catalog) throws SQLException { checkClosed(); // no-op } public String getCatalog() throws SQLException { checkClosed(); return queryExecutor.getDatabase(); } public boolean getHideUnprivilegedObjects() { return hideUnprivilegedObjects; } /** * <p>Overrides finalize(). If called, it closes the connection.</p> * * <p>This was done at the request of <a href="mailto:rachel@enlarion.demon.co.uk">Rachel * Greenham</a> who hit a problem where multiple clients didn't close the connection, and once a * fortnight enough clients were open to kill the postgres server.</p> */ protected void finalize() throws Throwable { try { if (openStackTrace != null) { LOGGER.log(Level.WARNING, GT.tr("Finalizing a Connection that was never closed:"), openStackTrace); } close(); } finally { super.finalize(); } } /** * Get server version number. * * @return server version number */ public String getDBVersionNumber() { return queryExecutor.getServerVersion(); } /** * Get server major version. * * @return server major version */ public int getServerMajorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd return integerPart(versionTokens.nextToken()); // return X } catch (NoSuchElementException e) { return 0; } } /** * Get server minor version. * * @return server minor version */ public int getServerMinorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd versionTokens.nextToken(); // Skip aaXbb return integerPart(versionTokens.nextToken()); // return Y } catch (NoSuchElementException e) { return 0; } } @Override public boolean haveMinimumServerVersion(int ver) { return queryExecutor.getServerVersionNum() >= ver; } @Override public boolean haveMinimumServerVersion(Version ver) { return haveMinimumServerVersion(ver.getVersionNum()); } @Override public Encoding getEncoding() { return queryExecutor.getEncoding(); } @Override public byte[] encodeString(String str) throws SQLException { try { return getEncoding().encode(str); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."), PSQLState.DATA_ERROR, ioe); } } @Override public String escapeString(String str) throws SQLException { return Utils.escapeLiteral(null, str, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public boolean getStandardConformingStrings() { return queryExecutor.getStandardConformingStrings(); } // This is a cache of the DatabaseMetaData instance for this connection protected java.sql.DatabaseMetaData metadata; @Override public boolean isClosed() throws SQLException { return queryExecutor.isClosed(); } @Override public void cancelQuery() throws SQLException { checkClosed(); queryExecutor.sendQueryCancel(); } @Override public PGNotification[] getNotifications() throws SQLException { return getNotifications(-1); } @Override public PGNotification[] getNotifications(int timeoutMillis) throws SQLException { checkClosed(); getQueryExecutor().processNotifies(timeoutMillis); // Backwards-compatibility hand-holding. PGNotification[] notifications = queryExecutor.getNotifications(); return (notifications.length == 0 ? null : notifications); } /** * Handler for transaction queries. */ private class TransactionCommandHandler extends ResultHandlerBase { public void handleCompletion() throws SQLException { SQLWarning warning = getWarning(); if (warning != null) { PgConnection.this.addWarning(warning); } super.handleCompletion(); } } public int getPrepareThreshold() { return prepareThreshold; } public void setDefaultFetchSize(int fetchSize) throws SQLException { if (fetchSize < 0) { throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } this.defaultFetchSize = fetchSize; LOGGER.log(Level.FINE, " setDefaultFetchSize = {0}", fetchSize); } public int getDefaultFetchSize() { return defaultFetchSize; } public void setPrepareThreshold(int newThreshold) { this.prepareThreshold = newThreshold; LOGGER.log(Level.FINE, " setPrepareThreshold = {0}", newThreshold); } public boolean getForceBinary() { return forcebinary; } public void setForceBinary(boolean newValue) { this.forcebinary = newValue; LOGGER.log(Level.FINE, " setForceBinary = {0}", newValue); } public void setTypeMapImpl(Map<String, Class<?>> map) throws SQLException { typemap = map; } public Logger getLogger() { return LOGGER; } public int getProtocolVersion() { return queryExecutor.getProtocolVersion(); } public boolean getStringVarcharFlag() { return bindStringAsVarchar; } private CopyManager copyManager = null; public CopyManager getCopyAPI() throws SQLException { checkClosed(); if (copyManager == null) { copyManager = new CopyManager(this); } return copyManager; } public boolean binaryTransferSend(int oid) { return queryExecutor.useBinaryForSend(oid); } public int getBackendPID() { return queryExecutor.getBackendPID(); } public boolean isColumnSanitiserDisabled() { return this.disableColumnSanitiser; } public void setDisableColumnSanitiser(boolean disableColumnSanitiser) { this.disableColumnSanitiser = disableColumnSanitiser; LOGGER.log(Level.FINE, " setDisableColumnSanitiser = {0}", disableColumnSanitiser); } @Override public PreferQueryMode getPreferQueryMode() { return queryExecutor.getPreferQueryMode(); } @Override public AutoSave getAutosave() { return queryExecutor.getAutoSave(); } @Override public void setAutosave(AutoSave autoSave) { queryExecutor.setAutoSave(autoSave); LOGGER.log(Level.FINE, " setAutosave = {0}", autoSave.value()); } protected void abort() { queryExecutor.abort(); } private synchronized Timer getTimer() { if (cancelTimer == null) { cancelTimer = Driver.getSharedTimer().getTimer(); } return cancelTimer; } private synchronized void releaseTimer() { if (cancelTimer != null) { cancelTimer = null; Driver.getSharedTimer().releaseTimer(); } } @Override public void addTimerTask(TimerTask timerTask, long milliSeconds) { Timer timer = getTimer(); timer.schedule(timerTask, milliSeconds); } @Override public void purgeTimerTasks() { Timer timer = cancelTimer; if (timer != null) { timer.purge(); } } @Override public String escapeIdentifier(String identifier) throws SQLException { return Utils.escapeIdentifier(null, identifier).toString(); } @Override public String escapeLiteral(String literal) throws SQLException { return Utils.escapeLiteral(null, literal, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache() { return fieldMetadataCache; } @Override public PGReplicationConnection getReplicationAPI() { return new PGReplicationConnectionImpl(this); } private static void appendArray(StringBuilder sb, Object elements, char delim) { sb.append('{'); int nElements = java.lang.reflect.Array.getLength(elements); for (int i = 0; i < nElements; i++) { if (i > 0) { sb.append(delim); } Object o = java.lang.reflect.Array.get(elements, i); if (o == null) { sb.append("NULL"); } else if (o.getClass().isArray()) { final PrimitiveArraySupport arraySupport = PrimitiveArraySupport.getArraySupport(o); if (arraySupport != null) { arraySupport.appendArray(sb, delim, o); } else { appendArray(sb, o, delim); } } else { String s = o.toString(); PgArray.escapeArrayElement(sb, s); } } sb.append('}'); } // Parse a "dirty" integer surrounded by non-numeric characters private static int integerPart(String dirtyString) { int start = 0; while (start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start))) { ++start; } int end = start; while (end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end))) { ++end; } if (start == end) { return 0; } return Integer.parseInt(dirtyString.substring(start, end)); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgPreparedStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgCallableStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); if (metadata == null) { metadata = new PgDatabaseMetaData(this); } return metadata; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { setTypeMapImpl(map); LOGGER.log(Level.FINE, " setTypeMap = {0}", map); } protected Array makeArray(int oid, String fieldString) throws SQLException { return new PgArray(this, oid, fieldString); } protected Blob makeBlob(long oid) throws SQLException { return new PgBlob(this, oid); } protected Clob makeClob(long oid) throws SQLException { return new PgClob(this, oid); } protected SQLXML makeSQLXML() throws SQLException { return new PgSQLXML(this); } @Override public Clob createClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createClob()"); } @Override public Blob createBlob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createBlob()"); } @Override public NClob createNClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createNClob()"); } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); return makeSQLXML(); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createStruct(String, Object[])"); } @Override public Array createArrayOf(String typeName, Object elements) throws SQLException { checkClosed(); final TypeInfo typeInfo = getTypeInfo(); final int oid = typeInfo.getPGArrayType(typeName); final char delim = typeInfo.getArrayDelimiter(oid); if (oid == Oid.UNSPECIFIED) { throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); } if (elements == null) { return makeArray(oid, null); } final String arrayString; final PrimitiveArraySupport arraySupport = PrimitiveArraySupport.getArraySupport(elements); if (arraySupport != null) { // if the oid for the given type matches the default type, we might be // able to go straight to binary representation if (oid == arraySupport.getDefaultArrayTypeOid(typeInfo) && arraySupport.supportBinaryRepresentation() && getPreferQueryMode() != PreferQueryMode.SIMPLE) { return new PgArray(this, oid, arraySupport.toBinaryRepresentation(this, elements)); } arrayString = arraySupport.toArrayString(delim, elements); } else { final Class<?> clazz = elements.getClass(); if (!clazz.isArray()) { throw new PSQLException(GT.tr("Invalid elements {0}", elements), PSQLState.INVALID_PARAMETER_TYPE); } StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); arrayString = sb.toString(); } return makeArray(oid, arrayString); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); int oid = getTypeInfo().getPGArrayType(typeName); if (oid == Oid.UNSPECIFIED) { throw new PSQLException( GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); } if (elements == null) { return makeArray(oid, null); } char delim = getTypeInfo().getArrayDelimiter(oid); StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); return makeArray(oid, sb.toString()); } @Override public boolean isValid(int timeout) throws SQLException { if (timeout < 0) { throw new PSQLException(GT.tr("Invalid timeout ({0}<0).", timeout), PSQLState.INVALID_PARAMETER_VALUE); } if (isClosed()) { return false; } try { int savedNetworkTimeOut = getNetworkTimeout(); try { setNetworkTimeout(null, timeout * 1000); if (replicationConnection) { Statement statement = createStatement(); statement.execute("IDENTIFY_SYSTEM"); statement.close(); } else { if (checkConnectionQuery == null) { checkConnectionQuery = prepareStatement(""); } checkConnectionQuery.setQueryTimeout(timeout); checkConnectionQuery.executeUpdate(); } return true; } finally { setNetworkTimeout(null, savedNetworkTimeOut); } } catch (SQLException e) { if (PSQLState.IN_FAILED_SQL_TRANSACTION.getState().equals(e.getSQLState())) { // "current transaction aborted", assume the connection is up and running return true; } LOGGER.log(Level.FINE, GT.tr("Validating connection."), e); } return false; } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } if (haveMinimumServerVersion(ServerVersion.v9_0) && "ApplicationName".equals(name)) { if (value == null) { value = ""; } final String oldValue = queryExecutor.getApplicationName(); if (value.equals(oldValue)) { return; } try { StringBuilder sql = new StringBuilder("SET application_name = '"); Utils.escapeLiteral(sql, value, getStandardConformingStrings()); sql.append("'"); execSQLUpdate(sql.toString()); } catch (SQLException sqle) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException( GT.tr("Failed to set ClientInfo property: {0}", "ApplicationName"), sqle.getSQLState(), failures, sqle); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, " setClientInfo = {0} {1}", new Object[]{name, value}); } clientInfo.put(name, value); return; } addWarning(new SQLWarning(GT.tr("ClientInfo property not supported."), PSQLState.NOT_IMPLEMENTED.getState())); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (Map.Entry<Object, Object> e : properties.entrySet()) { failures.put((String) e.getKey(), ClientInfoStatus.REASON_UNKNOWN); } throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (String name : new String[]{"ApplicationName"}) { try { setClientInfo(name, properties.getProperty(name, null)); } catch (SQLClientInfoException e) { failures.putAll(e.getFailedProperties()); } } if (!failures.isEmpty()) { throw new SQLClientInfoException(GT.tr("One or more ClientInfo failed."), PSQLState.NOT_IMPLEMENTED.getState(), failures); } } @Override public String getClientInfo(String name) throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo.getProperty(name); } @Override public Properties getClientInfo() throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo; } public <T> T createQueryObject(Class<T> ifc) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createQueryObject(Class<T>)"); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { checkClosed(); return iface.isAssignableFrom(getClass()); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { checkClosed(); if (iface.isAssignableFrom(getClass())) { return iface.cast(this); } throw new SQLException("Cannot unwrap to " + iface.getName()); } public String getSchema() throws SQLException { checkClosed(); Statement stmt = createStatement(); try { ResultSet rs = stmt.executeQuery("select current_schema()"); try { if (!rs.next()) { return null; // Is it ever possible? } return rs.getString(1); } finally { rs.close(); } } finally { stmt.close(); } } public void setSchema(String schema) throws SQLException { checkClosed(); Statement stmt = createStatement(); try { if (schema == null) { stmt.executeUpdate("SET SESSION search_path TO DEFAULT"); } else { StringBuilder sb = new StringBuilder(); sb.append("SET SESSION search_path TO '"); Utils.escapeLiteral(sb, schema, getStandardConformingStrings()); sb.append("'"); stmt.executeUpdate(sb.toString()); LOGGER.log(Level.FINE, " setSchema = {0}", schema); } } finally { stmt.close(); } } public class AbortCommand implements Runnable { public void run() { abort(); } } public void abort(Executor executor) throws SQLException { if (executor == null) { throw new SQLException("executor is null"); } if (isClosed()) { return; } SQL_PERMISSION_ABORT.checkGuard(this); AbortCommand command = new AbortCommand(); executor.execute(command); } public void setNetworkTimeout(Executor executor /*not used*/, int milliseconds) throws SQLException { checkClosed(); if (milliseconds < 0) { throw new PSQLException(GT.tr("Network timeout must be a value greater than or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { securityManager.checkPermission(SQL_PERMISSION_NETWORK_TIMEOUT); } try { queryExecutor.setNetworkTimeout(milliseconds); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to set network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } public int getNetworkTimeout() throws SQLException { checkClosed(); try { return queryExecutor.getNetworkTimeout(); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to get network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); switch (holdability) { case ResultSet.CLOSE_CURSORS_AT_COMMIT: rsHoldability = holdability; break; case ResultSet.HOLD_CURSORS_OVER_COMMIT: rsHoldability = holdability; break; default: throw new PSQLException(GT.tr("Unknown ResultSet holdability setting: {0}.", holdability), PSQLState.INVALID_PARAMETER_VALUE); } LOGGER.log(Level.FINE, " setHoldability = {0}", holdability); } @Override public int getHoldability() throws SQLException { checkClosed(); return rsHoldability; } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); String pgName; if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(savepointId++); pgName = savepoint.getPGName(); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + pgName); stmt.close(); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(name); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + savepoint.getPGName()); stmt.close(); return savepoint; } @Override public void rollback(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("ROLLBACK TO SAVEPOINT " + pgSavepoint.getPGName()); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("RELEASE SAVEPOINT " + pgSavepoint.getPGName()); pgSavepoint.invalidate(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return createStatement(resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareStatement(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareCall(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS) { return prepareStatement(sql); } return prepareStatement(sql, (String[]) null); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { if (columnIndexes != null && columnIndexes.length == 0) { return prepareStatement(sql); } checkClosed(); throw new PSQLException(GT.tr("Returning autogenerated keys is not supported."), PSQLState.NOT_IMPLEMENTED); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { if (columnNames != null && columnNames.length == 0) { return prepareStatement(sql); } CachedQuery cachedQuery = borrowReturningQuery(sql, columnNames); PgPreparedStatement ps = new PgPreparedStatement(this, cachedQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, getHoldability()); Query query = cachedQuery.query; SqlCommand sqlCommand = query.getSqlCommand(); if (sqlCommand != null) { ps.wantsGeneratedKeysAlways = sqlCommand.isReturningKeywordPresent(); } else { // If composite query is given, just ignore "generated keys" arguments } return ps; } @Override public final Map<String,String> getParameterStatuses() { return queryExecutor.getParameterStatuses(); } @Override public final String getParameterStatus(String parameterName) { return queryExecutor.getParameterStatus(parameterName); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4033_3
crossvul-java_data_good_1737_0
/* * Copyright 2015 McEvoy Software Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.milton.http.http11.auth; import io.milton.common.Utils; import io.milton.http.OAuth2TokenResponse; import io.milton.resource.OAuth2Resource.OAuth2ProfileDetails; import io.milton.resource.OAuth2Provider; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import org.apache.oltu.oauth2.client.OAuthClient; import org.apache.oltu.oauth2.client.URLConnectionClient; import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse; import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; import org.apache.oltu.oauth2.client.response.OAuthResourceResponse; import org.apache.oltu.oauth2.common.OAuth; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.message.types.GrantType; import org.apache.oltu.oauth2.common.utils.JSONUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Lee YOU */ public class OAuth2Helper { private static final Logger log = LoggerFactory.getLogger(OAuth2Helper.class); public static URL getOAuth2URL(OAuth2Provider provider) { log.trace("getOAuth2URL {}", provider); String oAuth2Location = provider.getAuthLocation(); String oAuth2ClientId = provider.getClientId(); String scopes = Utils.toCsv(provider.getPermissionScopes(), false); try { OAuthClientRequest oAuthRequest = OAuthClientRequest .authorizationLocation(oAuth2Location) .setClientId(oAuth2ClientId) .setResponseType("code") .setScope(scopes) .setState(provider.getProviderId()) .setRedirectURI(provider.getRedirectURI()) .buildQueryMessage(); return new URL(oAuthRequest.getLocationUri()); } catch (OAuthSystemException oAuthSystemException) { throw new RuntimeException(oAuthSystemException); } catch (MalformedURLException malformedURLException) { throw new RuntimeException(malformedURLException); } } private final NonceProvider nonceProvider; public OAuth2Helper(NonceProvider nonceProvider) { this.nonceProvider = nonceProvider; } // Sept 2, After Got The Authorization Code(a Access Permission), then Granting the Access Token. public OAuthAccessTokenResponse obtainAuth2Token(OAuth2Provider provider, String accessCode) throws OAuthSystemException, OAuthProblemException { log.trace("obtainAuth2Token code={}, provider={}", accessCode, provider); String oAuth2ClientId = provider.getClientId(); String oAuth2TokenLocation = provider.getTokenLocation(); String oAuth2ClientSecret = provider.getClientSecret(); String oAuth2RedirectURI = provider.getRedirectURI(); OAuthClientRequest oAuthRequest = OAuthClientRequest .tokenLocation(oAuth2TokenLocation) .setGrantType(GrantType.AUTHORIZATION_CODE) .setRedirectURI(oAuth2RedirectURI) .setCode(accessCode) .setClientId(oAuth2ClientId) .setClientSecret(oAuth2ClientSecret) .buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); // This works for facebook OAuthAccessTokenResponse oAuth2Response2 = oAuthClient.accessToken(oAuthRequest, OAuth2TokenResponse.class); //return oAuth2Response; // This might work for google OAuthJSONAccessTokenResponse o; //OAuthAccessTokenResponse oAuth2Response2 = oAuthClient.accessToken(oAuthRequest, OAuth2TokenResponse.class); return oAuth2Response2; } // Sept 3, GET the profile of the user. public OAuthResourceResponse getOAuth2Profile(OAuthAccessTokenResponse oAuth2Response, OAuth2Provider provider) throws OAuthSystemException, OAuthProblemException { log.trace("getOAuth2Profile start {}", oAuth2Response); String accessToken = oAuth2Response.getAccessToken(); String userProfileLocation = provider.getProfileLocation(); OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(userProfileLocation) .setAccessToken(accessToken) .buildQueryMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); return oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class); } public OAuth2ProfileDetails getOAuth2UserInfo(OAuthResourceResponse resourceResponse, OAuthAccessTokenResponse tokenResponse, String oAuth2Code) { log.trace(" getOAuth2UserId start..." + resourceResponse); if (resourceResponse == null) { return null; } String resourceResponseBody = resourceResponse.getBody(); log.trace(" OAuthResourceResponse, body{}" + resourceResponseBody); Map responseMap = JSONUtils.parseJSON(resourceResponseBody); String userID = (String) responseMap.get("id"); String userName = (String) responseMap.get("username"); OAuth2ProfileDetails user = new OAuth2ProfileDetails(); user.setCode(oAuth2Code); user.setAccessToken(tokenResponse.getAccessToken()); user.setDetails(responseMap); if (log.isTraceEnabled()) { log.trace(" userID{}" + userID); log.trace(" userName{}" + userName); log.trace(" oAuth2Code{}" + oAuth2Code); log.trace(" AccessToken{}" + user.getAccessToken()); log.trace("\n\n"); } return user; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1737_0
crossvul-java_data_good_3279_1
/* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.designer.web.server; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.*; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import bpsim.impl.BpsimFactoryImpl; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.html.simpleparser.HTMLWorker; import com.lowagie.text.pdf.PdfWriter; import org.apache.batik.transcoder.SVGAbstractTranscoder; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.ImageTranscoder; import org.apache.batik.transcoder.image.PNGTranscoder; import org.apache.commons.codec.binary.Base64; import org.eclipse.bpmn2.DataInputAssociation; import org.eclipse.bpmn2.Definitions; import org.eclipse.bpmn2.FlowElement; import org.eclipse.bpmn2.FlowElementsContainer; import org.eclipse.bpmn2.FlowNode; import org.eclipse.bpmn2.FormalExpression; import org.eclipse.bpmn2.Process; import org.eclipse.bpmn2.RootElement; import org.eclipse.bpmn2.SequenceFlow; import org.eclipse.bpmn2.Task; import org.eclipse.bpmn2.UserTask; import org.eclipse.bpmn2.di.BPMNDiagram; import org.eclipse.bpmn2.di.BPMNEdge; import org.eclipse.bpmn2.di.BPMNPlane; import org.eclipse.bpmn2.di.BPMNShape; import org.eclipse.bpmn2.di.BpmnDiFactory; import org.eclipse.dd.dc.Bounds; import org.eclipse.dd.dc.DcFactory; import org.eclipse.dd.dc.Point; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.util.FeatureMap; import org.jboss.drools.impl.DroolsFactoryImpl; import org.jbpm.designer.bpmn2.resource.JBPMBpmn2ResourceFactoryImpl; import org.jbpm.designer.bpmn2.resource.JBPMBpmn2ResourceImpl; import org.jbpm.designer.repository.Asset; import org.jbpm.designer.repository.AssetBuilderFactory; import org.jbpm.designer.repository.Repository; import org.jbpm.designer.repository.impl.AssetBuilder; import org.jbpm.designer.util.Utils; import org.jbpm.designer.web.profile.IDiagramProfile; import org.jbpm.designer.web.profile.IDiagramProfileService; import org.jbpm.designer.web.profile.impl.JbpmProfileImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Transformer for svg process representation to * various formats. * * @author Tihomir Surdilovic */ public class TransformerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger _logger = LoggerFactory.getLogger(TransformerServlet.class); private static final String TO_PDF = "pdf"; private static final String TO_PNG = "png"; private static final String TO_SVG = "svg"; private static final String BPMN2_TO_JSON = "bpmn2json"; private static final String JSON_TO_BPMN2 = "json2bpmn2"; private static final String HTML_TO_PDF = "html2pdf"; private static final String RESPACTION_SHOWURL = "showurl"; private static final String SVG_WIDTH_PARAM = "svgwidth"; private static final String SVG_HEIGHT_PARAM = "svgheight"; private static final float DEFAULT_PDF_WIDTH = (float) 750.0; private static final float DEFAULT_PDF_HEIGHT = (float) 500.0; static { StringTokenizer html2pdfTagsSupported = new StringTokenizer("ol ul li a pre font span br p div body table td th tr i b u sub sup em strong s strike h1 h2 h3 h4 h5 h6"); HTMLWorker.tagsSupported.clear(); while(html2pdfTagsSupported.hasMoreTokens()) { HTMLWorker.tagsSupported.put(html2pdfTagsSupported.nextToken(), null); } } private IDiagramProfile profile; // For unit testing purpose only public void setProfile(IDiagramProfile profile) { this.profile = profile; } @Inject private IDiagramProfileService _profileService = null; @Override public void init(ServletConfig config) throws ServletException { super.init(config); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String formattedSvgEncoded = req.getParameter("fsvg"); String uuid = Utils.getUUID(req); String profileName = Utils.getDefaultProfileName(req.getParameter("profile")); String transformto = req.getParameter("transformto"); String jpdl = req.getParameter("jpdl"); String gpd = req.getParameter("gpd"); String bpmn2in = req.getParameter("bpmn2"); String jsonin = req.getParameter("json"); String preprocessingData = req.getParameter("pp"); String respaction = req.getParameter("respaction"); String pp = req.getParameter("pp"); String processid = req.getParameter("processid"); String sourceEnc = req.getParameter("enc"); String convertServiceTasks = req.getParameter("convertservicetasks"); String htmlSourceEnc = req.getParameter("htmlenc"); String formattedSvg = ( formattedSvgEncoded == null ? "" : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8") ); String htmlSource = ( htmlSourceEnc == null ? "" : new String(Base64.decodeBase64(htmlSourceEnc), "UTF-8") ); if(sourceEnc != null && sourceEnc.equals("true")) { bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8"); } if (profile == null) { profile = _profileService.findProfile(req, profileName); } DroolsFactoryImpl.init(); BpsimFactoryImpl.init(); Repository repository = profile.getRepository(); if (transformto != null && transformto.equals(TO_PDF)) { if(respaction != null && respaction.equals(RESPACTION_SHOWURL)) { try { ByteArrayOutputStream pdfBout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfBout); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); float widthHint = getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH); float heightHint = getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT); String objStyle = "style=\"width:" + widthHint + "px;height:" + heightHint + "px;\""; t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, widthHint); t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, heightHint); ByteArrayOutputStream imageBout = new ByteArrayOutputStream(); TranscoderInput input = new TranscoderInput(new StringReader( formattedSvg)); TranscoderOutput output = new TranscoderOutput(imageBout); t.transcode(input, output); Image processImage = Image.getInstance(imageBout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); resp.getWriter().write("<object type=\"application/pdf\" " + objStyle + " data=\"data:application/pdf;base64," + Base64.encodeBase64String(pdfBout.toByteArray()) + "\"></object>"); } catch(Exception e) { resp.sendError(500, e.getMessage()); } } else { storeInRepository(uuid, formattedSvg, transformto, processid, repository); try { resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/pdf"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\""); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream()); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); Image processImage = Image.getInstance(bout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); } catch(Exception e) { resp.sendError(500, e.getMessage()); } } } else if (transformto != null && transformto.equals(TO_PNG)) { try { if(respaction != null && respaction.equals(RESPACTION_SHOWURL)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); if(req.getParameter(SVG_WIDTH_PARAM) != null && req.getParameter(SVG_HEIGHT_PARAM) != null) { int widthHint = (int) getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH); int heightHint = (int) getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT); resp.getWriter().write("<img width=\"" + widthHint + "\" height=\"" + heightHint + "\" src=\"data:image/png;base64," + Base64.encodeBase64String(bout.toByteArray()) + "\">"); } else { resp.getWriter().write("<img src=\"data:image/png;base64," + Base64.encodeBase64String(bout.toByteArray()) + "\">"); } } else { storeInRepository(uuid, formattedSvg, transformto, processid, repository); resp.setContentType("image/png"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\""); } PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( formattedSvg)); TranscoderOutput output = new TranscoderOutput( resp.getOutputStream()); t.transcode(input, output); } } catch (TranscoderException e) { resp.sendError(500, e.getMessage()); } } else if (transformto != null && transformto.equals(TO_SVG)) { storeInRepository(uuid, formattedSvg, transformto, processid, repository); } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) { try { if(convertServiceTasks != null && convertServiceTasks.equals("true")) { bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\""); bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\""); } Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in); def.setTargetNamespace("http://www.omg.org/bpmn20"); if(convertServiceTasks != null && convertServiceTasks.equals("true")) { // fix the data input associations for converted tasks List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { updateTaskDataInputs((Process) root, def); } } } // get the xml from Definitions ResourceSet rSet = new ResourceSetImpl(); rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2", new JBPMBpmn2ResourceFactoryImpl()); JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet.createResource(URI.createURI("virtual.bpmn2")); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8"); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION, true); bpmn2resource.getDefaultLoadOptions().put( JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true ); bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF, JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD); bpmn2resource.setEncoding("UTF-8"); rSet.getResources().add(bpmn2resource); bpmn2resource.getContents().add(def); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bpmn2resource.save(outputStream, new HashMap<Object, Object>()); String revisedXmlModel = outputStream.toString(); String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json"); resp.getWriter().print(json); } catch(Exception e) { e.printStackTrace(); _logger.error(e.getMessage()); resp.setContentType("application/json"); resp.getWriter().print("{}"); } } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) { try { DroolsFactoryImpl.init(); BpsimFactoryImpl.init(); if(preprocessingData == null) { preprocessingData = ""; } String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData); resp.setContentType("application/xml"); resp.getWriter().print(processXML); } catch(Exception e) { e.printStackTrace(); _logger.error(e.getMessage()); resp.setContentType("application/xml"); resp.getWriter().print(""); } } else if (transformto != null && transformto.equals(HTML_TO_PDF)) { try { resp.setContentType("application/pdf"); if (processid != null) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\""); } else { resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\""); } Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream()); pdfDoc.open(); pdfDoc.addCreator("jBPM Designer"); pdfDoc.addSubject("Business Process Documentation"); pdfDoc.addCreationDate(); pdfDoc.addTitle("Process Documentation"); HTMLWorker htmlWorker = new HTMLWorker(pdfDoc); htmlWorker.parse(new StringReader(htmlSource)); pdfDoc.close(); } catch(DocumentException e) { resp.sendError(500, e.getMessage()); } } } private void updateTaskDataInputs(FlowElementsContainer container, Definitions def) { List<FlowElement> flowElements = container.getFlowElements(); for(FlowElement fe : flowElements) { if(fe instanceof Task && !(fe instanceof UserTask)) { Task task = (Task) fe; boolean foundReadOnlyServiceTask = false; Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator(); while(iter.hasNext()) { FeatureMap.Entry entry = iter.next(); if(entry.getEStructuralFeature().getName().equals("taskName")) { if(entry.getValue().equals("ReadOnlyService")) { foundReadOnlyServiceTask = true; } } } if(foundReadOnlyServiceTask) { if(task.getDataInputAssociations() != null) { List<DataInputAssociation> dataInputAssociations = task.getDataInputAssociations(); for(DataInputAssociation dia : dataInputAssociations) { if(dia.getTargetRef().getId().endsWith("TaskNameInput")) { ((FormalExpression) dia.getAssignment().get(0).getFrom()).setBody("ReadOnlyService"); } } } } } else if(fe instanceof FlowElementsContainer) { updateTaskDataInputs((FlowElementsContainer) fe, def); } } } private void revisitNodeNames(Definitions def) { List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { Process process = (Process) root; List<FlowElement> flowElements = process.getFlowElements(); for(FlowElement fe : flowElements) { if(fe.getName() != null && fe.getId().equals(fe.getName())) { // change the name so they are not the same fe.setName("_" + fe.getName()); } } } } } private void revisitSequenceFlows(Definitions def, String orig) { try { Map<String, Map<String, String>> sequenceFlowMapping = new HashMap<String, Map<String,String>>(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(orig)); while(reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("sequenceFlow".equals(reader.getLocalName())) { String id = ""; String source = ""; String target = ""; for (int i = 0 ; i < reader.getAttributeCount() ; i++) { if ("id".equals(reader.getAttributeLocalName(i))) { id = reader.getAttributeValue(i); } if ("sourceRef".equals(reader.getAttributeLocalName(i))) { source = reader.getAttributeValue(i); } if ("targetRef".equals(reader.getAttributeLocalName(i))) { target = reader.getAttributeValue(i); } } Map<String, String> valueMap = new HashMap<String, String>(); valueMap.put("sourceRef", source); valueMap.put("targetRef", target); sequenceFlowMapping.put(id, valueMap); } } } List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { Process process = (Process) root; List<FlowElement> flowElements = process.getFlowElements(); for(FlowElement fe : flowElements) { if(fe instanceof SequenceFlow) { SequenceFlow sf = (SequenceFlow) fe; if(sequenceFlowMapping.containsKey(sf.getId())) { sf.setSourceRef(getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("sourceRef"))); sf.setTargetRef(getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("targetRef"))); } else { _logger.error("Could not find mapping for sequenceFlow: " + sf.getId()); } } } } } } catch (FactoryConfigurationError e) { _logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { _logger.error(e.getMessage()); e.printStackTrace(); } } private FlowNode getFlowNode(Definitions def, String nodeId) { List<RootElement> rootElements = def.getRootElements(); for(RootElement root : rootElements) { if(root instanceof Process) { Process process = (Process) root; List<FlowElement> flowElements = process.getFlowElements(); for(FlowElement fe : flowElements) { if(fe instanceof FlowNode) { if(fe.getId().equals(nodeId)) { return (FlowNode) fe; } } } } } return null; } private void addBpmnDiInfo(Definitions def, String gpd) { try { Map<String, Bounds> _bounds = new HashMap<String, Bounds>(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(gpd)); while(reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("node".equals(reader.getLocalName())) { Bounds b = DcFactory.eINSTANCE.createBounds(); String nodeName = null; String nodeX = null; String nodeY = null; String nodeWidth = null; String nodeHeight = null; for (int i = 0 ; i < reader.getAttributeCount() ; i++) { if ("name".equals(reader.getAttributeLocalName(i))) { nodeName = reader.getAttributeValue(i); } else if("x".equals(reader.getAttributeLocalName(i))) { nodeX = reader.getAttributeValue(i); } else if("y".equals(reader.getAttributeLocalName(i))) { nodeY = reader.getAttributeValue(i); } else if("width".equals(reader.getAttributeLocalName(i))) { nodeWidth = reader.getAttributeValue(i); } else if("height".equals(reader.getAttributeLocalName(i))) { nodeHeight = reader.getAttributeValue(i); } } b.setX(new Float(nodeX).floatValue()); b.setY(new Float(nodeY).floatValue()); b.setWidth(new Float(nodeWidth).floatValue()); b.setHeight(new Float(nodeHeight).floatValue()); _bounds.put(nodeName, b); } } } for (RootElement rootElement: def.getRootElements()) { if (rootElement instanceof Process) { Process process = (Process) rootElement; BpmnDiFactory diFactory = BpmnDiFactory.eINSTANCE; BPMNDiagram diagram = diFactory.createBPMNDiagram(); BPMNPlane plane = diFactory.createBPMNPlane(); plane.setBpmnElement(process); diagram.setPlane(plane); for (FlowElement flowElement: process.getFlowElements()) { if (flowElement instanceof FlowNode) { Bounds b = _bounds.get(flowElement.getId()); if (b != null) { BPMNShape shape = diFactory.createBPMNShape(); shape.setBpmnElement(flowElement); shape.setBounds(b); plane.getPlaneElement().add(shape); } } else if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; BPMNEdge edge = diFactory.createBPMNEdge(); edge.setBpmnElement(flowElement); DcFactory dcFactory = DcFactory.eINSTANCE; Point point = dcFactory.createPoint(); if(sequenceFlow.getSourceRef() != null) { Bounds sourceBounds = _bounds.get(sequenceFlow.getSourceRef().getId()); point.setX(sourceBounds.getX() + (sourceBounds.getWidth()/2)); point.setY(sourceBounds.getY() + (sourceBounds.getHeight()/2)); } edge.getWaypoint().add(point); // List<Point> dockers = _dockers.get(sequenceFlow.getId()); // for (int i = 1; i < dockers.size() - 1; i++) { // edge.getWaypoint().add(dockers.get(i)); // } point = dcFactory.createPoint(); if(sequenceFlow.getTargetRef() != null) { Bounds targetBounds = _bounds.get(sequenceFlow.getTargetRef().getId()); point.setX(targetBounds.getX() + (targetBounds.getWidth()/2)); point.setY(targetBounds.getY() + (targetBounds.getHeight()/2)); } edge.getWaypoint().add(point); plane.getPlaneElement().add(edge); } } def.getDiagrams().add(diagram); } } } catch (FactoryConfigurationError e) { _logger.error("Exception adding bpmndi info: " + e.getMessage()); } catch (Exception e) { _logger.error("Exception adding bpmndi info: " + e.getMessage()); } } protected void storeInRepository(String uuid, String svg, String transformto, String processid, Repository repository) { String assetFullName = ""; try { if(processid != null) { Asset<byte[]> processAsset = repository.loadAsset(uuid); String assetExt = ""; String assetFileExt = ""; if(transformto.equals(TO_PDF)) { assetExt = "-pdf"; assetFileExt = ".pdf"; } if(transformto.equals(TO_PNG)) { assetExt = "-image"; assetFileExt = ".png"; } if(transformto.equals(TO_SVG)) { assetExt = "-svg"; assetFileExt = ".svg"; } if(processid.startsWith(".")) { processid = processid.substring(1, processid.length()); } assetFullName = processid + assetExt + assetFileExt; repository.deleteAssetFromPath(processAsset.getAssetLocation() + File.separator + assetFullName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (transformto.equals(TO_PDF)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); Document pdfDoc = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, outputStream); pdfDoc.open(); pdfDoc.addCreationDate(); PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( svg)); TranscoderOutput output = new TranscoderOutput(bout); t.transcode(input, output); Image processImage = Image.getInstance(bout.toByteArray()); scalePDFImage(pdfDoc, processImage); pdfDoc.add(processImage); pdfDoc.close(); } else if (transformto.equals(TO_PNG)) { PNGTranscoder t = new PNGTranscoder(); t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen"); TranscoderInput input = new TranscoderInput(new StringReader( svg)); TranscoderOutput output = new TranscoderOutput(outputStream); try { t.transcode(input, output); } catch (Exception e) { // issue with batik here..do not make a big deal _logger.debug(e.getMessage()); } } else if(transformto.equals(TO_SVG)) { OutputStreamWriter outStreamWriter = new OutputStreamWriter(outputStream); outStreamWriter.write(svg); outStreamWriter.close(); } AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte); builder.name(processid + assetExt) .type(assetFileExt.substring(1)) .location(processAsset.getAssetLocation()) .version(processAsset.getVersion()) .content(outputStream.toByteArray()); Asset<byte[]> resourceAsset = builder.getAsset(); repository.createAsset(resourceAsset); } } catch (Exception e) { // just log that error happened if (e.getMessage() != null) { _logger.error(e.getMessage()); } else { _logger.error(e.getClass().toString() + " " + assetFullName); } e.printStackTrace(); } } private String getProcessContent(String uuid, Repository repository) { try { Asset<String> processAsset = repository.loadAsset(uuid); return processAsset.getAssetContent(); } catch (Exception e) { // we dont want to barf..just log that error happened _logger.error(e.getMessage()); return ""; } } private float getFloatParam(final HttpServletRequest req, final String paramName, final float defaultValue) { float value = defaultValue; String paramValue = req.getParameter(paramName); if (paramValue != null && !paramValue.isEmpty()) { try { value = Float.parseFloat(paramValue); } catch (NumberFormatException nfe) { value = defaultValue; } } return value; } public void scalePDFImage(Document document, Image image) { float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()) / image.getWidth()) * 100; image.scalePercent(scaler); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_3279_1
crossvul-java_data_bad_4033_1
/* * Copyright (c) 2003, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.core; import org.postgresql.PGConnection; import org.postgresql.PGProperty; import org.postgresql.jdbc.FieldMetadata; import org.postgresql.jdbc.TimestampUtils; import org.postgresql.util.LruCache; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.TimerTask; /** * Driver-internal connection interface. Application code should not use this interface. */ public interface BaseConnection extends PGConnection, Connection { /** * Cancel the current query executing on this connection. * * @throws SQLException if something goes wrong. */ void cancelQuery() throws SQLException; /** * Execute a SQL query that returns a single resultset. Never causes a new transaction to be * started regardless of the autocommit setting. * * @param s the query to execute * @return the (non-null) returned resultset * @throws SQLException if something goes wrong. */ ResultSet execSQLQuery(String s) throws SQLException; ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException; /** * Execute a SQL query that does not return results. Never causes a new transaction to be started * regardless of the autocommit setting. * * @param s the query to execute * @throws SQLException if something goes wrong. */ void execSQLUpdate(String s) throws SQLException; /** * Get the QueryExecutor implementation for this connection. * * @return the (non-null) executor */ QueryExecutor getQueryExecutor(); /** * Internal protocol for work with physical and logical replication. Physical replication available * only since PostgreSQL version 9.1. Logical replication available only since PostgreSQL version 9.4. * * @return not null replication protocol */ ReplicationProtocol getReplicationProtocol(); /** * <p>Construct and return an appropriate object for the given type and value. This only considers * the types registered via {@link org.postgresql.PGConnection#addDataType(String, Class)} and * {@link org.postgresql.PGConnection#addDataType(String, String)}.</p> * * <p>If no class is registered as handling the given type, then a generic * {@link org.postgresql.util.PGobject} instance is returned.</p> * * @param type the backend typename * @param value the type-specific string representation of the value * @param byteValue the type-specific binary representation of the value * @return an appropriate object; never null. * @throws SQLException if something goes wrong */ Object getObject(String type, String value, byte[] byteValue) throws SQLException; Encoding getEncoding() throws SQLException; TypeInfo getTypeInfo(); /** * <p>Check if we have at least a particular server version.</p> * * <p>The input version is of the form xxyyzz, matching a PostgreSQL version like xx.yy.zz. So 9.0.12 * is 90012.</p> * * @param ver the server version to check, of the form xxyyzz eg 90401 * @return true if the server version is at least "ver". */ boolean haveMinimumServerVersion(int ver); /** * <p>Check if we have at least a particular server version.</p> * * <p>The input version is of the form xxyyzz, matching a PostgreSQL version like xx.yy.zz. So 9.0.12 * is 90012.</p> * * @param ver the server version to check * @return true if the server version is at least "ver". */ boolean haveMinimumServerVersion(Version ver); /** * Encode a string using the database's client_encoding (usually UTF8, but can vary on older * server versions). This is used when constructing synthetic resultsets (for example, in metadata * methods). * * @param str the string to encode * @return an encoded representation of the string * @throws SQLException if something goes wrong. */ byte[] encodeString(String str) throws SQLException; /** * Escapes a string for use as string-literal within an SQL command. The method chooses the * applicable escaping rules based on the value of {@link #getStandardConformingStrings()}. * * @param str a string value * @return the escaped representation of the string * @throws SQLException if the string contains a {@code \0} character */ String escapeString(String str) throws SQLException; /** * Returns whether the server treats string-literals according to the SQL standard or if it uses * traditional PostgreSQL escaping rules. Versions up to 8.1 always treated backslashes as escape * characters in string-literals. Since 8.2, this depends on the value of the * {@code standard_conforming_strings} server variable. * * @return true if the server treats string literals according to the SQL standard * @see QueryExecutor#getStandardConformingStrings() */ boolean getStandardConformingStrings(); // Ew. Quick hack to give access to the connection-specific utils implementation. TimestampUtils getTimestampUtils(); // Get the per-connection logger. java.util.logging.Logger getLogger(); // Get the bind-string-as-varchar config flag boolean getStringVarcharFlag(); /** * Get the current transaction state of this connection. * * @return current transaction state of this connection */ TransactionState getTransactionState(); /** * Returns true if value for the given oid should be sent using binary transfer. False if value * should be sent using text transfer. * * @param oid The oid to check. * @return True for binary transfer, false for text transfer. */ boolean binaryTransferSend(int oid); /** * Return whether to disable column name sanitation. * * @return true column sanitizer is disabled */ boolean isColumnSanitiserDisabled(); /** * Schedule a TimerTask for later execution. The task will be scheduled with the shared Timer for * this connection. * * @param timerTask timer task to schedule * @param milliSeconds delay in milliseconds */ void addTimerTask(TimerTask timerTask, long milliSeconds); /** * Invoke purge() on the underlying shared Timer so that internal resources will be released. */ void purgeTimerTasks(); /** * Return metadata cache for given connection. * * @return metadata cache */ LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache(); CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized, String... columnNames) throws SQLException; /** * By default, the connection resets statement cache in case deallocate all/discard all * message is observed. * This API allows to disable that feature for testing purposes. * * @param flushCacheOnDeallocate true if statement cache should be reset when "deallocate/discard" message observed */ void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate); /** * Indicates if statements to backend should be hinted as read only. * * @return Indication if hints to backend (such as when transaction begins) * should be read only. * @see PGProperty#READ_ONLY_MODE */ boolean hintReadOnly(); }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4033_1
crossvul-java_data_good_1910_1
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.avmfritz.internal.hardware.callbacks; import static org.eclipse.jetty.http.HttpMethod.GET; import java.io.StringReader; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.avmfritz.internal.dto.templates.TemplateListModel; import org.openhab.binding.avmfritz.internal.handler.AVMFritzBaseBridgeHandler; import org.openhab.binding.avmfritz.internal.hardware.FritzAhaWebInterface; import org.openhab.binding.avmfritz.internal.util.JAXBUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Callback implementation for updating templates from a xml response. * * @author Christoph Weitkamp - Initial contribution */ @NonNullByDefault public class FritzAhaUpdateTemplatesCallback extends FritzAhaReauthCallback { private final Logger logger = LoggerFactory.getLogger(FritzAhaUpdateTemplatesCallback.class); private static final String WEBSERVICE_COMMAND = "switchcmd=gettemplatelistinfos"; private final AVMFritzBaseBridgeHandler handler; /** * Constructor * * @param webInterface web interface to FRITZ!Box * @param handler handler that will update things */ public FritzAhaUpdateTemplatesCallback(FritzAhaWebInterface webInterface, AVMFritzBaseBridgeHandler handler) { super(WEBSERVICE_PATH, WEBSERVICE_COMMAND, webInterface, GET, 1); this.handler = handler; } @Override public void execute(int status, String response) { super.execute(status, response); logger.trace("Received response '{}'", response); if (isValidRequest()) { try { XMLStreamReader xsr = JAXBUtils.XMLINPUTFACTORY.createXMLStreamReader(new StringReader(response)); Unmarshaller unmarshaller = JAXBUtils.JAXBCONTEXT_TEMPLATES.createUnmarshaller(); TemplateListModel model = (TemplateListModel) unmarshaller.unmarshal(xsr); if (model != null) { handler.addTemplateList(model.getTemplates()); } else { logger.debug("no template in response"); } } catch (JAXBException | XMLStreamException e) { logger.error("Exception creating Unmarshaller: {}", e.getLocalizedMessage(), e); } } else { logger.debug("request is invalid: {}", status); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_1
crossvul-java_data_good_4290_5
/* * file: GanttDesignerReader.java * author: Jon Iles * copyright: (c) Packwood Software 2019 * date: 10 February 2019 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.ganttdesigner; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import net.sf.mpxj.ChildTaskContainer; import net.sf.mpxj.Day; import net.sf.mpxj.EventManager; import net.sf.mpxj.MPXJException; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectCalendarWeek; import net.sf.mpxj.ProjectConfig; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.ProjectProperties; import net.sf.mpxj.RelationType; import net.sf.mpxj.Task; import net.sf.mpxj.common.UnmarshalHelper; import net.sf.mpxj.ganttdesigner.schema.Gantt; import net.sf.mpxj.ganttdesigner.schema.GanttDesignerRemark; import net.sf.mpxj.listener.ProjectListener; import net.sf.mpxj.reader.AbstractProjectReader; /** * This class creates a new ProjectFile instance by reading a GanttDesigner file. */ public final class GanttDesignerReader extends AbstractProjectReader { /** * {@inheritDoc} */ @Override public void addProjectListener(ProjectListener listener) { if (m_projectListeners == null) { m_projectListeners = new ArrayList<>(); } m_projectListeners.add(listener); } /** * {@inheritDoc} */ @Override public ProjectFile read(InputStream stream) throws MPXJException { try { if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_taskMap = new HashMap<>(); ProjectConfig config = m_projectFile.getProjectConfig(); config.setAutoWBS(false); m_projectFile.getProjectProperties().setFileApplication("GanttDesigner"); m_projectFile.getProjectProperties().setFileType("GNT"); m_eventManager.addProjectListeners(m_projectListeners); Gantt gantt = (Gantt) UnmarshalHelper.unmarshal(CONTEXT, stream); readProjectProperties(gantt); readCalendar(gantt); readTasks(gantt); return m_projectFile; } catch (ParserConfigurationException ex) { throw new MPXJException("Failed to parse file", ex); } catch (JAXBException ex) { throw new MPXJException("Failed to parse file", ex); } catch (SAXException ex) { throw new MPXJException("Failed to parse file", ex); } finally { m_projectFile = null; m_eventManager = null; m_projectListeners = null; m_taskMap = null; } } /** * Read project properties. * * @param gantt Gantt Designer file */ private void readProjectProperties(Gantt gantt) { Gantt.File file = gantt.getFile(); ProjectProperties props = m_projectFile.getProjectProperties(); props.setLastSaved(file.getSaved()); props.setCreationDate(file.getCreated()); props.setName(file.getName()); } /** * Read the calendar data from a Gantt Designer file. * * @param gantt Gantt Designer file. */ private void readCalendar(Gantt gantt) { Gantt.Calendar ganttCalendar = gantt.getCalendar(); m_projectFile.getProjectProperties().setWeekStartDay(ganttCalendar.getWeekStart()); ProjectCalendar calendar = m_projectFile.addCalendar(); calendar.setName("Standard"); m_projectFile.setDefaultCalendar(calendar); String workingDays = ganttCalendar.getWorkDays(); calendar.setWorkingDay(Day.SUNDAY, workingDays.charAt(0) == '1'); calendar.setWorkingDay(Day.MONDAY, workingDays.charAt(1) == '1'); calendar.setWorkingDay(Day.TUESDAY, workingDays.charAt(2) == '1'); calendar.setWorkingDay(Day.WEDNESDAY, workingDays.charAt(3) == '1'); calendar.setWorkingDay(Day.THURSDAY, workingDays.charAt(4) == '1'); calendar.setWorkingDay(Day.FRIDAY, workingDays.charAt(5) == '1'); calendar.setWorkingDay(Day.SATURDAY, workingDays.charAt(6) == '1'); for (int i = 1; i <= 7; i++) { Day day = Day.getInstance(i); ProjectCalendarHours hours = calendar.addCalendarHours(day); if (calendar.isWorkingDay(day)) { hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } for (Gantt.Holidays.Holiday holiday : gantt.getHolidays().getHoliday()) { ProjectCalendarException exception = calendar.addCalendarException(holiday.getDate(), holiday.getDate()); exception.setName(holiday.getContent()); } } /** * Read task data from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void readTasks(Gantt gantt) { processTasks(gantt); processPredecessors(gantt); processRemarks(gantt); } /** * Read task data from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void processTasks(Gantt gantt) { ProjectCalendar calendar = m_projectFile.getDefaultCalendar(); for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask()) { String wbs = ganttTask.getID(); ChildTaskContainer parentTask = getParentTask(wbs); Task task = parentTask.addTask(); //ganttTask.getB() // bar type //ganttTask.getBC() // bar color task.setCost(ganttTask.getC()); task.setName(ganttTask.getContent()); task.setDuration(ganttTask.getD()); task.setDeadline(ganttTask.getDL()); //ganttTask.getH() // height //ganttTask.getIn(); // indent task.setWBS(wbs); task.setPercentageComplete(ganttTask.getPC()); task.setStart(ganttTask.getS()); //ganttTask.getU(); // Unknown //ganttTask.getVA(); // Valign task.setFinish(calendar.getDate(task.getStart(), task.getDuration(), false)); m_taskMap.put(wbs, task); } } /** * Read predecessors from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void processPredecessors(Gantt gantt) { for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask()) { String predecessors = ganttTask.getP(); if (predecessors != null && !predecessors.isEmpty()) { String wbs = ganttTask.getID(); Task task = m_taskMap.get(wbs); for (String predecessor : predecessors.split(";")) { Task predecessorTask = m_projectFile.getTaskByID(Integer.valueOf(predecessor)); task.addPredecessor(predecessorTask, RelationType.FINISH_START, ganttTask.getL()); } } } } /** * Read remarks from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void processRemarks(Gantt gantt) { processRemarks(gantt.getRemarks()); processRemarks(gantt.getRemarks1()); processRemarks(gantt.getRemarks2()); processRemarks(gantt.getRemarks3()); processRemarks(gantt.getRemarks4()); } /** * Read an individual remark type from a Gantt Designer file. * * @param remark remark type */ private void processRemarks(GanttDesignerRemark remark) { for (GanttDesignerRemark.Task remarkTask : remark.getTask()) { Integer id = remarkTask.getRow(); Task task = m_projectFile.getTaskByID(id); String notes = task.getNotes(); if (notes.isEmpty()) { notes = remarkTask.getContent(); } else { notes = notes + '\n' + remarkTask.getContent(); } task.setNotes(notes); } } /** * Extract the parent WBS from a WBS. * * @param wbs current WBS * @return parent WBS */ private String getParentWBS(String wbs) { String result; int index = wbs.lastIndexOf('.'); if (index == -1) { result = null; } else { result = wbs.substring(0, index); } return result; } /** * Retrieve the parent task based on its WBS. * * @param wbs parent WBS * @return parent task */ private ChildTaskContainer getParentTask(String wbs) { ChildTaskContainer result; String parentWbs = getParentWBS(wbs); if (parentWbs == null) { result = m_projectFile; } else { result = m_taskMap.get(parentWbs); } return result; } private ProjectFile m_projectFile; private EventManager m_eventManager; private List<ProjectListener> m_projectListeners; Map<String, Task> m_taskMap; /** * Cached context to minimise construction cost. */ private static JAXBContext CONTEXT; /** * Note any error occurring during context construction. */ private static JAXBException CONTEXT_EXCEPTION; static { try { // // JAXB RI property to speed up construction // System.setProperty("com.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot", "true"); // // Construct the context // CONTEXT = JAXBContext.newInstance("net.sf.mpxj.ganttdesigner.schema", GanttDesignerReader.class.getClassLoader()); } catch (JAXBException ex) { CONTEXT_EXCEPTION = ex; CONTEXT = null; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4290_5
crossvul-java_data_good_4175_0
package org.mapfish.print.map.style; import org.geotools.factory.CommonFactoryFinder; import org.geotools.styling.DefaultResourceLocator; import org.geotools.styling.Style; import org.geotools.xml.styling.SLDParser; import org.locationtech.jts.util.Assert; import org.mapfish.print.Constants; import org.mapfish.print.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Optional; import java.util.function.Function; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Basic implementation for loading and parsing an SLD style. */ public class SLDParserPlugin implements StyleParserPlugin { /** * The separator between the path or url segment for loading the sld and an index of the style to obtain. * <p> * SLDs can contains multiple styles. Because of this there needs to be a way to indicate which style is * referred to. That is the purpose of the style index. */ public static final String STYLE_INDEX_REF_SEPARATOR = "##"; @Override public final Optional<Style> parseStyle( @Nullable final Configuration configuration, @Nonnull final ClientHttpRequestFactory clientHttpRequestFactory, @Nonnull final String styleString) { // try to load xml final Optional<Style> styleOptional = tryLoadSLD( styleString.getBytes(Constants.DEFAULT_CHARSET), null, clientHttpRequestFactory); if (styleOptional.isPresent()) { return styleOptional; } final Integer styleIndex = lookupStyleIndex(styleString).orElse(null); final String styleStringWithoutIndexReference = removeIndexReference(styleString); Function<byte[], Optional<Style>> loadFunction = input -> tryLoadSLD(input, styleIndex, clientHttpRequestFactory); return ParserPluginUtils.loadStyleAsURI(clientHttpRequestFactory, styleStringWithoutIndexReference, loadFunction); } private String removeIndexReference(final String styleString) { int styleIdentifier = styleString.lastIndexOf(STYLE_INDEX_REF_SEPARATOR); if (styleIdentifier > 0) { return styleString.substring(0, styleIdentifier); } return styleString; } private Optional<Integer> lookupStyleIndex(final String ref) { int styleIdentifier = ref.lastIndexOf(STYLE_INDEX_REF_SEPARATOR); if (styleIdentifier > 0) { return Optional.of(Integer.parseInt(ref.substring(styleIdentifier + 2)) - 1); } return Optional.empty(); } private Optional<Style> tryLoadSLD( final byte[] bytes, final Integer styleIndex, final ClientHttpRequestFactory clientHttpRequestFactory) { Assert.isTrue(styleIndex == null || styleIndex > -1, "styleIndex must be > -1 but was: " + styleIndex); final Style[] styles; try { // check if the XML is valid // this is only done in a separate step to avoid that fatal errors show up in the logs // by setting a custom error handler. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler()); db.parse(new ByteArrayInputStream(bytes)); // then read the styles final SLDParser sldParser = new SLDParser(CommonFactoryFinder.getStyleFactory()); sldParser.setOnLineResourceLocator(new DefaultResourceLocator() { @Override public URL locateResource(final String uri) { try { final URL theUrl = super.locateResource(uri); final URI theUri; if (theUrl != null) { theUri = theUrl.toURI(); } else { theUri = URI.create(uri); } if (theUri.getScheme().startsWith("http")) { final ClientHttpRequest request = clientHttpRequestFactory.createRequest( theUri, HttpMethod.GET); return request.getURI().toURL(); } return null; } catch (IOException | URISyntaxException e) { return null; } } }); sldParser.setInput(new ByteArrayInputStream(bytes)); styles = sldParser.readXML(); } catch (Throwable e) { return Optional.empty(); } if (styleIndex != null) { Assert.isTrue(styleIndex < styles.length, String.format("There where %s styles in file but " + "requested index was: %s", styles.length, styleIndex + 1)); } else { Assert.isTrue(styles.length < 2, String.format("There are %s therefore the styleRef must " + "contain an index identifying the style." + " The index starts at 1 for the first " + "style.\n" + "\tExample: thinline.sld##1", styles.length)); } if (styleIndex == null) { return Optional.of(styles[0]); } else { return Optional.of(styles[styleIndex]); } } /** * A default error handler to avoid that error messages like "[Fatal Error] :1:1: Content is not allowed * in prolog." are directly printed to STDERR. */ public static class ErrorHandler extends DefaultHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ErrorHandler.class); /** * @param e Exception */ public final void error(final SAXParseException e) throws SAXException { LOGGER.debug("XML error: {}", e.getLocalizedMessage()); super.error(e); } /** * @param e Exception */ public final void fatalError(final SAXParseException e) throws SAXException { LOGGER.debug("XML fatal error: {}", e.getLocalizedMessage()); super.fatalError(e); } /** * @param e Exception */ public final void warning(final SAXParseException e) { //ignore } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4175_0
crossvul-java_data_good_1910_8
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.fmiweather.internal.client; import java.io.IOException; import java.io.StringReader; import java.math.BigDecimal; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.openhab.binding.fmiweather.internal.client.FMIResponse.Builder; import org.openhab.binding.fmiweather.internal.client.exception.FMIExceptionReportException; import org.openhab.binding.fmiweather.internal.client.exception.FMIIOException; import org.openhab.binding.fmiweather.internal.client.exception.FMIUnexpectedResponseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * * Client for accessing FMI weather data * * Subject to license terms https://en.ilmatieteenlaitos.fi/open-data * * * All weather stations: * https://opendata.fmi.fi/wfs/fin?service=WFS&version=2.0.0&request=GetFeature&storedquery_id=fmi::ef::stations&networkid=121& * Networkid parameter isexplained in entries of * https://opendata.fmi.fi/wfs/fin?service=WFS&version=2.0.0&request=GetFeature&storedquery_id=fmi::ef::stations * * @author Sami Salonen - Initial contribution * */ @NonNullByDefault public class Client { private final Logger logger = LoggerFactory.getLogger(Client.class); public static final String WEATHER_STATIONS_URL = "https://opendata.fmi.fi/wfs/fin?service=WFS&version=2.0.0&request=GetFeature&storedquery_id=fmi::ef::stations&networkid=121&"; private static final Map<String, String> NAMESPACES = new HashMap<>(); static { NAMESPACES.put("target", "http://xml.fmi.fi/namespace/om/atmosphericfeatures/1.0"); NAMESPACES.put("gml", "http://www.opengis.net/gml/3.2"); NAMESPACES.put("xlink", "http://www.w3.org/1999/xlink"); NAMESPACES.put("ows", "http://www.opengis.net/ows/1.1"); NAMESPACES.put("gmlcov", "http://www.opengis.net/gmlcov/1.0"); NAMESPACES.put("swe", "http://www.opengis.net/swe/2.0"); NAMESPACES.put("wfs", "http://www.opengis.net/wfs/2.0"); NAMESPACES.put("ef", "http://inspire.ec.europa.eu/schemas/ef/4.0"); } private static final NamespaceContext NAMESPACE_CONTEXT = new NamespaceContext() { @Override public String getNamespaceURI(@Nullable String prefix) { return NAMESPACES.get(prefix); } @SuppressWarnings("rawtypes") @Override public @Nullable Iterator getPrefixes(@Nullable String val) { return null; } @Override public @Nullable String getPrefix(@Nullable String uri) { return null; } }; private DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); private DocumentBuilder documentBuilder; public Client() { documentBuilderFactory.setNamespaceAware(true); try { // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); documentBuilderFactory.setXIncludeAware(false); documentBuilderFactory.setExpandEntityReferences(false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } /** * Query request and return the data * * @param request request to process * @param timeoutMillis timeout for the http call * @return data corresponding to the query * @throws FMIIOException on all I/O errors * @throws FMIUnexpectedResponseException on all unexpected content errors * @throw FMIExceptionReportException on explicit error responses from the server */ public FMIResponse query(Request request, int timeoutMillis) throws FMIExceptionReportException, FMIUnexpectedResponseException, FMIIOException { try { String url = request.toUrl(); String responseText = HttpUtil.executeUrl("GET", url, timeoutMillis); if (responseText == null) { throw new FMIIOException(String.format("HTTP error with %s", request.toUrl())); } FMIResponse response = parseMultiPointCoverageXml(responseText); logger.debug("Request {} translated to url {}. Response: {}", request, url, response); return response; } catch (IOException e) { throw new FMIIOException(e); } catch (SAXException | XPathExpressionException e) { throw new FMIUnexpectedResponseException(e); } } /** * Query all weather stations * * @param timeoutMillis timeout for the http call * @return locations representing stations * @throws FMIIOException on all I/O errors * @throws FMIUnexpectedResponseException on all unexpected content errors * @throw FMIExceptionReportException on explicit error responses from the server */ public Set<Location> queryWeatherStations(int timeoutMillis) throws FMIIOException, FMIUnexpectedResponseException, FMIExceptionReportException { try { String response = HttpUtil.executeUrl("GET", WEATHER_STATIONS_URL, timeoutMillis); if (response == null) { throw new FMIIOException(String.format("HTTP error with %s", WEATHER_STATIONS_URL)); } return parseStations(response); } catch (IOException e) { throw new FMIIOException(e); } catch (XPathExpressionException | SAXException e) { throw new FMIUnexpectedResponseException(e); } } private Set<Location> parseStations(String response) throws FMIExceptionReportException, FMIUnexpectedResponseException, SAXException, IOException, XPathExpressionException { Document document = documentBuilder.parse(new InputSource(new StringReader(response))); XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(NAMESPACE_CONTEXT); boolean isExceptionReport = ((Node) xPath.compile("/ows:ExceptionReport").evaluate(document, XPathConstants.NODE)) != null; if (isExceptionReport) { Node exceptionCode = (Node) xPath.compile("/ows:ExceptionReport/ows:Exception/@exceptionCode") .evaluate(document, XPathConstants.NODE); String[] exceptionText = queryNodeValues(xPath.compile("//ows:ExceptionText/text()"), document); throw new FMIExceptionReportException(exceptionCode.getNodeValue(), exceptionText); } String[] fmisids = queryNodeValues( xPath.compile( "/wfs:FeatureCollection/wfs:member/ef:EnvironmentalMonitoringFacility/gml:identifier/text()"), document); String[] names = queryNodeValues(xPath.compile( "/wfs:FeatureCollection/wfs:member/ef:EnvironmentalMonitoringFacility/gml:name[@codeSpace='http://xml.fmi.fi/namespace/locationcode/name']/text()"), document); String[] representativePoints = queryNodeValues(xPath.compile( "/wfs:FeatureCollection/wfs:member/ef:EnvironmentalMonitoringFacility/ef:representativePoint/gml:Point/gml:pos/text()"), document); if (fmisids.length != names.length || fmisids.length != representativePoints.length) { throw new FMIUnexpectedResponseException(String.format( "Could not all properties of locations: fmisids: %d, names: %d, representativePoints: %d", fmisids.length, names.length, representativePoints.length)); } Set<Location> locations = new HashSet<>(representativePoints.length); for (int i = 0; i < representativePoints.length; i++) { BigDecimal[] latlon = parseLatLon(representativePoints[i]); locations.add(new Location(names[i], fmisids[i], latlon[0], latlon[1])); } return locations; } /** * Parse FMI multipointcoverage formatted xml response * */ private FMIResponse parseMultiPointCoverageXml(String response) throws FMIUnexpectedResponseException, FMIExceptionReportException, SAXException, IOException, XPathExpressionException { Document document = documentBuilder.parse(new InputSource(new StringReader(response))); XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(NAMESPACE_CONTEXT); boolean isExceptionReport = ((Node) xPath.compile("/ows:ExceptionReport").evaluate(document, XPathConstants.NODE)) != null; if (isExceptionReport) { Node exceptionCode = (Node) xPath.compile("/ows:ExceptionReport/ows:Exception/@exceptionCode") .evaluate(document, XPathConstants.NODE); String[] exceptionText = queryNodeValues(xPath.compile("//ows:ExceptionText/text()"), document); throw new FMIExceptionReportException(exceptionCode.getNodeValue(), exceptionText); } Builder builder = new FMIResponse.Builder(); String[] parameters = queryNodeValues(xPath.compile("//swe:field/@name"), document); /** * Observations have FMISID (FMI Station ID?), with forecasts we use lat & lon */ String[] ids = queryNodeValues(xPath.compile( "//target:Location/gml:identifier[@codeSpace='http://xml.fmi.fi/namespace/stationcode/fmisid']/text()"), document); String[] names = queryNodeValues(xPath.compile( "//target:Location/gml:name[@codeSpace='http://xml.fmi.fi/namespace/locationcode/name']/text()"), document); String[] representativePointRefs = queryNodeValues( xPath.compile("//target:Location/target:representativePoint/@xlink:href"), document); if ((ids.length > 0 && ids.length != names.length) || names.length != representativePointRefs.length) { throw new FMIUnexpectedResponseException(String.format( "Could not all properties of locations: ids: %d, names: %d, representativePointRefs: %d", ids.length, names.length, representativePointRefs.length)); } Location[] locations = new Location[representativePointRefs.length]; for (int i = 0; i < locations.length; i++) { BigDecimal[] latlon = findLatLon(xPath, i, document, representativePointRefs[i]); String id = ids.length == 0 ? String.format("%s,%s", latlon[0].toPlainString(), latlon[1].toPlainString()) : ids[i]; locations[i] = new Location(names[i], id, latlon[0], latlon[1]); } logger.trace("names ({}): {}", names.length, names); logger.trace("parameters ({}): {}", parameters.length, parameters); if (names.length == 0) { // No data, e.g. when starttime=endtime return builder.build(); } String latLonTimeTripletText = takeFirstOrError("positions", queryNodeValues(xPath.compile("//gmlcov:positions/text()"), document)); String[] latLonTimeTripletEntries = latLonTimeTripletText.trim().split("\\s+"); logger.trace("latLonTimeTripletText: {}", latLonTimeTripletText); logger.trace("latLonTimeTripletEntries ({}): {}", latLonTimeTripletEntries.length, latLonTimeTripletEntries); int countTimestamps = latLonTimeTripletEntries.length / 3 / locations.length; long[] timestampsEpoch = IntStream.range(0, latLonTimeTripletEntries.length).filter(i -> i % 3 == 0) .limit(countTimestamps).mapToLong(i -> Long.parseLong(latLonTimeTripletEntries[i + 2])).toArray(); // Invariant assert countTimestamps == timestampsEpoch.length; logger.trace("countTimestamps ({}): {}", countTimestamps, timestampsEpoch); validatePositionEntries(locations, timestampsEpoch, latLonTimeTripletEntries); String valuesText = takeFirstOrError("doubleOrNilReasonTupleList", queryNodeValues(xPath.compile(".//gml:doubleOrNilReasonTupleList/text()"), document)); String[] valuesEntries = valuesText.trim().split("\\s+"); logger.trace("valuesText: {}", valuesText); logger.trace("valuesEntries ({}): {}", valuesEntries.length, valuesEntries); if (valuesEntries.length != locations.length * parameters.length * countTimestamps) { throw new FMIUnexpectedResponseException(String.format( "Wrong number of values (%d). Expecting %d * %d * %d = %d", valuesEntries.length, locations.length, parameters.length, countTimestamps, countTimestamps * locations.length * parameters.length)); } IntStream.range(0, locations.length).forEach(locationIndex -> { for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) { for (int timestepIndex = 0; timestepIndex < countTimestamps; timestepIndex++) { BigDecimal val = toBigDecimalOrNullIfNaN( valuesEntries[locationIndex * countTimestamps * parameters.length + timestepIndex * parameters.length + parameterIndex]); logger.trace("Found value {}={} @ time={} for location {}", parameters[parameterIndex], val, timestampsEpoch[timestepIndex], locations[locationIndex].id); builder.appendLocationData(locations[locationIndex], countTimestamps, parameters[parameterIndex], timestampsEpoch[timestepIndex], val); } } }); return builder.build(); } /** * Find representative latitude and longitude matching given xlink href attribute value * * @param xPath xpath object used for query * @param entryIndex index of the location, for logging only on errors * @param document document object * @param href xlink href attribute value. Should start with # * @return latitude and longitude values as array * @throws FMIUnexpectedResponseException parsing errors or when entry is not found * @throws XPathExpressionException xpath errors */ private BigDecimal[] findLatLon(XPath xPath, int entryIndex, Document document, String href) throws FMIUnexpectedResponseException, XPathExpressionException { if (!href.startsWith("#")) { throw new FMIUnexpectedResponseException( "Could not find valid representativePoint xlink:href, does not start with #"); } String pointId = href.substring(1); String pointLatLon = takeFirstOrError(String.format("[%d]/pos", entryIndex), queryNodeValues(xPath.compile(".//gml:Point[@gml:id='" + pointId + "']/gml:pos/text()"), document)); return parseLatLon(pointLatLon); } /** * Parse string reprsenting latitude longitude string separated by space * * @param pointLatLon latitude longitude string separated by space * @return latitude and longitude values as array * @throws FMIUnexpectedResponseException on parsing errors */ private BigDecimal[] parseLatLon(String pointLatLon) throws FMIUnexpectedResponseException { String[] latlon = pointLatLon.split(" "); BigDecimal lat, lon; if (latlon.length != 2) { throw new FMIUnexpectedResponseException(String.format( "Invalid latitude or longitude format, expected two values separated by space, got %d values: '%s'", latlon.length, latlon)); } try { lat = new BigDecimal(latlon[0]); lon = new BigDecimal(latlon[1]); } catch (NumberFormatException e) { throw new FMIUnexpectedResponseException( String.format("Invalid latitude or longitude format: %s", e.getMessage())); } return new BigDecimal[] { lat, lon }; } private String[] queryNodeValues(XPathExpression expression, Object source) throws XPathExpressionException { NodeList nodeList = (NodeList) expression.evaluate(source, XPathConstants.NODESET); String[] values = new String[nodeList.getLength()]; for (int i = 0; i < nodeList.getLength(); i++) { values[i] = nodeList.item(i).getNodeValue(); } return values; } /** * Asserts that length of values is exactly 1, and returns it * * @param errorDescription error description for FMIResponseException * @param values * @return * @throws FMIUnexpectedResponseException when length of values != 1 */ private String takeFirstOrError(String errorDescription, String[] values) throws FMIUnexpectedResponseException { if (values.length != 1) { throw new FMIUnexpectedResponseException(String.format("No unique match found: %s", errorDescription)); } return values[0]; } /** * Convert string to BigDecimal. "NaN" string is converted to null * * @param value * @return null when value is "NaN". Otherwise BigDecimal representing the string */ private @Nullable BigDecimal toBigDecimalOrNullIfNaN(String value) { if ("NaN".equals(value)) { return null; } else { return new BigDecimal(value); } } /** * Validate ordering and values of gmlcov:positions (latLonTimeTripletEntries) * essentially * pos1_lat, pos1_lon, time1 * pos1_lat, pos1_lon, time2 * pos1_lat, pos1_lon, time3 * pos2_lat, pos2_lon, time1 * pos2_lat, pos2_lon, time2 * ..etc.. * * - lat, lon should be in correct order and match position entries ("locations") * - time should values should be exactly same for each point (above time1, time2, ...), and match given timestamps * ("timestampsEpoch") * * * @param locations previously discovered locations * @param timestampsEpoch expected timestamps * @param latLonTimeTripletEntries flat array of strings representing the array, [row1_cell1, row1_cell2, * row2_cell1, ...] * @throws FMIUnexpectedResponseException when value ordering is not matching the expected */ private void validatePositionEntries(Location[] locations, long[] timestampsEpoch, String[] latLonTimeTripletEntries) throws FMIUnexpectedResponseException { int countTimestamps = timestampsEpoch.length; for (int locationIndex = 0; locationIndex < locations.length; locationIndex++) { String firstLat = latLonTimeTripletEntries[locationIndex * countTimestamps * 3]; String fistLon = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + 1]; // step through entries for this position for (int timestepIndex = 0; timestepIndex < countTimestamps; timestepIndex++) { String lat = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + timestepIndex * 3]; String lon = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + timestepIndex * 3 + 1]; String timeEpochSec = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + timestepIndex * 3 + 2]; if (!lat.equals(firstLat) || !lon.equals(fistLon)) { throw new FMIUnexpectedResponseException(String.format( "positions[%d] lat, lon for time index [%d] was not matching expected ordering", locationIndex, timestepIndex)); } String expectedLat = locations[locationIndex].latitude.toPlainString(); String expectedLon = locations[locationIndex].longitude.toPlainString(); if (!lat.equals(expectedLat) || !lon.equals(expectedLon)) { throw new FMIUnexpectedResponseException(String.format( "positions[%d] lat, lon for time index [%d] was not matching representativePoint", locationIndex, timestepIndex)); } if (Long.parseLong(timeEpochSec) != timestampsEpoch[timestepIndex]) { throw new FMIUnexpectedResponseException(String.format( "positions[%d] time (%s) for time index [%d] was not matching expected (%d) ordering", locationIndex, timeEpochSec, timestepIndex, timestampsEpoch[timestepIndex])); } } } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_8
crossvul-java_data_good_1910_0
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.avmfritz.internal.hardware.callbacks; import static org.eclipse.jetty.http.HttpMethod.GET; import java.io.StringReader; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.openhab.binding.avmfritz.internal.dto.DeviceListModel; import org.openhab.binding.avmfritz.internal.handler.AVMFritzBaseBridgeHandler; import org.openhab.binding.avmfritz.internal.hardware.FritzAhaWebInterface; import org.openhab.binding.avmfritz.internal.util.JAXBUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Callback implementation for updating multiple numbers decoded from a xml * response. Supports reauthorization. * * @author Robert Bausdorf - Initial contribution * @author Christoph Weitkamp - Added support for groups */ @NonNullByDefault public class FritzAhaUpdateCallback extends FritzAhaReauthCallback { private final Logger logger = LoggerFactory.getLogger(FritzAhaUpdateCallback.class); private static final String WEBSERVICE_COMMAND = "switchcmd=getdevicelistinfos"; private final AVMFritzBaseBridgeHandler handler; /** * Constructor * * @param webIface Webinterface to FRITZ!Box * @param handler Bridge handler that will update things. */ public FritzAhaUpdateCallback(FritzAhaWebInterface webIface, AVMFritzBaseBridgeHandler handler) { super(WEBSERVICE_PATH, WEBSERVICE_COMMAND, webIface, GET, 1); this.handler = handler; } @Override public void execute(int status, String response) { super.execute(status, response); logger.trace("Received State response {}", response); if (isValidRequest()) { try { XMLStreamReader xsr = JAXBUtils.XMLINPUTFACTORY.createXMLStreamReader(new StringReader(response)); Unmarshaller unmarshaller = JAXBUtils.JAXBCONTEXT_DEVICES.createUnmarshaller(); DeviceListModel model = (DeviceListModel) unmarshaller.unmarshal(xsr); if (model != null) { handler.onDeviceListAdded(model.getDevicelist()); } else { logger.debug("no model in response"); } handler.setStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null); } catch (JAXBException | XMLStreamException e) { logger.error("Exception creating Unmarshaller: {}", e.getLocalizedMessage(), e); handler.setStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage()); } } else { logger.debug("request is invalid: {}", status); handler.setStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Request is invalid"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_0
crossvul-java_data_good_1738_0
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.milton.http; import io.milton.resource.AccessControlledResource; import io.milton.resource.AccessControlledResource.Priviledge; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * * @author brad */ public class AclUtils { /** * Recurisve function which checks the given collection of priviledges, * and checks inside the contains property of those priviledges * * Returns true if the required priviledge is directly present in the collection * or is implied * * @param required * @param privs * @return */ public static boolean containsPriviledge(AccessControlledResource.Priviledge required, Iterable<AccessControlledResource.Priviledge> privs) { if( privs == null ) { return false; } for (AccessControlledResource.Priviledge p : privs) { if (p.equals(required)) { return true; } if( containsPriviledge(required, p.contains)) { return true; } } return false; } public static Set<AccessControlledResource.Priviledge> asSet(AccessControlledResource.Priviledge ... privs) { Set<AccessControlledResource.Priviledge> set = new HashSet<AccessControlledResource.Priviledge>(privs.length); set.addAll(Arrays.asList(privs)); return set; } /** * Return a set containing all privs in the given collection, and also all priviledges * implies by those, and so on recursively * * @param privs * @return - a set containiing all priviledges, direct or implied, by the given collection */ public static Set<AccessControlledResource.Priviledge> expand(Iterable<AccessControlledResource.Priviledge> privs) { Set<AccessControlledResource.Priviledge> set = new HashSet<AccessControlledResource.Priviledge>(); _expand(privs, set); return set; } private static void _expand(Iterable<AccessControlledResource.Priviledge> privs, Set<AccessControlledResource.Priviledge> output) { if( privs == null ) { return ; } for( Priviledge p : privs ) { output.add(p); _expand(p.contains, output); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1738_0
crossvul-java_data_bad_4033_4
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.jdbc; import org.postgresql.core.BaseConnection; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.sql.SQLException; import java.sql.SQLXML; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stax.StAXResult; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class PgSQLXML implements SQLXML { private final BaseConnection conn; private String data; // The actual data contained. private boolean initialized; // Has someone assigned the data for this object? private boolean active; // Is anyone in the process of loading data into us? private boolean freed; private ByteArrayOutputStream byteArrayOutputStream; private StringWriter stringWriter; private DOMResult domResult; public PgSQLXML(BaseConnection conn) { this(conn, null, false); } public PgSQLXML(BaseConnection conn, String data) { this(conn, data, true); } private PgSQLXML(BaseConnection conn, String data, boolean initialized) { this.conn = conn; this.data = data; this.initialized = initialized; this.active = false; this.freed = false; } @Override public synchronized void free() { freed = true; data = null; } @Override public synchronized InputStream getBinaryStream() throws SQLException { checkFreed(); ensureInitialized(); if (data == null) { return null; } try { return new ByteArrayInputStream(conn.getEncoding().encode(data)); } catch (IOException ioe) { // This should be a can't happen exception. We just // decoded this data, so it would be surprising that // we couldn't encode it. // For this reason don't make it translatable. throw new PSQLException("Failed to re-encode xml data.", PSQLState.DATA_ERROR, ioe); } } @Override public synchronized Reader getCharacterStream() throws SQLException { checkFreed(); ensureInitialized(); if (data == null) { return null; } return new StringReader(data); } // We must implement this unsafely because that's what the // interface requires. Because it says we're returning T // which is unknown, none of the return values can satisfy it // as Java isn't going to understand the if statements that // ensure they are the same. // @Override public synchronized <T extends Source> T getSource(Class<T> sourceClass) throws SQLException { checkFreed(); ensureInitialized(); if (data == null) { return null; } try { if (sourceClass == null || DOMSource.class.equals(sourceClass)) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new NonPrintingErrorHandler()); InputSource input = new InputSource(new StringReader(data)); return (T) new DOMSource(builder.parse(input)); } else if (SAXSource.class.equals(sourceClass)) { InputSource is = new InputSource(new StringReader(data)); return (T) new SAXSource(is); } else if (StreamSource.class.equals(sourceClass)) { return (T) new StreamSource(new StringReader(data)); } else if (StAXSource.class.equals(sourceClass)) { XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(data)); return (T) new StAXSource(xsr); } } catch (Exception e) { throw new PSQLException(GT.tr("Unable to decode xml data."), PSQLState.DATA_ERROR, e); } throw new PSQLException(GT.tr("Unknown XML Source class: {0}", sourceClass), PSQLState.INVALID_PARAMETER_TYPE); } @Override public synchronized String getString() throws SQLException { checkFreed(); ensureInitialized(); return data; } @Override public synchronized OutputStream setBinaryStream() throws SQLException { checkFreed(); initialize(); active = true; byteArrayOutputStream = new ByteArrayOutputStream(); return byteArrayOutputStream; } @Override public synchronized Writer setCharacterStream() throws SQLException { checkFreed(); initialize(); active = true; stringWriter = new StringWriter(); return stringWriter; } @Override public synchronized <T extends Result> T setResult(Class<T> resultClass) throws SQLException { checkFreed(); initialize(); if (resultClass == null || DOMResult.class.equals(resultClass)) { domResult = new DOMResult(); active = true; return (T) domResult; } else if (SAXResult.class.equals(resultClass)) { try { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); stringWriter = new StringWriter(); transformerHandler.setResult(new StreamResult(stringWriter)); active = true; return (T) new SAXResult(transformerHandler); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to create SAXResult for SQLXML."), PSQLState.UNEXPECTED_ERROR, te); } } else if (StreamResult.class.equals(resultClass)) { stringWriter = new StringWriter(); active = true; return (T) new StreamResult(stringWriter); } else if (StAXResult.class.equals(resultClass)) { stringWriter = new StringWriter(); try { XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xsw = xof.createXMLStreamWriter(stringWriter); active = true; return (T) new StAXResult(xsw); } catch (XMLStreamException xse) { throw new PSQLException(GT.tr("Unable to create StAXResult for SQLXML"), PSQLState.UNEXPECTED_ERROR, xse); } } throw new PSQLException(GT.tr("Unknown XML Result class: {0}", resultClass), PSQLState.INVALID_PARAMETER_TYPE); } @Override public synchronized void setString(String value) throws SQLException { checkFreed(); initialize(); data = value; } private void checkFreed() throws SQLException { if (freed) { throw new PSQLException(GT.tr("This SQLXML object has already been freed."), PSQLState.OBJECT_NOT_IN_STATE); } } private void ensureInitialized() throws SQLException { if (!initialized) { throw new PSQLException( GT.tr( "This SQLXML object has not been initialized, so you cannot retrieve data from it."), PSQLState.OBJECT_NOT_IN_STATE); } // Is anyone loading data into us at the moment? if (!active) { return; } if (byteArrayOutputStream != null) { try { data = conn.getEncoding().decode(byteArrayOutputStream.toByteArray()); } catch (IOException ioe) { throw new PSQLException(GT.tr("Failed to convert binary xml data to encoding: {0}.", conn.getEncoding().name()), PSQLState.DATA_ERROR, ioe); } finally { byteArrayOutputStream = null; active = false; } } else if (stringWriter != null) { // This is also handling the work for Stream, SAX, and StAX Results // as they will use the same underlying stringwriter variable. // data = stringWriter.toString(); stringWriter = null; active = false; } else if (domResult != null) { // Copy the content from the result to a source // and use the identify transform to get it into a // friendlier result format. try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DOMSource domSource = new DOMSource(domResult.getNode()); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); transformer.transform(domSource, streamResult); data = stringWriter.toString(); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to convert DOMResult SQLXML data to a string."), PSQLState.DATA_ERROR, te); } finally { domResult = null; active = false; } } } private void initialize() throws SQLException { if (initialized) { throw new PSQLException( GT.tr( "This SQLXML object has already been initialized, so you cannot manipulate it further."), PSQLState.OBJECT_NOT_IN_STATE); } initialized = true; } // Don't clutter System.err with errors the user can't silence. // If something bad really happens an exception will be thrown. static class NonPrintingErrorHandler implements ErrorHandler { public void error(SAXParseException e) { } public void fatalError(SAXParseException e) { } public void warning(SAXParseException e) { } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4033_4
crossvul-java_data_good_2449_9
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.platformlambda.example; import org.platformlambda.core.annotations.MainApplication; import org.platformlambda.core.models.EntryPoint; import org.platformlambda.core.models.LambdaFunction; import org.platformlambda.core.system.AppStarter; import org.platformlambda.core.system.Platform; import org.platformlambda.services.HelloGeneric; import org.platformlambda.services.HelloPoJo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; @MainApplication public class MainApp implements EntryPoint { private static final Logger log = LoggerFactory.getLogger(MainApp.class); public static void main(String[] args) { AppStarter.main(args); } @Override public void start(String[] args) throws Exception { // Start the platform Platform platform = Platform.getInstance(); // You can create a microservice as a lambda function inline or write it as a regular Java class LambdaFunction echo = (headers, body, instance) -> { log.info("echo @"+instance+" received - "+headers+", "+body); Map<String, Object> result = new HashMap<>(); result.put("headers", headers); result.put("body", body); result.put("instance", instance); result.put("origin", platform.getOrigin()); return result; }; // register your services platform.register("hello.world", echo, 10); platform.register("hello.pojo", new HelloPoJo(), 5); platform.register("hello.generic", new HelloGeneric(), 5); // connect to cloud according to "cloud.connector" in application.properties platform.connectToCloud(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_2449_9
crossvul-java_data_bad_1737_0
/* * Copyright 2015 McEvoy Software Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.milton.http.http11.auth; import io.milton.common.Utils; import io.milton.http.OAuth2TokenResponse; import io.milton.resource.OAuth2Resource.OAuth2ProfileDetails; import io.milton.resource.OAuth2Provider; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import org.apache.oltu.oauth2.client.OAuthClient; import org.apache.oltu.oauth2.client.URLConnectionClient; import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; import org.apache.oltu.oauth2.client.request.OAuthClientRequest; import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse; import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; import org.apache.oltu.oauth2.client.response.OAuthResourceResponse; import org.apache.oltu.oauth2.common.OAuth; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.message.types.GrantType; import org.apache.oltu.oauth2.common.utils.JSONUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Lee YOU */ public class OAuth2Helper { private static final Logger log = LoggerFactory.getLogger(OAuth2Helper.class); public static URL getOAuth2URL(OAuth2Provider provider) { log.trace("getOAuth2URL {}", provider); String oAuth2Location = provider.getAuthLocation(); String oAuth2ClientId = provider.getClientId(); String scopes = Utils.toCsv(provider.getPermissionScopes()); try { OAuthClientRequest oAuthRequest = OAuthClientRequest .authorizationLocation(oAuth2Location) .setClientId(oAuth2ClientId) .setResponseType("code") .setScope(scopes) .setState(provider.getProviderId()) .setRedirectURI(provider.getRedirectURI()) .buildQueryMessage(); return new URL(oAuthRequest.getLocationUri()); } catch (OAuthSystemException oAuthSystemException) { throw new RuntimeException(oAuthSystemException); } catch (MalformedURLException malformedURLException) { throw new RuntimeException(malformedURLException); } } private final NonceProvider nonceProvider; public OAuth2Helper(NonceProvider nonceProvider) { this.nonceProvider = nonceProvider; } // Sept 2, After Got The Authorization Code(a Access Permission), then Granting the Access Token. public OAuthAccessTokenResponse obtainAuth2Token(OAuth2Provider provider, String accessCode) throws OAuthSystemException, OAuthProblemException { log.trace("obtainAuth2Token code={}, provider={}", accessCode, provider); String oAuth2ClientId = provider.getClientId(); String oAuth2TokenLocation = provider.getTokenLocation(); String oAuth2ClientSecret = provider.getClientSecret(); String oAuth2RedirectURI = provider.getRedirectURI(); OAuthClientRequest oAuthRequest = OAuthClientRequest .tokenLocation(oAuth2TokenLocation) .setGrantType(GrantType.AUTHORIZATION_CODE) .setRedirectURI(oAuth2RedirectURI) .setCode(accessCode) .setClientId(oAuth2ClientId) .setClientSecret(oAuth2ClientSecret) .buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); // This works for facebook OAuthAccessTokenResponse oAuth2Response2 = oAuthClient.accessToken(oAuthRequest, OAuth2TokenResponse.class); //return oAuth2Response; // This might work for google OAuthJSONAccessTokenResponse o; //OAuthAccessTokenResponse oAuth2Response2 = oAuthClient.accessToken(oAuthRequest, OAuth2TokenResponse.class); return oAuth2Response2; } // Sept 3, GET the profile of the user. public OAuthResourceResponse getOAuth2Profile(OAuthAccessTokenResponse oAuth2Response, OAuth2Provider provider) throws OAuthSystemException, OAuthProblemException { log.trace("getOAuth2Profile start {}", oAuth2Response); String accessToken = oAuth2Response.getAccessToken(); String userProfileLocation = provider.getProfileLocation(); OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(userProfileLocation) .setAccessToken(accessToken) .buildQueryMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); return oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class); } public OAuth2ProfileDetails getOAuth2UserInfo(OAuthResourceResponse resourceResponse, OAuthAccessTokenResponse tokenResponse, String oAuth2Code) { log.trace(" getOAuth2UserId start..." + resourceResponse); if (resourceResponse == null) { return null; } String resourceResponseBody = resourceResponse.getBody(); log.trace(" OAuthResourceResponse, body{}" + resourceResponseBody); Map responseMap = JSONUtils.parseJSON(resourceResponseBody); String userID = (String) responseMap.get("id"); String userName = (String) responseMap.get("username"); OAuth2ProfileDetails user = new OAuth2ProfileDetails(); user.setCode(oAuth2Code); user.setAccessToken(tokenResponse.getAccessToken()); user.setDetails(responseMap); if (log.isTraceEnabled()) { log.trace(" userID{}" + userID); log.trace(" userName{}" + userName); log.trace(" oAuth2Code{}" + oAuth2Code); log.trace(" AccessToken{}" + user.getAccessToken()); log.trace("\n\n"); } return user; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1737_0
crossvul-java_data_bad_1910_17
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.onkyo.internal.handler; import static org.openhab.binding.onkyo.internal.OnkyoBindingConstants.*; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.smarthome.core.audio.AudioHTTPServer; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.NextPreviousType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.library.types.PlayPauseType; import org.eclipse.smarthome.core.library.types.RawType; import org.eclipse.smarthome.core.library.types.RewindFastforwardType; import org.eclipse.smarthome.core.library.types.StringType; import org.eclipse.smarthome.core.thing.Channel; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.binding.ThingHandlerService; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.StateOption; import org.eclipse.smarthome.core.types.UnDefType; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.eclipse.smarthome.io.transport.upnp.UpnpIOService; import org.openhab.binding.onkyo.internal.OnkyoAlbumArt; import org.openhab.binding.onkyo.internal.OnkyoConnection; import org.openhab.binding.onkyo.internal.OnkyoEventListener; import org.openhab.binding.onkyo.internal.OnkyoStateDescriptionProvider; import org.openhab.binding.onkyo.internal.ServiceType; import org.openhab.binding.onkyo.internal.automation.modules.OnkyoThingActionsService; import org.openhab.binding.onkyo.internal.config.OnkyoDeviceConfiguration; import org.openhab.binding.onkyo.internal.eiscp.EiscpCommand; import org.openhab.binding.onkyo.internal.eiscp.EiscpMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link OnkyoHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Paul Frank - Initial contribution * @author Marcel Verpaalen - parsing additional commands * @author Pauli Anttila - lot of refactoring * @author Stewart Cossey - add dynamic state description provider */ public class OnkyoHandler extends UpnpAudioSinkHandler implements OnkyoEventListener { private final Logger logger = LoggerFactory.getLogger(OnkyoHandler.class); private OnkyoDeviceConfiguration configuration; private OnkyoConnection connection; private ScheduledFuture<?> resourceUpdaterFuture; @SuppressWarnings("unused") private int currentInput = -1; private State volumeLevelZone1 = UnDefType.UNDEF; private State volumeLevelZone2 = UnDefType.UNDEF; private State volumeLevelZone3 = UnDefType.UNDEF; private State lastPowerState = OnOffType.OFF; private final OnkyoStateDescriptionProvider stateDescriptionProvider; private final OnkyoAlbumArt onkyoAlbumArt = new OnkyoAlbumArt(); private static final int NET_USB_ID = 43; public OnkyoHandler(Thing thing, UpnpIOService upnpIOService, AudioHTTPServer audioHTTPServer, String callbackUrl, OnkyoStateDescriptionProvider stateDescriptionProvider) { super(thing, upnpIOService, audioHTTPServer, callbackUrl); this.stateDescriptionProvider = stateDescriptionProvider; } /** * Initialize the state of the receiver. */ @Override public void initialize() { logger.debug("Initializing handler for Onkyo Receiver"); configuration = getConfigAs(OnkyoDeviceConfiguration.class); logger.info("Using configuration: {}", configuration.toString()); connection = new OnkyoConnection(configuration.ipAddress, configuration.port); connection.addEventListener(this); scheduler.execute(() -> { logger.debug("Open connection to Onkyo Receiver @{}", connection.getConnectionName()); connection.openConnection(); if (connection.isConnected()) { updateStatus(ThingStatus.ONLINE); sendCommand(EiscpCommand.INFO_QUERY); } }); if (configuration.refreshInterval > 0) { // Start resource refresh updater resourceUpdaterFuture = scheduler.scheduleWithFixedDelay(() -> { try { logger.debug("Send resource update requests to Onkyo Receiver @{}", connection.getConnectionName()); checkStatus(); } catch (LinkageError e) { logger.warn("Failed to send resource update requests to Onkyo Receiver @{}. Cause: {}", connection.getConnectionName(), e.getMessage()); } catch (Exception ex) { logger.warn("Exception in resource refresh Thread Onkyo Receiver @{}. Cause: {}", connection.getConnectionName(), ex.getMessage()); } }, configuration.refreshInterval, configuration.refreshInterval, TimeUnit.SECONDS); } } @Override public void dispose() { super.dispose(); if (resourceUpdaterFuture != null) { resourceUpdaterFuture.cancel(true); } if (connection != null) { connection.removeEventListener(this); connection.closeConnection(); } } @Override public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("handleCommand for channel {}: {}", channelUID.getId(), command.toString()); switch (channelUID.getId()) { /* * ZONE 1 */ case CHANNEL_POWER: if (command instanceof OnOffType) { sendCommand(EiscpCommand.POWER_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.POWER_QUERY); } break; case CHANNEL_MUTE: if (command instanceof OnOffType) { sendCommand(EiscpCommand.MUTE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.MUTE_QUERY); } break; case CHANNEL_VOLUME: handleVolumeSet(EiscpCommand.Zone.ZONE1, volumeLevelZone1, command); break; case CHANNEL_INPUT: if (command instanceof DecimalType) { selectInput(((DecimalType) command).intValue()); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.SOURCE_QUERY); } break; case CHANNEL_LISTENMODE: if (command instanceof DecimalType) { sendCommand(EiscpCommand.LISTEN_MODE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.LISTEN_MODE_QUERY); } break; /* * ZONE 2 */ case CHANNEL_POWERZONE2: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE2_POWER_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE2_POWER_QUERY); } break; case CHANNEL_MUTEZONE2: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE2_MUTE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE2_MUTE_QUERY); } break; case CHANNEL_VOLUMEZONE2: handleVolumeSet(EiscpCommand.Zone.ZONE2, volumeLevelZone2, command); break; case CHANNEL_INPUTZONE2: if (command instanceof DecimalType) { sendCommand(EiscpCommand.ZONE2_SOURCE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE2_SOURCE_QUERY); } break; /* * ZONE 3 */ case CHANNEL_POWERZONE3: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE3_POWER_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE3_POWER_QUERY); } break; case CHANNEL_MUTEZONE3: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE3_MUTE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE3_MUTE_QUERY); } break; case CHANNEL_VOLUMEZONE3: handleVolumeSet(EiscpCommand.Zone.ZONE3, volumeLevelZone3, command); break; case CHANNEL_INPUTZONE3: if (command instanceof DecimalType) { sendCommand(EiscpCommand.ZONE3_SOURCE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE3_SOURCE_QUERY); } break; /* * NET PLAYER */ case CHANNEL_CONTROL: if (command instanceof PlayPauseType) { if (command.equals(PlayPauseType.PLAY)) { sendCommand(EiscpCommand.NETUSB_OP_PLAY); } else if (command.equals(PlayPauseType.PAUSE)) { sendCommand(EiscpCommand.NETUSB_OP_PAUSE); } } else if (command instanceof NextPreviousType) { if (command.equals(NextPreviousType.NEXT)) { sendCommand(EiscpCommand.NETUSB_OP_TRACKUP); } else if (command.equals(NextPreviousType.PREVIOUS)) { sendCommand(EiscpCommand.NETUSB_OP_TRACKDWN); } } else if (command instanceof RewindFastforwardType) { if (command.equals(RewindFastforwardType.REWIND)) { sendCommand(EiscpCommand.NETUSB_OP_REW); } else if (command.equals(RewindFastforwardType.FASTFORWARD)) { sendCommand(EiscpCommand.NETUSB_OP_FF); } } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_PLAY_STATUS_QUERY); } break; case CHANNEL_PLAY_URI: handlePlayUri(command); break; case CHANNEL_ALBUM_ART: case CHANNEL_ALBUM_ART_URL: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_ALBUM_ART_QUERY); } break; case CHANNEL_ARTIST: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_ARTIST_QUERY); } break; case CHANNEL_ALBUM: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_ALBUM_QUERY); } break; case CHANNEL_TITLE: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_TITLE_QUERY); } break; case CHANNEL_CURRENTPLAYINGTIME: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_ELAPSEDTIME_QUERY); } break; /* * NET MENU */ case CHANNEL_NET_MENU_CONTROL: if (command instanceof StringType) { final String cmdName = command.toString(); handleNetMenuCommand(cmdName); } break; case CHANNEL_NET_MENU_TITLE: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_TITLE_QUERY); } break; /* * MISC */ default: logger.debug("Command received for an unknown channel: {}", channelUID.getId()); break; } } private void populateInputs(NodeList selectorlist) { List<StateOption> options = new ArrayList<>(); for (int i = 0; i < selectorlist.getLength(); i++) { Element selectorItem = (Element) selectorlist.item(i); options.add(new StateOption(String.valueOf(Integer.parseInt(selectorItem.getAttribute("id"), 16)), selectorItem.getAttribute("name"))); } logger.debug("Got Input List from Receiver {}", options); stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), options); stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_INPUTZONE2), options); stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_INPUTZONE3), options); } private void doPowerOnCheck(State state) { if (configuration.refreshInterval == 0 && lastPowerState == OnOffType.OFF && state == OnOffType.ON) { sendCommand(EiscpCommand.INFO_QUERY); } lastPowerState = state; } @Override public void statusUpdateReceived(String ip, EiscpMessage data) { logger.debug("Received status update from Onkyo Receiver @{}: data={}", connection.getConnectionName(), data); updateStatus(ThingStatus.ONLINE); try { EiscpCommand receivedCommand = null; try { receivedCommand = EiscpCommand.getCommandByCommandAndValueStr(data.getCommand(), ""); } catch (IllegalArgumentException ex) { logger.debug("Received unknown status update from Onkyo Receiver @{}: data={}", connection.getConnectionName(), data); return; } logger.debug("Received command {}", receivedCommand); switch (receivedCommand) { /* * ZONE 1 */ case POWER: State powerState = convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class); updateState(CHANNEL_POWER, powerState); doPowerOnCheck(powerState); break; case MUTE: updateState(CHANNEL_MUTE, convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class)); break; case VOLUME: volumeLevelZone1 = handleReceivedVolume( convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); updateState(CHANNEL_VOLUME, volumeLevelZone1); break; case SOURCE: updateState(CHANNEL_INPUT, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; case LISTEN_MODE: updateState(CHANNEL_LISTENMODE, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; /* * ZONE 2 */ case ZONE2_POWER: State powerZone2State = convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class); updateState(CHANNEL_POWERZONE2, powerZone2State); doPowerOnCheck(powerZone2State); break; case ZONE2_MUTE: updateState(CHANNEL_MUTEZONE2, convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class)); break; case ZONE2_VOLUME: volumeLevelZone2 = handleReceivedVolume( convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); updateState(CHANNEL_VOLUMEZONE2, volumeLevelZone2); break; case ZONE2_SOURCE: updateState(CHANNEL_INPUTZONE2, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; /* * ZONE 3 */ case ZONE3_POWER: State powerZone3State = convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class); updateState(CHANNEL_POWERZONE3, powerZone3State); doPowerOnCheck(powerZone3State); break; case ZONE3_MUTE: updateState(CHANNEL_MUTEZONE3, convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class)); break; case ZONE3_VOLUME: volumeLevelZone3 = handleReceivedVolume( convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); updateState(CHANNEL_VOLUMEZONE3, volumeLevelZone3); break; case ZONE3_SOURCE: updateState(CHANNEL_INPUTZONE3, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; /* * NET PLAYER */ case NETUSB_SONG_ARTIST: updateState(CHANNEL_ARTIST, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_SONG_ALBUM: updateState(CHANNEL_ALBUM, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_SONG_TITLE: updateState(CHANNEL_TITLE, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_SONG_ELAPSEDTIME: updateState(CHANNEL_CURRENTPLAYINGTIME, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_PLAY_STATUS: updateState(CHANNEL_CONTROL, convertNetUsbPlayStatus(data.getValue())); break; case NETUSB_ALBUM_ART: updateAlbumArt(data.getValue()); break; case NETUSB_TITLE: updateNetTitle(data.getValue()); break; case NETUSB_MENU: updateNetMenu(data.getValue()); break; /* * MISC */ case INFO: processInfo(data.getValue()); logger.debug("Info message: '{}'", data.getValue()); break; default: logger.debug("Received unhandled status update from Onkyo Receiver @{}: data={}", connection.getConnectionName(), data); } } catch (Exception ex) { logger.warn("Exception in statusUpdateReceived for Onkyo Receiver @{}. Cause: {}, data received: {}", connection.getConnectionName(), ex.getMessage(), data); } } private void processInfo(String infoXML) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); try (StringReader sr = new StringReader(infoXML)) { InputSource is = new InputSource(sr); Document doc = builder.parse(is); NodeList selectableInputs = doc.getDocumentElement().getElementsByTagName("selector"); populateInputs(selectableInputs); } } catch (ParserConfigurationException | SAXException | IOException e) { logger.debug("Error occured during Info XML parsing.", e); } } @Override public void connectionError(String ip, String errorMsg) { logger.debug("Connection error occurred to Onkyo Receiver @{}", ip); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, errorMsg); } private State convertDeviceValueToOpenHabState(String data, Class<?> classToConvert) { State state = UnDefType.UNDEF; try { int index; if (data.contentEquals("N/A")) { state = UnDefType.UNDEF; } else if (classToConvert == OnOffType.class) { index = Integer.parseInt(data, 16); state = index == 0 ? OnOffType.OFF : OnOffType.ON; } else if (classToConvert == DecimalType.class) { index = Integer.parseInt(data, 16); state = new DecimalType(index); } else if (classToConvert == PercentType.class) { index = Integer.parseInt(data, 16); state = new PercentType(index); } else if (classToConvert == StringType.class) { state = new StringType(data); } } catch (Exception e) { logger.debug("Cannot convert value '{}' to data type {}", data, classToConvert); } logger.debug("Converted data '{}' to openHAB state '{}' ({})", data, state, classToConvert); return state; } private void handleNetMenuCommand(String cmdName) { if ("Up".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_UP); } else if ("Down".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_DOWN); } else if ("Select".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_SELECT); } else if ("PageUp".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_LEFT); } else if ("PageDown".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_RIGHT); } else if ("Back".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_RETURN); } else if (cmdName.matches("Select[0-9]")) { int pos = Integer.parseInt(cmdName.substring(6)); sendCommand(EiscpCommand.NETUSB_MENU_SELECT, new DecimalType(pos)); } else { logger.debug("Received unknown menucommand {}", cmdName); } } private void selectInput(int inputId) { sendCommand(EiscpCommand.SOURCE_SET, new DecimalType(inputId)); currentInput = inputId; } @SuppressWarnings("unused") private void onInputChanged(int newInput) { currentInput = newInput; if (newInput != NET_USB_ID) { resetNetMenu(); updateState(CHANNEL_ARTIST, UnDefType.UNDEF); updateState(CHANNEL_ALBUM, UnDefType.UNDEF); updateState(CHANNEL_TITLE, UnDefType.UNDEF); updateState(CHANNEL_CURRENTPLAYINGTIME, UnDefType.UNDEF); } } private void updateAlbumArt(String data) { onkyoAlbumArt.addFrame(data); if (onkyoAlbumArt.isAlbumCoverReady()) { try { byte[] imgData = onkyoAlbumArt.getAlbumArt(); if (imgData != null && imgData.length > 0) { String mimeType = onkyoAlbumArt.getAlbumArtMimeType(); if (mimeType.isEmpty()) { mimeType = guessMimeTypeFromData(imgData); } updateState(CHANNEL_ALBUM_ART, new RawType(imgData, mimeType)); } else { updateState(CHANNEL_ALBUM_ART, UnDefType.UNDEF); } } catch (IllegalArgumentException e) { updateState(CHANNEL_ALBUM_ART, UnDefType.UNDEF); } onkyoAlbumArt.clearAlbumArt(); } if (data.startsWith("2-")) { updateState(CHANNEL_ALBUM_ART_URL, new StringType(data.substring(2, data.length()))); } else if (data.startsWith("n-")) { updateState(CHANNEL_ALBUM_ART_URL, UnDefType.UNDEF); } else { logger.debug("Not supported album art URL type: {}", data.substring(0, 2)); updateState(CHANNEL_ALBUM_ART_URL, UnDefType.UNDEF); } } private void updateNetTitle(String data) { // first 2 characters is service type int type = Integer.parseInt(data.substring(0, 2), 16); ServiceType service = ServiceType.getType(type); String title = ""; if (data.length() > 21) { title = data.substring(22, data.length()); } updateState(CHANNEL_NET_MENU_TITLE, new StringType(service.toString() + ((title.length() > 0) ? ": " + title : ""))); } private void updateNetMenu(String data) { switch (data.charAt(0)) { case 'U': String itemData = data.substring(3, data.length()); switch (data.charAt(1)) { case '0': updateState(CHANNEL_NET_MENU0, new StringType(itemData)); break; case '1': updateState(CHANNEL_NET_MENU1, new StringType(itemData)); break; case '2': updateState(CHANNEL_NET_MENU2, new StringType(itemData)); break; case '3': updateState(CHANNEL_NET_MENU3, new StringType(itemData)); break; case '4': updateState(CHANNEL_NET_MENU4, new StringType(itemData)); break; case '5': updateState(CHANNEL_NET_MENU5, new StringType(itemData)); break; case '6': updateState(CHANNEL_NET_MENU6, new StringType(itemData)); break; case '7': updateState(CHANNEL_NET_MENU7, new StringType(itemData)); break; case '8': updateState(CHANNEL_NET_MENU8, new StringType(itemData)); break; case '9': updateState(CHANNEL_NET_MENU9, new StringType(itemData)); break; } break; case 'C': updateMenuPosition(data); break; } } private void updateMenuPosition(String data) { char position = data.charAt(1); int pos = Character.getNumericValue(position); logger.debug("Updating menu position to {}", pos); if (pos == -1) { updateState(CHANNEL_NET_MENU_SELECTION, UnDefType.UNDEF); } else { updateState(CHANNEL_NET_MENU_SELECTION, new DecimalType(pos)); } if (data.endsWith("P")) { resetNetMenu(); } } private void resetNetMenu() { logger.debug("Reset net menu"); updateState(CHANNEL_NET_MENU0, new StringType("-")); updateState(CHANNEL_NET_MENU1, new StringType("-")); updateState(CHANNEL_NET_MENU2, new StringType("-")); updateState(CHANNEL_NET_MENU3, new StringType("-")); updateState(CHANNEL_NET_MENU4, new StringType("-")); updateState(CHANNEL_NET_MENU5, new StringType("-")); updateState(CHANNEL_NET_MENU6, new StringType("-")); updateState(CHANNEL_NET_MENU7, new StringType("-")); updateState(CHANNEL_NET_MENU8, new StringType("-")); updateState(CHANNEL_NET_MENU9, new StringType("-")); } private State convertNetUsbPlayStatus(String data) { State state = UnDefType.UNDEF; switch (data.charAt(0)) { case 'P': state = PlayPauseType.PLAY; break; case 'p': case 'S': state = PlayPauseType.PAUSE; break; case 'F': state = RewindFastforwardType.FASTFORWARD; break; case 'R': state = RewindFastforwardType.REWIND; break; } return state; } public void sendRawCommand(String command, String value) { if (connection != null) { connection.send(command, value); } else { logger.debug("Cannot send command to onkyo receiver since the onkyo binding is not initialized"); } } private void sendCommand(EiscpCommand deviceCommand) { if (connection != null) { connection.send(deviceCommand.getCommand(), deviceCommand.getValue()); } else { logger.debug("Connect send command to onkyo receiver since the onkyo binding is not initialized"); } } private void sendCommand(EiscpCommand deviceCommand, Command command) { if (connection != null) { final String cmd = deviceCommand.getCommand(); String valTemplate = deviceCommand.getValue(); String val; if (command instanceof OnOffType) { val = String.format(valTemplate, command == OnOffType.ON ? 1 : 0); } else if (command instanceof StringType) { val = String.format(valTemplate, command); } else if (command instanceof DecimalType) { val = String.format(valTemplate, ((DecimalType) command).intValue()); } else if (command instanceof PercentType) { val = String.format(valTemplate, ((DecimalType) command).intValue()); } else { val = valTemplate; } logger.debug("Sending command '{}' with value '{}' to Onkyo Receiver @{}", cmd, val, connection.getConnectionName()); connection.send(cmd, val); } else { logger.debug("Connect send command to onkyo receiver since the onkyo binding is not initialized"); } } /** * Check the status of the AVR. * * @return */ private void checkStatus() { sendCommand(EiscpCommand.POWER_QUERY); if (connection != null && connection.isConnected()) { sendCommand(EiscpCommand.VOLUME_QUERY); sendCommand(EiscpCommand.SOURCE_QUERY); sendCommand(EiscpCommand.MUTE_QUERY); sendCommand(EiscpCommand.NETUSB_TITLE_QUERY); sendCommand(EiscpCommand.LISTEN_MODE_QUERY); sendCommand(EiscpCommand.INFO_QUERY); if (isChannelAvailable(CHANNEL_POWERZONE2)) { sendCommand(EiscpCommand.ZONE2_POWER_QUERY); sendCommand(EiscpCommand.ZONE2_VOLUME_QUERY); sendCommand(EiscpCommand.ZONE2_SOURCE_QUERY); sendCommand(EiscpCommand.ZONE2_MUTE_QUERY); } if (isChannelAvailable(CHANNEL_POWERZONE3)) { sendCommand(EiscpCommand.ZONE3_POWER_QUERY); sendCommand(EiscpCommand.ZONE3_VOLUME_QUERY); sendCommand(EiscpCommand.ZONE3_SOURCE_QUERY); sendCommand(EiscpCommand.ZONE3_MUTE_QUERY); } } else { updateStatus(ThingStatus.OFFLINE); } } private boolean isChannelAvailable(String channel) { List<Channel> channels = getThing().getChannels(); for (Channel c : channels) { if (c.getUID().getId().equals(channel)) { return true; } } return false; } private void handleVolumeSet(EiscpCommand.Zone zone, final State currentValue, final Command command) { if (command instanceof PercentType) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_SET), downScaleVolume((PercentType) command)); } else if (command.equals(IncreaseDecreaseType.INCREASE)) { if (currentValue instanceof PercentType) { if (((DecimalType) currentValue).intValue() < configuration.volumeLimit) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_UP)); } else { logger.info("Volume level is limited to {}, ignore volume up command.", configuration.volumeLimit); } } } else if (command.equals(IncreaseDecreaseType.DECREASE)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_DOWN)); } else if (command.equals(OnOffType.OFF)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.MUTE_SET), command); } else if (command.equals(OnOffType.ON)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.MUTE_SET), command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_QUERY)); sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.MUTE_QUERY)); } } private State handleReceivedVolume(State volume) { if (volume instanceof DecimalType) { return upScaleVolume(((DecimalType) volume)); } return volume; } private PercentType upScaleVolume(DecimalType volume) { PercentType newVolume = scaleVolumeFromReceiver(volume); if (configuration.volumeLimit < 100) { double scaleCoefficient = 100d / configuration.volumeLimit; PercentType unLimitedVolume = newVolume; newVolume = new PercentType(((Double) (newVolume.doubleValue() * scaleCoefficient)).intValue()); logger.debug("Up scaled volume level '{}' to '{}'", unLimitedVolume, newVolume); } return newVolume; } private DecimalType downScaleVolume(PercentType volume) { PercentType limitedVolume = volume; if (configuration.volumeLimit < 100) { double scaleCoefficient = configuration.volumeLimit / 100d; limitedVolume = new PercentType(((Double) (volume.doubleValue() * scaleCoefficient)).intValue()); logger.debug("Limited volume level '{}' to '{}'", volume, limitedVolume); } return scaleVolumeForReceiver(limitedVolume); } private DecimalType scaleVolumeForReceiver(PercentType volume) { return new DecimalType(((Double) (volume.doubleValue() * configuration.volumeScale)).intValue()); } private PercentType scaleVolumeFromReceiver(DecimalType volume) { return new PercentType(((Double) (volume.intValue() / configuration.volumeScale)).intValue()); } @Override public PercentType getVolume() throws IOException { if (volumeLevelZone1 instanceof PercentType) { return (PercentType) volumeLevelZone1; } throw new IOException(); } @Override public void setVolume(PercentType volume) throws IOException { handleVolumeSet(EiscpCommand.Zone.ZONE1, volumeLevelZone1, downScaleVolume(volume)); } private String guessMimeTypeFromData(byte[] data) { String mimeType = HttpUtil.guessContentTypeFromData(data); logger.debug("Mime type guess from content: {}", mimeType); if (mimeType == null) { mimeType = RawType.DEFAULT_MIME_TYPE; } logger.debug("Mime type: {}", mimeType); return mimeType; } @Override public Collection<Class<? extends ThingHandlerService>> getServices() { return Collections.singletonList(OnkyoThingActionsService.class); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_17
crossvul-java_data_bad_1910_19
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.sonos.internal; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringEscapeUtils; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** * The {@link SonosXMLParser} is a class of helper functions * to parse XML data returned by the Zone Players * * @author Karel Goderis - Initial contribution */ @NonNullByDefault public class SonosXMLParser { static final Logger LOGGER = LoggerFactory.getLogger(SonosXMLParser.class); private static final MessageFormat METADATA_FORMAT = new MessageFormat( "<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" " + "xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" " + "xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\" " + "xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">" + "<item id=\"{0}\" parentID=\"{1}\" restricted=\"true\">" + "<dc:title>{2}</dc:title>" + "<upnp:class>{3}</upnp:class>" + "<desc id=\"cdudn\" nameSpace=\"urn:schemas-rinconnetworks-com:metadata-1-0/\">" + "{4}</desc>" + "</item></DIDL-Lite>"); private enum Element { TITLE, CLASS, ALBUM, ALBUM_ART_URI, CREATOR, RES, TRACK_NUMBER, RESMD, DESC } private enum CurrentElement { item, res, streamContent, albumArtURI, title, upnpClass, creator, album, albumArtist, desc } /** * @param xml * @return a list of alarms from the given xml string. * @throws IOException * @throws SAXException */ public static List<SonosAlarm> getAlarmsFromStringResult(String xml) { AlarmHandler handler = new AlarmHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { LOGGER.error("Could not parse Alarms from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Alarms from string '{}'", xml); } return handler.getAlarms(); } /** * @param xml * @return a list of Entries from the given xml string. * @throws IOException * @throws SAXException */ public static List<SonosEntry> getEntriesFromString(String xml) { EntryHandler handler = new EntryHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { LOGGER.error("Could not parse Entries from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Entries from string '{}'", xml); } return handler.getArtists(); } /** * Returns the meta data which is needed to play Pandora * (and others?) favorites * * @param xml * @return The value of the desc xml tag * @throws SAXException */ public static @Nullable SonosResourceMetaData getResourceMetaData(String xml) throws SAXException { XMLReader reader = XMLReaderFactory.createXMLReader(); ResourceMetaDataHandler handler = new ResourceMetaDataHandler(); reader.setContentHandler(handler); try { reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { LOGGER.error("Could not parse Resource MetaData from String '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Resource MetaData from string '{}'", xml); } return handler.getMetaData(); } /** * @param controller * @param xml * @return zone group from the given xml * @throws IOException * @throws SAXException */ public static List<SonosZoneGroup> getZoneGroupFromXML(String xml) { ZoneGroupHandler handler = new ZoneGroupHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse ZoneGroup from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse ZoneGroup from string '{}'", xml); } return handler.getGroups(); } public static List<String> getRadioTimeFromXML(String xml) { OpmlHandler handler = new OpmlHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse RadioTime from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse RadioTime from string '{}'", xml); } return handler.getTextFields(); } public static Map<String, @Nullable String> getRenderingControlFromXML(String xml) { RenderingControlEventHandler handler = new RenderingControlEventHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse Rendering Control from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Rendering Control from string '{}'", xml); } return handler.getChanges(); } public static Map<String, @Nullable String> getAVTransportFromXML(String xml) { AVTransportEventHandler handler = new AVTransportEventHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse AV Transport from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse AV Transport from string '{}'", xml); } return handler.getChanges(); } public static SonosMetaData getMetaDataFromXML(String xml) { MetaDataHandler handler = new MetaDataHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse MetaData from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse MetaData from string '{}'", xml); } return handler.getMetaData(); } public static List<SonosMusicService> getMusicServicesFromXML(String xml) { MusicServiceHandler handler = new MusicServiceHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse music services from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse music services from string '{}'", xml); } return handler.getServices(); } private static class EntryHandler extends DefaultHandler { // Maintain a set of elements about which it is unuseful to complain about. // This list will be initialized on the first failure case private static @Nullable List<String> ignore; private String id = ""; private String parentId = ""; private StringBuilder upnpClass = new StringBuilder(); private StringBuilder res = new StringBuilder(); private StringBuilder title = new StringBuilder(); private StringBuilder album = new StringBuilder(); private StringBuilder albumArtUri = new StringBuilder(); private StringBuilder creator = new StringBuilder(); private StringBuilder trackNumber = new StringBuilder(); private StringBuilder desc = new StringBuilder(); private @Nullable Element element; private List<SonosEntry> artists = new ArrayList<>(); EntryHandler() { // shouldn't be used outside of this package. } @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { String name = qName == null ? "" : qName; switch (name) { case "container": case "item": if (attributes != null) { id = attributes.getValue("id"); parentId = attributes.getValue("parentID"); } break; case "res": element = Element.RES; break; case "dc:title": element = Element.TITLE; break; case "upnp:class": element = Element.CLASS; break; case "dc:creator": element = Element.CREATOR; break; case "upnp:album": element = Element.ALBUM; break; case "upnp:albumArtURI": element = Element.ALBUM_ART_URI; break; case "upnp:originalTrackNumber": element = Element.TRACK_NUMBER; break; case "r:resMD": element = Element.RESMD; break; default: List<String> curIgnore = ignore; if (curIgnore == null) { curIgnore = new ArrayList<>(); curIgnore.add("DIDL-Lite"); curIgnore.add("type"); curIgnore.add("ordinal"); curIgnore.add("description"); ignore = curIgnore; } if (!curIgnore.contains(localName)) { LOGGER.debug("Did not recognise element named {}", localName); } element = null; break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { Element elt = element; if (elt == null) { return; } switch (elt) { case TITLE: title.append(ch, start, length); break; case CLASS: upnpClass.append(ch, start, length); break; case RES: res.append(ch, start, length); break; case ALBUM: album.append(ch, start, length); break; case ALBUM_ART_URI: albumArtUri.append(ch, start, length); break; case CREATOR: creator.append(ch, start, length); break; case TRACK_NUMBER: trackNumber.append(ch, start, length); break; case RESMD: desc.append(ch, start, length); break; case DESC: break; } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if (("container".equals(qName) || "item".equals(qName))) { element = null; int trackNumberVal = 0; try { trackNumberVal = Integer.parseInt(trackNumber.toString()); } catch (Exception e) { } SonosResourceMetaData md = null; // The resource description is needed for playing favorites on pandora if (!desc.toString().isEmpty()) { try { md = getResourceMetaData(desc.toString()); } catch (SAXException ignore) { LOGGER.debug("Failed to parse embeded", ignore); } } artists.add(new SonosEntry(id, title.toString(), parentId, album.toString(), albumArtUri.toString(), creator.toString(), upnpClass.toString(), res.toString(), trackNumberVal, md)); title = new StringBuilder(); upnpClass = new StringBuilder(); res = new StringBuilder(); album = new StringBuilder(); albumArtUri = new StringBuilder(); creator = new StringBuilder(); trackNumber = new StringBuilder(); desc = new StringBuilder(); } } public List<SonosEntry> getArtists() { return artists; } } private static class ResourceMetaDataHandler extends DefaultHandler { private String id = ""; private String parentId = ""; private StringBuilder title = new StringBuilder(); private StringBuilder upnpClass = new StringBuilder(); private StringBuilder desc = new StringBuilder(); private @Nullable Element element; private @Nullable SonosResourceMetaData metaData; ResourceMetaDataHandler() { // shouldn't be used outside of this package. } @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { String name = qName == null ? "" : qName; switch (name) { case "container": case "item": if (attributes != null) { id = attributes.getValue("id"); parentId = attributes.getValue("parentID"); } break; case "desc": element = Element.DESC; break; case "upnp:class": element = Element.CLASS; break; case "dc:title": element = Element.TITLE; break; default: element = null; break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { Element elt = element; if (elt == null) { return; } switch (elt) { case TITLE: title.append(ch, start, length); break; case CLASS: upnpClass.append(ch, start, length); break; case DESC: desc.append(ch, start, length); break; default: break; } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("DIDL-Lite".equals(qName)) { metaData = new SonosResourceMetaData(id, parentId, title.toString(), upnpClass.toString(), desc.toString()); element = null; desc = new StringBuilder(); upnpClass = new StringBuilder(); title = new StringBuilder(); } } public @Nullable SonosResourceMetaData getMetaData() { return metaData; } } private static class AlarmHandler extends DefaultHandler { private @Nullable String id; private String startTime = ""; private String duration = ""; private String recurrence = ""; private @Nullable String enabled; private String roomUUID = ""; private String programURI = ""; private String programMetaData = ""; private String playMode = ""; private @Nullable String volume; private @Nullable String includeLinkedZones; private List<SonosAlarm> alarms = new ArrayList<>(); AlarmHandler() { // shouldn't be used outside of this package. } @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("Alarm".equals(qName) && attributes != null) { id = attributes.getValue("ID"); duration = attributes.getValue("Duration"); recurrence = attributes.getValue("Recurrence"); startTime = attributes.getValue("StartTime"); enabled = attributes.getValue("Enabled"); roomUUID = attributes.getValue("RoomUUID"); programURI = attributes.getValue("ProgramURI"); programMetaData = attributes.getValue("ProgramMetaData"); playMode = attributes.getValue("PlayMode"); volume = attributes.getValue("Volume"); includeLinkedZones = attributes.getValue("IncludeLinkedZones"); } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("Alarm".equals(qName)) { int finalID = 0; int finalVolume = 0; boolean finalEnabled = !"0".equals(enabled); boolean finalIncludeLinkedZones = !"0".equals(includeLinkedZones); try { finalID = Integer.parseInt(id); finalVolume = Integer.parseInt(volume); } catch (Exception e) { LOGGER.debug("Error parsing Integer"); } alarms.add(new SonosAlarm(finalID, startTime, duration, recurrence, finalEnabled, roomUUID, programURI, programMetaData, playMode, finalVolume, finalIncludeLinkedZones)); } } public List<SonosAlarm> getAlarms() { return alarms; } } private static class ZoneGroupHandler extends DefaultHandler { private final List<SonosZoneGroup> groups = new ArrayList<>(); private final List<String> currentGroupPlayers = new ArrayList<>(); private final List<String> currentGroupPlayerZones = new ArrayList<>(); private String coordinator = ""; private String groupId = ""; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("ZoneGroup".equals(qName) && attributes != null) { groupId = attributes.getValue("ID"); coordinator = attributes.getValue("Coordinator"); } else if ("ZoneGroupMember".equals(qName) && attributes != null) { currentGroupPlayers.add(attributes.getValue("UUID")); String zoneName = attributes.getValue("ZoneName"); if (zoneName != null) { currentGroupPlayerZones.add(zoneName); } String htInfoSet = attributes.getValue("HTSatChanMapSet"); if (htInfoSet != null) { currentGroupPlayers.addAll(getAllHomeTheaterMembers(htInfoSet)); } } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("ZoneGroup".equals(qName)) { groups.add(new SonosZoneGroup(groupId, coordinator, currentGroupPlayers, currentGroupPlayerZones)); currentGroupPlayers.clear(); currentGroupPlayerZones.clear(); } } public List<SonosZoneGroup> getGroups() { return groups; } private Set<String> getAllHomeTheaterMembers(String homeTheaterDescription) { Set<String> homeTheaterMembers = new HashSet<>(); Matcher matcher = Pattern.compile("(RINCON_\\w+)").matcher(homeTheaterDescription); while (matcher.find()) { String member = matcher.group(); homeTheaterMembers.add(member); } return homeTheaterMembers; } } private static class OpmlHandler extends DefaultHandler { // <opml version="1"> // <head> // <status>200</status> // // </head> // <body> // <outline type="text" text="Q-Music 103.3" guide_id="s2398" key="station" // image="http://radiotime-logos.s3.amazonaws.com/s87683q.png" preset_id="s2398"/> // <outline type="text" text="Bjorn Verhoeven" guide_id="p257265" seconds_remaining="2230" duration="7200" // key="show"/> // <outline type="text" text="Top 40-Pop"/> // <outline type="text" text="37m remaining"/> // <outline type="object" text="NowPlaying"> // <nowplaying> // <logo>http://radiotime-logos.s3.amazonaws.com/s87683.png</logo> // <twitter_id /> // </nowplaying> // </outline> // </body> // </opml> private final List<String> textFields = new ArrayList<>(); private @Nullable String textField; private @Nullable String type; // private String logo; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("outline".equals(qName)) { type = attributes == null ? null : attributes.getValue("type"); if ("text".equals(type)) { textField = attributes == null ? null : attributes.getValue("text"); } else { textField = null; } } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("outline".equals(qName)) { String field = textField; if (field != null) { textFields.add(field); } } } public List<String> getTextFields() { return textFields; } } private static class AVTransportEventHandler extends DefaultHandler { /* * <Event xmlns="urn:schemas-upnp-org:metadata-1-0/AVT/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/"> * <InstanceID val="0"> * <TransportState val="PLAYING"/> * <CurrentPlayMode val="NORMAL"/> * <CurrentPlayMode val="0"/> * <NumberOfTracks val="29"/> * <CurrentTrack val="12"/> * <CurrentSection val="0"/> * <CurrentTrackURI val= * "x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2012%20-%20Broken%20Box.wma" * /> * <CurrentTrackDuration val="0:03:02"/> * <CurrentTrackMetaData val= * "&lt;DIDL-Lite xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:upnp=&quot;urn:schemas-upnp-org:metadata-1-0/upnp/&quot; xmlns:r=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot; xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/&quot;&gt;&lt;item id=&quot;-1&quot; parentID=&quot;-1&quot; restricted=&quot;true&quot;&gt;&lt;res protocolInfo=&quot;x-file-cifs:*:audio/x-ms-wma:*&quot; duration=&quot;0:03:02&quot;&gt;x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2012%20-%20Broken%20Box.wma&lt;/res&gt;&lt;r:streamContent&gt;&lt;/r:streamContent&gt;&lt;dc:title&gt;Broken Box&lt;/dc:title&gt;&lt;upnp:class&gt;object.item.audioItem.musicTrack&lt;/upnp:class&gt;&lt;dc:creator&gt;Queens Of The Stone Age&lt;/dc:creator&gt;&lt;upnp:album&gt;Lullabies To Paralyze&lt;/upnp:album&gt;&lt;r:albumArtist&gt;Queens Of The Stone Age&lt;/r:albumArtist&gt;&lt;/item&gt;&lt;/DIDL-Lite&gt;" * /><r:NextTrackURI val= * "x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2013%20-%20&apos;&apos;You%20Got%20A%20Killer%20Scene%20There,%20Man...&apos;&apos;.wma" * /><r:NextTrackMetaData val= * "&lt;DIDL-Lite xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:upnp=&quot;urn:schemas-upnp-org:metadata-1-0/upnp/&quot; xmlns:r=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot; xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/&quot;&gt;&lt;item id=&quot;-1&quot; parentID=&quot;-1&quot; restricted=&quot;true&quot;&gt;&lt;res protocolInfo=&quot;x-file-cifs:*:audio/x-ms-wma:*&quot; duration=&quot;0:04:56&quot;&gt;x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2013%20-%20&amp;apos;&amp;apos;You%20Got%20A%20Killer%20Scene%20There,%20Man...&amp;apos;&amp;apos;.wma&lt;/res&gt;&lt;dc:title&gt;&amp;apos;&amp;apos;You Got A Killer Scene There, Man...&amp;apos;&amp;apos;&lt;/dc:title&gt;&lt;upnp:class&gt;object.item.audioItem.musicTrack&lt;/upnp:class&gt;&lt;dc:creator&gt;Queens Of The Stone Age&lt;/dc:creator&gt;&lt;upnp:album&gt;Lullabies To Paralyze&lt;/upnp:album&gt;&lt;r:albumArtist&gt;Queens Of The Stone Age&lt;/r:albumArtist&gt;&lt;/item&gt;&lt;/DIDL-Lite&gt;" * /><r:EnqueuedTransportURI * val="x-rincon-playlist:RINCON_000E582126EE01400#A:ALBUMARTIST/Queens%20Of%20The%20Stone%20Age"/><r: * EnqueuedTransportURIMetaData val= * "&lt;DIDL-Lite xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:upnp=&quot;urn:schemas-upnp-org:metadata-1-0/upnp/&quot; xmlns:r=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot; xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/&quot;&gt;&lt;item id=&quot;A:ALBUMARTIST/Queens%20Of%20The%20Stone%20Age&quot; parentID=&quot;A:ALBUMARTIST&quot; restricted=&quot;true&quot;&gt;&lt;dc:title&gt;Queens Of The Stone Age&lt;/dc:title&gt;&lt;upnp:class&gt;object.container&lt;/upnp:class&gt;&lt;desc id=&quot;cdudn&quot; nameSpace=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot;&gt;RINCON_AssociatedZPUDN&lt;/desc&gt;&lt;/item&gt;&lt;/DIDL-Lite&gt;" * /> * <PlaybackStorageMedium val="NETWORK"/> * <AVTransportURI val="x-rincon-queue:RINCON_000E5812BC1801400#0"/> * <AVTransportURIMetaData val=""/> * <CurrentTransportActions val="Play, Stop, Pause, Seek, Next, Previous"/> * <TransportStatus val="OK"/> * <r:SleepTimerGeneration val="0"/> * <r:AlarmRunning val="0"/> * <r:SnoozeRunning val="0"/> * <r:RestartPending val="0"/> * <TransportPlaySpeed val="NOT_IMPLEMENTED"/> * <CurrentMediaDuration val="NOT_IMPLEMENTED"/> * <RecordStorageMedium val="NOT_IMPLEMENTED"/> * <PossiblePlaybackStorageMedia val="NONE, NETWORK"/> * <PossibleRecordStorageMedia val="NOT_IMPLEMENTED"/> * <RecordMediumWriteStatus val="NOT_IMPLEMENTED"/> * <CurrentRecordQualityMode val="NOT_IMPLEMENTED"/> * <PossibleRecordQualityModes val="NOT_IMPLEMENTED"/> * <NextAVTransportURI val="NOT_IMPLEMENTED"/> * <NextAVTransportURIMetaData val="NOT_IMPLEMENTED"/> * </InstanceID> * </Event> */ private final Map<String, @Nullable String> changes = new HashMap<>(); @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { /* * The events are all of the form <qName val="value"/> so we can get all * the info we need from here. */ if (localName == null) { // this means that localName isn't defined in EventType, which is expected for some elements LOGGER.info("{} is not defined in EventType. ", localName); } else { String val = attributes == null ? null : attributes.getValue("val"); if (val != null) { changes.put(localName, val); } } } public Map<String, @Nullable String> getChanges() { return changes; } } private static class MetaDataHandler extends DefaultHandler { private @Nullable CurrentElement currentElement; private String id = "-1"; private String parentId = "-1"; private StringBuilder resource = new StringBuilder(); private StringBuilder streamContent = new StringBuilder(); private StringBuilder albumArtUri = new StringBuilder(); private StringBuilder title = new StringBuilder(); private StringBuilder upnpClass = new StringBuilder(); private StringBuilder creator = new StringBuilder(); private StringBuilder album = new StringBuilder(); private StringBuilder albumArtist = new StringBuilder(); @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { String name = localName == null ? "" : localName; switch (name) { case "item": currentElement = CurrentElement.item; if (attributes != null) { id = attributes.getValue("id"); parentId = attributes.getValue("parentID"); } break; case "res": currentElement = CurrentElement.res; break; case "streamContent": currentElement = CurrentElement.streamContent; break; case "albumArtURI": currentElement = CurrentElement.albumArtURI; break; case "title": currentElement = CurrentElement.title; break; case "class": currentElement = CurrentElement.upnpClass; break; case "creator": currentElement = CurrentElement.creator; break; case "album": currentElement = CurrentElement.album; break; case "albumArtist": currentElement = CurrentElement.albumArtist; break; default: // unknown element currentElement = null; break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { CurrentElement elt = currentElement; if (elt == null) { return; } switch (elt) { case item: break; case res: resource.append(ch, start, length); break; case streamContent: streamContent.append(ch, start, length); break; case albumArtURI: albumArtUri.append(ch, start, length); break; case title: title.append(ch, start, length); break; case upnpClass: upnpClass.append(ch, start, length); break; case creator: creator.append(ch, start, length); break; case album: album.append(ch, start, length); break; case albumArtist: albumArtist.append(ch, start, length); break; case desc: break; } } public SonosMetaData getMetaData() { return new SonosMetaData(id, parentId, resource.toString(), streamContent.toString(), albumArtUri.toString(), title.toString(), upnpClass.toString(), creator.toString(), album.toString(), albumArtist.toString()); } } private static class RenderingControlEventHandler extends DefaultHandler { private final Map<String, @Nullable String> changes = new HashMap<>(); private boolean getPresetName = false; private @Nullable String presetName; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if (qName == null) { return; } String channel; String val; switch (qName) { case "Volume": case "Mute": case "Loudness": channel = attributes == null ? null : attributes.getValue("channel"); val = attributes == null ? null : attributes.getValue("val"); if (channel != null && val != null) { changes.put(qName + channel, val); } break; case "Bass": case "Treble": case "OutputFixed": val = attributes == null ? null : attributes.getValue("val"); if (val != null) { changes.put(qName, val); } break; case "PresetNameList": getPresetName = true; break; default: break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { if (getPresetName) { presetName = new String(ch, start, length); } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if (getPresetName) { getPresetName = false; String preset = presetName; if (qName != null && preset != null) { changes.put(qName, preset); } } } public Map<String, @Nullable String> getChanges() { return changes; } } private static class MusicServiceHandler extends DefaultHandler { private final List<SonosMusicService> services = new ArrayList<>(); @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { // All services are of the form <services Id="value" Name="value">...</Service> if ("Service".equals(qName) && attributes != null && attributes.getValue("Id") != null && attributes.getValue("Name") != null) { services.add(new SonosMusicService(attributes.getValue("Id"), attributes.getValue("Name"))); } } public List<SonosMusicService> getServices() { return services; } } public static @Nullable String getRoomName(String descriptorXML) { RoomNameHandler roomNameHandler = new RoomNameHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(roomNameHandler); URL url = new URL(descriptorXML); reader.parse(new InputSource(url.openStream())); } catch (IOException | SAXException e) { LOGGER.error("Could not parse Sonos room name from string '{}'", descriptorXML); } return roomNameHandler.getRoomName(); } private static class RoomNameHandler extends DefaultHandler { private @Nullable String roomName; private boolean roomNameTag; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("roomName".equalsIgnoreCase(localName)) { roomNameTag = true; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { if (roomNameTag) { roomName = new String(ch, start, length); roomNameTag = false; } } public @Nullable String getRoomName() { return roomName; } } public static @Nullable String parseModelDescription(URL descriptorURL) { ModelNameHandler modelNameHandler = new ModelNameHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(modelNameHandler); URL url = new URL(descriptorURL.toString()); reader.parse(new InputSource(url.openStream())); } catch (IOException | SAXException e) { LOGGER.error("Could not parse Sonos model name from string '{}'", descriptorURL.toString()); } return modelNameHandler.getModelName(); } private static class ModelNameHandler extends DefaultHandler { private @Nullable String modelName; private boolean modelNameTag; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("modelName".equalsIgnoreCase(localName)) { modelNameTag = true; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { if (modelNameTag) { modelName = new String(ch, start, length); modelNameTag = false; } } public @Nullable String getModelName() { return modelName; } } /** * The model name provided by upnp is formated like in the example form "Sonos PLAY:1" or "Sonos PLAYBAR" * * @param sonosModelName Sonos model name provided via upnp device * @return the extracted players model name without column (:) character used for ThingType creation */ public static String extractModelName(String sonosModelName) { String ret = sonosModelName; Matcher matcher = Pattern.compile("\\s(.*)").matcher(ret); if (matcher.find()) { ret = matcher.group(1); } if (ret.contains(":")) { ret = ret.replace(":", ""); } return ret; } public static String compileMetadataString(SonosEntry entry) { /** * If the entry contains resource meta data we will override this with * that data. */ String id = entry.getId(); String parentId = entry.getParentId(); String title = entry.getTitle(); String upnpClass = entry.getUpnpClass(); /** * By default 'RINCON_AssociatedZPUDN' is used for most operations, * however when playing a favorite entry that is associated withh a * subscription like pandora we need to use the desc string asscoiated * with that item. */ String desc = entry.getDesc(); if (desc == null) { desc = "RINCON_AssociatedZPUDN"; } /** * If resource meta data exists, use it over the parent data */ SonosResourceMetaData resourceMetaData = entry.getResourceMetaData(); if (resourceMetaData != null) { id = resourceMetaData.getId(); parentId = resourceMetaData.getParentId(); title = resourceMetaData.getTitle(); desc = resourceMetaData.getDesc(); upnpClass = resourceMetaData.getUpnpClass(); } title = StringEscapeUtils.escapeXml(title); String metadata = METADATA_FORMAT.format(new Object[] { id, parentId, title, upnpClass, desc }); return metadata; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_19
crossvul-java_data_bad_1577_0
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.selector.filter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.StringReader; import org.apache.xpath.CachedXPathAPI; import org.apache.xpath.objects.XObject; import org.w3c.dom.Document; import org.w3c.dom.traversal.NodeIterator; import org.xml.sax.InputSource; public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { private final String xpath; public XalanXPathEvaluator(String xpath) { this.xpath = xpath; } public boolean evaluate(Filterable m) throws FilterException { String stringBody = m.getBodyAs(String.class); if (stringBody != null) { return evaluate(stringBody); } return false; } protected boolean evaluate(String text) { return evaluate(new InputSource(new StringReader(text))); } protected boolean evaluate(InputSource inputSource) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder = factory.newDocumentBuilder(); Document doc = dbuilder.parse(inputSource); //An XPath expression could return a true or false value instead of a node. //eval() is a better way to determine the boolean value of the exp. //For compliance with legacy behavior where selecting an empty node returns true, //selectNodeIterator is attempted in case of a failure. CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); XObject result = cachedXPathAPI.eval(doc, xpath); if (result.bool()) return true; else { NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); return (iterator.nextNode() != null); } } catch (Throwable e) { return false; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1577_0
crossvul-java_data_bad_4290_4
/* * file: ConceptDrawProjectReader.java * author: Jon Iles * copyright: (c) Packwood Software 2018 * date: 9 July 2018 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.conceptdraw; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.UnmarshallerHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import net.sf.mpxj.DateRange; import net.sf.mpxj.Duration; import net.sf.mpxj.EventManager; import net.sf.mpxj.MPXJException; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectConfig; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.ProjectProperties; import net.sf.mpxj.Rate; import net.sf.mpxj.Relation; import net.sf.mpxj.RelationType; import net.sf.mpxj.Resource; import net.sf.mpxj.ResourceAssignment; import net.sf.mpxj.Task; import net.sf.mpxj.TimeUnit; import net.sf.mpxj.common.AlphanumComparator; import net.sf.mpxj.conceptdraw.schema.Document; import net.sf.mpxj.conceptdraw.schema.Document.Calendars.Calendar; import net.sf.mpxj.conceptdraw.schema.Document.Calendars.Calendar.ExceptedDays.ExceptedDay; import net.sf.mpxj.conceptdraw.schema.Document.Calendars.Calendar.WeekDays.WeekDay; import net.sf.mpxj.conceptdraw.schema.Document.Links.Link; import net.sf.mpxj.conceptdraw.schema.Document.Projects.Project; import net.sf.mpxj.conceptdraw.schema.Document.WorkspaceProperties; import net.sf.mpxj.listener.ProjectListener; import net.sf.mpxj.reader.AbstractProjectReader; /** * This class creates a new ProjectFile instance by reading a ConceptDraw Project file. */ public final class ConceptDrawProjectReader extends AbstractProjectReader { /** * {@inheritDoc} */ @Override public void addProjectListener(ProjectListener listener) { if (m_projectListeners == null) { m_projectListeners = new ArrayList<>(); } m_projectListeners.add(listener); } /** * {@inheritDoc} */ @Override public ProjectFile read(InputStream stream) throws MPXJException { try { m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_calendarMap = new HashMap<>(); m_taskIdMap = new HashMap<>(); ProjectConfig config = m_projectFile.getProjectConfig(); config.setAutoResourceUniqueID(false); config.setAutoResourceID(false); m_projectFile.getProjectProperties().setFileApplication("ConceptDraw PROJECT"); m_projectFile.getProjectProperties().setFileType("CDP"); m_eventManager.addProjectListeners(m_projectListeners); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } Unmarshaller unmarshaller = CONTEXT.createUnmarshaller(); XMLFilter filter = new NamespaceFilter(); filter.setParent(xmlReader); UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); filter.setContentHandler(unmarshallerHandler); filter.parse(new InputSource(new InputStreamReader(stream))); Document cdp = (Document) unmarshallerHandler.getResult(); readProjectProperties(cdp); readCalendars(cdp); readResources(cdp); readTasks(cdp); readRelationships(cdp); // // Ensure that the unique ID counters are correct // config.updateUniqueCounters(); return m_projectFile; } catch (ParserConfigurationException ex) { throw new MPXJException("Failed to parse file", ex); } catch (JAXBException ex) { throw new MPXJException("Failed to parse file", ex); } catch (SAXException ex) { throw new MPXJException("Failed to parse file", ex); } catch (IOException ex) { throw new MPXJException("Failed to parse file", ex); } finally { m_projectFile = null; m_eventManager = null; m_projectListeners = null; m_calendarMap = null; m_taskIdMap = null; } } /** * Extracts project properties from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readProjectProperties(Document cdp) { WorkspaceProperties props = cdp.getWorkspaceProperties(); ProjectProperties mpxjProps = m_projectFile.getProjectProperties(); mpxjProps.setSymbolPosition(props.getCurrencyPosition()); mpxjProps.setCurrencyDigits(props.getCurrencyDigits()); mpxjProps.setCurrencySymbol(props.getCurrencySymbol()); mpxjProps.setDaysPerMonth(props.getDaysPerMonth()); mpxjProps.setMinutesPerDay(props.getHoursPerDay()); mpxjProps.setMinutesPerWeek(props.getHoursPerWeek()); m_workHoursPerDay = mpxjProps.getMinutesPerDay().doubleValue() / 60.0; } /** * Extracts calendar data from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readCalendars(Document cdp) { for (Calendar calendar : cdp.getCalendars().getCalendar()) { readCalendar(calendar); } for (Calendar calendar : cdp.getCalendars().getCalendar()) { ProjectCalendar child = m_calendarMap.get(calendar.getID()); ProjectCalendar parent = m_calendarMap.get(calendar.getBaseCalendarID()); if (parent == null) { m_projectFile.setDefaultCalendar(child); } else { child.setParent(parent); } } } /** * Read a calendar. * * @param calendar ConceptDraw PROJECT calendar */ private void readCalendar(Calendar calendar) { ProjectCalendar mpxjCalendar = m_projectFile.addCalendar(); mpxjCalendar.setName(calendar.getName()); m_calendarMap.put(calendar.getID(), mpxjCalendar); for (WeekDay day : calendar.getWeekDays().getWeekDay()) { readWeekDay(mpxjCalendar, day); } for (ExceptedDay day : calendar.getExceptedDays().getExceptedDay()) { readExceptionDay(mpxjCalendar, day); } } /** * Reads a single day for a calendar. * * @param mpxjCalendar ProjectCalendar instance * @param day ConceptDraw PROJECT week day */ private void readWeekDay(ProjectCalendar mpxjCalendar, WeekDay day) { if (day.isIsDayWorking()) { ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day.getDay()); for (Document.Calendars.Calendar.WeekDays.WeekDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod()) { hours.addRange(new DateRange(period.getFrom(), period.getTo())); } } } /** * Read an exception day for a calendar. * * @param mpxjCalendar ProjectCalendar instance * @param day ConceptDraw PROJECT exception day */ private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day) { ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate()); if (day.isIsDayWorking()) { for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod()) { mpxjException.addRange(new DateRange(period.getFrom(), period.getTo())); } } } /** * Reads resource data from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readResources(Document cdp) { for (Document.Resources.Resource resource : cdp.getResources().getResource()) { readResource(resource); } } /** * Reads a single resource from a ConceptDraw PROJECT file. * * @param resource ConceptDraw PROJECT resource */ private void readResource(Document.Resources.Resource resource) { Resource mpxjResource = m_projectFile.addResource(); mpxjResource.setName(resource.getName()); mpxjResource.setResourceCalendar(m_calendarMap.get(resource.getCalendarID())); mpxjResource.setStandardRate(new Rate(resource.getCost(), resource.getCostTimeUnit())); mpxjResource.setEmailAddress(resource.getEMail()); mpxjResource.setGroup(resource.getGroup()); //resource.getHyperlinks() mpxjResource.setUniqueID(resource.getID()); //resource.getMarkerID() mpxjResource.setNotes(resource.getNote()); mpxjResource.setID(Integer.valueOf(resource.getOutlineNumber())); //resource.getStyleProject() mpxjResource.setType(resource.getSubType() == null ? resource.getType() : resource.getSubType()); } /** * Read the projects from a ConceptDraw PROJECT file as top level tasks. * * @param cdp ConceptDraw PROJECT file */ private void readTasks(Document cdp) { // // Sort the projects into the correct order // List<Project> projects = new ArrayList<>(cdp.getProjects().getProject()); final AlphanumComparator comparator = new AlphanumComparator(); Collections.sort(projects, new Comparator<Project>() { @Override public int compare(Project o1, Project o2) { return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber()); } }); for (Project project : cdp.getProjects().getProject()) { readProject(project); } } /** * Read a project from a ConceptDraw PROJECT file. * * @param project ConceptDraw PROJECT project */ private void readProject(Project project) { Task mpxjTask = m_projectFile.addTask(); //project.getAuthor() mpxjTask.setBaselineCost(project.getBaselineCost()); mpxjTask.setBaselineFinish(project.getBaselineFinishDate()); mpxjTask.setBaselineStart(project.getBaselineStartDate()); //project.getBudget(); //project.getCompany() mpxjTask.setFinish(project.getFinishDate()); //project.getGoal() //project.getHyperlinks() //project.getMarkerID() mpxjTask.setName(project.getName()); mpxjTask.setNotes(project.getNote()); mpxjTask.setPriority(project.getPriority()); // project.getSite() mpxjTask.setStart(project.getStartDate()); // project.getStyleProject() // project.getTask() // project.getTimeScale() // project.getViewProperties() String projectIdentifier = project.getID().toString(); mpxjTask.setGUID(UUID.nameUUIDFromBytes(projectIdentifier.getBytes())); // // Sort the tasks into the correct order // List<Document.Projects.Project.Task> tasks = new ArrayList<>(project.getTask()); final AlphanumComparator comparator = new AlphanumComparator(); Collections.sort(tasks, new Comparator<Document.Projects.Project.Task>() { @Override public int compare(Document.Projects.Project.Task o1, Document.Projects.Project.Task o2) { return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber()); } }); Map<String, Task> map = new HashMap<>(); map.put("", mpxjTask); for (Document.Projects.Project.Task task : tasks) { readTask(projectIdentifier, map, task); } } /** * Read a task from a ConceptDraw PROJECT file. * * @param projectIdentifier parent project identifier * @param map outline number to task map * @param task ConceptDraw PROJECT task */ private void readTask(String projectIdentifier, Map<String, Task> map, Document.Projects.Project.Task task) { Task parentTask = map.get(getParentOutlineNumber(task.getOutlineNumber())); Task mpxjTask = parentTask.addTask(); TimeUnit units = task.getBaseDurationTimeUnit(); mpxjTask.setCost(task.getActualCost()); mpxjTask.setDuration(getDuration(units, task.getActualDuration())); mpxjTask.setFinish(task.getActualFinishDate()); mpxjTask.setStart(task.getActualStartDate()); mpxjTask.setBaselineDuration(getDuration(units, task.getBaseDuration())); mpxjTask.setBaselineFinish(task.getBaseFinishDate()); mpxjTask.setBaselineCost(task.getBaselineCost()); // task.getBaselineFinishDate() // task.getBaselineFinishTemplateOffset() // task.getBaselineStartDate() // task.getBaselineStartTemplateOffset() mpxjTask.setBaselineStart(task.getBaseStartDate()); // task.getCallouts() mpxjTask.setPercentageComplete(task.getComplete()); mpxjTask.setDeadline(task.getDeadlineDate()); // task.getDeadlineTemplateOffset() // task.getHyperlinks() // task.getMarkerID() mpxjTask.setName(task.getName()); mpxjTask.setNotes(task.getNote()); mpxjTask.setPriority(task.getPriority()); // task.getRecalcBase1() // task.getRecalcBase2() mpxjTask.setType(task.getSchedulingType()); // task.getStyleProject() // task.getTemplateOffset() // task.getValidatedByProject() if (task.isIsMilestone()) { mpxjTask.setMilestone(true); mpxjTask.setDuration(Duration.getInstance(0, TimeUnit.HOURS)); mpxjTask.setBaselineDuration(Duration.getInstance(0, TimeUnit.HOURS)); } String taskIdentifier = projectIdentifier + "." + task.getID(); m_taskIdMap.put(task.getID(), mpxjTask); mpxjTask.setGUID(UUID.nameUUIDFromBytes(taskIdentifier.getBytes())); map.put(task.getOutlineNumber(), mpxjTask); for (Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment : task.getResourceAssignments().getResourceAssignment()) { readResourceAssignment(mpxjTask, assignment); } } /** * Read resource assignments. * * @param task Parent task * @param assignment ConceptDraw PROJECT resource assignment */ private void readResourceAssignment(Task task, Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment) { Resource resource = m_projectFile.getResourceByUniqueID(assignment.getResourceID()); if (resource != null) { ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource); mpxjAssignment.setUniqueID(assignment.getID()); mpxjAssignment.setWork(Duration.getInstance(assignment.getManHour().doubleValue() * m_workHoursPerDay, TimeUnit.HOURS)); mpxjAssignment.setUnits(assignment.getUse()); } } /** * Read all task relationships from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readRelationships(Document cdp) { for (Link link : cdp.getLinks().getLink()) { readRelationship(link); } } /** * Read a task relationship. * * @param link ConceptDraw PROJECT task link */ private void readRelationship(Link link) { Task sourceTask = m_taskIdMap.get(link.getSourceTaskID()); Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID()); if (sourceTask != null && destinationTask != null) { Duration lag = getDuration(link.getLagUnit(), link.getLag()); RelationType type = link.getType(); Relation relation = destinationTask.addPredecessor(sourceTask, type, lag); relation.setUniqueID(link.getID()); } } /** * Read a duration. * * @param units duration units * @param duration duration value * @return Duration instance */ private Duration getDuration(TimeUnit units, Double duration) { Duration result = null; if (duration != null) { double durationValue = duration.doubleValue() * 100.0; switch (units) { case MINUTES: { durationValue *= MINUTES_PER_DAY; break; } case HOURS: { durationValue *= HOURS_PER_DAY; break; } case DAYS: { durationValue *= 3.0; break; } case WEEKS: { durationValue *= 0.6; break; } case MONTHS: { durationValue *= 0.15; break; } default: { throw new IllegalArgumentException("Unsupported time units " + units); } } durationValue = Math.round(durationValue) / 100.0; result = Duration.getInstance(durationValue, units); } return result; } /** * Return the parent outline number, or an empty string if * we have a root task. * * @param outlineNumber child outline number * @return parent outline number */ private String getParentOutlineNumber(String outlineNumber) { String result; int index = outlineNumber.lastIndexOf('.'); if (index == -1) { result = ""; } else { result = outlineNumber.substring(0, index); } return result; } private ProjectFile m_projectFile; private EventManager m_eventManager; private List<ProjectListener> m_projectListeners; private Map<Integer, ProjectCalendar> m_calendarMap; private Map<Integer, Task> m_taskIdMap; private double m_workHoursPerDay; private static final int HOURS_PER_DAY = 24; private static final int MINUTES_PER_DAY = HOURS_PER_DAY * 60; /** * Cached context to minimise construction cost. */ private static JAXBContext CONTEXT; /** * Note any error occurring during context construction. */ private static JAXBException CONTEXT_EXCEPTION; static { try { // // JAXB RI property to speed up construction // System.setProperty("com.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot", "true"); // // Construct the context // CONTEXT = JAXBContext.newInstance("net.sf.mpxj.conceptdraw.schema", ConceptDrawProjectReader.class.getClassLoader()); } catch (JAXBException ex) { CONTEXT_EXCEPTION = ex; CONTEXT = null; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4290_4
crossvul-java_data_bad_1910_16
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.insteon.internal.message; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.insteon.internal.utils.Pair; import org.openhab.binding.insteon.internal.utils.Utils.DataTypeParser; import org.openhab.binding.insteon.internal.utils.Utils.ParsingException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Reads the Msg definitions from an XML file * * @author Daniel Pfrommer - Initial contribution * @author Rob Nielsen - Port to openHAB 2 insteon binding */ @NonNullByDefault @SuppressWarnings("null") public class XMLMessageReader { /** * Reads the message definitions from an xml file * * @param input input stream from which to read * @return what was read from file: the map between clear text string and Msg objects * @throws IOException couldn't read file etc * @throws ParsingException something wrong with the file format * @throws FieldException something wrong with the field definition */ public static HashMap<String, Msg> readMessageDefinitions(InputStream input) throws IOException, ParsingException, FieldException { HashMap<String, Msg> messageMap = new HashMap<>(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Parse it! Document doc = dBuilder.parse(input); doc.getDocumentElement().normalize(); Node root = doc.getDocumentElement(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("msg")) { Pair<String, Msg> msgDef = readMessageDefinition((Element) node); messageMap.put(msgDef.getKey(), msgDef.getValue()); } } } } catch (SAXException e) { throw new ParsingException("Failed to parse XML!", e); } catch (ParserConfigurationException e) { throw new ParsingException("Got parser config exception! ", e); } return messageMap; } private static Pair<String, Msg> readMessageDefinition(Element msg) throws FieldException, ParsingException { int length = 0; int hlength = 0; LinkedHashMap<Field, Object> fieldMap = new LinkedHashMap<>(); String dir = msg.getAttribute("direction"); String name = msg.getAttribute("name"); Msg.Direction direction = Msg.Direction.getDirectionFromString(dir); if (msg.hasAttribute("length")) { length = Integer.parseInt(msg.getAttribute("length")); } NodeList nodes = msg.getChildNodes(); int offset = 0; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("header")) { int o = readHeaderElement((Element) node, fieldMap); hlength = o; // Increment the offset by the header length offset += o; } else { Pair<Field, Object> field = readField((Element) node, offset); fieldMap.put(field.getKey(), field.getValue()); // Increment the offset offset += field.getKey().getType().getSize(); } } } if (offset != length) { throw new ParsingException( "Actual msg length " + offset + " differs from given msg length " + length + "!"); } if (length == 0) { length = offset; } return new Pair<>(name, createMsg(fieldMap, length, hlength, direction)); } private static int readHeaderElement(Element header, LinkedHashMap<Field, Object> fields) throws ParsingException { int offset = 0; int headerLen = Integer.parseInt(header.getAttribute("length")); NodeList nodes = header.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { @Nullable Pair<Field, Object> definition = readField((Element) node, offset); if (definition != null) { offset += definition.getKey().getType().getSize(); fields.put(definition.getKey(), definition.getValue()); } } } if (headerLen != offset) { throw new ParsingException( "Actual header length " + offset + " differs from given length " + headerLen + "!"); } return headerLen; } private static Pair<Field, Object> readField(Element field, int offset) { DataType dType = DataType.getDataType(field.getTagName()); // Will return blank if no name attribute String name = field.getAttribute("name"); Field f = new Field(name, dType, offset); // Now we have field, only need value String sVal = field.getTextContent(); Object val = DataTypeParser.parseDataType(dType, sVal); Pair<Field, Object> pair = new Pair<>(f, val); return pair; } private static Msg createMsg(HashMap<Field, Object> values, int length, int headerLength, Msg.Direction dir) throws FieldException { Msg msg = new Msg(headerLength, new byte[length], length, dir); for (Entry<Field, Object> e : values.entrySet()) { Field f = e.getKey(); f.set(msg.getData(), e.getValue()); if (f.getName() != null && !f.getName().equals("")) { msg.addField(f); } } return msg; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_16
crossvul-java_data_good_1736_1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.milton.http.webdav; import io.milton.common.ReadingException; import io.milton.common.StreamUtils; import io.milton.common.WritingException; import java.io.ByteArrayInputStream; import org.apache.commons.io.output.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import javax.xml.namespace.QName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * * @author brad */ public class DefaultPropPatchParser implements PropPatchRequestParser { private final static Logger log = LoggerFactory.getLogger( DefaultPropPatchParser.class ); @Override public PropPatchParseResult getRequestedFields( InputStream in ) { log.debug( "getRequestedFields" ); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); StreamUtils.readTo( in, bout, false, true ); byte[] arr = bout.toByteArray(); return parseContent( arr ); } catch( SAXException ex ) { throw new RuntimeException( ex ); } catch( ReadingException ex ) { throw new RuntimeException( ex ); } catch( WritingException ex ) { throw new RuntimeException( ex ); } catch( IOException ex ) { throw new RuntimeException( ex ); } } private PropPatchParseResult parseContent( byte[] arr ) throws IOException, SAXException { if( arr.length > 0 ) { log.debug( "processing content" ); ByteArrayInputStream bin = new ByteArrayInputStream( arr ); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); // https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); PropPatchSaxHandler handler = new PropPatchSaxHandler(); reader.setContentHandler( handler ); reader.parse( new InputSource( bin ) ); log.debug( "toset: " + handler.getAttributesToSet().size()); return new PropPatchParseResult( handler.getAttributesToSet(), handler.getAttributesToRemove().keySet() ); } else { log.debug( "empty content" ); return new PropPatchParseResult( new HashMap<QName, String>(), new HashSet<QName>() ); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1736_1
crossvul-java_data_good_1910_2
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.avmfritz.internal.util; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.stream.XMLInputFactory; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.avmfritz.internal.dto.DeviceListModel; import org.openhab.binding.avmfritz.internal.dto.templates.TemplateListModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation for a static use of JAXBContext as singleton instance. * * @author Christoph Weitkamp - Initial contribution */ @NonNullByDefault public class JAXBUtils { private static final Logger LOGGER = LoggerFactory.getLogger(JAXBUtils.class); public static final @Nullable JAXBContext JAXBCONTEXT_DEVICES = initJAXBContextDevices(); public static final @Nullable JAXBContext JAXBCONTEXT_TEMPLATES = initJAXBContextTemplates(); public static final XMLInputFactory XMLINPUTFACTORY = initXMLInputFactory(); private static @Nullable JAXBContext initJAXBContextDevices() { try { return JAXBContext.newInstance(DeviceListModel.class); } catch (JAXBException e) { LOGGER.error("Exception creating JAXBContext for devices: {}", e.getLocalizedMessage(), e); return null; } } private static @Nullable JAXBContext initJAXBContextTemplates() { try { return JAXBContext.newInstance(TemplateListModel.class); } catch (JAXBException e) { LOGGER.error("Exception creating JAXBContext for templates: {}", e.getLocalizedMessage(), e); return null; } } private static XMLInputFactory initXMLInputFactory() { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); return xif; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_2
crossvul-java_data_bad_1910_6
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.dlinksmarthome.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeader; import javax.xml.soap.MimeHeaders; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.util.BytesContentProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * The {@link DLinkHNAPCommunication} is responsible for communicating with D-Link * Smart Home devices using the HNAP interface. * * This abstract class handles login and authentication which is common between devices. * * Reverse engineered from Login.html and soapclient.js retrieved from the device. * * @author Mike Major - Initial contribution */ public abstract class DLinkHNAPCommunication { // SOAP actions private static final String LOGIN_ACTION = "\"http://purenetworks.com/HNAP1/LOGIN\""; // Strings used more than once private static final String LOGIN = "LOGIN"; private static final String ACTION = "Action"; private static final String USERNAME = "Username"; private static final String LOGINPASSWORD = "LoginPassword"; private static final String CAPTCHA = "Captcha"; private static final String ADMIN = "Admin"; private static final String LOGINRESULT = "LOGINResult"; private static final String COOKIE = "Cookie"; /** * HNAP XMLNS */ protected static final String HNAP_XMLNS = "http://purenetworks.com/HNAP1"; /** * The SOAP action HTML header */ protected static final String SOAPACTION = "SOAPAction"; /** * OK represents a successful action */ protected static final String OK = "OK"; /** * Use to log connection issues */ private final Logger logger = LoggerFactory.getLogger(DLinkHNAPCommunication.class); private URI uri; private final HttpClient httpClient; private final String pin; private String privateKey; private DocumentBuilder parser; private SOAPMessage requestAction; private SOAPMessage loginAction; private HNAPStatus status = HNAPStatus.INITIALISED; /** * Indicates the status of the HNAP interface * */ protected enum HNAPStatus { /** * Ready to start communication with device */ INITIALISED, /** * Successfully logged in to device */ LOGGED_IN, /** * Problem communicating with device */ COMMUNICATION_ERROR, /** * Internal error */ INTERNAL_ERROR, /** * Error due to unsupported firmware */ UNSUPPORTED_FIRMWARE, /** * Error due to invalid pin code */ INVALID_PIN } /** * Use {@link #getHNAPStatus()} to determine the status of the HNAP connection * after construction. * * @param ipAddress * @param pin */ public DLinkHNAPCommunication(final String ipAddress, final String pin) { this.pin = pin; httpClient = new HttpClient(); try { uri = new URI("http://" + ipAddress + "/HNAP1"); httpClient.start(); parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final MessageFactory messageFactory = MessageFactory.newInstance(); requestAction = messageFactory.createMessage(); loginAction = messageFactory.createMessage(); buildRequestAction(); buildLoginAction(); } catch (final SOAPException e) { logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final URISyntaxException e) { logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final ParserConfigurationException e) { logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final Exception e) { // Thrown by httpClient.start() logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } } /** * Stop communicating with the device */ public void dispose() { try { httpClient.stop(); } catch (final Exception e) { // Ignored } } /** * This is the first SOAP message used in the login process and is used to retrieve * the cookie, challenge and public key used for authentication. * * @throws SOAPException */ private void buildRequestAction() throws SOAPException { requestAction.getSOAPHeader().detachNode(); final SOAPBody soapBody = requestAction.getSOAPBody(); final SOAPElement soapBodyElem = soapBody.addChildElement(LOGIN, "", HNAP_XMLNS); soapBodyElem.addChildElement(ACTION).addTextNode("request"); soapBodyElem.addChildElement(USERNAME).addTextNode(ADMIN); soapBodyElem.addChildElement(LOGINPASSWORD); soapBodyElem.addChildElement(CAPTCHA); final MimeHeaders headers = requestAction.getMimeHeaders(); headers.addHeader(SOAPACTION, LOGIN_ACTION); requestAction.saveChanges(); } /** * This is the second SOAP message used in the login process and uses a password derived * from the challenge, public key and the device's pin code. * * @throws SOAPException */ private void buildLoginAction() throws SOAPException { loginAction.getSOAPHeader().detachNode(); final SOAPBody soapBody = loginAction.getSOAPBody(); final SOAPElement soapBodyElem = soapBody.addChildElement(LOGIN, "", HNAP_XMLNS); soapBodyElem.addChildElement(ACTION).addTextNode("login"); soapBodyElem.addChildElement(USERNAME).addTextNode(ADMIN); soapBodyElem.addChildElement(LOGINPASSWORD); soapBodyElem.addChildElement(CAPTCHA); final MimeHeaders headers = loginAction.getMimeHeaders(); headers.addHeader(SOAPACTION, LOGIN_ACTION); } /** * Sets the password for the second login message based on the data received from the * first login message. Also sets the private key used to generate the authentication header. * * @param challenge * @param cookie * @param publicKey * @throws SOAPException * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ private void setAuthenticationData(final String challenge, final String cookie, final String publicKey) throws SOAPException, InvalidKeyException, NoSuchAlgorithmException { final MimeHeaders loginHeaders = loginAction.getMimeHeaders(); loginHeaders.setHeader(COOKIE, "uid=" + cookie); privateKey = hash(challenge, publicKey + pin); final String password = hash(challenge, privateKey); loginAction.getSOAPBody().getElementsByTagName(LOGINPASSWORD).item(0).setTextContent(password); loginAction.saveChanges(); } /** * Used to hash the authentication data such as the login password and the authentication header * for the detection message. * * @param data * @param key * @return The hashed data * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ private String hash(final String data, final String key) throws NoSuchAlgorithmException, InvalidKeyException { final Mac mac = Mac.getInstance("HMACMD5"); final SecretKeySpec sKey = new SecretKeySpec(key.getBytes(), "ASCII"); mac.init(sKey); final byte[] bytes = mac.doFinal(data.getBytes()); final StringBuilder hashBuf = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { final String hex = Integer.toHexString(0xFF & bytes[i]).toUpperCase(); if (hex.length() == 1) { hashBuf.append('0'); } hashBuf.append(hex); } return hashBuf.toString(); } /** * Output unexpected responses to the debug log and sets the FIRMWARE error. * * @param message * @param soapResponse */ private void unexpectedResult(final String message, final Document soapResponse) { logUnexpectedResult(message, soapResponse); // Best guess when receiving unexpected responses status = HNAPStatus.UNSUPPORTED_FIRMWARE; } /** * Get the status of the HNAP interface * * @return the HNAP status */ protected HNAPStatus getHNAPStatus() { return status; } /** * Sends the two login messages and stores the private key used to generate the * authentication header required for actions. * * Use {@link #getHNAPStatus()} to determine the status of the HNAP connection * after calling this method. * * @param timeout - Connection timeout in milliseconds */ protected void login(final int timeout) { if (status != HNAPStatus.INTERNAL_ERROR) { try { Document soapResponse = sendReceive(requestAction, timeout); Node result = soapResponse.getElementsByTagName(LOGINRESULT).item(0); if (result != null && OK.equals(result.getTextContent())) { final Node challengeNode = soapResponse.getElementsByTagName("Challenge").item(0); final Node cookieNode = soapResponse.getElementsByTagName(COOKIE).item(0); final Node publicKeyNode = soapResponse.getElementsByTagName("PublicKey").item(0); if (challengeNode != null && cookieNode != null && publicKeyNode != null) { setAuthenticationData(challengeNode.getTextContent(), cookieNode.getTextContent(), publicKeyNode.getTextContent()); soapResponse = sendReceive(loginAction, timeout); result = soapResponse.getElementsByTagName(LOGINRESULT).item(0); if (result != null) { if ("success".equals(result.getTextContent())) { status = HNAPStatus.LOGGED_IN; } else { logger.debug("login - Check pin is correct"); // Assume pin code problem rather than a firmware change status = HNAPStatus.INVALID_PIN; } } else { unexpectedResult("login - Unexpected login response", soapResponse); } } else { unexpectedResult("login - Unexpected request response", soapResponse); } } else { unexpectedResult("login - Unexpected request response", soapResponse); } } catch (final InvalidKeyException e) { logger.debug("login - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final NoSuchAlgorithmException e) { logger.debug("login - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final Exception e) { // Assume there has been some problem trying to send one of the messages if (status != HNAPStatus.COMMUNICATION_ERROR) { logger.debug("login - Communication error", e); status = HNAPStatus.COMMUNICATION_ERROR; } } } } /** * Sets the authentication headers for the action message. This should only be called * after a successful login. * * Use {@link #getHNAPStatus()} to determine the status of the HNAP connection * after calling this method. * * @param action - SOAP Action to add headers */ protected void setAuthenticationHeaders(final SOAPMessage action) { if (status == HNAPStatus.LOGGED_IN) { try { final MimeHeaders loginHeaders = loginAction.getMimeHeaders(); final MimeHeaders actionHeaders = action.getMimeHeaders(); actionHeaders.setHeader(COOKIE, loginHeaders.getHeader(COOKIE)[0]); final String timeStamp = String.valueOf(System.currentTimeMillis() / 1000); final String auth = hash(timeStamp + actionHeaders.getHeader(SOAPACTION)[0], privateKey) + " " + timeStamp; actionHeaders.setHeader("HNAP_AUTH", auth); action.saveChanges(); } catch (final InvalidKeyException e) { logger.debug("setAuthenticationHeaders - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final NoSuchAlgorithmException e) { logger.debug("setAuthenticationHeaders - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final SOAPException e) { // No communication happening so assume system error logger.debug("setAuthenticationHeaders - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } } } /** * Send the SOAP message using Jetty HTTP client. Jetty is used in preference to * HttpURLConnection which can result in the HNAP interface becoming unresponsive. * * @param action - SOAP Action to send * @param timeout - Connection timeout in milliseconds * @return The result * @throws IOException * @throws SOAPException * @throws SAXException * @throws ExecutionException * @throws TimeoutException * @throws InterruptedException */ protected Document sendReceive(final SOAPMessage action, final int timeout) throws IOException, SOAPException, SAXException, InterruptedException, TimeoutException, ExecutionException { Document result; final Request request = httpClient.POST(uri); request.timeout(timeout, TimeUnit.MILLISECONDS); final Iterator<?> it = action.getMimeHeaders().getAllHeaders(); while (it.hasNext()) { final MimeHeader header = (MimeHeader) it.next(); request.header(header.getName(), header.getValue()); } try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { action.writeTo(os); request.content(new BytesContentProvider(os.toByteArray())); final ContentResponse response = request.send(); try (final ByteArrayInputStream is = new ByteArrayInputStream(response.getContent())) { result = parser.parse(is); } } return result; } /** * Output unexpected responses to the debug log. * * @param message * @param soapResponse */ protected void logUnexpectedResult(final String message, final Document soapResponse) { // No point formatting for output if debug logging is not enabled if (logger.isDebugEnabled()) { try { final TransformerFactory transFactory = TransformerFactory.newInstance(); final Transformer transformer = transFactory.newTransformer(); final StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(soapResponse), new StreamResult(buffer)); logger.debug("{} : {}", message, buffer); } catch (final TransformerException e) { logger.debug("{}", message); } } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_6
crossvul-java_data_bad_4033_0
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql; import org.postgresql.util.DriverInfo; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import java.sql.Connection; import java.sql.DriverPropertyInfo; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * All connection parameters that can be either set in JDBC URL, in Driver properties or in * datasource setters. */ public enum PGProperty { /** * When using the V3 protocol the driver monitors changes in certain server configuration * parameters that should not be touched by end users. The {@code client_encoding} setting is set * by the driver and should not be altered. If the driver detects a change it will abort the * connection. */ ALLOW_ENCODING_CHANGES( "allowEncodingChanges", "false", "Allow for changes in client_encoding"), /** * The application name (require server version &gt;= 9.0). */ APPLICATION_NAME( "ApplicationName", DriverInfo.DRIVER_NAME, "Name of the Application (backend >= 9.0)"), /** * Assume the server is at least that version. */ ASSUME_MIN_SERVER_VERSION( "assumeMinServerVersion", null, "Assume the server is at least that version"), /** * Specifies what the driver should do if a query fails. In {@code autosave=always} mode, JDBC driver sets a savepoint before each query, * and rolls back to that savepoint in case of failure. In {@code autosave=never} mode (default), no savepoint dance is made ever. * In {@code autosave=conservative} mode, savepoint is set for each query, however the rollback is done only for rare cases * like 'cached statement cannot change return type' or 'statement XXX is not valid' so JDBC driver rollsback and retries */ AUTOSAVE( "autosave", "never", "Specifies what the driver should do if a query fails. In autosave=always mode, JDBC driver sets a savepoint before each query, " + "and rolls back to that savepoint in case of failure. In autosave=never mode (default), no savepoint dance is made ever. " + "In autosave=conservative mode, safepoint is set for each query, however the rollback is done only for rare cases" + " like 'cached statement cannot change return type' or 'statement XXX is not valid' so JDBC driver rollsback and retries", false, new String[] {"always", "never", "conservative"}), /** * Use binary format for sending and receiving data if possible. */ BINARY_TRANSFER( "binaryTransfer", "true", "Use binary format for sending and receiving data if possible"), /** * Comma separated list of types to disable binary transfer. Either OID numbers or names. * Overrides values in the driver default set and values set with binaryTransferEnable. */ BINARY_TRANSFER_DISABLE( "binaryTransferDisable", "", "Comma separated list of types to disable binary transfer. Either OID numbers or names. Overrides values in the driver default set and values set with binaryTransferEnable."), /** * Comma separated list of types to enable binary transfer. Either OID numbers or names */ BINARY_TRANSFER_ENABLE( "binaryTransferEnable", "", "Comma separated list of types to enable binary transfer. Either OID numbers or names"), /** * Cancel command is sent out of band over its own connection, so cancel message can itself get * stuck. * This property controls "connect timeout" and "socket timeout" used for cancel commands. * The timeout is specified in seconds. Default value is 10 seconds. */ CANCEL_SIGNAL_TIMEOUT( "cancelSignalTimeout", "10", "The timeout that is used for sending cancel command."), /** * Determine whether SAVEPOINTS used in AUTOSAVE will be released per query or not */ CLEANUP_SAVEPOINTS( "cleanupSavepoints", "false", "Determine whether SAVEPOINTS used in AUTOSAVE will be released per query or not", false, new String[] {"true", "false"}), /** * <p>The timeout value used for socket connect operations. If connecting to the server takes longer * than this value, the connection is broken.</p> * * <p>The timeout is specified in seconds and a value of zero means that it is disabled.</p> */ CONNECT_TIMEOUT( "connectTimeout", "10", "The timeout value used for socket connect operations."), /** * Specify the schema (or several schema separated by commas) to be set in the search-path. This schema will be used to resolve * unqualified object names used in statements over this connection. */ CURRENT_SCHEMA( "currentSchema", null, "Specify the schema (or several schema separated by commas) to be set in the search-path"), /** * Specifies the maximum number of fields to be cached per connection. A value of {@code 0} disables the cache. */ DATABASE_METADATA_CACHE_FIELDS( "databaseMetadataCacheFields", "65536", "Specifies the maximum number of fields to be cached per connection. A value of {@code 0} disables the cache."), /** * Specifies the maximum size (in megabytes) of fields to be cached per connection. A value of {@code 0} disables the cache. */ DATABASE_METADATA_CACHE_FIELDS_MIB( "databaseMetadataCacheFieldsMiB", "5", "Specifies the maximum size (in megabytes) of fields to be cached per connection. A value of {@code 0} disables the cache."), /** * Default parameter for {@link java.sql.Statement#getFetchSize()}. A value of {@code 0} means * that need fetch all rows at once */ DEFAULT_ROW_FETCH_SIZE( "defaultRowFetchSize", "0", "Positive number of rows that should be fetched from the database when more rows are needed for ResultSet by each fetch iteration"), /** * Enable optimization that disables column name sanitiser. */ DISABLE_COLUMN_SANITISER( "disableColumnSanitiser", "false", "Enable optimization that disables column name sanitiser"), /** * Specifies how the driver transforms JDBC escape call syntax into underlying SQL, for invoking procedures or functions. (backend &gt;= 11) * In {@code escapeSyntaxCallMode=select} mode (the default), the driver always uses a SELECT statement (allowing function invocation only). * In {@code escapeSyntaxCallMode=callIfNoReturn} mode, the driver uses a CALL statement (allowing procedure invocation) if there is no return parameter specified, otherwise the driver uses a SELECT statement. * In {@code escapeSyntaxCallMode=call} mode, the driver always uses a CALL statement (allowing procedure invocation only). */ ESCAPE_SYNTAX_CALL_MODE( "escapeSyntaxCallMode", "select", "Specifies how the driver transforms JDBC escape call syntax into underlying SQL, for invoking procedures or functions. (backend >= 11)" + "In escapeSyntaxCallMode=select mode (the default), the driver always uses a SELECT statement (allowing function invocation only)." + "In escapeSyntaxCallMode=callIfNoReturn mode, the driver uses a CALL statement (allowing procedure invocation) if there is no return parameter specified, otherwise the driver uses a SELECT statement." + "In escapeSyntaxCallMode=call mode, the driver always uses a CALL statement (allowing procedure invocation only).", false, new String[] {"select", "callIfNoReturn", "call"}), /** * Force one of * <ul> * <li>SSPI (Windows transparent single-sign-on)</li> * <li>GSSAPI (Kerberos, via JSSE)</li> * </ul> * to be used when the server requests Kerberos or SSPI authentication. */ GSS_LIB( "gsslib", "auto", "Force SSSPI or GSSAPI", false, new String[] {"auto", "sspi", "gssapi"}), /** * Enable mode to filter out the names of database objects for which the current user has no privileges * granted from appearing in the DatabaseMetaData returned by the driver. */ HIDE_UNPRIVILEGED_OBJECTS( "hideUnprivilegedObjects", "false", "Enable hiding of database objects for which the current user has no privileges granted from the DatabaseMetaData"), HOST_RECHECK_SECONDS( "hostRecheckSeconds", "10", "Specifies period (seconds) after which the host status is checked again in case it has changed"), /** * Specifies the name of the JAAS system or application login configuration. */ JAAS_APPLICATION_NAME( "jaasApplicationName", null, "Specifies the name of the JAAS system or application login configuration."), /** * Flag to enable/disable obtaining a GSS credential via JAAS login before authenticating. * Useful if setting system property javax.security.auth.useSubjectCredsOnly=false * or using native GSS with system property sun.security.jgss.native=true */ JAAS_LOGIN( "jaasLogin", "true", "Login with JAAS before doing GSSAPI authentication"), /** * The Kerberos service name to use when authenticating with GSSAPI. This is equivalent to libpq's * PGKRBSRVNAME environment variable. */ KERBEROS_SERVER_NAME( "kerberosServerName", null, "The Kerberos service name to use when authenticating with GSSAPI."), LOAD_BALANCE_HOSTS( "loadBalanceHosts", "false", "If disabled hosts are connected in the given order. If enabled hosts are chosen randomly from the set of suitable candidates"), /** * <p>File name output of the Logger, if set, the Logger will use a * {@link java.util.logging.FileHandler} to write to a specified file. If the parameter is not set * or the file can't be created the {@link java.util.logging.ConsoleHandler} will be used instead.</p> * * <p>Parameter should be use together with {@link PGProperty#LOGGER_LEVEL}</p> */ LOGGER_FILE( "loggerFile", null, "File name output of the Logger"), /** * <p>Logger level of the driver. Allowed values: {@code OFF}, {@code DEBUG} or {@code TRACE}.</p> * * <p>This enable the {@link java.util.logging.Logger} of the driver based on the following mapping * of levels:</p> * <ul> * <li>FINE -&gt; DEBUG</li> * <li>FINEST -&gt; TRACE</li> * </ul> * * <p><b>NOTE:</b> The recommended approach to enable java.util.logging is using a * {@code logging.properties} configuration file with the property * {@code -Djava.util.logging.config.file=myfile} or if your are using an application server * you should use the appropriate logging subsystem.</p> */ LOGGER_LEVEL( "loggerLevel", null, "Logger level of the driver", false, new String[] {"OFF", "DEBUG", "TRACE"}), /** * Specify how long to wait for establishment of a database connection. The timeout is specified * in seconds. */ LOGIN_TIMEOUT( "loginTimeout", "0", "Specify how long to wait for establishment of a database connection."), /** * Whether to include full server error detail in exception messages. */ LOG_SERVER_ERROR_DETAIL( "logServerErrorDetail", "true", "Include full server error detail in exception messages. If disabled then only the error itself will be included."), /** * When connections that are not explicitly closed are garbage collected, log the stacktrace from * the opening of the connection to trace the leak source. */ LOG_UNCLOSED_CONNECTIONS( "logUnclosedConnections", "false", "When connections that are not explicitly closed are garbage collected, log the stacktrace from the opening of the connection to trace the leak source"), /** * Specifies size of buffer during fetching result set. Can be specified as specified size or * percent of heap memory. */ MAX_RESULT_BUFFER( "maxResultBuffer", null, "Specifies size of buffer during fetching result set. Can be specified as specified size or percent of heap memory."), /** * Specify 'options' connection initialization parameter. * The value of this parameter may contain spaces and other special characters or their URL representation. */ OPTIONS( "options", null, "Specify 'options' connection initialization parameter."), /** * Password to use when authenticating. */ PASSWORD( "password", null, "Password to use when authenticating.", false), /** * Database name to connect to (may be specified directly in the JDBC URL). */ PG_DBNAME( "PGDBNAME", null, "Database name to connect to (may be specified directly in the JDBC URL)", true), /** * Hostname of the PostgreSQL server (may be specified directly in the JDBC URL). */ PG_HOST( "PGHOST", null, "Hostname of the PostgreSQL server (may be specified directly in the JDBC URL)", false), /** * Port of the PostgreSQL server (may be specified directly in the JDBC URL). */ PG_PORT( "PGPORT", null, "Port of the PostgreSQL server (may be specified directly in the JDBC URL)"), /** * <p>Specifies which mode is used to execute queries to database: simple means ('Q' execute, no parse, no bind, text mode only), * extended means always use bind/execute messages, extendedForPrepared means extended for prepared statements only, * extendedCacheEverything means use extended protocol and try cache every statement (including Statement.execute(String sql)) in a query cache.</p> * * <p>This mode is meant for debugging purposes and/or for cases when extended protocol cannot be used (e.g. logical replication protocol)</p> */ PREFER_QUERY_MODE( "preferQueryMode", "extended", "Specifies which mode is used to execute queries to database: simple means ('Q' execute, no parse, no bind, text mode only), " + "extended means always use bind/execute messages, extendedForPrepared means extended for prepared statements only, " + "extendedCacheEverything means use extended protocol and try cache every statement (including Statement.execute(String sql)) in a query cache.", false, new String[] {"extended", "extendedForPrepared", "extendedCacheEverything", "simple"}), /** * Specifies the maximum number of entries in cache of prepared statements. A value of {@code 0} * disables the cache. */ PREPARED_STATEMENT_CACHE_QUERIES( "preparedStatementCacheQueries", "256", "Specifies the maximum number of entries in per-connection cache of prepared statements. A value of {@code 0} disables the cache."), /** * Specifies the maximum size (in megabytes) of the prepared statement cache. A value of {@code 0} * disables the cache. */ PREPARED_STATEMENT_CACHE_SIZE_MIB( "preparedStatementCacheSizeMiB", "5", "Specifies the maximum size (in megabytes) of a per-connection prepared statement cache. A value of {@code 0} disables the cache."), /** * Sets the default threshold for enabling server-side prepare. A value of {@code -1} stands for * forceBinary */ PREPARE_THRESHOLD( "prepareThreshold", "5", "Statement prepare threshold. A value of {@code -1} stands for forceBinary"), /** * Force use of a particular protocol version when connecting, if set, disables protocol version * fallback. */ PROTOCOL_VERSION( "protocolVersion", null, "Force use of a particular protocol version when connecting, currently only version 3 is supported.", false, new String[] {"3"}), /** * Puts this connection in read-only mode. */ READ_ONLY( "readOnly", "false", "Puts this connection in read-only mode"), /** * Connection parameter to control behavior when * {@link Connection#setReadOnly(boolean)} is set to {@code true}. */ READ_ONLY_MODE( "readOnlyMode", "transaction", "Controls the behavior when a connection is set to be read only, one of 'ignore', 'transaction', or 'always' " + "When 'ignore', setting readOnly has no effect. " + "When 'transaction' setting readOnly to 'true' will cause transactions to BEGIN READ ONLY if autocommit is 'false'. " + "When 'always' setting readOnly to 'true' will set the session to READ ONLY if autoCommit is 'true' " + "and the transaction to BEGIN READ ONLY if autocommit is 'false'.", false, new String[] {"ignore", "transaction", "always"}), /** * Socket read buffer size (SO_RECVBUF). A value of {@code -1}, which is the default, means system * default. */ RECEIVE_BUFFER_SIZE( "receiveBufferSize", "-1", "Socket read buffer size"), /** * <p>Connection parameter passed in the startup message. This parameter accepts two values; "true" * and "database". Passing "true" tells the backend to go into walsender mode, wherein a small set * of replication commands can be issued instead of SQL statements. Only the simple query protocol * can be used in walsender mode. Passing "database" as the value instructs walsender to connect * to the database specified in the dbname parameter, which will allow the connection to be used * for logical replication from that database.</p> * <p>Parameter should be use together with {@link PGProperty#ASSUME_MIN_SERVER_VERSION} with * parameter &gt;= 9.4 (backend &gt;= 9.4)</p> */ REPLICATION( "replication", null, "Connection parameter passed in startup message, one of 'true' or 'database' " + "Passing 'true' tells the backend to go into walsender mode, " + "wherein a small set of replication commands can be issued instead of SQL statements. " + "Only the simple query protocol can be used in walsender mode. " + "Passing 'database' as the value instructs walsender to connect " + "to the database specified in the dbname parameter, " + "which will allow the connection to be used for logical replication " + "from that database. " + "(backend >= 9.4)"), /** * Configure optimization to enable batch insert re-writing. */ REWRITE_BATCHED_INSERTS( "reWriteBatchedInserts", "false", "Enable optimization to rewrite and collapse compatible INSERT statements that are batched."), /** * Socket write buffer size (SO_SNDBUF). A value of {@code -1}, which is the default, means system * default. */ SEND_BUFFER_SIZE( "sendBufferSize", "-1", "Socket write buffer size"), /** * Socket factory used to create socket. A null value, which is the default, means system default. */ SOCKET_FACTORY( "socketFactory", null, "Specify a socket factory for socket creation"), /** * The String argument to give to the constructor of the Socket Factory. * @deprecated use {@code ..Factory(Properties)} constructor. */ @Deprecated SOCKET_FACTORY_ARG( "socketFactoryArg", null, "Argument forwarded to constructor of SocketFactory class."), /** * The timeout value used for socket read operations. If reading from the server takes longer than * this value, the connection is closed. This can be used as both a brute force global query * timeout and a method of detecting network problems. The timeout is specified in seconds and a * value of zero means that it is disabled. */ SOCKET_TIMEOUT( "socketTimeout", "0", "The timeout value used for socket read operations."), /** * Control use of SSL: empty or {@code true} values imply {@code sslmode==verify-full} */ SSL( "ssl", null, "Control use of SSL (any non-null value causes SSL to be required)"), /** * File containing the SSL Certificate. Default will be the file {@code postgresql.crt} in {@code * $HOME/.postgresql} (*nix) or {@code %APPDATA%\postgresql} (windows). */ SSL_CERT( "sslcert", null, "The location of the client's SSL certificate"), /** * Classname of the SSL Factory to use (instance of {@code javax.net.ssl.SSLSocketFactory}). */ SSL_FACTORY( "sslfactory", null, "Provide a SSLSocketFactory class when using SSL."), /** * The String argument to give to the constructor of the SSL Factory. * @deprecated use {@code ..Factory(Properties)} constructor. */ @Deprecated SSL_FACTORY_ARG( "sslfactoryarg", null, "Argument forwarded to constructor of SSLSocketFactory class."), /** * Classname of the SSL HostnameVerifier to use (instance of {@code * javax.net.ssl.HostnameVerifier}). */ SSL_HOSTNAME_VERIFIER( "sslhostnameverifier", null, "A class, implementing javax.net.ssl.HostnameVerifier that can verify the server"), /** * File containing the SSL Key. Default will be the file {@code postgresql.pk8} in {@code * $HOME/.postgresql} (*nix) or {@code %APPDATA%\postgresql} (windows). */ SSL_KEY( "sslkey", null, "The location of the client's PKCS#8 SSL key"), /** * Parameter governing the use of SSL. The allowed values are {@code disable}, {@code allow}, * {@code prefer}, {@code require}, {@code verify-ca}, {@code verify-full}. * If {@code ssl} property is empty or set to {@code true} it implies {@code verify-full}. * Default mode is "require" */ SSL_MODE( "sslmode", null, "Parameter governing the use of SSL", false, new String[] {"disable", "allow", "prefer", "require", "verify-ca", "verify-full"}), /** * The SSL password to use in the default CallbackHandler. */ SSL_PASSWORD( "sslpassword", null, "The password for the client's ssl key (ignored if sslpasswordcallback is set)"), /** * The classname instantiating {@code javax.security.auth.callback.CallbackHandler} to use. */ SSL_PASSWORD_CALLBACK( "sslpasswordcallback", null, "A class, implementing javax.security.auth.callback.CallbackHandler that can handle PassworCallback for the ssl password."), /** * File containing the root certificate when validating server ({@code sslmode} = {@code * verify-ca} or {@code verify-full}). Default will be the file {@code root.crt} in {@code * $HOME/.postgresql} (*nix) or {@code %APPDATA%\postgresql} (windows). */ SSL_ROOT_CERT( "sslrootcert", null, "The location of the root certificate for authenticating the server."), /** * Specifies the name of the SSPI service class that forms the service class part of the SPN. The * default, {@code POSTGRES}, is almost always correct. */ SSPI_SERVICE_CLASS( "sspiServiceClass", "POSTGRES", "The Windows SSPI service class for SPN"), /** * Bind String to either {@code unspecified} or {@code varchar}. Default is {@code varchar} for * 8.0+ backends. */ STRING_TYPE( "stringtype", null, "The type to bind String parameters as (usually 'varchar', 'unspecified' allows implicit casting to other types)", false, new String[] {"unspecified", "varchar"}), TARGET_SERVER_TYPE( "targetServerType", "any", "Specifies what kind of server to connect", false, new String [] {"any", "primary", "master", "slave", "secondary", "preferSlave", "preferSecondary"}), /** * Enable or disable TCP keep-alive. The default is {@code false}. */ TCP_KEEP_ALIVE( "tcpKeepAlive", "false", "Enable or disable TCP keep-alive. The default is {@code false}."), /** * Specifies the length to return for types of unknown length. */ UNKNOWN_LENGTH( "unknownLength", Integer.toString(Integer.MAX_VALUE), "Specifies the length to return for types of unknown length"), /** * Username to connect to the database as. */ USER( "user", null, "Username to connect to the database as.", true), /** * Use SPNEGO in SSPI authentication requests. */ USE_SPNEGO( "useSpnego", "false", "Use SPNEGO in SSPI authentication requests"), ; private final String name; private final String defaultValue; private final boolean required; private final String description; private final String[] choices; private final boolean deprecated; PGProperty(String name, String defaultValue, String description) { this(name, defaultValue, description, false); } PGProperty(String name, String defaultValue, String description, boolean required) { this(name, defaultValue, description, required, (String[]) null); } PGProperty(String name, String defaultValue, String description, boolean required, String[] choices) { this.name = name; this.defaultValue = defaultValue; this.required = required; this.description = description; this.choices = choices; try { this.deprecated = PGProperty.class.getField(name()).getAnnotation(Deprecated.class) != null; } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } private static final Map<String, PGProperty> PROPS_BY_NAME = new HashMap<String, PGProperty>(); static { for (PGProperty prop : PGProperty.values()) { if (PROPS_BY_NAME.put(prop.getName(), prop) != null) { throw new IllegalStateException("Duplicate PGProperty name: " + prop.getName()); } } } /** * Returns the name of the connection parameter. The name is the key that must be used in JDBC URL * or in Driver properties * * @return the name of the connection parameter */ public String getName() { return name; } /** * Returns the default value for this connection parameter. * * @return the default value for this connection parameter or null */ public String getDefaultValue() { return defaultValue; } /** * Returns whether this parameter is required. * * @return whether this parameter is required */ public boolean isRequired() { return required; } /** * Returns the description for this connection parameter. * * @return the description for this connection parameter */ public String getDescription() { return description; } /** * Returns the available values for this connection parameter. * * @return the available values for this connection parameter or null */ public String[] getChoices() { return choices; } /** * Returns whether this connection parameter is deprecated. * * @return whether this connection parameter is deprecated */ public boolean isDeprecated() { return deprecated; } /** * Returns the value of the connection parameters according to the given {@code Properties} or the * default value. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter */ public String get(Properties properties) { return properties.getProperty(name, defaultValue); } /** * Set the value for this connection parameter in the given {@code Properties}. * * @param properties properties in which the value should be set * @param value value for this connection parameter */ public void set(Properties properties, String value) { if (value == null) { properties.remove(name); } else { properties.setProperty(name, value); } } /** * Return the boolean value for this connection parameter in the given {@code Properties}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to boolean */ public boolean getBoolean(Properties properties) { return Boolean.valueOf(get(properties)); } /** * Return the int value for this connection parameter in the given {@code Properties}. Prefer the * use of {@link #getInt(Properties)} anywhere you can throw an {@link java.sql.SQLException}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to int * @throws NumberFormatException if it cannot be converted to int. */ public int getIntNoCheck(Properties properties) { String value = get(properties); return Integer.parseInt(value); } /** * Return the int value for this connection parameter in the given {@code Properties}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to int * @throws PSQLException if it cannot be converted to int. */ public int getInt(Properties properties) throws PSQLException { String value = get(properties); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { throw new PSQLException(GT.tr("{0} parameter value must be an integer but was: {1}", getName(), value), PSQLState.INVALID_PARAMETER_VALUE, nfe); } } /** * Return the {@code Integer} value for this connection parameter in the given {@code Properties}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to Integer or null * @throws PSQLException if unable to parse property as integer */ public Integer getInteger(Properties properties) throws PSQLException { String value = get(properties); if (value == null) { return null; } try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { throw new PSQLException(GT.tr("{0} parameter value must be an integer but was: {1}", getName(), value), PSQLState.INVALID_PARAMETER_VALUE, nfe); } } /** * Set the boolean value for this connection parameter in the given {@code Properties}. * * @param properties properties in which the value should be set * @param value boolean value for this connection parameter */ public void set(Properties properties, boolean value) { properties.setProperty(name, Boolean.toString(value)); } /** * Set the int value for this connection parameter in the given {@code Properties}. * * @param properties properties in which the value should be set * @param value int value for this connection parameter */ public void set(Properties properties, int value) { properties.setProperty(name, Integer.toString(value)); } /** * Test whether this property is present in the given {@code Properties}. * * @param properties set of properties to check current in * @return true if the parameter is specified in the given properties */ public boolean isPresent(Properties properties) { return getSetString(properties) != null; } /** * Convert this connection parameter and the value read from the given {@code Properties} into a * {@code DriverPropertyInfo}. * * @param properties properties to take actual value from * @return a DriverPropertyInfo representing this connection parameter */ public DriverPropertyInfo toDriverPropertyInfo(Properties properties) { DriverPropertyInfo propertyInfo = new DriverPropertyInfo(name, get(properties)); propertyInfo.required = required; propertyInfo.description = description; propertyInfo.choices = choices; return propertyInfo; } public static PGProperty forName(String name) { return PROPS_BY_NAME.get(name); } /** * Return the property if exists but avoiding the default. Allowing the caller to detect the lack * of a property. * * @param properties properties bundle * @return the value of a set property */ public String getSetString(Properties properties) { Object o = properties.get(name); if (o instanceof String) { return (String) o; } return null; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4033_0
crossvul-java_data_bad_2449_9
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.platformlambda.example; import org.platformlambda.core.annotations.MainApplication; import org.platformlambda.core.models.EntryPoint; import org.platformlambda.core.models.LambdaFunction; import org.platformlambda.core.system.AppStarter; import org.platformlambda.core.system.Platform; import org.platformlambda.core.system.ServerPersonality; import org.platformlambda.services.HelloGeneric; import org.platformlambda.services.HelloPoJo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; @MainApplication public class MainApp implements EntryPoint { private static final Logger log = LoggerFactory.getLogger(MainApp.class); public static void main(String[] args) { AppStarter.main(args); } @Override public void start(String[] args) throws Exception { // Start the platform Platform platform = Platform.getInstance(); // You can create a microservice as a lambda function inline or write it as a regular Java class LambdaFunction echo = (headers, body, instance) -> { log.info("echo @"+instance+" received - "+headers+", "+body); Map<String, Object> result = new HashMap<>(); result.put("headers", headers); result.put("body", body); result.put("instance", instance); result.put("origin", platform.getOrigin()); return result; }; // register your services platform.register("hello.world", echo, 10); platform.register("hello.pojo", new HelloPoJo(), 5); platform.register("hello.generic", new HelloGeneric(), 5); // connect to cloud according to "cloud.connector" in application.properties platform.connectToCloud(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_2449_9
crossvul-java_data_bad_4033_6
404: Not Found
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4033_6
crossvul-java_data_good_1910_11
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.homematic.internal.communicator.message; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Decodes a XML-RPC message from the Homematic server. * * @author Gerhard Riegler - Initial contribution */ public class XmlRpcResponse implements RpcResponse { private String methodName; private Object[] responseData; /** * Decodes a XML-RPC message from the given InputStream. */ public XmlRpcResponse(InputStream is, String encoding) throws SAXException, ParserConfigurationException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); saxParser.getXMLReader().setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); InputSource inputSource = new InputSource(is); inputSource.setEncoding(encoding); saxParser.parse(inputSource, new XmlRpcHandler()); } @Override public Object[] getResponseData() { return responseData; } @Override public String getMethodName() { return methodName; } @Override public String toString() { return RpcUtils.dumpRpcMessage(methodName, responseData); } /** * SAX parser implementation to decode XML-RPC. * * @author Gerhard Riegler */ private class XmlRpcHandler extends DefaultHandler { private List<Object> result = new ArrayList<>(); private LinkedList<List<Object>> currentDataObject = new LinkedList<>(); private StringBuilder tagValue; private boolean isValueTag; @Override public void startDocument() throws SAXException { currentDataObject.addLast(new ArrayList<>()); } @Override public void endDocument() throws SAXException { result.addAll(currentDataObject.removeLast()); responseData = result.toArray(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String tag = qName.toLowerCase(); if (tag.equals("array") || tag.equals("struct")) { currentDataObject.addLast(new ArrayList<>()); } isValueTag = tag.equals("value"); tagValue = new StringBuilder(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String currentTag = qName.toLowerCase(); String currentValue = tagValue.toString(); List<Object> data = currentDataObject.peekLast(); switch (currentTag) { case "boolean": data.add("1".equals(currentValue) ? Boolean.TRUE : Boolean.FALSE); break; case "int": case "i4": data.add(new Integer(currentValue)); break; case "double": data.add(new Double(currentValue)); break; case "string": case "name": data.add(currentValue); break; case "value": if (isValueTag) { data.add(currentValue); isValueTag = false; } break; case "array": List<Object> arrayData = currentDataObject.removeLast(); currentDataObject.peekLast().add(arrayData.toArray()); break; case "struct": List<Object> mapData = currentDataObject.removeLast(); Map<Object, Object> resultMap = new HashMap<>(); for (int i = 0; i < mapData.size(); i += 2) { resultMap.put(mapData.get(i), mapData.get(i + 1)); } currentDataObject.peekLast().add(resultMap); break; case "base64": data.add(Base64.getDecoder().decode(currentValue)); break; case "datetime.iso8601": try { data.add(XmlRpcRequest.xmlRpcDateFormat.parse(currentValue)); } catch (ParseException ex) { throw new SAXException(ex.getMessage(), ex); } break; case "methodname": methodName = currentValue; break; case "params": case "param": case "methodcall": case "methodresponse": case "member": case "data": case "fault": break; default: throw new SAXException("Unknown XML-RPC tag: " + currentTag); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { tagValue.append(new String(ch, start, length)); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_11
crossvul-java_data_good_4290_6
/* * file: GanttProjectReader.java * author: Jon Iles * copyright: (c) Packwood Software 2017 * date: 22 March 2017 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.ganttproject; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import net.sf.mpxj.ChildTaskContainer; import net.sf.mpxj.ConstraintType; import net.sf.mpxj.CustomField; import net.sf.mpxj.Day; import net.sf.mpxj.Duration; import net.sf.mpxj.EventManager; import net.sf.mpxj.FieldType; import net.sf.mpxj.MPXJException; import net.sf.mpxj.Priority; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectCalendarWeek; import net.sf.mpxj.ProjectConfig; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.ProjectProperties; import net.sf.mpxj.Rate; import net.sf.mpxj.Relation; import net.sf.mpxj.RelationType; import net.sf.mpxj.Resource; import net.sf.mpxj.ResourceAssignment; import net.sf.mpxj.ResourceField; import net.sf.mpxj.Task; import net.sf.mpxj.TimeUnit; import net.sf.mpxj.common.DateHelper; import net.sf.mpxj.common.NumberHelper; import net.sf.mpxj.common.Pair; import net.sf.mpxj.common.ResourceFieldLists; import net.sf.mpxj.common.TaskFieldLists; import net.sf.mpxj.common.UnmarshalHelper; import net.sf.mpxj.ganttproject.schema.Allocation; import net.sf.mpxj.ganttproject.schema.Allocations; import net.sf.mpxj.ganttproject.schema.Calendars; import net.sf.mpxj.ganttproject.schema.CustomPropertyDefinition; import net.sf.mpxj.ganttproject.schema.CustomResourceProperty; import net.sf.mpxj.ganttproject.schema.CustomTaskProperty; import net.sf.mpxj.ganttproject.schema.DayTypes; import net.sf.mpxj.ganttproject.schema.DefaultWeek; import net.sf.mpxj.ganttproject.schema.Depend; import net.sf.mpxj.ganttproject.schema.Project; import net.sf.mpxj.ganttproject.schema.Resources; import net.sf.mpxj.ganttproject.schema.Role; import net.sf.mpxj.ganttproject.schema.Roles; import net.sf.mpxj.ganttproject.schema.Taskproperty; import net.sf.mpxj.ganttproject.schema.Tasks; import net.sf.mpxj.listener.ProjectListener; import net.sf.mpxj.reader.AbstractProjectReader; /** * This class creates a new ProjectFile instance by reading a GanttProject file. */ public final class GanttProjectReader extends AbstractProjectReader { /** * {@inheritDoc} */ @Override public void addProjectListener(ProjectListener listener) { if (m_projectListeners == null) { m_projectListeners = new ArrayList<>(); } m_projectListeners.add(listener); } /** * {@inheritDoc} */ @Override public ProjectFile read(InputStream stream) throws MPXJException { try { if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_resourcePropertyDefinitions = new HashMap<>(); m_taskPropertyDefinitions = new HashMap<>(); m_roleDefinitions = new HashMap<>(); m_dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); ProjectConfig config = m_projectFile.getProjectConfig(); config.setAutoResourceUniqueID(false); config.setAutoTaskUniqueID(false); config.setAutoOutlineLevel(true); config.setAutoOutlineNumber(true); config.setAutoWBS(true); m_projectFile.getProjectProperties().setFileApplication("GanttProject"); m_projectFile.getProjectProperties().setFileType("GAN"); m_eventManager.addProjectListeners(m_projectListeners); Project ganttProject = (Project) UnmarshalHelper.unmarshal(CONTEXT, stream); readProjectProperties(ganttProject); readCalendars(ganttProject); readResources(ganttProject); readTasks(ganttProject); readRelationships(ganttProject); readResourceAssignments(ganttProject); // // Ensure that the unique ID counters are correct // config.updateUniqueCounters(); return m_projectFile; } catch (ParserConfigurationException ex) { throw new MPXJException("Failed to parse file", ex); } catch (JAXBException ex) { throw new MPXJException("Failed to parse file", ex); } catch (SAXException ex) { throw new MPXJException("Failed to parse file", ex); } finally { m_projectFile = null; m_mpxjCalendar = null; m_eventManager = null; m_projectListeners = null; m_localeDateFormat = null; m_resourcePropertyDefinitions = null; m_taskPropertyDefinitions = null; m_roleDefinitions = null; } } /** * This method extracts project properties from a GanttProject file. * * @param ganttProject GanttProject file */ private void readProjectProperties(Project ganttProject) { ProjectProperties mpxjProperties = m_projectFile.getProjectProperties(); mpxjProperties.setName(ganttProject.getName()); mpxjProperties.setCompany(ganttProject.getCompany()); mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS); String locale = ganttProject.getLocale(); if (locale == null) { locale = "en_US"; } m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale)); } /** * This method extracts calendar data from a GanttProject file. * * @param ganttProject Root node of the GanttProject file */ private void readCalendars(Project ganttProject) { m_mpxjCalendar = m_projectFile.addCalendar(); m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME); Calendars gpCalendar = ganttProject.getCalendars(); setWorkingDays(m_mpxjCalendar, gpCalendar); setExceptions(m_mpxjCalendar, gpCalendar); m_eventManager.fireCalendarReadEvent(m_mpxjCalendar); } /** * Add working days and working time to a calendar. * * @param mpxjCalendar MPXJ calendar * @param gpCalendar GanttProject calendar */ private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar) { DayTypes dayTypes = gpCalendar.getDayTypes(); DefaultWeek defaultWeek = dayTypes.getDefaultWeek(); if (defaultWeek == null) { mpxjCalendar.setWorkingDay(Day.SUNDAY, false); mpxjCalendar.setWorkingDay(Day.MONDAY, true); mpxjCalendar.setWorkingDay(Day.TUESDAY, true); mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true); mpxjCalendar.setWorkingDay(Day.THURSDAY, true); mpxjCalendar.setWorkingDay(Day.FRIDAY, true); mpxjCalendar.setWorkingDay(Day.SATURDAY, false); } else { mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon())); mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue())); mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed())); mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu())); mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri())); mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat())); mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun())); } for (Day day : Day.values()) { if (mpxjCalendar.isWorkingDay(day)) { ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } } /** * Returns true if the flag indicates a working day. * * @param value flag value * @return true if this is a working day */ private boolean isWorkingDay(Integer value) { return NumberHelper.getInt(value) == 0; } /** * Add exceptions to the calendar. * * @param mpxjCalendar MPXJ calendar * @param gpCalendar GanttProject calendar */ private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar) { List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate(); for (net.sf.mpxj.ganttproject.schema.Date date : dates) { addException(mpxjCalendar, date); } } /** * Add a single exception to a calendar. * * @param mpxjCalendar MPXJ calendar * @param date calendar exception */ private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date) { String year = date.getYear(); if (year == null || year.isEmpty()) { // In order to process recurring exceptions using MPXJ, we need a start and end date // to constrain the number of dates we generate. // May need to pre-process the tasks in order to calculate a start and finish date. // TODO: handle recurring exceptions } else { Calendar calendar = DateHelper.popCalendar(); calendar.set(Calendar.YEAR, Integer.parseInt(year)); calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth())); calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate())); Date exceptionDate = calendar.getTime(); DateHelper.pushCalendar(calendar); ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate); // TODO: not sure how NEUTRAL should be handled if ("WORKING_DAY".equals(date.getType())) { exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } } /** * This method extracts resource data from a GanttProject file. * * @param ganttProject parent node for resources */ private void readResources(Project ganttProject) { Resources resources = ganttProject.getResources(); readResourceCustomPropertyDefinitions(resources); readRoleDefinitions(ganttProject); for (net.sf.mpxj.ganttproject.schema.Resource gpResource : resources.getResource()) { readResource(gpResource); } } /** * Read custom property definitions for resources. * * @param gpResources GanttProject resources */ private void readResourceCustomPropertyDefinitions(Resources gpResources) { CustomField field = m_projectFile.getCustomFields().getCustomField(ResourceField.TEXT1); field.setAlias("Phone"); for (CustomPropertyDefinition definition : gpResources.getCustomPropertyDefinition()) { // // Find the next available field of the correct type. // String type = definition.getType(); FieldType fieldType = RESOURCE_PROPERTY_TYPES.get(type).getField(); // // If we have run out of fields of the right type, try using a text field. // if (fieldType == null) { fieldType = RESOURCE_PROPERTY_TYPES.get("text").getField(); } // // If we actually have a field available, set the alias to match // the name used in GanttProject. // if (fieldType != null) { field = m_projectFile.getCustomFields().getCustomField(fieldType); field.setAlias(definition.getName()); String defaultValue = definition.getDefaultValue(); if (defaultValue != null && defaultValue.isEmpty()) { defaultValue = null; } m_resourcePropertyDefinitions.put(definition.getId(), new Pair<>(fieldType, defaultValue)); } } } /** * Read custom property definitions for tasks. * * @param gpTasks GanttProject tasks */ private void readTaskCustomPropertyDefinitions(Tasks gpTasks) { for (Taskproperty definition : gpTasks.getTaskproperties().getTaskproperty()) { // // Ignore everything but custom values // if (!"custom".equals(definition.getType())) { continue; } // // Find the next available field of the correct type. // String type = definition.getValuetype(); FieldType fieldType = TASK_PROPERTY_TYPES.get(type).getField(); // // If we have run out of fields of the right type, try using a text field. // if (fieldType == null) { fieldType = TASK_PROPERTY_TYPES.get("text").getField(); } // // If we actually have a field available, set the alias to match // the name used in GanttProject. // if (fieldType != null) { CustomField field = m_projectFile.getCustomFields().getCustomField(fieldType); field.setAlias(definition.getName()); String defaultValue = definition.getDefaultvalue(); if (defaultValue != null && defaultValue.isEmpty()) { defaultValue = null; } m_taskPropertyDefinitions.put(definition.getId(), new Pair<>(fieldType, defaultValue)); } } } /** * Read the role definitions from a GanttProject project. * * @param gpProject GanttProject project */ private void readRoleDefinitions(Project gpProject) { m_roleDefinitions.put("Default:1", "project manager"); for (Roles roles : gpProject.getRoles()) { if ("Default".equals(roles.getRolesetName())) { continue; } for (Role role : roles.getRole()) { m_roleDefinitions.put(role.getId(), role.getName()); } } } /** * This method extracts data for a single resource from a GanttProject file. * * @param gpResource resource data */ private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource) { Resource mpxjResource = m_projectFile.addResource(); mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1)); mpxjResource.setName(gpResource.getName()); mpxjResource.setEmailAddress(gpResource.getContacts()); mpxjResource.setText(1, gpResource.getPhone()); mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction())); net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate(); if (gpRate != null) { mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS)); } readResourceCustomFields(gpResource, mpxjResource); m_eventManager.fireResourceReadEvent(mpxjResource); } /** * Read custom fields for a GanttProject resource. * * @param gpResource GanttProject resource * @param mpxjResource MPXJ Resource instance */ private void readResourceCustomFields(net.sf.mpxj.ganttproject.schema.Resource gpResource, Resource mpxjResource) { // // Populate custom field default values // Map<FieldType, Object> customFields = new HashMap<>(); for (Pair<FieldType, String> definition : m_resourcePropertyDefinitions.values()) { customFields.put(definition.getFirst(), definition.getSecond()); } // // Update with custom field actual values // for (CustomResourceProperty property : gpResource.getCustomProperty()) { Pair<FieldType, String> definition = m_resourcePropertyDefinitions.get(property.getDefinitionId()); if (definition != null) { // // Retrieve the value. If it is empty, use the default. // String value = property.getValueAttribute(); if (value.isEmpty()) { value = null; } // // If we have a value,convert it to the correct type // if (value != null) { Object result; switch (definition.getFirst().getDataType()) { case NUMERIC: { if (value.indexOf('.') == -1) { result = Integer.valueOf(value); } else { result = Double.valueOf(value); } break; } case DATE: { try { result = m_localeDateFormat.parse(value); } catch (ParseException ex) { result = null; } break; } case BOOLEAN: { result = Boolean.valueOf(value.equals("true")); break; } default: { result = value; break; } } if (result != null) { customFields.put(definition.getFirst(), result); } } } } for (Map.Entry<FieldType, Object> item : customFields.entrySet()) { if (item.getValue() != null) { mpxjResource.set(item.getKey(), item.getValue()); } } } /** * Read custom fields for a GanttProject task. * * @param gpTask GanttProject task * @param mpxjTask MPXJ Task instance */ private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask) { // // Populate custom field default values // Map<FieldType, Object> customFields = new HashMap<>(); for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values()) { customFields.put(definition.getFirst(), definition.getSecond()); } // // Update with custom field actual values // for (CustomTaskProperty property : gpTask.getCustomproperty()) { Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId()); if (definition != null) { // // Retrieve the value. If it is empty, use the default. // String value = property.getValueAttribute(); if (value.isEmpty()) { value = null; } // // If we have a value,convert it to the correct type // if (value != null) { Object result; switch (definition.getFirst().getDataType()) { case NUMERIC: { if (value.indexOf('.') == -1) { result = Integer.valueOf(value); } else { result = Double.valueOf(value); } break; } case DATE: { try { result = m_dateFormat.parse(value); } catch (ParseException ex) { result = null; } break; } case BOOLEAN: { result = Boolean.valueOf(value.equals("true")); break; } default: { result = value; break; } } if (result != null) { customFields.put(definition.getFirst(), result); } } } } for (Map.Entry<FieldType, Object> item : customFields.entrySet()) { if (item.getValue() != null) { mpxjTask.set(item.getKey(), item.getValue()); } } } /** * Read the top level tasks from GanttProject. * * @param gpProject GanttProject project */ private void readTasks(Project gpProject) { Tasks tasks = gpProject.getTasks(); readTaskCustomPropertyDefinitions(tasks); for (net.sf.mpxj.ganttproject.schema.Task task : tasks.getTask()) { readTask(m_projectFile, task); } } /** * Recursively read a task, and any sub tasks. * * @param mpxjParent Parent for the MPXJ tasks * @param gpTask GanttProject task */ private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask) { Task mpxjTask = mpxjParent.addTask(); mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1)); mpxjTask.setName(gpTask.getName()); mpxjTask.setPercentageComplete(gpTask.getComplete()); mpxjTask.setPriority(getPriority(gpTask.getPriority())); mpxjTask.setHyperlink(gpTask.getWebLink()); Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS); mpxjTask.setDuration(duration); if (duration.getDuration() == 0) { mpxjTask.setMilestone(true); } else { mpxjTask.setStart(gpTask.getStart()); mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false)); } mpxjTask.setConstraintDate(gpTask.getThirdDate()); if (mpxjTask.getConstraintDate() != null) { // TODO: you don't appear to be able to change this setting in GanttProject // task.getThirdDateConstraint() mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN); } readTaskCustomFields(gpTask, mpxjTask); m_eventManager.fireTaskReadEvent(mpxjTask); // TODO: read custom values // // Process child tasks // for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask()) { readTask(mpxjTask, childTask); } } /** * Given a GanttProject priority value, turn this into an MPXJ Priority instance. * * @param gpPriority GanttProject priority * @return Priority instance */ private Priority getPriority(Integer gpPriority) { int result; if (gpPriority == null) { result = Priority.MEDIUM; } else { int index = gpPriority.intValue(); if (index < 0 || index >= PRIORITY.length) { result = Priority.MEDIUM; } else { result = PRIORITY[index]; } } return Priority.getInstance(result); } /** * Read all task relationships from a GanttProject. * * @param gpProject GanttProject project */ private void readRelationships(Project gpProject) { for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask()) { readRelationships(gpTask); } } /** * Read the relationships for an individual GanttProject task. * * @param gpTask GanttProject task */ private void readRelationships(net.sf.mpxj.ganttproject.schema.Task gpTask) { for (Depend depend : gpTask.getDepend()) { Task task1 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1)); Task task2 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(depend.getId()) + 1)); if (task1 != null && task2 != null) { Duration lag = Duration.getInstance(NumberHelper.getInt(depend.getDifference()), TimeUnit.DAYS); Relation relation = task2.addPredecessor(task1, getRelationType(depend.getType()), lag); m_eventManager.fireRelationReadEvent(relation); } } } /** * Convert a GanttProject task relationship type into an MPXJ RelationType instance. * * @param gpType GanttProject task relation type * @return RelationType instance */ private RelationType getRelationType(Integer gpType) { RelationType result = null; if (gpType != null) { int index = NumberHelper.getInt(gpType); if (index > 0 && index < RELATION.length) { result = RELATION[index]; } } if (result == null) { result = RelationType.FINISH_START; } return result; } /** * Read all resource assignments from a GanttProject project. * * @param gpProject GanttProject project */ private void readResourceAssignments(Project gpProject) { Allocations allocations = gpProject.getAllocations(); if (allocations != null) { for (Allocation allocation : allocations.getAllocation()) { readResourceAssignment(allocation); } } } /** * Read an individual GanttProject resource assignment. * * @param gpAllocation GanttProject resource assignment. */ private void readResourceAssignment(Allocation gpAllocation) { Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1); Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1); Task task = m_projectFile.getTaskByUniqueID(taskID); Resource resource = m_projectFile.getResourceByUniqueID(resourceID); if (task != null && resource != null) { ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource); mpxjAssignment.setUnits(gpAllocation.getLoad()); m_eventManager.fireAssignmentReadEvent(mpxjAssignment); } } private ProjectFile m_projectFile; private ProjectCalendar m_mpxjCalendar; private EventManager m_eventManager; private List<ProjectListener> m_projectListeners; private DateFormat m_localeDateFormat; private DateFormat m_dateFormat; private Map<String, Pair<FieldType, String>> m_resourcePropertyDefinitions; private Map<String, Pair<FieldType, String>> m_taskPropertyDefinitions; private Map<String, String> m_roleDefinitions; private static final Map<String, CustomProperty> RESOURCE_PROPERTY_TYPES = new HashMap<>(); static { CustomProperty numeric = new CustomProperty(ResourceFieldLists.CUSTOM_NUMBER); RESOURCE_PROPERTY_TYPES.put("int", numeric); RESOURCE_PROPERTY_TYPES.put("double", numeric); RESOURCE_PROPERTY_TYPES.put("text", new CustomProperty(ResourceFieldLists.CUSTOM_TEXT, 1)); RESOURCE_PROPERTY_TYPES.put("date", new CustomProperty(ResourceFieldLists.CUSTOM_DATE)); RESOURCE_PROPERTY_TYPES.put("boolean", new CustomProperty(ResourceFieldLists.CUSTOM_FLAG)); } private static final Map<String, CustomProperty> TASK_PROPERTY_TYPES = new HashMap<>(); static { CustomProperty numeric = new CustomProperty(TaskFieldLists.CUSTOM_NUMBER); TASK_PROPERTY_TYPES.put("int", numeric); TASK_PROPERTY_TYPES.put("double", numeric); TASK_PROPERTY_TYPES.put("text", new CustomProperty(TaskFieldLists.CUSTOM_TEXT)); TASK_PROPERTY_TYPES.put("date", new CustomProperty(TaskFieldLists.CUSTOM_DATE)); TASK_PROPERTY_TYPES.put("boolean", new CustomProperty(TaskFieldLists.CUSTOM_FLAG)); } private static final int[] PRIORITY = { Priority.LOW, // 0 - Low Priority.MEDIUM, // 1 - Normal Priority.HIGH, // 2 - High Priority.LOWEST, // 3- Lowest Priority.HIGHEST, // 4 - Highest }; static final RelationType[] RELATION = { null, //0 RelationType.START_START, // 1 - Start Start RelationType.FINISH_START, // 2 - Finish Start RelationType.FINISH_FINISH, // 3 - Finish Finish RelationType.START_FINISH // 4 - Start Finish }; /** * Cached context to minimise construction cost. */ private static JAXBContext CONTEXT; /** * Note any error occurring during context construction. */ private static JAXBException CONTEXT_EXCEPTION; static { try { // // JAXB RI property to speed up construction // System.setProperty("com.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot", "true"); // // Construct the context // CONTEXT = JAXBContext.newInstance("net.sf.mpxj.ganttproject.schema", GanttProjectReader.class.getClassLoader()); } catch (JAXBException ex) { CONTEXT_EXCEPTION = ex; CONTEXT = null; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4290_6
crossvul-java_data_good_4033_0
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql; import org.postgresql.util.DriverInfo; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import java.sql.Connection; import java.sql.DriverPropertyInfo; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * All connection parameters that can be either set in JDBC URL, in Driver properties or in * datasource setters. */ public enum PGProperty { /** * When using the V3 protocol the driver monitors changes in certain server configuration * parameters that should not be touched by end users. The {@code client_encoding} setting is set * by the driver and should not be altered. If the driver detects a change it will abort the * connection. */ ALLOW_ENCODING_CHANGES( "allowEncodingChanges", "false", "Allow for changes in client_encoding"), /** * The application name (require server version &gt;= 9.0). */ APPLICATION_NAME( "ApplicationName", DriverInfo.DRIVER_NAME, "Name of the Application (backend >= 9.0)"), /** * Assume the server is at least that version. */ ASSUME_MIN_SERVER_VERSION( "assumeMinServerVersion", null, "Assume the server is at least that version"), /** * Specifies what the driver should do if a query fails. In {@code autosave=always} mode, JDBC driver sets a savepoint before each query, * and rolls back to that savepoint in case of failure. In {@code autosave=never} mode (default), no savepoint dance is made ever. * In {@code autosave=conservative} mode, savepoint is set for each query, however the rollback is done only for rare cases * like 'cached statement cannot change return type' or 'statement XXX is not valid' so JDBC driver rollsback and retries */ AUTOSAVE( "autosave", "never", "Specifies what the driver should do if a query fails. In autosave=always mode, JDBC driver sets a savepoint before each query, " + "and rolls back to that savepoint in case of failure. In autosave=never mode (default), no savepoint dance is made ever. " + "In autosave=conservative mode, safepoint is set for each query, however the rollback is done only for rare cases" + " like 'cached statement cannot change return type' or 'statement XXX is not valid' so JDBC driver rollsback and retries", false, new String[] {"always", "never", "conservative"}), /** * Use binary format for sending and receiving data if possible. */ BINARY_TRANSFER( "binaryTransfer", "true", "Use binary format for sending and receiving data if possible"), /** * Comma separated list of types to disable binary transfer. Either OID numbers or names. * Overrides values in the driver default set and values set with binaryTransferEnable. */ BINARY_TRANSFER_DISABLE( "binaryTransferDisable", "", "Comma separated list of types to disable binary transfer. Either OID numbers or names. Overrides values in the driver default set and values set with binaryTransferEnable."), /** * Comma separated list of types to enable binary transfer. Either OID numbers or names */ BINARY_TRANSFER_ENABLE( "binaryTransferEnable", "", "Comma separated list of types to enable binary transfer. Either OID numbers or names"), /** * Cancel command is sent out of band over its own connection, so cancel message can itself get * stuck. * This property controls "connect timeout" and "socket timeout" used for cancel commands. * The timeout is specified in seconds. Default value is 10 seconds. */ CANCEL_SIGNAL_TIMEOUT( "cancelSignalTimeout", "10", "The timeout that is used for sending cancel command."), /** * Determine whether SAVEPOINTS used in AUTOSAVE will be released per query or not */ CLEANUP_SAVEPOINTS( "cleanupSavepoints", "false", "Determine whether SAVEPOINTS used in AUTOSAVE will be released per query or not", false, new String[] {"true", "false"}), /** * <p>The timeout value used for socket connect operations. If connecting to the server takes longer * than this value, the connection is broken.</p> * * <p>The timeout is specified in seconds and a value of zero means that it is disabled.</p> */ CONNECT_TIMEOUT( "connectTimeout", "10", "The timeout value used for socket connect operations."), /** * Specify the schema (or several schema separated by commas) to be set in the search-path. This schema will be used to resolve * unqualified object names used in statements over this connection. */ CURRENT_SCHEMA( "currentSchema", null, "Specify the schema (or several schema separated by commas) to be set in the search-path"), /** * Specifies the maximum number of fields to be cached per connection. A value of {@code 0} disables the cache. */ DATABASE_METADATA_CACHE_FIELDS( "databaseMetadataCacheFields", "65536", "Specifies the maximum number of fields to be cached per connection. A value of {@code 0} disables the cache."), /** * Specifies the maximum size (in megabytes) of fields to be cached per connection. A value of {@code 0} disables the cache. */ DATABASE_METADATA_CACHE_FIELDS_MIB( "databaseMetadataCacheFieldsMiB", "5", "Specifies the maximum size (in megabytes) of fields to be cached per connection. A value of {@code 0} disables the cache."), /** * Default parameter for {@link java.sql.Statement#getFetchSize()}. A value of {@code 0} means * that need fetch all rows at once */ DEFAULT_ROW_FETCH_SIZE( "defaultRowFetchSize", "0", "Positive number of rows that should be fetched from the database when more rows are needed for ResultSet by each fetch iteration"), /** * Enable optimization that disables column name sanitiser. */ DISABLE_COLUMN_SANITISER( "disableColumnSanitiser", "false", "Enable optimization that disables column name sanitiser"), /** * Specifies how the driver transforms JDBC escape call syntax into underlying SQL, for invoking procedures or functions. (backend &gt;= 11) * In {@code escapeSyntaxCallMode=select} mode (the default), the driver always uses a SELECT statement (allowing function invocation only). * In {@code escapeSyntaxCallMode=callIfNoReturn} mode, the driver uses a CALL statement (allowing procedure invocation) if there is no return parameter specified, otherwise the driver uses a SELECT statement. * In {@code escapeSyntaxCallMode=call} mode, the driver always uses a CALL statement (allowing procedure invocation only). */ ESCAPE_SYNTAX_CALL_MODE( "escapeSyntaxCallMode", "select", "Specifies how the driver transforms JDBC escape call syntax into underlying SQL, for invoking procedures or functions. (backend >= 11)" + "In escapeSyntaxCallMode=select mode (the default), the driver always uses a SELECT statement (allowing function invocation only)." + "In escapeSyntaxCallMode=callIfNoReturn mode, the driver uses a CALL statement (allowing procedure invocation) if there is no return parameter specified, otherwise the driver uses a SELECT statement." + "In escapeSyntaxCallMode=call mode, the driver always uses a CALL statement (allowing procedure invocation only).", false, new String[] {"select", "callIfNoReturn", "call"}), /** * Force one of * <ul> * <li>SSPI (Windows transparent single-sign-on)</li> * <li>GSSAPI (Kerberos, via JSSE)</li> * </ul> * to be used when the server requests Kerberos or SSPI authentication. */ GSS_LIB( "gsslib", "auto", "Force SSSPI or GSSAPI", false, new String[] {"auto", "sspi", "gssapi"}), /** * Enable mode to filter out the names of database objects for which the current user has no privileges * granted from appearing in the DatabaseMetaData returned by the driver. */ HIDE_UNPRIVILEGED_OBJECTS( "hideUnprivilegedObjects", "false", "Enable hiding of database objects for which the current user has no privileges granted from the DatabaseMetaData"), HOST_RECHECK_SECONDS( "hostRecheckSeconds", "10", "Specifies period (seconds) after which the host status is checked again in case it has changed"), /** * Specifies the name of the JAAS system or application login configuration. */ JAAS_APPLICATION_NAME( "jaasApplicationName", null, "Specifies the name of the JAAS system or application login configuration."), /** * Flag to enable/disable obtaining a GSS credential via JAAS login before authenticating. * Useful if setting system property javax.security.auth.useSubjectCredsOnly=false * or using native GSS with system property sun.security.jgss.native=true */ JAAS_LOGIN( "jaasLogin", "true", "Login with JAAS before doing GSSAPI authentication"), /** * The Kerberos service name to use when authenticating with GSSAPI. This is equivalent to libpq's * PGKRBSRVNAME environment variable. */ KERBEROS_SERVER_NAME( "kerberosServerName", null, "The Kerberos service name to use when authenticating with GSSAPI."), LOAD_BALANCE_HOSTS( "loadBalanceHosts", "false", "If disabled hosts are connected in the given order. If enabled hosts are chosen randomly from the set of suitable candidates"), /** * <p>File name output of the Logger, if set, the Logger will use a * {@link java.util.logging.FileHandler} to write to a specified file. If the parameter is not set * or the file can't be created the {@link java.util.logging.ConsoleHandler} will be used instead.</p> * * <p>Parameter should be use together with {@link PGProperty#LOGGER_LEVEL}</p> */ LOGGER_FILE( "loggerFile", null, "File name output of the Logger"), /** * <p>Logger level of the driver. Allowed values: {@code OFF}, {@code DEBUG} or {@code TRACE}.</p> * * <p>This enable the {@link java.util.logging.Logger} of the driver based on the following mapping * of levels:</p> * <ul> * <li>FINE -&gt; DEBUG</li> * <li>FINEST -&gt; TRACE</li> * </ul> * * <p><b>NOTE:</b> The recommended approach to enable java.util.logging is using a * {@code logging.properties} configuration file with the property * {@code -Djava.util.logging.config.file=myfile} or if your are using an application server * you should use the appropriate logging subsystem.</p> */ LOGGER_LEVEL( "loggerLevel", null, "Logger level of the driver", false, new String[] {"OFF", "DEBUG", "TRACE"}), /** * Specify how long to wait for establishment of a database connection. The timeout is specified * in seconds. */ LOGIN_TIMEOUT( "loginTimeout", "0", "Specify how long to wait for establishment of a database connection."), /** * Whether to include full server error detail in exception messages. */ LOG_SERVER_ERROR_DETAIL( "logServerErrorDetail", "true", "Include full server error detail in exception messages. If disabled then only the error itself will be included."), /** * When connections that are not explicitly closed are garbage collected, log the stacktrace from * the opening of the connection to trace the leak source. */ LOG_UNCLOSED_CONNECTIONS( "logUnclosedConnections", "false", "When connections that are not explicitly closed are garbage collected, log the stacktrace from the opening of the connection to trace the leak source"), /** * Specifies size of buffer during fetching result set. Can be specified as specified size or * percent of heap memory. */ MAX_RESULT_BUFFER( "maxResultBuffer", null, "Specifies size of buffer during fetching result set. Can be specified as specified size or percent of heap memory."), /** * Specify 'options' connection initialization parameter. * The value of this parameter may contain spaces and other special characters or their URL representation. */ OPTIONS( "options", null, "Specify 'options' connection initialization parameter."), /** * Password to use when authenticating. */ PASSWORD( "password", null, "Password to use when authenticating.", false), /** * Database name to connect to (may be specified directly in the JDBC URL). */ PG_DBNAME( "PGDBNAME", null, "Database name to connect to (may be specified directly in the JDBC URL)", true), /** * Hostname of the PostgreSQL server (may be specified directly in the JDBC URL). */ PG_HOST( "PGHOST", null, "Hostname of the PostgreSQL server (may be specified directly in the JDBC URL)", false), /** * Port of the PostgreSQL server (may be specified directly in the JDBC URL). */ PG_PORT( "PGPORT", null, "Port of the PostgreSQL server (may be specified directly in the JDBC URL)"), /** * <p>Specifies which mode is used to execute queries to database: simple means ('Q' execute, no parse, no bind, text mode only), * extended means always use bind/execute messages, extendedForPrepared means extended for prepared statements only, * extendedCacheEverything means use extended protocol and try cache every statement (including Statement.execute(String sql)) in a query cache.</p> * * <p>This mode is meant for debugging purposes and/or for cases when extended protocol cannot be used (e.g. logical replication protocol)</p> */ PREFER_QUERY_MODE( "preferQueryMode", "extended", "Specifies which mode is used to execute queries to database: simple means ('Q' execute, no parse, no bind, text mode only), " + "extended means always use bind/execute messages, extendedForPrepared means extended for prepared statements only, " + "extendedCacheEverything means use extended protocol and try cache every statement (including Statement.execute(String sql)) in a query cache.", false, new String[] {"extended", "extendedForPrepared", "extendedCacheEverything", "simple"}), /** * Specifies the maximum number of entries in cache of prepared statements. A value of {@code 0} * disables the cache. */ PREPARED_STATEMENT_CACHE_QUERIES( "preparedStatementCacheQueries", "256", "Specifies the maximum number of entries in per-connection cache of prepared statements. A value of {@code 0} disables the cache."), /** * Specifies the maximum size (in megabytes) of the prepared statement cache. A value of {@code 0} * disables the cache. */ PREPARED_STATEMENT_CACHE_SIZE_MIB( "preparedStatementCacheSizeMiB", "5", "Specifies the maximum size (in megabytes) of a per-connection prepared statement cache. A value of {@code 0} disables the cache."), /** * Sets the default threshold for enabling server-side prepare. A value of {@code -1} stands for * forceBinary */ PREPARE_THRESHOLD( "prepareThreshold", "5", "Statement prepare threshold. A value of {@code -1} stands for forceBinary"), /** * Force use of a particular protocol version when connecting, if set, disables protocol version * fallback. */ PROTOCOL_VERSION( "protocolVersion", null, "Force use of a particular protocol version when connecting, currently only version 3 is supported.", false, new String[] {"3"}), /** * Puts this connection in read-only mode. */ READ_ONLY( "readOnly", "false", "Puts this connection in read-only mode"), /** * Connection parameter to control behavior when * {@link Connection#setReadOnly(boolean)} is set to {@code true}. */ READ_ONLY_MODE( "readOnlyMode", "transaction", "Controls the behavior when a connection is set to be read only, one of 'ignore', 'transaction', or 'always' " + "When 'ignore', setting readOnly has no effect. " + "When 'transaction' setting readOnly to 'true' will cause transactions to BEGIN READ ONLY if autocommit is 'false'. " + "When 'always' setting readOnly to 'true' will set the session to READ ONLY if autoCommit is 'true' " + "and the transaction to BEGIN READ ONLY if autocommit is 'false'.", false, new String[] {"ignore", "transaction", "always"}), /** * Socket read buffer size (SO_RECVBUF). A value of {@code -1}, which is the default, means system * default. */ RECEIVE_BUFFER_SIZE( "receiveBufferSize", "-1", "Socket read buffer size"), /** * <p>Connection parameter passed in the startup message. This parameter accepts two values; "true" * and "database". Passing "true" tells the backend to go into walsender mode, wherein a small set * of replication commands can be issued instead of SQL statements. Only the simple query protocol * can be used in walsender mode. Passing "database" as the value instructs walsender to connect * to the database specified in the dbname parameter, which will allow the connection to be used * for logical replication from that database.</p> * <p>Parameter should be use together with {@link PGProperty#ASSUME_MIN_SERVER_VERSION} with * parameter &gt;= 9.4 (backend &gt;= 9.4)</p> */ REPLICATION( "replication", null, "Connection parameter passed in startup message, one of 'true' or 'database' " + "Passing 'true' tells the backend to go into walsender mode, " + "wherein a small set of replication commands can be issued instead of SQL statements. " + "Only the simple query protocol can be used in walsender mode. " + "Passing 'database' as the value instructs walsender to connect " + "to the database specified in the dbname parameter, " + "which will allow the connection to be used for logical replication " + "from that database. " + "(backend >= 9.4)"), /** * Configure optimization to enable batch insert re-writing. */ REWRITE_BATCHED_INSERTS( "reWriteBatchedInserts", "false", "Enable optimization to rewrite and collapse compatible INSERT statements that are batched."), /** * Socket write buffer size (SO_SNDBUF). A value of {@code -1}, which is the default, means system * default. */ SEND_BUFFER_SIZE( "sendBufferSize", "-1", "Socket write buffer size"), /** * Socket factory used to create socket. A null value, which is the default, means system default. */ SOCKET_FACTORY( "socketFactory", null, "Specify a socket factory for socket creation"), /** * The String argument to give to the constructor of the Socket Factory. * @deprecated use {@code ..Factory(Properties)} constructor. */ @Deprecated SOCKET_FACTORY_ARG( "socketFactoryArg", null, "Argument forwarded to constructor of SocketFactory class."), /** * The timeout value used for socket read operations. If reading from the server takes longer than * this value, the connection is closed. This can be used as both a brute force global query * timeout and a method of detecting network problems. The timeout is specified in seconds and a * value of zero means that it is disabled. */ SOCKET_TIMEOUT( "socketTimeout", "0", "The timeout value used for socket read operations."), /** * Control use of SSL: empty or {@code true} values imply {@code sslmode==verify-full} */ SSL( "ssl", null, "Control use of SSL (any non-null value causes SSL to be required)"), /** * File containing the SSL Certificate. Default will be the file {@code postgresql.crt} in {@code * $HOME/.postgresql} (*nix) or {@code %APPDATA%\postgresql} (windows). */ SSL_CERT( "sslcert", null, "The location of the client's SSL certificate"), /** * Classname of the SSL Factory to use (instance of {@code javax.net.ssl.SSLSocketFactory}). */ SSL_FACTORY( "sslfactory", null, "Provide a SSLSocketFactory class when using SSL."), /** * The String argument to give to the constructor of the SSL Factory. * @deprecated use {@code ..Factory(Properties)} constructor. */ @Deprecated SSL_FACTORY_ARG( "sslfactoryarg", null, "Argument forwarded to constructor of SSLSocketFactory class."), /** * Classname of the SSL HostnameVerifier to use (instance of {@code * javax.net.ssl.HostnameVerifier}). */ SSL_HOSTNAME_VERIFIER( "sslhostnameverifier", null, "A class, implementing javax.net.ssl.HostnameVerifier that can verify the server"), /** * File containing the SSL Key. Default will be the file {@code postgresql.pk8} in {@code * $HOME/.postgresql} (*nix) or {@code %APPDATA%\postgresql} (windows). */ SSL_KEY( "sslkey", null, "The location of the client's PKCS#8 SSL key"), /** * Parameter governing the use of SSL. The allowed values are {@code disable}, {@code allow}, * {@code prefer}, {@code require}, {@code verify-ca}, {@code verify-full}. * If {@code ssl} property is empty or set to {@code true} it implies {@code verify-full}. * Default mode is "require" */ SSL_MODE( "sslmode", null, "Parameter governing the use of SSL", false, new String[] {"disable", "allow", "prefer", "require", "verify-ca", "verify-full"}), /** * The SSL password to use in the default CallbackHandler. */ SSL_PASSWORD( "sslpassword", null, "The password for the client's ssl key (ignored if sslpasswordcallback is set)"), /** * The classname instantiating {@code javax.security.auth.callback.CallbackHandler} to use. */ SSL_PASSWORD_CALLBACK( "sslpasswordcallback", null, "A class, implementing javax.security.auth.callback.CallbackHandler that can handle PassworCallback for the ssl password."), /** * File containing the root certificate when validating server ({@code sslmode} = {@code * verify-ca} or {@code verify-full}). Default will be the file {@code root.crt} in {@code * $HOME/.postgresql} (*nix) or {@code %APPDATA%\postgresql} (windows). */ SSL_ROOT_CERT( "sslrootcert", null, "The location of the root certificate for authenticating the server."), /** * Specifies the name of the SSPI service class that forms the service class part of the SPN. The * default, {@code POSTGRES}, is almost always correct. */ SSPI_SERVICE_CLASS( "sspiServiceClass", "POSTGRES", "The Windows SSPI service class for SPN"), /** * Bind String to either {@code unspecified} or {@code varchar}. Default is {@code varchar} for * 8.0+ backends. */ STRING_TYPE( "stringtype", null, "The type to bind String parameters as (usually 'varchar', 'unspecified' allows implicit casting to other types)", false, new String[] {"unspecified", "varchar"}), TARGET_SERVER_TYPE( "targetServerType", "any", "Specifies what kind of server to connect", false, new String [] {"any", "primary", "master", "slave", "secondary", "preferSlave", "preferSecondary"}), /** * Enable or disable TCP keep-alive. The default is {@code false}. */ TCP_KEEP_ALIVE( "tcpKeepAlive", "false", "Enable or disable TCP keep-alive. The default is {@code false}."), /** * Specifies the length to return for types of unknown length. */ UNKNOWN_LENGTH( "unknownLength", Integer.toString(Integer.MAX_VALUE), "Specifies the length to return for types of unknown length"), /** * Username to connect to the database as. */ USER( "user", null, "Username to connect to the database as.", true), /** * Use SPNEGO in SSPI authentication requests. */ USE_SPNEGO( "useSpnego", "false", "Use SPNEGO in SSPI authentication requests"), /** * Factory class to instantiate factories for XML processing. * The default factory disables external entity processing. * Legacy behavior with external entity processing can be enabled by specifying a value of LEGACY_INSECURE. * Or specify a custom class that implements {@code org.postgresql.xml.PGXmlFactoryFactory}. */ XML_FACTORY_FACTORY( "xmlFactoryFactory", "", "Factory class to instantiate factories for XML processing"), ; private final String name; private final String defaultValue; private final boolean required; private final String description; private final String[] choices; private final boolean deprecated; PGProperty(String name, String defaultValue, String description) { this(name, defaultValue, description, false); } PGProperty(String name, String defaultValue, String description, boolean required) { this(name, defaultValue, description, required, (String[]) null); } PGProperty(String name, String defaultValue, String description, boolean required, String[] choices) { this.name = name; this.defaultValue = defaultValue; this.required = required; this.description = description; this.choices = choices; try { this.deprecated = PGProperty.class.getField(name()).getAnnotation(Deprecated.class) != null; } catch (NoSuchFieldException e) { throw new RuntimeException(e); } } private static final Map<String, PGProperty> PROPS_BY_NAME = new HashMap<String, PGProperty>(); static { for (PGProperty prop : PGProperty.values()) { if (PROPS_BY_NAME.put(prop.getName(), prop) != null) { throw new IllegalStateException("Duplicate PGProperty name: " + prop.getName()); } } } /** * Returns the name of the connection parameter. The name is the key that must be used in JDBC URL * or in Driver properties * * @return the name of the connection parameter */ public String getName() { return name; } /** * Returns the default value for this connection parameter. * * @return the default value for this connection parameter or null */ public String getDefaultValue() { return defaultValue; } /** * Returns whether this parameter is required. * * @return whether this parameter is required */ public boolean isRequired() { return required; } /** * Returns the description for this connection parameter. * * @return the description for this connection parameter */ public String getDescription() { return description; } /** * Returns the available values for this connection parameter. * * @return the available values for this connection parameter or null */ public String[] getChoices() { return choices; } /** * Returns whether this connection parameter is deprecated. * * @return whether this connection parameter is deprecated */ public boolean isDeprecated() { return deprecated; } /** * Returns the value of the connection parameters according to the given {@code Properties} or the * default value. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter */ public String get(Properties properties) { return properties.getProperty(name, defaultValue); } /** * Set the value for this connection parameter in the given {@code Properties}. * * @param properties properties in which the value should be set * @param value value for this connection parameter */ public void set(Properties properties, String value) { if (value == null) { properties.remove(name); } else { properties.setProperty(name, value); } } /** * Return the boolean value for this connection parameter in the given {@code Properties}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to boolean */ public boolean getBoolean(Properties properties) { return Boolean.valueOf(get(properties)); } /** * Return the int value for this connection parameter in the given {@code Properties}. Prefer the * use of {@link #getInt(Properties)} anywhere you can throw an {@link java.sql.SQLException}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to int * @throws NumberFormatException if it cannot be converted to int. */ public int getIntNoCheck(Properties properties) { String value = get(properties); return Integer.parseInt(value); } /** * Return the int value for this connection parameter in the given {@code Properties}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to int * @throws PSQLException if it cannot be converted to int. */ public int getInt(Properties properties) throws PSQLException { String value = get(properties); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { throw new PSQLException(GT.tr("{0} parameter value must be an integer but was: {1}", getName(), value), PSQLState.INVALID_PARAMETER_VALUE, nfe); } } /** * Return the {@code Integer} value for this connection parameter in the given {@code Properties}. * * @param properties properties to take actual value from * @return evaluated value for this connection parameter converted to Integer or null * @throws PSQLException if unable to parse property as integer */ public Integer getInteger(Properties properties) throws PSQLException { String value = get(properties); if (value == null) { return null; } try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { throw new PSQLException(GT.tr("{0} parameter value must be an integer but was: {1}", getName(), value), PSQLState.INVALID_PARAMETER_VALUE, nfe); } } /** * Set the boolean value for this connection parameter in the given {@code Properties}. * * @param properties properties in which the value should be set * @param value boolean value for this connection parameter */ public void set(Properties properties, boolean value) { properties.setProperty(name, Boolean.toString(value)); } /** * Set the int value for this connection parameter in the given {@code Properties}. * * @param properties properties in which the value should be set * @param value int value for this connection parameter */ public void set(Properties properties, int value) { properties.setProperty(name, Integer.toString(value)); } /** * Test whether this property is present in the given {@code Properties}. * * @param properties set of properties to check current in * @return true if the parameter is specified in the given properties */ public boolean isPresent(Properties properties) { return getSetString(properties) != null; } /** * Convert this connection parameter and the value read from the given {@code Properties} into a * {@code DriverPropertyInfo}. * * @param properties properties to take actual value from * @return a DriverPropertyInfo representing this connection parameter */ public DriverPropertyInfo toDriverPropertyInfo(Properties properties) { DriverPropertyInfo propertyInfo = new DriverPropertyInfo(name, get(properties)); propertyInfo.required = required; propertyInfo.description = description; propertyInfo.choices = choices; return propertyInfo; } public static PGProperty forName(String name) { return PROPS_BY_NAME.get(name); } /** * Return the property if exists but avoiding the default. Allowing the caller to detect the lack * of a property. * * @param properties properties bundle * @return the value of a set property */ public String getSetString(Properties properties) { Object o = properties.get(name); if (o instanceof String) { return (String) o; } return null; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4033_0
crossvul-java_data_good_4033_3
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.jdbc; import org.postgresql.Driver; import org.postgresql.PGNotification; import org.postgresql.PGProperty; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; import org.postgresql.core.BaseStatement; import org.postgresql.core.CachedQuery; import org.postgresql.core.ConnectionFactory; import org.postgresql.core.Encoding; import org.postgresql.core.Oid; import org.postgresql.core.Provider; import org.postgresql.core.Query; import org.postgresql.core.QueryExecutor; import org.postgresql.core.ReplicationProtocol; import org.postgresql.core.ResultHandlerBase; import org.postgresql.core.ServerVersion; import org.postgresql.core.SqlCommand; import org.postgresql.core.TransactionState; import org.postgresql.core.TypeInfo; import org.postgresql.core.Utils; import org.postgresql.core.Version; import org.postgresql.fastpath.Fastpath; import org.postgresql.largeobject.LargeObjectManager; import org.postgresql.replication.PGReplicationConnection; import org.postgresql.replication.PGReplicationConnectionImpl; import org.postgresql.util.GT; import org.postgresql.util.HostSpec; import org.postgresql.util.LruCache; import org.postgresql.util.PGBinaryObject; import org.postgresql.util.PGobject; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.xml.DefaultPGXmlFactoryFactory; import org.postgresql.xml.LegacyInsecurePGXmlFactoryFactory; import org.postgresql.xml.PGXmlFactoryFactory; import java.io.IOException; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.ClientInfoStatus; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLPermission; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.sql.Types; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; public class PgConnection implements BaseConnection { private static final Logger LOGGER = Logger.getLogger(PgConnection.class.getName()); private static final Set<Integer> SUPPORTED_BINARY_OIDS = getSupportedBinaryOids(); private static final SQLPermission SQL_PERMISSION_ABORT = new SQLPermission("callAbort"); private static final SQLPermission SQL_PERMISSION_NETWORK_TIMEOUT = new SQLPermission("setNetworkTimeout"); private enum ReadOnlyBehavior { ignore, transaction, always; } // // Data initialized on construction: // private final Properties clientInfo; /* URL we were created via */ private final String creatingURL; private final ReadOnlyBehavior readOnlyBehavior; private Throwable openStackTrace; /* Actual network handler */ private final QueryExecutor queryExecutor; /* Query that runs COMMIT */ private final Query commitQuery; /* Query that runs ROLLBACK */ private final Query rollbackQuery; private final CachedQuery setSessionReadOnly; private final CachedQuery setSessionNotReadOnly; private final TypeInfo typeCache; private boolean disableColumnSanitiser = false; // Default statement prepare threshold. protected int prepareThreshold; /** * Default fetch size for statement. * * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ protected int defaultFetchSize; // Default forcebinary option. protected boolean forcebinary = false; private int rsHoldability = ResultSet.CLOSE_CURSORS_AT_COMMIT; private int savepointId = 0; // Connection's autocommit state. private boolean autoCommit = true; // Connection's readonly state. private boolean readOnly = false; // Filter out database objects for which the current user has no privileges granted from the DatabaseMetaData private boolean hideUnprivilegedObjects ; // Bind String to UNSPECIFIED or VARCHAR? private final boolean bindStringAsVarchar; // Current warnings; there might be more on queryExecutor too. private SQLWarning firstWarning = null; // Timer for scheduling TimerTasks for this connection. // Only instantiated if a task is actually scheduled. private volatile Timer cancelTimer = null; private PreparedStatement checkConnectionQuery; /** * Replication protocol in current version postgresql(10devel) supports a limited number of * commands. */ private final boolean replicationConnection; private final LruCache<FieldMetadata.Key, FieldMetadata> fieldMetadataCache; private final String xmlFactoryFactoryClass; private PGXmlFactoryFactory xmlFactoryFactory; final CachedQuery borrowQuery(String sql) throws SQLException { return queryExecutor.borrowQuery(sql); } final CachedQuery borrowCallableQuery(String sql) throws SQLException { return queryExecutor.borrowCallableQuery(sql); } private CachedQuery borrowReturningQuery(String sql, String[] columnNames) throws SQLException { return queryExecutor.borrowReturningQuery(sql, columnNames); } @Override public CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized, String... columnNames) throws SQLException { return queryExecutor.createQuery(sql, escapeProcessing, isParameterized, columnNames); } void releaseQuery(CachedQuery cachedQuery) { queryExecutor.releaseQuery(cachedQuery); } @Override public void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate) { queryExecutor.setFlushCacheOnDeallocate(flushCacheOnDeallocate); LOGGER.log(Level.FINE, " setFlushCacheOnDeallocate = {0}", flushCacheOnDeallocate); } // // Ctor. // public PgConnection(HostSpec[] hostSpecs, String user, String database, Properties info, String url) throws SQLException { // Print out the driver version number LOGGER.log(Level.FINE, org.postgresql.util.DriverInfo.DRIVER_FULL_NAME); this.creatingURL = url; this.readOnlyBehavior = getReadOnlyBehavior(PGProperty.READ_ONLY_MODE.get(info)); setDefaultFetchSize(PGProperty.DEFAULT_ROW_FETCH_SIZE.getInt(info)); setPrepareThreshold(PGProperty.PREPARE_THRESHOLD.getInt(info)); if (prepareThreshold == -1) { setForceBinary(true); } // Now make the initial connection and set up local state this.queryExecutor = ConnectionFactory.openConnection(hostSpecs, user, database, info); // WARNING for unsupported servers (8.1 and lower are not supported) if (LOGGER.isLoggable(Level.WARNING) && !haveMinimumServerVersion(ServerVersion.v8_2)) { LOGGER.log(Level.WARNING, "Unsupported Server Version: {0}", queryExecutor.getServerVersion()); } setSessionReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", false, true); setSessionNotReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", false, true); // Set read-only early if requested if (PGProperty.READ_ONLY.getBoolean(info)) { setReadOnly(true); } this.hideUnprivilegedObjects = PGProperty.HIDE_UNPRIVILEGED_OBJECTS.getBoolean(info); Set<Integer> binaryOids = getBinaryOids(info); // split for receive and send for better control Set<Integer> useBinarySendForOids = new HashSet<Integer>(binaryOids); Set<Integer> useBinaryReceiveForOids = new HashSet<Integer>(binaryOids); /* * Does not pass unit tests because unit tests expect setDate to have millisecond accuracy * whereas the binary transfer only supports date accuracy. */ useBinarySendForOids.remove(Oid.DATE); queryExecutor.setBinaryReceiveOids(useBinaryReceiveForOids); queryExecutor.setBinarySendOids(useBinarySendForOids); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, " types using binary send = {0}", oidsToString(useBinarySendForOids)); LOGGER.log(Level.FINEST, " types using binary receive = {0}", oidsToString(useBinaryReceiveForOids)); LOGGER.log(Level.FINEST, " integer date/time = {0}", queryExecutor.getIntegerDateTimes()); } // // String -> text or unknown? // String stringType = PGProperty.STRING_TYPE.get(info); if (stringType != null) { if (stringType.equalsIgnoreCase("unspecified")) { bindStringAsVarchar = false; } else if (stringType.equalsIgnoreCase("varchar")) { bindStringAsVarchar = true; } else { throw new PSQLException( GT.tr("Unsupported value for stringtype parameter: {0}", stringType), PSQLState.INVALID_PARAMETER_VALUE); } } else { bindStringAsVarchar = true; } // Initialize timestamp stuff timestampUtils = new TimestampUtils(!queryExecutor.getIntegerDateTimes(), new Provider<TimeZone>() { @Override public TimeZone get() { return queryExecutor.getTimeZone(); } }); // Initialize common queries. // isParameterized==true so full parse is performed and the engine knows the query // is not a compound query with ; inside, so it could use parse/bind/exec messages commitQuery = createQuery("COMMIT", false, true).query; rollbackQuery = createQuery("ROLLBACK", false, true).query; int unknownLength = PGProperty.UNKNOWN_LENGTH.getInt(info); // Initialize object handling typeCache = createTypeInfo(this, unknownLength); initObjectTypes(info); if (PGProperty.LOG_UNCLOSED_CONNECTIONS.getBoolean(info)) { openStackTrace = new Throwable("Connection was created at this point:"); } this.disableColumnSanitiser = PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(info); if (haveMinimumServerVersion(ServerVersion.v8_3)) { typeCache.addCoreType("uuid", Oid.UUID, Types.OTHER, "java.util.UUID", Oid.UUID_ARRAY); typeCache.addCoreType("xml", Oid.XML, Types.SQLXML, "java.sql.SQLXML", Oid.XML_ARRAY); } this.clientInfo = new Properties(); if (haveMinimumServerVersion(ServerVersion.v9_0)) { String appName = PGProperty.APPLICATION_NAME.get(info); if (appName == null) { appName = ""; } this.clientInfo.put("ApplicationName", appName); } fieldMetadataCache = new LruCache<FieldMetadata.Key, FieldMetadata>( Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS.getInt(info)), Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.getInt(info) * 1024 * 1024), false); replicationConnection = PGProperty.REPLICATION.get(info) != null; xmlFactoryFactoryClass = PGProperty.XML_FACTORY_FACTORY.get(info); } private static ReadOnlyBehavior getReadOnlyBehavior(String property) { try { return ReadOnlyBehavior.valueOf(property); } catch (IllegalArgumentException e) { try { return ReadOnlyBehavior.valueOf(property.toLowerCase(Locale.US)); } catch (IllegalArgumentException e2) { return ReadOnlyBehavior.transaction; } } } private static Set<Integer> getSupportedBinaryOids() { return new HashSet<Integer>(Arrays.asList( Oid.BYTEA, Oid.INT2, Oid.INT4, Oid.INT8, Oid.FLOAT4, Oid.FLOAT8, Oid.TIME, Oid.DATE, Oid.TIMETZ, Oid.TIMESTAMP, Oid.TIMESTAMPTZ, Oid.INT2_ARRAY, Oid.INT4_ARRAY, Oid.INT8_ARRAY, Oid.FLOAT4_ARRAY, Oid.FLOAT8_ARRAY, Oid.VARCHAR_ARRAY, Oid.TEXT_ARRAY, Oid.POINT, Oid.BOX, Oid.UUID)); } private static Set<Integer> getBinaryOids(Properties info) throws PSQLException { boolean binaryTransfer = PGProperty.BINARY_TRANSFER.getBoolean(info); // Formats that currently have binary protocol support Set<Integer> binaryOids = new HashSet<Integer>(32); if (binaryTransfer) { binaryOids.addAll(SUPPORTED_BINARY_OIDS); } binaryOids.addAll(getOidSet(PGProperty.BINARY_TRANSFER_ENABLE.get(info))); binaryOids.removeAll(getOidSet(PGProperty.BINARY_TRANSFER_DISABLE.get(info))); binaryOids.retainAll(SUPPORTED_BINARY_OIDS); return binaryOids; } private static Set<Integer> getOidSet(String oidList) throws PSQLException { Set<Integer> oids = new HashSet<Integer>(); StringTokenizer tokenizer = new StringTokenizer(oidList, ","); while (tokenizer.hasMoreTokens()) { String oid = tokenizer.nextToken(); oids.add(Oid.valueOf(oid)); } return oids; } private String oidsToString(Set<Integer> oids) { StringBuilder sb = new StringBuilder(); for (Integer oid : oids) { sb.append(Oid.toString(oid)); sb.append(','); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } else { sb.append(" <none>"); } return sb.toString(); } private final TimestampUtils timestampUtils; public TimestampUtils getTimestampUtils() { return timestampUtils; } /** * The current type mappings. */ protected Map<String, Class<?>> typemap = new HashMap<String, Class<?>>(); @Override public Statement createStatement() throws SQLException { // We now follow the spec and default to TYPE_FORWARD_ONLY. return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public CallableStatement prepareCall(String sql) throws SQLException { return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return typemap; } public QueryExecutor getQueryExecutor() { return queryExecutor; } public ReplicationProtocol getReplicationProtocol() { return queryExecutor.getReplicationProtocol(); } /** * This adds a warning to the warning chain. * * @param warn warning to add */ public void addWarning(SQLWarning warn) { // Add the warning to the chain if (firstWarning != null) { firstWarning.setNextWarning(warn); } else { firstWarning = warn; } } @Override public ResultSet execSQLQuery(String s) throws SQLException { return execSQLQuery(s, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } @Override public ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency) throws SQLException { BaseStatement stat = (BaseStatement) createStatement(resultSetType, resultSetConcurrency); boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN); while (!hasResultSet && stat.getUpdateCount() != -1) { hasResultSet = stat.getMoreResults(); } if (!hasResultSet) { throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stat.getWarnings(); if (warnings != null) { addWarning(warnings); } return stat.getResultSet(); } @Override public void execSQLUpdate(String s) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } void execSQLUpdate(CachedQuery query) throws SQLException { BaseStatement stmt = (BaseStatement) createStatement(); if (stmt.executeWithFlags(query, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN)) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } // Transfer warnings to the connection, since the user never // has a chance to see the statement itself. SQLWarning warnings = stmt.getWarnings(); if (warnings != null) { addWarning(warnings); } stmt.close(); } /** * <p>In SQL, a result table can be retrieved through a cursor that is named. The current row of a * result can be updated or deleted using a positioned update/delete statement that references the * cursor name.</p> * * <p>We do not support positioned update/delete, so this is a no-op.</p> * * @param cursor the cursor name * @throws SQLException if a database access error occurs */ public void setCursorName(String cursor) throws SQLException { checkClosed(); // No-op. } /** * getCursorName gets the cursor name. * * @return the current cursor name * @throws SQLException if a database access error occurs */ public String getCursorName() throws SQLException { checkClosed(); return null; } /** * <p>We are required to bring back certain information by the DatabaseMetaData class. These * functions do that.</p> * * <p>Method getURL() brings back the URL (good job we saved it)</p> * * @return the url * @throws SQLException just in case... */ public String getURL() throws SQLException { return creatingURL; } /** * Method getUserName() brings back the User Name (again, we saved it). * * @return the user name * @throws SQLException just in case... */ public String getUserName() throws SQLException { return queryExecutor.getUser(); } public Fastpath getFastpathAPI() throws SQLException { checkClosed(); if (fastpath == null) { fastpath = new Fastpath(this); } return fastpath; } // This holds a reference to the Fastpath API if already open private Fastpath fastpath = null; public LargeObjectManager getLargeObjectAPI() throws SQLException { checkClosed(); if (largeobject == null) { largeobject = new LargeObjectManager(this); } return largeobject; } // This holds a reference to the LargeObject API if already open private LargeObjectManager largeobject = null; /* * This method is used internally to return an object based around org.postgresql's more unique * data types. * * <p>It uses an internal HashMap to get the handling class. If the type is not supported, then an * instance of org.postgresql.util.PGobject is returned. * * You can use the getValue() or setValue() methods to handle the returned object. Custom objects * can have their own methods. * * @return PGobject for this type, and set to value * * @exception SQLException if value is not correct for this type */ @Override public Object getObject(String type, String value, byte[] byteValue) throws SQLException { if (typemap != null) { Class<?> c = typemap.get(type); if (c != null) { // Handle the type (requires SQLInput & SQLOutput classes to be implemented) throw new PSQLException(GT.tr("Custom type maps are not supported."), PSQLState.NOT_IMPLEMENTED); } } PGobject obj = null; if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Constructing object from type={0} value=<{1}>", new Object[]{type, value}); } try { Class<? extends PGobject> klass = typeCache.getPGobject(type); // If className is not null, then try to instantiate it, // It must be basetype PGobject // This is used to implement the org.postgresql unique types (like lseg, // point, etc). if (klass != null) { obj = klass.newInstance(); obj.setType(type); if (byteValue != null && obj instanceof PGBinaryObject) { PGBinaryObject binObj = (PGBinaryObject) obj; binObj.setByteValue(byteValue, 0); } else { obj.setValue(value); } } else { // If className is null, then the type is unknown. // so return a PGobject with the type set, and the value set obj = new PGobject(); obj.setType(type); obj.setValue(value); } return obj; } catch (SQLException sx) { // rethrow the exception. Done because we capture any others next throw sx; } catch (Exception ex) { throw new PSQLException(GT.tr("Failed to create object for: {0}.", type), PSQLState.CONNECTION_FAILURE, ex); } } protected TypeInfo createTypeInfo(BaseConnection conn, int unknownLength) { return new TypeInfoCache(conn, unknownLength); } public TypeInfo getTypeInfo() { return typeCache; } @Override public void addDataType(String type, String name) { try { addDataType(type, Class.forName(name).asSubclass(PGobject.class)); } catch (Exception e) { throw new RuntimeException("Cannot register new type: " + e); } } @Override public void addDataType(String type, Class<? extends PGobject> klass) throws SQLException { checkClosed(); typeCache.addDataType(type, klass); } // This initialises the objectTypes hash map private void initObjectTypes(Properties info) throws SQLException { // Add in the types that come packaged with the driver. // These can be overridden later if desired. addDataType("box", org.postgresql.geometric.PGbox.class); addDataType("circle", org.postgresql.geometric.PGcircle.class); addDataType("line", org.postgresql.geometric.PGline.class); addDataType("lseg", org.postgresql.geometric.PGlseg.class); addDataType("path", org.postgresql.geometric.PGpath.class); addDataType("point", org.postgresql.geometric.PGpoint.class); addDataType("polygon", org.postgresql.geometric.PGpolygon.class); addDataType("money", org.postgresql.util.PGmoney.class); addDataType("interval", org.postgresql.util.PGInterval.class); Enumeration<?> e = info.propertyNames(); while (e.hasMoreElements()) { String propertyName = (String) e.nextElement(); if (propertyName.startsWith("datatype.")) { String typeName = propertyName.substring(9); String className = info.getProperty(propertyName); Class<?> klass; try { klass = Class.forName(className); } catch (ClassNotFoundException cnfe) { throw new PSQLException( GT.tr("Unable to load the class {0} responsible for the datatype {1}", className, typeName), PSQLState.SYSTEM_ERROR, cnfe); } addDataType(typeName, klass.asSubclass(PGobject.class)); } } } /** * <B>Note:</B> even though {@code Statement} is automatically closed when it is garbage * collected, it is better to close it explicitly to lower resource consumption. * * {@inheritDoc} */ @Override public void close() throws SQLException { if (queryExecutor == null) { // This might happen in case constructor throws an exception (e.g. host being not available). // When that happens the connection is still registered in the finalizer queue, so it gets finalized return; } releaseTimer(); queryExecutor.close(); openStackTrace = null; } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); CachedQuery cachedQuery = queryExecutor.createQuery(sql, false, true); return cachedQuery.query.getNativeSql(); } @Override public synchronized SQLWarning getWarnings() throws SQLException { checkClosed(); SQLWarning newWarnings = queryExecutor.getWarnings(); // NB: also clears them. if (firstWarning == null) { firstWarning = newWarnings; } else { firstWarning.setNextWarning(newWarnings); // Chain them on. } return firstWarning; } @Override public synchronized void clearWarnings() throws SQLException { checkClosed(); queryExecutor.getWarnings(); // Clear and discard. firstWarning = null; } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction read-only property in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } if (readOnly != this.readOnly && autoCommit && this.readOnlyBehavior == ReadOnlyBehavior.always) { execSQLUpdate(readOnly ? setSessionReadOnly : setSessionNotReadOnly); } this.readOnly = readOnly; LOGGER.log(Level.FINE, " setReadOnly = {0}", readOnly); } @Override public boolean isReadOnly() throws SQLException { checkClosed(); return readOnly; } @Override public boolean hintReadOnly() { return readOnly && readOnlyBehavior != ReadOnlyBehavior.ignore; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); if (this.autoCommit == autoCommit) { return; } if (!this.autoCommit) { commit(); } // if the connection is read only, we need to make sure session settings are // correct when autocommit status changed if (this.readOnly && readOnlyBehavior == ReadOnlyBehavior.always) { // if we are turning on autocommit, we need to set session // to read only if (autoCommit) { this.autoCommit = true; execSQLUpdate(setSessionReadOnly); } else { // if we are turning auto commit off, we need to // disable session execSQLUpdate(setSessionNotReadOnly); } } this.autoCommit = autoCommit; LOGGER.log(Level.FINE, " setAutoCommit = {0}", autoCommit); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return this.autoCommit; } private void executeTransactionCommand(Query query) throws SQLException { int flags = QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS | QueryExecutor.QUERY_SUPPRESS_BEGIN; if (prepareThreshold == 0) { flags |= QueryExecutor.QUERY_ONESHOT; } try { getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } catch (SQLException e) { // Don't retry composite queries as it might get partially executed if (query.getSubqueries() != null || !queryExecutor.willHealOnRetry(e)) { throw e; } query.close(); // retry getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags); } } @Override public void commit() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot commit when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(commitQuery); } } protected void checkClosed() throws SQLException { if (isClosed()) { throw new PSQLException(GT.tr("This connection has been closed."), PSQLState.CONNECTION_DOES_NOT_EXIST); } } @Override public void rollback() throws SQLException { checkClosed(); if (autoCommit) { throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { executeTransactionCommand(rollbackQuery); } else { // just log for debugging LOGGER.log(Level.FINE, "Rollback requested but no transaction in progress"); } } public TransactionState getTransactionState() { return queryExecutor.getTransactionState(); } public int getTransactionIsolation() throws SQLException { checkClosed(); String level = null; final ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered if (rs.next()) { level = rs.getString(1); } rs.close(); // TODO revisit: throw exception instead of silently eating the error in unknown cases? if (level == null) { return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } level = level.toUpperCase(Locale.US); if (level.equals("READ COMMITTED")) { return Connection.TRANSACTION_READ_COMMITTED; } if (level.equals("READ UNCOMMITTED")) { return Connection.TRANSACTION_READ_UNCOMMITTED; } if (level.equals("REPEATABLE READ")) { return Connection.TRANSACTION_REPEATABLE_READ; } if (level.equals("SERIALIZABLE")) { return Connection.TRANSACTION_SERIALIZABLE; } return Connection.TRANSACTION_READ_COMMITTED; // Best guess. } public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction isolation level in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } String isolationLevelName = getIsolationLevelName(level); if (isolationLevelName == null) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", level), PSQLState.NOT_IMPLEMENTED); } String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName; execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered LOGGER.log(Level.FINE, " setTransactionIsolation = {0}", isolationLevelName); } protected String getIsolationLevelName(int level) { switch (level) { case Connection.TRANSACTION_READ_COMMITTED: return "READ COMMITTED"; case Connection.TRANSACTION_SERIALIZABLE: return "SERIALIZABLE"; case Connection.TRANSACTION_READ_UNCOMMITTED: return "READ UNCOMMITTED"; case Connection.TRANSACTION_REPEATABLE_READ: return "REPEATABLE READ"; default: return null; } } public void setCatalog(String catalog) throws SQLException { checkClosed(); // no-op } public String getCatalog() throws SQLException { checkClosed(); return queryExecutor.getDatabase(); } public boolean getHideUnprivilegedObjects() { return hideUnprivilegedObjects; } /** * <p>Overrides finalize(). If called, it closes the connection.</p> * * <p>This was done at the request of <a href="mailto:rachel@enlarion.demon.co.uk">Rachel * Greenham</a> who hit a problem where multiple clients didn't close the connection, and once a * fortnight enough clients were open to kill the postgres server.</p> */ protected void finalize() throws Throwable { try { if (openStackTrace != null) { LOGGER.log(Level.WARNING, GT.tr("Finalizing a Connection that was never closed:"), openStackTrace); } close(); } finally { super.finalize(); } } /** * Get server version number. * * @return server version number */ public String getDBVersionNumber() { return queryExecutor.getServerVersion(); } /** * Get server major version. * * @return server major version */ public int getServerMajorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd return integerPart(versionTokens.nextToken()); // return X } catch (NoSuchElementException e) { return 0; } } /** * Get server minor version. * * @return server minor version */ public int getServerMinorVersion() { try { StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd versionTokens.nextToken(); // Skip aaXbb return integerPart(versionTokens.nextToken()); // return Y } catch (NoSuchElementException e) { return 0; } } @Override public boolean haveMinimumServerVersion(int ver) { return queryExecutor.getServerVersionNum() >= ver; } @Override public boolean haveMinimumServerVersion(Version ver) { return haveMinimumServerVersion(ver.getVersionNum()); } @Override public Encoding getEncoding() { return queryExecutor.getEncoding(); } @Override public byte[] encodeString(String str) throws SQLException { try { return getEncoding().encode(str); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."), PSQLState.DATA_ERROR, ioe); } } @Override public String escapeString(String str) throws SQLException { return Utils.escapeLiteral(null, str, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public boolean getStandardConformingStrings() { return queryExecutor.getStandardConformingStrings(); } // This is a cache of the DatabaseMetaData instance for this connection protected java.sql.DatabaseMetaData metadata; @Override public boolean isClosed() throws SQLException { return queryExecutor.isClosed(); } @Override public void cancelQuery() throws SQLException { checkClosed(); queryExecutor.sendQueryCancel(); } @Override public PGNotification[] getNotifications() throws SQLException { return getNotifications(-1); } @Override public PGNotification[] getNotifications(int timeoutMillis) throws SQLException { checkClosed(); getQueryExecutor().processNotifies(timeoutMillis); // Backwards-compatibility hand-holding. PGNotification[] notifications = queryExecutor.getNotifications(); return (notifications.length == 0 ? null : notifications); } /** * Handler for transaction queries. */ private class TransactionCommandHandler extends ResultHandlerBase { public void handleCompletion() throws SQLException { SQLWarning warning = getWarning(); if (warning != null) { PgConnection.this.addWarning(warning); } super.handleCompletion(); } } public int getPrepareThreshold() { return prepareThreshold; } public void setDefaultFetchSize(int fetchSize) throws SQLException { if (fetchSize < 0) { throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } this.defaultFetchSize = fetchSize; LOGGER.log(Level.FINE, " setDefaultFetchSize = {0}", fetchSize); } public int getDefaultFetchSize() { return defaultFetchSize; } public void setPrepareThreshold(int newThreshold) { this.prepareThreshold = newThreshold; LOGGER.log(Level.FINE, " setPrepareThreshold = {0}", newThreshold); } public boolean getForceBinary() { return forcebinary; } public void setForceBinary(boolean newValue) { this.forcebinary = newValue; LOGGER.log(Level.FINE, " setForceBinary = {0}", newValue); } public void setTypeMapImpl(Map<String, Class<?>> map) throws SQLException { typemap = map; } public Logger getLogger() { return LOGGER; } public int getProtocolVersion() { return queryExecutor.getProtocolVersion(); } public boolean getStringVarcharFlag() { return bindStringAsVarchar; } private CopyManager copyManager = null; public CopyManager getCopyAPI() throws SQLException { checkClosed(); if (copyManager == null) { copyManager = new CopyManager(this); } return copyManager; } public boolean binaryTransferSend(int oid) { return queryExecutor.useBinaryForSend(oid); } public int getBackendPID() { return queryExecutor.getBackendPID(); } public boolean isColumnSanitiserDisabled() { return this.disableColumnSanitiser; } public void setDisableColumnSanitiser(boolean disableColumnSanitiser) { this.disableColumnSanitiser = disableColumnSanitiser; LOGGER.log(Level.FINE, " setDisableColumnSanitiser = {0}", disableColumnSanitiser); } @Override public PreferQueryMode getPreferQueryMode() { return queryExecutor.getPreferQueryMode(); } @Override public AutoSave getAutosave() { return queryExecutor.getAutoSave(); } @Override public void setAutosave(AutoSave autoSave) { queryExecutor.setAutoSave(autoSave); LOGGER.log(Level.FINE, " setAutosave = {0}", autoSave.value()); } protected void abort() { queryExecutor.abort(); } private synchronized Timer getTimer() { if (cancelTimer == null) { cancelTimer = Driver.getSharedTimer().getTimer(); } return cancelTimer; } private synchronized void releaseTimer() { if (cancelTimer != null) { cancelTimer = null; Driver.getSharedTimer().releaseTimer(); } } @Override public void addTimerTask(TimerTask timerTask, long milliSeconds) { Timer timer = getTimer(); timer.schedule(timerTask, milliSeconds); } @Override public void purgeTimerTasks() { Timer timer = cancelTimer; if (timer != null) { timer.purge(); } } @Override public String escapeIdentifier(String identifier) throws SQLException { return Utils.escapeIdentifier(null, identifier).toString(); } @Override public String escapeLiteral(String literal) throws SQLException { return Utils.escapeLiteral(null, literal, queryExecutor.getStandardConformingStrings()) .toString(); } @Override public LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache() { return fieldMetadataCache; } @Override public PGReplicationConnection getReplicationAPI() { return new PGReplicationConnectionImpl(this); } private static void appendArray(StringBuilder sb, Object elements, char delim) { sb.append('{'); int nElements = java.lang.reflect.Array.getLength(elements); for (int i = 0; i < nElements; i++) { if (i > 0) { sb.append(delim); } Object o = java.lang.reflect.Array.get(elements, i); if (o == null) { sb.append("NULL"); } else if (o.getClass().isArray()) { final PrimitiveArraySupport arraySupport = PrimitiveArraySupport.getArraySupport(o); if (arraySupport != null) { arraySupport.appendArray(sb, delim, o); } else { appendArray(sb, o, delim); } } else { String s = o.toString(); PgArray.escapeArrayElement(sb, s); } } sb.append('}'); } // Parse a "dirty" integer surrounded by non-numeric characters private static int integerPart(String dirtyString) { int start = 0; while (start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start))) { ++start; } int end = start; while (end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end))) { ++end; } if (start == end) { return 0; } return Integer.parseInt(dirtyString.substring(start, end)); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgPreparedStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); return new PgCallableStatement(this, sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); if (metadata == null) { metadata = new PgDatabaseMetaData(this); } return metadata; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { setTypeMapImpl(map); LOGGER.log(Level.FINE, " setTypeMap = {0}", map); } protected Array makeArray(int oid, String fieldString) throws SQLException { return new PgArray(this, oid, fieldString); } protected Blob makeBlob(long oid) throws SQLException { return new PgBlob(this, oid); } protected Clob makeClob(long oid) throws SQLException { return new PgClob(this, oid); } protected SQLXML makeSQLXML() throws SQLException { return new PgSQLXML(this); } @Override public Clob createClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createClob()"); } @Override public Blob createBlob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createBlob()"); } @Override public NClob createNClob() throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createNClob()"); } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); return makeSQLXML(); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createStruct(String, Object[])"); } @Override public Array createArrayOf(String typeName, Object elements) throws SQLException { checkClosed(); final TypeInfo typeInfo = getTypeInfo(); final int oid = typeInfo.getPGArrayType(typeName); final char delim = typeInfo.getArrayDelimiter(oid); if (oid == Oid.UNSPECIFIED) { throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); } if (elements == null) { return makeArray(oid, null); } final String arrayString; final PrimitiveArraySupport arraySupport = PrimitiveArraySupport.getArraySupport(elements); if (arraySupport != null) { // if the oid for the given type matches the default type, we might be // able to go straight to binary representation if (oid == arraySupport.getDefaultArrayTypeOid(typeInfo) && arraySupport.supportBinaryRepresentation() && getPreferQueryMode() != PreferQueryMode.SIMPLE) { return new PgArray(this, oid, arraySupport.toBinaryRepresentation(this, elements)); } arrayString = arraySupport.toArrayString(delim, elements); } else { final Class<?> clazz = elements.getClass(); if (!clazz.isArray()) { throw new PSQLException(GT.tr("Invalid elements {0}", elements), PSQLState.INVALID_PARAMETER_TYPE); } StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); arrayString = sb.toString(); } return makeArray(oid, arrayString); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); int oid = getTypeInfo().getPGArrayType(typeName); if (oid == Oid.UNSPECIFIED) { throw new PSQLException( GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); } if (elements == null) { return makeArray(oid, null); } char delim = getTypeInfo().getArrayDelimiter(oid); StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); return makeArray(oid, sb.toString()); } @Override public boolean isValid(int timeout) throws SQLException { if (timeout < 0) { throw new PSQLException(GT.tr("Invalid timeout ({0}<0).", timeout), PSQLState.INVALID_PARAMETER_VALUE); } if (isClosed()) { return false; } try { int savedNetworkTimeOut = getNetworkTimeout(); try { setNetworkTimeout(null, timeout * 1000); if (replicationConnection) { Statement statement = createStatement(); statement.execute("IDENTIFY_SYSTEM"); statement.close(); } else { if (checkConnectionQuery == null) { checkConnectionQuery = prepareStatement(""); } checkConnectionQuery.setQueryTimeout(timeout); checkConnectionQuery.executeUpdate(); } return true; } finally { setNetworkTimeout(null, savedNetworkTimeOut); } } catch (SQLException e) { if (PSQLState.IN_FAILED_SQL_TRANSACTION.getState().equals(e.getSQLState())) { // "current transaction aborted", assume the connection is up and running return true; } LOGGER.log(Level.FINE, GT.tr("Validating connection."), e); } return false; } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } if (haveMinimumServerVersion(ServerVersion.v9_0) && "ApplicationName".equals(name)) { if (value == null) { value = ""; } final String oldValue = queryExecutor.getApplicationName(); if (value.equals(oldValue)) { return; } try { StringBuilder sql = new StringBuilder("SET application_name = '"); Utils.escapeLiteral(sql, value, getStandardConformingStrings()); sql.append("'"); execSQLUpdate(sql.toString()); } catch (SQLException sqle) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); failures.put(name, ClientInfoStatus.REASON_UNKNOWN); throw new SQLClientInfoException( GT.tr("Failed to set ClientInfo property: {0}", "ApplicationName"), sqle.getSQLState(), failures, sqle); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, " setClientInfo = {0} {1}", new Object[]{name, value}); } clientInfo.put(name, value); return; } addWarning(new SQLWarning(GT.tr("ClientInfo property not supported."), PSQLState.NOT_IMPLEMENTED.getState())); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { try { checkClosed(); } catch (final SQLException cause) { Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (Map.Entry<Object, Object> e : properties.entrySet()) { failures.put((String) e.getKey(), ClientInfoStatus.REASON_UNKNOWN); } throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause); } Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>(); for (String name : new String[]{"ApplicationName"}) { try { setClientInfo(name, properties.getProperty(name, null)); } catch (SQLClientInfoException e) { failures.putAll(e.getFailedProperties()); } } if (!failures.isEmpty()) { throw new SQLClientInfoException(GT.tr("One or more ClientInfo failed."), PSQLState.NOT_IMPLEMENTED.getState(), failures); } } @Override public String getClientInfo(String name) throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo.getProperty(name); } @Override public Properties getClientInfo() throws SQLException { checkClosed(); clientInfo.put("ApplicationName", queryExecutor.getApplicationName()); return clientInfo; } public <T> T createQueryObject(Class<T> ifc) throws SQLException { checkClosed(); throw org.postgresql.Driver.notImplemented(this.getClass(), "createQueryObject(Class<T>)"); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { checkClosed(); return iface.isAssignableFrom(getClass()); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { checkClosed(); if (iface.isAssignableFrom(getClass())) { return iface.cast(this); } throw new SQLException("Cannot unwrap to " + iface.getName()); } public String getSchema() throws SQLException { checkClosed(); Statement stmt = createStatement(); try { ResultSet rs = stmt.executeQuery("select current_schema()"); try { if (!rs.next()) { return null; // Is it ever possible? } return rs.getString(1); } finally { rs.close(); } } finally { stmt.close(); } } public void setSchema(String schema) throws SQLException { checkClosed(); Statement stmt = createStatement(); try { if (schema == null) { stmt.executeUpdate("SET SESSION search_path TO DEFAULT"); } else { StringBuilder sb = new StringBuilder(); sb.append("SET SESSION search_path TO '"); Utils.escapeLiteral(sb, schema, getStandardConformingStrings()); sb.append("'"); stmt.executeUpdate(sb.toString()); LOGGER.log(Level.FINE, " setSchema = {0}", schema); } } finally { stmt.close(); } } public class AbortCommand implements Runnable { public void run() { abort(); } } public void abort(Executor executor) throws SQLException { if (executor == null) { throw new SQLException("executor is null"); } if (isClosed()) { return; } SQL_PERMISSION_ABORT.checkGuard(this); AbortCommand command = new AbortCommand(); executor.execute(command); } public void setNetworkTimeout(Executor executor /*not used*/, int milliseconds) throws SQLException { checkClosed(); if (milliseconds < 0) { throw new PSQLException(GT.tr("Network timeout must be a value greater than or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); } SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { securityManager.checkPermission(SQL_PERMISSION_NETWORK_TIMEOUT); } try { queryExecutor.setNetworkTimeout(milliseconds); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to set network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } public int getNetworkTimeout() throws SQLException { checkClosed(); try { return queryExecutor.getNetworkTimeout(); } catch (IOException ioe) { throw new PSQLException(GT.tr("Unable to get network timeout."), PSQLState.COMMUNICATION_ERROR, ioe); } } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); switch (holdability) { case ResultSet.CLOSE_CURSORS_AT_COMMIT: rsHoldability = holdability; break; case ResultSet.HOLD_CURSORS_OVER_COMMIT: rsHoldability = holdability; break; default: throw new PSQLException(GT.tr("Unknown ResultSet holdability setting: {0}.", holdability), PSQLState.INVALID_PARAMETER_VALUE); } LOGGER.log(Level.FINE, " setHoldability = {0}", holdability); } @Override public int getHoldability() throws SQLException { checkClosed(); return rsHoldability; } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); String pgName; if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(savepointId++); pgName = savepoint.getPGName(); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + pgName); stmt.close(); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); if (getAutoCommit()) { throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."), PSQLState.NO_ACTIVE_SQL_TRANSACTION); } PSQLSavepoint savepoint = new PSQLSavepoint(name); // Note we can't use execSQLUpdate because we don't want // to suppress BEGIN. Statement stmt = createStatement(); stmt.executeUpdate("SAVEPOINT " + savepoint.getPGName()); stmt.close(); return savepoint; } @Override public void rollback(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("ROLLBACK TO SAVEPOINT " + pgSavepoint.getPGName()); } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { checkClosed(); PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint; execSQLUpdate("RELEASE SAVEPOINT " + pgSavepoint.getPGName()); pgSavepoint.invalidate(); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return createStatement(resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareStatement(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); return prepareCall(sql, resultSetType, resultSetConcurrency, getHoldability()); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS) { return prepareStatement(sql); } return prepareStatement(sql, (String[]) null); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { if (columnIndexes != null && columnIndexes.length == 0) { return prepareStatement(sql); } checkClosed(); throw new PSQLException(GT.tr("Returning autogenerated keys is not supported."), PSQLState.NOT_IMPLEMENTED); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { if (columnNames != null && columnNames.length == 0) { return prepareStatement(sql); } CachedQuery cachedQuery = borrowReturningQuery(sql, columnNames); PgPreparedStatement ps = new PgPreparedStatement(this, cachedQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, getHoldability()); Query query = cachedQuery.query; SqlCommand sqlCommand = query.getSqlCommand(); if (sqlCommand != null) { ps.wantsGeneratedKeysAlways = sqlCommand.isReturningKeywordPresent(); } else { // If composite query is given, just ignore "generated keys" arguments } return ps; } @Override public final Map<String,String> getParameterStatuses() { return queryExecutor.getParameterStatuses(); } @Override public final String getParameterStatus(String parameterName) { return queryExecutor.getParameterStatus(parameterName); } @Override public PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException { if (xmlFactoryFactory == null) { if (xmlFactoryFactoryClass == null || xmlFactoryFactoryClass.equals("")) { xmlFactoryFactory = DefaultPGXmlFactoryFactory.INSTANCE; } else if (xmlFactoryFactoryClass.equals("LEGACY_INSECURE")) { xmlFactoryFactory = LegacyInsecurePGXmlFactoryFactory.INSTANCE; } else { Class<?> clazz; try { clazz = Class.forName(xmlFactoryFactoryClass); } catch (ClassNotFoundException ex) { throw new PSQLException( GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE, ex); } if (!clazz.isAssignableFrom(PGXmlFactoryFactory.class)) { throw new PSQLException( GT.tr("Connection property xmlFactoryFactory must implement PGXmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE); } try { xmlFactoryFactory = (PGXmlFactoryFactory) clazz.newInstance(); } catch (Exception ex) { throw new PSQLException( GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass), PSQLState.INVALID_PARAMETER_VALUE, ex); } } } return xmlFactoryFactory; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4033_3
crossvul-java_data_good_2449_10
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.platformlambda.services; import org.platformlambda.core.exception.AppException; import org.platformlambda.core.models.EventEnvelope; import org.platformlambda.core.models.LambdaFunction; import org.platformlambda.core.system.Platform; import org.platformlambda.models.ObjectWithGenericType; import org.platformlambda.models.SamplePoJo; import java.io.IOException; import java.util.Date; import java.util.Map; public class HelloGeneric implements LambdaFunction { @Override public Object handleEvent(Map<String, String> headers, Object body, int instance) throws AppException, IOException { String id = headers.get("id"); if (id == null) { throw new IllegalArgumentException("Missing parameter 'id'"); } if (id.equals("1")) { // to set status, key-values or parametric types, we can use EventEnvelope as a result wrapper EventEnvelope result = new EventEnvelope(); ObjectWithGenericType<SamplePoJo> genericObject = new ObjectWithGenericType<>(); // return some place-holder values to demonstrate the PoJo can be transported over the network SamplePoJo mock = new SamplePoJo(1, "Generic class with parametric type SamplePoJo", "200 World Blvd, Planet Earth"); // set current timestamp to indicate that the object is a new one mock.setDate(new Date()); // set instance count and service origin ID to show that the object comes from a different instance mock.setInstance(instance); mock.setOrigin(Platform.getInstance().getOrigin()); genericObject.setId(101); genericObject.setContent(mock); result.setBody(genericObject); result.setParametricType(SamplePoJo.class); return result; } else { throw new AppException(404, "Not found. Try id = 1"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_2449_10
crossvul-java_data_bad_1910_1
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.avmfritz.internal.hardware.callbacks; import static org.eclipse.jetty.http.HttpMethod.GET; import java.io.StringReader; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.avmfritz.internal.dto.templates.TemplateListModel; import org.openhab.binding.avmfritz.internal.handler.AVMFritzBaseBridgeHandler; import org.openhab.binding.avmfritz.internal.hardware.FritzAhaWebInterface; import org.openhab.binding.avmfritz.internal.util.JAXBUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Callback implementation for updating templates from a xml response. * * @author Christoph Weitkamp - Initial contribution */ @NonNullByDefault public class FritzAhaUpdateTemplatesCallback extends FritzAhaReauthCallback { private final Logger logger = LoggerFactory.getLogger(FritzAhaUpdateTemplatesCallback.class); private static final String WEBSERVICE_COMMAND = "switchcmd=gettemplatelistinfos"; private final AVMFritzBaseBridgeHandler handler; /** * Constructor * * @param webInterface web interface to FRITZ!Box * @param handler handler that will update things */ public FritzAhaUpdateTemplatesCallback(FritzAhaWebInterface webInterface, AVMFritzBaseBridgeHandler handler) { super(WEBSERVICE_PATH, WEBSERVICE_COMMAND, webInterface, GET, 1); this.handler = handler; } @Override public void execute(int status, String response) { super.execute(status, response); logger.trace("Received response '{}'", response); if (isValidRequest()) { try { Unmarshaller unmarshaller = JAXBUtils.JAXBCONTEXT_TEMPLATES.createUnmarshaller(); TemplateListModel model = (TemplateListModel) unmarshaller.unmarshal(new StringReader(response)); if (model != null) { handler.addTemplateList(model.getTemplates()); } else { logger.debug("no template in response"); } } catch (JAXBException e) { logger.error("Exception creating Unmarshaller: {}", e.getLocalizedMessage(), e); } } else { logger.debug("request is invalid: {}", status); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_1
crossvul-java_data_bad_4290_5
/* * file: GanttDesignerReader.java * author: Jon Iles * copyright: (c) Packwood Software 2019 * date: 10 February 2019 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.ganttdesigner; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import net.sf.mpxj.ChildTaskContainer; import net.sf.mpxj.Day; import net.sf.mpxj.EventManager; import net.sf.mpxj.MPXJException; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectCalendarWeek; import net.sf.mpxj.ProjectConfig; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.ProjectProperties; import net.sf.mpxj.RelationType; import net.sf.mpxj.Task; import net.sf.mpxj.ganttdesigner.schema.Gantt; import net.sf.mpxj.ganttdesigner.schema.GanttDesignerRemark; import net.sf.mpxj.listener.ProjectListener; import net.sf.mpxj.reader.AbstractProjectReader; /** * This class creates a new ProjectFile instance by reading a GanttDesigner file. */ public final class GanttDesignerReader extends AbstractProjectReader { /** * {@inheritDoc} */ @Override public void addProjectListener(ProjectListener listener) { if (m_projectListeners == null) { m_projectListeners = new ArrayList<>(); } m_projectListeners.add(listener); } /** * {@inheritDoc} */ @Override public ProjectFile read(InputStream stream) throws MPXJException { try { m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_taskMap = new HashMap<>(); ProjectConfig config = m_projectFile.getProjectConfig(); config.setAutoWBS(false); m_projectFile.getProjectProperties().setFileApplication("GanttDesigner"); m_projectFile.getProjectProperties().setFileType("GNT"); m_eventManager.addProjectListeners(m_projectListeners); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); SAXSource doc = new SAXSource(xmlReader, new InputSource(stream)); if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } Unmarshaller unmarshaller = CONTEXT.createUnmarshaller(); Gantt gantt = (Gantt) unmarshaller.unmarshal(doc); readProjectProperties(gantt); readCalendar(gantt); readTasks(gantt); return m_projectFile; } catch (ParserConfigurationException ex) { throw new MPXJException("Failed to parse file", ex); } catch (JAXBException ex) { throw new MPXJException("Failed to parse file", ex); } catch (SAXException ex) { throw new MPXJException("Failed to parse file", ex); } finally { m_projectFile = null; m_eventManager = null; m_projectListeners = null; m_taskMap = null; } } /** * Read project properties. * * @param gantt Gantt Designer file */ private void readProjectProperties(Gantt gantt) { Gantt.File file = gantt.getFile(); ProjectProperties props = m_projectFile.getProjectProperties(); props.setLastSaved(file.getSaved()); props.setCreationDate(file.getCreated()); props.setName(file.getName()); } /** * Read the calendar data from a Gantt Designer file. * * @param gantt Gantt Designer file. */ private void readCalendar(Gantt gantt) { Gantt.Calendar ganttCalendar = gantt.getCalendar(); m_projectFile.getProjectProperties().setWeekStartDay(ganttCalendar.getWeekStart()); ProjectCalendar calendar = m_projectFile.addCalendar(); calendar.setName("Standard"); m_projectFile.setDefaultCalendar(calendar); String workingDays = ganttCalendar.getWorkDays(); calendar.setWorkingDay(Day.SUNDAY, workingDays.charAt(0) == '1'); calendar.setWorkingDay(Day.MONDAY, workingDays.charAt(1) == '1'); calendar.setWorkingDay(Day.TUESDAY, workingDays.charAt(2) == '1'); calendar.setWorkingDay(Day.WEDNESDAY, workingDays.charAt(3) == '1'); calendar.setWorkingDay(Day.THURSDAY, workingDays.charAt(4) == '1'); calendar.setWorkingDay(Day.FRIDAY, workingDays.charAt(5) == '1'); calendar.setWorkingDay(Day.SATURDAY, workingDays.charAt(6) == '1'); for (int i = 1; i <= 7; i++) { Day day = Day.getInstance(i); ProjectCalendarHours hours = calendar.addCalendarHours(day); if (calendar.isWorkingDay(day)) { hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } for (Gantt.Holidays.Holiday holiday : gantt.getHolidays().getHoliday()) { ProjectCalendarException exception = calendar.addCalendarException(holiday.getDate(), holiday.getDate()); exception.setName(holiday.getContent()); } } /** * Read task data from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void readTasks(Gantt gantt) { processTasks(gantt); processPredecessors(gantt); processRemarks(gantt); } /** * Read task data from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void processTasks(Gantt gantt) { ProjectCalendar calendar = m_projectFile.getDefaultCalendar(); for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask()) { String wbs = ganttTask.getID(); ChildTaskContainer parentTask = getParentTask(wbs); Task task = parentTask.addTask(); //ganttTask.getB() // bar type //ganttTask.getBC() // bar color task.setCost(ganttTask.getC()); task.setName(ganttTask.getContent()); task.setDuration(ganttTask.getD()); task.setDeadline(ganttTask.getDL()); //ganttTask.getH() // height //ganttTask.getIn(); // indent task.setWBS(wbs); task.setPercentageComplete(ganttTask.getPC()); task.setStart(ganttTask.getS()); //ganttTask.getU(); // Unknown //ganttTask.getVA(); // Valign task.setFinish(calendar.getDate(task.getStart(), task.getDuration(), false)); m_taskMap.put(wbs, task); } } /** * Read predecessors from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void processPredecessors(Gantt gantt) { for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask()) { String predecessors = ganttTask.getP(); if (predecessors != null && !predecessors.isEmpty()) { String wbs = ganttTask.getID(); Task task = m_taskMap.get(wbs); for (String predecessor : predecessors.split(";")) { Task predecessorTask = m_projectFile.getTaskByID(Integer.valueOf(predecessor)); task.addPredecessor(predecessorTask, RelationType.FINISH_START, ganttTask.getL()); } } } } /** * Read remarks from a Gantt Designer file. * * @param gantt Gantt Designer file */ private void processRemarks(Gantt gantt) { processRemarks(gantt.getRemarks()); processRemarks(gantt.getRemarks1()); processRemarks(gantt.getRemarks2()); processRemarks(gantt.getRemarks3()); processRemarks(gantt.getRemarks4()); } /** * Read an individual remark type from a Gantt Designer file. * * @param remark remark type */ private void processRemarks(GanttDesignerRemark remark) { for (GanttDesignerRemark.Task remarkTask : remark.getTask()) { Integer id = remarkTask.getRow(); Task task = m_projectFile.getTaskByID(id); String notes = task.getNotes(); if (notes.isEmpty()) { notes = remarkTask.getContent(); } else { notes = notes + '\n' + remarkTask.getContent(); } task.setNotes(notes); } } /** * Extract the parent WBS from a WBS. * * @param wbs current WBS * @return parent WBS */ private String getParentWBS(String wbs) { String result; int index = wbs.lastIndexOf('.'); if (index == -1) { result = null; } else { result = wbs.substring(0, index); } return result; } /** * Retrieve the parent task based on its WBS. * * @param wbs parent WBS * @return parent task */ private ChildTaskContainer getParentTask(String wbs) { ChildTaskContainer result; String parentWbs = getParentWBS(wbs); if (parentWbs == null) { result = m_projectFile; } else { result = m_taskMap.get(parentWbs); } return result; } private ProjectFile m_projectFile; private EventManager m_eventManager; private List<ProjectListener> m_projectListeners; Map<String, Task> m_taskMap; /** * Cached context to minimise construction cost. */ private static JAXBContext CONTEXT; /** * Note any error occurring during context construction. */ private static JAXBException CONTEXT_EXCEPTION; static { try { // // JAXB RI property to speed up construction // System.setProperty("com.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot", "true"); // // Construct the context // CONTEXT = JAXBContext.newInstance("net.sf.mpxj.ganttdesigner.schema", GanttDesignerReader.class.getClassLoader()); } catch (JAXBException ex) { CONTEXT_EXCEPTION = ex; CONTEXT = null; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4290_5
crossvul-java_data_bad_1738_0
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.milton.http; import io.milton.resource.AccessControlledResource; import io.milton.resource.AccessControlledResource.Priviledge; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * * @author brad */ public class AclUtils { /** * Recurisve function which checks the given collection of priviledges, * and checks inside the contains property of those priviledges * * Returns true if the required priviledge is directly present in the collection * or is implied * * @param required * @param privs * @return */ public static boolean containsPriviledge(AccessControlledResource.Priviledge required, Iterable<AccessControlledResource.Priviledge> privs) { for (AccessControlledResource.Priviledge p : privs) { if (p.equals(required)) { return true; } if( containsPriviledge(required, p.contains)) { return true; } } return false; } public static Set<AccessControlledResource.Priviledge> asSet(AccessControlledResource.Priviledge ... privs) { Set<AccessControlledResource.Priviledge> set = new HashSet<AccessControlledResource.Priviledge>(privs.length); set.addAll(Arrays.asList(privs)); return set; } /** * Return a set containing all privs in the given collection, and also all priviledges * implies by those, and so on recursively * * @param privs * @return - a set containiing all priviledges, direct or implied, by the given collection */ public static Set<AccessControlledResource.Priviledge> expand(Iterable<AccessControlledResource.Priviledge> privs) { Set<AccessControlledResource.Priviledge> set = new HashSet<AccessControlledResource.Priviledge>(); _expand(privs, set); return set; } private static void _expand(Iterable<AccessControlledResource.Priviledge> privs, Set<AccessControlledResource.Priviledge> output) { if( privs == null ) { return ; } for( Priviledge p : privs ) { output.add(p); _expand(p.contains, output); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1738_0
crossvul-java_data_good_1910_13
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.ihc.internal.ws.projectfile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.FileUtils; import org.openhab.binding.ihc.internal.ws.datatypes.WSProjectInfo; import org.openhab.binding.ihc.internal.ws.exeptions.IhcExecption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Generic methods related to IHC / ELKO project file handling. * * @author Pauli Anttila - Initial contribution */ public class ProjectFileUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ProjectFileUtils.class); /** * Read IHC project file from local file. * * @param filePath File to read. * @return XML document. * @throws IhcExecption when file read fails. */ public static Document readFromFile(String filePath) throws IhcExecption { File fXmlFile = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); try { // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbFactory.setXIncludeAware(false); dbFactory.setExpandEntityReferences(false); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); return doc; } catch (IOException | ParserConfigurationException | SAXException e) { throw new IhcExecption(e); } } /** * Save IHC project file to local file. * * @param filePath File path. * @param data Data to write * @throws IhcExecption when file write fails. */ public static void saveToFile(String filePath, byte[] data) throws IhcExecption { try { FileUtils.writeByteArrayToFile(new File(filePath), data); } catch (IOException e) { throw new IhcExecption(e); } } /** * Convert bytes to XML document. * * @return XML document or null if conversion fails. */ public static Document converteBytesToDocument(byte[] data) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(data)); } catch (ParserConfigurationException | SAXException | IOException e) { LOGGER.warn("Error occured when trying to convert data to XML, reason {}", e.getMessage()); } return null; } /** * Compare XML document header information to project info. * * @return true if information is equal and false if not. */ public static boolean projectEqualsToControllerProject(Document projectfile, WSProjectInfo projectInfo) { if (projectInfo != null) { try { NodeList nodes = projectfile.getElementsByTagName("modified"); if (nodes.getLength() == 1) { Element node = (Element) nodes.item(0); int year = Integer.parseInt(node.getAttribute("year")); int month = Integer.parseInt(node.getAttribute("month")); int day = Integer.parseInt(node.getAttribute("day")); int hour = Integer.parseInt(node.getAttribute("hour")); int minute = Integer.parseInt(node.getAttribute("minute")); LOGGER.debug("Project file from file, date: {}.{}.{} {}:{}", year, month, day, hour, minute); LOGGER.debug("Project file in controller, date: {}.{}.{} {}:{}", projectInfo.getLastmodified().getYear(), projectInfo.getLastmodified().getMonthWithJanuaryAsOne(), projectInfo.getLastmodified().getDay(), projectInfo.getLastmodified().getHours(), projectInfo.getLastmodified().getMinutes()); if (projectInfo.getLastmodified().getYear() == year && projectInfo.getLastmodified().getMonthWithJanuaryAsOne() == month && projectInfo.getLastmodified().getDay() == day && projectInfo.getLastmodified().getHours() == hour && projectInfo.getLastmodified().getMinutes() == minute) { return true; } } } catch (RuntimeException e) { LOGGER.debug("Error occured during project file date comparasion, reason {}.", e.getMessage(), e); // There is no documentation available for XML content. This is part of inessential feature, so do // nothing, but return false } } return false; } /** * Parse all enum values from IHC project file. * * @param doc IHC project file in XML format. * @return enum dictionary. */ public static Map<Integer, List<IhcEnumValue>> parseEnums(Document doc) { Map<Integer, List<IhcEnumValue>> enumDictionary = new HashMap<>(); if (doc != null) { NodeList nodes = doc.getElementsByTagName("enum_definition"); // iterate enum definitions from project for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); int typedefId = Integer.parseInt(element.getAttribute("id").replace("_0x", ""), 16); String enumName = element.getAttribute("name"); List<IhcEnumValue> enumValues = new ArrayList<>(); NodeList name = element.getElementsByTagName("enum_value"); for (int j = 0; j < name.getLength(); j++) { Element val = (Element) name.item(j); int id = Integer.parseInt(val.getAttribute("id").replace("_0x", ""), 16); String n = val.getAttribute("name"); IhcEnumValue enumVal = new IhcEnumValue(id, n); enumValues.add(enumVal); } LOGGER.debug("Enum values found: typedefId={}, name={}: {}", typedefId, enumName, enumValues); enumDictionary.put(typedefId, enumValues); } } return enumDictionary; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_13
crossvul-java_data_good_2449_11
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.platformlambda.services; import org.platformlambda.core.exception.AppException; import org.platformlambda.core.models.LambdaFunction; import org.platformlambda.core.system.Platform; import org.platformlambda.models.SamplePoJo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Date; import java.util.Map; public class HelloPoJo implements LambdaFunction { private static final Logger log = LoggerFactory.getLogger(HelloPoJo.class); @Override public Object handleEvent(Map<String, String> headers, Object body, int instance) throws AppException, IOException { String id = headers.get("id"); if (id == null) { throw new IllegalArgumentException("Missing parameter 'id'"); } if (id.equals("1")) { // return some place-holder values to demonstrate the PoJo can be transported over the network SamplePoJo mock = new SamplePoJo(1, "Simple PoJo class", "100 World Blvd, Planet Earth"); // set current timestamp to indicate that the object is a new one mock.setDate(new Date()); // set instance count and service origin ID to show that the object comes from a different instance mock.setInstance(instance); mock.setOrigin(Platform.getInstance().getOrigin()); log.info("Pojo delivered by instance #{}", instance); return mock; } else { throw new AppException(404, "Not found. Try id = 1"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_2449_11
crossvul-java_data_good_1397_0
/* * Copyright 2017 - 2019 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream; import io.netty.channel.Channel; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import org.traccar.BaseHttpProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.Protocol; import org.traccar.helper.DateUtil; import org.traccar.model.Position; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.net.SocketAddress; import java.util.LinkedList; import java.util.List; public class SpotProtocolDecoder extends BaseHttpProtocolDecoder { private DocumentBuilder documentBuilder; private XPath xPath; private XPathExpression messageExpression; public SpotProtocolDecoder(Protocol protocol) { super(protocol); try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); builderFactory.setXIncludeAware(false); builderFactory.setExpandEntityReferences(false); documentBuilder = builderFactory.newDocumentBuilder(); xPath = XPathFactory.newInstance().newXPath(); messageExpression = xPath.compile("//messageList/message"); } catch (ParserConfigurationException | XPathExpressionException e) { throw new RuntimeException(e); } } @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { FullHttpRequest request = (FullHttpRequest) msg; Document document = documentBuilder.parse(new ByteBufferBackedInputStream(request.content().nioBuffer())); NodeList nodes = (NodeList) messageExpression.evaluate(document, XPathConstants.NODESET); List<Position> positions = new LinkedList<>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, xPath.evaluate("esnName", node)); if (deviceSession != null) { Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); position.setValid(true); position.setTime(DateUtil.parseDate(xPath.evaluate("timestamp", node))); position.setLatitude(Double.parseDouble(xPath.evaluate("latitude", node))); position.setLongitude(Double.parseDouble(xPath.evaluate("longitude", node))); position.set(Position.KEY_EVENT, xPath.evaluate("messageType", node)); positions.add(position); } } sendResponse(channel, HttpResponseStatus.OK); return positions; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1397_0
crossvul-java_data_good_1910_4
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.denonmarantz.internal.connector.http; import java.beans.Introspector; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.UnmarshalException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.StreamReaderDelegate; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.openhab.binding.denonmarantz.internal.DenonMarantzState; import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration; import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnector; import org.openhab.binding.denonmarantz.internal.xml.entities.Deviceinfo; import org.openhab.binding.denonmarantz.internal.xml.entities.Main; import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatus; import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatusLite; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandRequest; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandResponse; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandRx; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandTx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class makes the connection to the receiver and manages it. * It is also responsible for sending commands to the receiver. * * * * @author Jeroen Idserda - Initial Contribution (1.x Binding) * @author Jan-Willem Veldhuis - Refactored for 2.x */ public class DenonMarantzHttpConnector extends DenonMarantzConnector { private Logger logger = LoggerFactory.getLogger(DenonMarantzHttpConnector.class); private static final int REQUEST_TIMEOUT_MS = 5000; // 5 seconds // Main URL for the receiver private static final String URL_MAIN = "formMainZone_MainZoneXml.xml"; // Main Zone Status URL private static final String URL_ZONE_MAIN = "formMainZone_MainZoneXmlStatus.xml"; // Secondary zone lite status URL (contains less info) private static final String URL_ZONE_SECONDARY_LITE = "formZone%d_Zone%dXmlStatusLite.xml"; // Device info URL private static final String URL_DEVICE_INFO = "Deviceinfo.xml"; // URL to send app commands to private static final String URL_APP_COMMAND = "AppCommand.xml"; private static final String CONTENT_TYPE_XML = "application/xml"; private final String cmdUrl; private final String statusUrl; private final HttpClient httpClient; private ScheduledFuture<?> pollingJob; public DenonMarantzHttpConnector(DenonMarantzConfiguration config, DenonMarantzState state, ScheduledExecutorService scheduler, HttpClient httpClient) { this.config = config; this.scheduler = scheduler; this.state = state; this.cmdUrl = String.format("http://%s:%d/goform/formiPhoneAppDirect.xml?", config.getHost(), config.getHttpPort()); this.statusUrl = String.format("http://%s:%d/goform/", config.getHost(), config.getHttpPort()); this.httpClient = httpClient; } public DenonMarantzState getState() { return state; } /** * Set up the connection to the receiver by starting to poll the HTTP API. */ @Override public void connect() { if (!isPolling()) { logger.debug("HTTP polling started."); try { setConfigProperties(); } catch (IOException e) { logger.debug("IO error while retrieving document:", e); state.connectionError("IO error while connecting to AVR: " + e.getMessage()); return; } pollingJob = scheduler.scheduleWithFixedDelay(() -> { try { refreshHttpProperties(); } catch (IOException e) { logger.debug("IO error while retrieving document", e); state.connectionError("IO error while connecting to AVR: " + e.getMessage()); stopPolling(); } catch (RuntimeException e) { /** * We need to catch this RuntimeException, as otherwise the polling stops. * Log as error as it could be a user configuration error. */ StringBuilder sb = new StringBuilder(); for (StackTraceElement s : e.getStackTrace()) { sb.append(s.toString()).append("\n"); } logger.error("Error while polling Http: \"{}\". Stacktrace: \n{}", e.getMessage(), sb.toString()); } }, 0, config.httpPollingInterval, TimeUnit.SECONDS); } } private boolean isPolling() { return pollingJob != null && !pollingJob.isCancelled(); } private void stopPolling() { if (isPolling()) { pollingJob.cancel(true); logger.debug("HTTP polling stopped."); } } /** * Shutdown the http client */ @Override public void dispose() { logger.debug("disposing connector"); stopPolling(); } @Override protected void internalSendCommand(String command) { logger.debug("Sending command '{}'", command); if (StringUtils.isBlank(command)) { logger.warn("Trying to send empty command"); return; } try { String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName()); logger.trace("Calling url {}", url); httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() { @Override public void onComplete(Result result) { if (result.getResponse().getStatus() != 200) { logger.warn("Error {} while sending command", result.getResponse().getReason()); } } }); } catch (UnsupportedEncodingException e) { logger.warn("Error sending command", e); } } private void updateMain() throws IOException { String url = statusUrl + URL_MAIN; logger.trace("Refreshing URL: {}", url); Main statusMain = getDocument(url, Main.class); if (statusMain != null) { state.setPower(statusMain.getPower().getValue()); } } private void updateMainZone() throws IOException { String url = statusUrl + URL_ZONE_MAIN; logger.trace("Refreshing URL: {}", url); ZoneStatus mainZone = getDocument(url, ZoneStatus.class); if (mainZone != null) { state.setInput(mainZone.getInputFuncSelect().getValue()); state.setMainVolume(mainZone.getMasterVolume().getValue()); state.setMainZonePower(mainZone.getPower().getValue()); state.setMute(mainZone.getMute().getValue()); if (config.inputOptions == null) { config.inputOptions = mainZone.getInputFuncList(); } if (mainZone.getSurrMode() == null) { logger.debug("Unable to get the SURROUND_MODE. MainZone update may not be correct."); } else { state.setSurroundProgram(mainZone.getSurrMode().getValue()); } } } private void updateSecondaryZones() throws IOException { for (int i = 2; i <= config.getZoneCount(); i++) { String url = String.format("%s" + URL_ZONE_SECONDARY_LITE, statusUrl, i, i); logger.trace("Refreshing URL: {}", url); ZoneStatusLite zoneSecondary = getDocument(url, ZoneStatusLite.class); if (zoneSecondary != null) { switch (i) { // maximum 2 secondary zones are supported case 2: state.setZone2Power(zoneSecondary.getPower().getValue()); state.setZone2Volume(zoneSecondary.getMasterVolume().getValue()); state.setZone2Mute(zoneSecondary.getMute().getValue()); state.setZone2Input(zoneSecondary.getInputFuncSelect().getValue()); break; case 3: state.setZone3Power(zoneSecondary.getPower().getValue()); state.setZone3Volume(zoneSecondary.getMasterVolume().getValue()); state.setZone3Mute(zoneSecondary.getMute().getValue()); state.setZone3Input(zoneSecondary.getInputFuncSelect().getValue()); break; case 4: state.setZone4Power(zoneSecondary.getPower().getValue()); state.setZone4Volume(zoneSecondary.getMasterVolume().getValue()); state.setZone4Mute(zoneSecondary.getMute().getValue()); state.setZone4Input(zoneSecondary.getInputFuncSelect().getValue()); break; } } } } private void updateDisplayInfo() throws IOException { String url = statusUrl + URL_APP_COMMAND; logger.trace("Refreshing URL: {}", url); AppCommandRequest request = AppCommandRequest.of(CommandTx.CMD_NET_STATUS); AppCommandResponse response = postDocument(url, AppCommandResponse.class, request); if (response != null) { CommandRx titleInfo = response.getCommands().get(0); state.setNowPlayingArtist(titleInfo.getText("artist")); state.setNowPlayingAlbum(titleInfo.getText("album")); state.setNowPlayingTrack(titleInfo.getText("track")); } } private boolean setConfigProperties() throws IOException { String url = statusUrl + URL_DEVICE_INFO; logger.debug("Refreshing URL: {}", url); Deviceinfo deviceinfo = getDocument(url, Deviceinfo.class); if (deviceinfo != null) { config.setZoneCount(deviceinfo.getDeviceZones()); } /** * The maximum volume is received from the telnet connection in the * form of the MVMAX property. It is not always received reliable however, * so we're using a default for now. */ config.setMainVolumeMax(DenonMarantzConfiguration.MAX_VOLUME); // if deviceinfo is null, something went wrong (and is logged in getDocument catch blocks) return (deviceinfo != null); } private void refreshHttpProperties() throws IOException { logger.trace("Refreshing Denon status"); updateMain(); updateMainZone(); updateSecondaryZones(); updateDisplayInfo(); } @Nullable private <T> T getDocument(String uri, Class<T> response) throws IOException { try { String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS); logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result); if (StringUtils.isNotBlank(result)) { JAXBContext jc = JAXBContext.newInstance(response); XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(result)); xsr = new PropertyRenamerDelegate(xsr); @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xsr); return obj; } } catch (UnmarshalException e) { logger.debug("Failed to unmarshal xml document: {}", e.getMessage()); } catch (JAXBException e) { logger.debug("Unexpected error occurred during unmarshalling of document: {}", e.getMessage()); } catch (XMLStreamException e) { logger.debug("Communication error: {}", e.getMessage()); } return null; } @Nullable private <T, S> T postDocument(String uri, Class<T> response, S request) throws IOException { try { JAXBContext jaxbContext = JAXBContext.newInstance(request.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); StringWriter sw = new StringWriter(); jaxbMarshaller.marshal(request, sw); ByteArrayInputStream inputStream = new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8)); String result = HttpUtil.executeUrl("POST", uri, inputStream, CONTENT_TYPE_XML, REQUEST_TIMEOUT_MS); if (StringUtils.isNotBlank(result)) { JAXBContext jcResponse = JAXBContext.newInstance(response); @SuppressWarnings("unchecked") T obj = (T) jcResponse.createUnmarshaller().unmarshal(IOUtils.toInputStream(result)); return obj; } } catch (JAXBException e) { logger.debug("Encoding error in post", e); } return null; } private static class PropertyRenamerDelegate extends StreamReaderDelegate { public PropertyRenamerDelegate(XMLStreamReader xsr) { super(xsr); } @Override public String getAttributeLocalName(int index) { return Introspector.decapitalize(super.getAttributeLocalName(index)); } @Override public String getLocalName() { return Introspector.decapitalize(super.getLocalName()); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_4
crossvul-java_data_bad_298_0
/* * Copyright 2008-2017 by Emeric Vernat * * This file is part of Java Melody. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bull.javamelody; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.regex.Pattern; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import net.bull.javamelody.internal.common.LOG; //20091201 dhartford GWTRequestWrapper //20100519 dhartford adjustments for UTF-8, however did not have an impact so removed. //20100520 dhartford adjustments for reader/inputstream. //20110206 evernat refactoring //20131111 roy.paterson SOAP request wrapper //20131111 evernat refactoring /** * Simple Wrapper class to inspect payload for name. * @author dhartford, roy.paterson, evernat */ public class PayloadNameRequestWrapper extends HttpServletRequestWrapper { private static final Pattern GWT_RPC_SEPARATOR_CHAR_PATTERN = Pattern .compile(Pattern.quote("|")); /** * Name of request, or null if we don't know based on payload @null */ private String name; /** * Type of request if name != null, or null if we don't know based on the payload @null */ private String requestType; private BufferedInputStream bufferedInputStream; private ServletInputStream inputStream; private BufferedReader reader; /** * Constructor. * @param request the original HttpServletRequest */ public PayloadNameRequestWrapper(HttpServletRequest request) { super(request); } protected void initialize() throws IOException { //name on a best-effort basis name = null; requestType = null; final HttpServletRequest request = (HttpServletRequest) getRequest(); final String contentType = request.getContentType(); if (contentType == null) { //don't know how to handle this content type return; } if (!"POST".equalsIgnoreCase(request.getMethod())) { //no payload return; } //Try look for name in payload on a best-effort basis... try { if (contentType.startsWith("text/x-gwt-rpc")) { //parse GWT-RPC method name name = parseGwtRpcMethodName(getBufferedInputStream(), getCharacterEncoding()); requestType = "GWT-RPC"; } else if (contentType.startsWith("application/soap+xml") //SOAP 1.2 || contentType.startsWith("text/xml") //SOAP 1.1 && request.getHeader("SOAPAction") != null) { //parse SOAP method name name = parseSoapMethodName(getBufferedInputStream(), getCharacterEncoding()); requestType = "SOAP"; } else { //don't know how to name this request based on payload //(don't parse if text/xml for XML-RPC, because it is obsolete) name = null; requestType = null; } } catch (final Exception e) { LOG.debug("Error trying to parse payload content for request name", e); //best-effort - couldn't figure it out name = null; requestType = null; } finally { //reset stream so application is unaffected resetBufferedInputStream(); } } protected BufferedInputStream getBufferedInputStream() throws IOException { if (bufferedInputStream == null) { //workaround Tomcat issue with form POSTs //see http://stackoverflow.com/questions/18489399/read-httpservletrequests-post-body-and-then-call-getparameter-in-tomcat final ServletRequest request = getRequest(); request.getParameterMap(); //buffer the payload so we can inspect it bufferedInputStream = new BufferedInputStream(request.getInputStream()); // and mark to allow the stream to be reset bufferedInputStream.mark(Integer.MAX_VALUE); } return bufferedInputStream; } protected void resetBufferedInputStream() throws IOException { if (bufferedInputStream != null) { bufferedInputStream.reset(); } } /** * Try to parse GWT-RPC method name from request body stream. Does not close the stream. * * @param stream GWT-RPC request body stream @nonnull * @param charEncoding character encoding of stream, or null for platform default @null * @return GWT-RPC method name, or null if unable to parse @null */ @SuppressWarnings("resource") private static String parseGwtRpcMethodName(InputStream stream, String charEncoding) { //commented out code uses GWT-user library for a more 'proper' approach. //GWT-user library approach is more future-proof, but requires more dependency management. // RPCRequest decodeRequest = RPC.decodeRequest(readLine); // gwtmethodname = decodeRequest.getMethod().getName(); try { final Scanner scanner; if (charEncoding == null) { scanner = new Scanner(stream); } else { scanner = new Scanner(stream, charEncoding); } scanner.useDelimiter(GWT_RPC_SEPARATOR_CHAR_PATTERN); //AbstractSerializationStream.RPC_SEPARATOR_CHAR //AbstractSerializationStreamReader.prepareToRead(...) scanner.next(); //stream version number scanner.next(); //flags //ServerSerializationStreamReader.deserializeStringTable() scanner.next(); //type name count //ServerSerializationStreamReader.preapreToRead(...) scanner.next(); //module base URL scanner.next(); //strong name //RPC.decodeRequest(...) scanner.next(); //service interface name return "." + scanner.next(); //service method name //note we don't close the scanner because we don't want to close the underlying stream } catch (final NoSuchElementException e) { LOG.debug("Unable to parse GWT-RPC request", e); //code above is best-effort - we were unable to parse GWT payload so //treat as a normal HTTP request return null; } } /** * Scan xml for tag child of the current element * * @param reader reader, must be at "start element" @nonnull * @param tagName name of child tag to find @nonnull * @return if found tag * @throws XMLStreamException on error */ static boolean scanForChildTag(XMLStreamReader reader, String tagName) throws XMLStreamException { assert reader.isStartElement(); int level = -1; while (reader.hasNext()) { //keep track of level so we only search children, not descendants if (reader.isStartElement()) { level++; } else if (reader.isEndElement()) { level--; } if (level < 0) { //end parent tag - no more children break; } reader.next(); if (level == 0 && reader.isStartElement() && reader.getLocalName().equals(tagName)) { return true; //found } } return false; //got to end of parent element and not found } /** * Try to parse SOAP method name from request body stream. Does not close the stream. * * @param stream SOAP request body stream @nonnull * @param charEncoding character encoding of stream, or null for platform default @null * @return SOAP method name, or null if unable to parse @null */ private static String parseSoapMethodName(InputStream stream, String charEncoding) { try { // newInstance() et pas newFactory() pour java 1.5 (issue 367) final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader xmlReader; if (charEncoding != null) { xmlReader = factory.createXMLStreamReader(stream, charEncoding); } else { xmlReader = factory.createXMLStreamReader(stream); } //best-effort parsing //start document, go to first tag xmlReader.nextTag(); //expect first tag to be "Envelope" if (!"Envelope".equals(xmlReader.getLocalName())) { LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName() + "' (expected 'Envelope')"); return null; //failed } //scan for body tag if (!scanForChildTag(xmlReader, "Body")) { LOG.debug("Unable to find SOAP 'Body' tag"); return null; //failed } xmlReader.nextTag(); //tag is method name return "." + xmlReader.getLocalName(); } catch (final XMLStreamException e) { LOG.debug("Unable to parse SOAP request", e); //failed return null; } } /** {@inheritDoc} */ @Override public BufferedReader getReader() throws IOException { if (bufferedInputStream == null) { return super.getReader(); } if (reader == null) { // use character encoding as said in the API final String characterEncoding = this.getCharacterEncoding(); if (characterEncoding == null) { reader = new BufferedReader(new InputStreamReader(this.getInputStream())); } else { reader = new BufferedReader( new InputStreamReader(this.getInputStream(), characterEncoding)); } } return reader; } /** {@inheritDoc} */ @Override public ServletInputStream getInputStream() throws IOException { final ServletInputStream requestInputStream = super.getInputStream(); if (bufferedInputStream == null) { return requestInputStream; } if (inputStream == null) { final BufferedInputStream myBufferedInputStream = bufferedInputStream; //CHECKSTYLE:OFF inputStream = new ServletInputStream() { //CHECKSTYLE:ON @Override public int read() throws IOException { return myBufferedInputStream.read(); } @Override public boolean isFinished() { return requestInputStream.isFinished(); } @Override public boolean isReady() { return requestInputStream.isReady(); } @Override public void setReadListener(ReadListener readListener) { requestInputStream.setReadListener(readListener); } }; } return inputStream; } /** * @return name of request, or null if we can't figure out a good name based on * the request payload @null */ public String getPayloadRequestName() { return name; } /** * Get type of request. If {@link #getPayloadRequestName()} returns non-null then * this method also returns non-null. * * @return type of request if or null if don't know @null */ public String getPayloadRequestType() { return requestType; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_298_0
crossvul-java_data_good_1910_17
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.onkyo.internal.handler; import static org.openhab.binding.onkyo.internal.OnkyoBindingConstants.*; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.smarthome.core.audio.AudioHTTPServer; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.NextPreviousType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.library.types.PlayPauseType; import org.eclipse.smarthome.core.library.types.RawType; import org.eclipse.smarthome.core.library.types.RewindFastforwardType; import org.eclipse.smarthome.core.library.types.StringType; import org.eclipse.smarthome.core.thing.Channel; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.binding.ThingHandlerService; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.StateOption; import org.eclipse.smarthome.core.types.UnDefType; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.eclipse.smarthome.io.transport.upnp.UpnpIOService; import org.openhab.binding.onkyo.internal.OnkyoAlbumArt; import org.openhab.binding.onkyo.internal.OnkyoConnection; import org.openhab.binding.onkyo.internal.OnkyoEventListener; import org.openhab.binding.onkyo.internal.OnkyoStateDescriptionProvider; import org.openhab.binding.onkyo.internal.ServiceType; import org.openhab.binding.onkyo.internal.automation.modules.OnkyoThingActionsService; import org.openhab.binding.onkyo.internal.config.OnkyoDeviceConfiguration; import org.openhab.binding.onkyo.internal.eiscp.EiscpCommand; import org.openhab.binding.onkyo.internal.eiscp.EiscpMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link OnkyoHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Paul Frank - Initial contribution * @author Marcel Verpaalen - parsing additional commands * @author Pauli Anttila - lot of refactoring * @author Stewart Cossey - add dynamic state description provider */ public class OnkyoHandler extends UpnpAudioSinkHandler implements OnkyoEventListener { private final Logger logger = LoggerFactory.getLogger(OnkyoHandler.class); private OnkyoDeviceConfiguration configuration; private OnkyoConnection connection; private ScheduledFuture<?> resourceUpdaterFuture; @SuppressWarnings("unused") private int currentInput = -1; private State volumeLevelZone1 = UnDefType.UNDEF; private State volumeLevelZone2 = UnDefType.UNDEF; private State volumeLevelZone3 = UnDefType.UNDEF; private State lastPowerState = OnOffType.OFF; private final OnkyoStateDescriptionProvider stateDescriptionProvider; private final OnkyoAlbumArt onkyoAlbumArt = new OnkyoAlbumArt(); private static final int NET_USB_ID = 43; public OnkyoHandler(Thing thing, UpnpIOService upnpIOService, AudioHTTPServer audioHTTPServer, String callbackUrl, OnkyoStateDescriptionProvider stateDescriptionProvider) { super(thing, upnpIOService, audioHTTPServer, callbackUrl); this.stateDescriptionProvider = stateDescriptionProvider; } /** * Initialize the state of the receiver. */ @Override public void initialize() { logger.debug("Initializing handler for Onkyo Receiver"); configuration = getConfigAs(OnkyoDeviceConfiguration.class); logger.info("Using configuration: {}", configuration.toString()); connection = new OnkyoConnection(configuration.ipAddress, configuration.port); connection.addEventListener(this); scheduler.execute(() -> { logger.debug("Open connection to Onkyo Receiver @{}", connection.getConnectionName()); connection.openConnection(); if (connection.isConnected()) { updateStatus(ThingStatus.ONLINE); sendCommand(EiscpCommand.INFO_QUERY); } }); if (configuration.refreshInterval > 0) { // Start resource refresh updater resourceUpdaterFuture = scheduler.scheduleWithFixedDelay(() -> { try { logger.debug("Send resource update requests to Onkyo Receiver @{}", connection.getConnectionName()); checkStatus(); } catch (LinkageError e) { logger.warn("Failed to send resource update requests to Onkyo Receiver @{}. Cause: {}", connection.getConnectionName(), e.getMessage()); } catch (Exception ex) { logger.warn("Exception in resource refresh Thread Onkyo Receiver @{}. Cause: {}", connection.getConnectionName(), ex.getMessage()); } }, configuration.refreshInterval, configuration.refreshInterval, TimeUnit.SECONDS); } } @Override public void dispose() { super.dispose(); if (resourceUpdaterFuture != null) { resourceUpdaterFuture.cancel(true); } if (connection != null) { connection.removeEventListener(this); connection.closeConnection(); } } @Override public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("handleCommand for channel {}: {}", channelUID.getId(), command.toString()); switch (channelUID.getId()) { /* * ZONE 1 */ case CHANNEL_POWER: if (command instanceof OnOffType) { sendCommand(EiscpCommand.POWER_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.POWER_QUERY); } break; case CHANNEL_MUTE: if (command instanceof OnOffType) { sendCommand(EiscpCommand.MUTE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.MUTE_QUERY); } break; case CHANNEL_VOLUME: handleVolumeSet(EiscpCommand.Zone.ZONE1, volumeLevelZone1, command); break; case CHANNEL_INPUT: if (command instanceof DecimalType) { selectInput(((DecimalType) command).intValue()); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.SOURCE_QUERY); } break; case CHANNEL_LISTENMODE: if (command instanceof DecimalType) { sendCommand(EiscpCommand.LISTEN_MODE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.LISTEN_MODE_QUERY); } break; /* * ZONE 2 */ case CHANNEL_POWERZONE2: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE2_POWER_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE2_POWER_QUERY); } break; case CHANNEL_MUTEZONE2: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE2_MUTE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE2_MUTE_QUERY); } break; case CHANNEL_VOLUMEZONE2: handleVolumeSet(EiscpCommand.Zone.ZONE2, volumeLevelZone2, command); break; case CHANNEL_INPUTZONE2: if (command instanceof DecimalType) { sendCommand(EiscpCommand.ZONE2_SOURCE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE2_SOURCE_QUERY); } break; /* * ZONE 3 */ case CHANNEL_POWERZONE3: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE3_POWER_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE3_POWER_QUERY); } break; case CHANNEL_MUTEZONE3: if (command instanceof OnOffType) { sendCommand(EiscpCommand.ZONE3_MUTE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE3_MUTE_QUERY); } break; case CHANNEL_VOLUMEZONE3: handleVolumeSet(EiscpCommand.Zone.ZONE3, volumeLevelZone3, command); break; case CHANNEL_INPUTZONE3: if (command instanceof DecimalType) { sendCommand(EiscpCommand.ZONE3_SOURCE_SET, command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.ZONE3_SOURCE_QUERY); } break; /* * NET PLAYER */ case CHANNEL_CONTROL: if (command instanceof PlayPauseType) { if (command.equals(PlayPauseType.PLAY)) { sendCommand(EiscpCommand.NETUSB_OP_PLAY); } else if (command.equals(PlayPauseType.PAUSE)) { sendCommand(EiscpCommand.NETUSB_OP_PAUSE); } } else if (command instanceof NextPreviousType) { if (command.equals(NextPreviousType.NEXT)) { sendCommand(EiscpCommand.NETUSB_OP_TRACKUP); } else if (command.equals(NextPreviousType.PREVIOUS)) { sendCommand(EiscpCommand.NETUSB_OP_TRACKDWN); } } else if (command instanceof RewindFastforwardType) { if (command.equals(RewindFastforwardType.REWIND)) { sendCommand(EiscpCommand.NETUSB_OP_REW); } else if (command.equals(RewindFastforwardType.FASTFORWARD)) { sendCommand(EiscpCommand.NETUSB_OP_FF); } } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_PLAY_STATUS_QUERY); } break; case CHANNEL_PLAY_URI: handlePlayUri(command); break; case CHANNEL_ALBUM_ART: case CHANNEL_ALBUM_ART_URL: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_ALBUM_ART_QUERY); } break; case CHANNEL_ARTIST: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_ARTIST_QUERY); } break; case CHANNEL_ALBUM: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_ALBUM_QUERY); } break; case CHANNEL_TITLE: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_TITLE_QUERY); } break; case CHANNEL_CURRENTPLAYINGTIME: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_SONG_ELAPSEDTIME_QUERY); } break; /* * NET MENU */ case CHANNEL_NET_MENU_CONTROL: if (command instanceof StringType) { final String cmdName = command.toString(); handleNetMenuCommand(cmdName); } break; case CHANNEL_NET_MENU_TITLE: if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.NETUSB_TITLE_QUERY); } break; /* * MISC */ default: logger.debug("Command received for an unknown channel: {}", channelUID.getId()); break; } } private void populateInputs(NodeList selectorlist) { List<StateOption> options = new ArrayList<>(); for (int i = 0; i < selectorlist.getLength(); i++) { Element selectorItem = (Element) selectorlist.item(i); options.add(new StateOption(String.valueOf(Integer.parseInt(selectorItem.getAttribute("id"), 16)), selectorItem.getAttribute("name"))); } logger.debug("Got Input List from Receiver {}", options); stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), options); stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_INPUTZONE2), options); stateDescriptionProvider.setStateOptions(new ChannelUID(getThing().getUID(), CHANNEL_INPUTZONE3), options); } private void doPowerOnCheck(State state) { if (configuration.refreshInterval == 0 && lastPowerState == OnOffType.OFF && state == OnOffType.ON) { sendCommand(EiscpCommand.INFO_QUERY); } lastPowerState = state; } @Override public void statusUpdateReceived(String ip, EiscpMessage data) { logger.debug("Received status update from Onkyo Receiver @{}: data={}", connection.getConnectionName(), data); updateStatus(ThingStatus.ONLINE); try { EiscpCommand receivedCommand = null; try { receivedCommand = EiscpCommand.getCommandByCommandAndValueStr(data.getCommand(), ""); } catch (IllegalArgumentException ex) { logger.debug("Received unknown status update from Onkyo Receiver @{}: data={}", connection.getConnectionName(), data); return; } logger.debug("Received command {}", receivedCommand); switch (receivedCommand) { /* * ZONE 1 */ case POWER: State powerState = convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class); updateState(CHANNEL_POWER, powerState); doPowerOnCheck(powerState); break; case MUTE: updateState(CHANNEL_MUTE, convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class)); break; case VOLUME: volumeLevelZone1 = handleReceivedVolume( convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); updateState(CHANNEL_VOLUME, volumeLevelZone1); break; case SOURCE: updateState(CHANNEL_INPUT, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; case LISTEN_MODE: updateState(CHANNEL_LISTENMODE, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; /* * ZONE 2 */ case ZONE2_POWER: State powerZone2State = convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class); updateState(CHANNEL_POWERZONE2, powerZone2State); doPowerOnCheck(powerZone2State); break; case ZONE2_MUTE: updateState(CHANNEL_MUTEZONE2, convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class)); break; case ZONE2_VOLUME: volumeLevelZone2 = handleReceivedVolume( convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); updateState(CHANNEL_VOLUMEZONE2, volumeLevelZone2); break; case ZONE2_SOURCE: updateState(CHANNEL_INPUTZONE2, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; /* * ZONE 3 */ case ZONE3_POWER: State powerZone3State = convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class); updateState(CHANNEL_POWERZONE3, powerZone3State); doPowerOnCheck(powerZone3State); break; case ZONE3_MUTE: updateState(CHANNEL_MUTEZONE3, convertDeviceValueToOpenHabState(data.getValue(), OnOffType.class)); break; case ZONE3_VOLUME: volumeLevelZone3 = handleReceivedVolume( convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); updateState(CHANNEL_VOLUMEZONE3, volumeLevelZone3); break; case ZONE3_SOURCE: updateState(CHANNEL_INPUTZONE3, convertDeviceValueToOpenHabState(data.getValue(), DecimalType.class)); break; /* * NET PLAYER */ case NETUSB_SONG_ARTIST: updateState(CHANNEL_ARTIST, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_SONG_ALBUM: updateState(CHANNEL_ALBUM, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_SONG_TITLE: updateState(CHANNEL_TITLE, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_SONG_ELAPSEDTIME: updateState(CHANNEL_CURRENTPLAYINGTIME, convertDeviceValueToOpenHabState(data.getValue(), StringType.class)); break; case NETUSB_PLAY_STATUS: updateState(CHANNEL_CONTROL, convertNetUsbPlayStatus(data.getValue())); break; case NETUSB_ALBUM_ART: updateAlbumArt(data.getValue()); break; case NETUSB_TITLE: updateNetTitle(data.getValue()); break; case NETUSB_MENU: updateNetMenu(data.getValue()); break; /* * MISC */ case INFO: processInfo(data.getValue()); logger.debug("Info message: '{}'", data.getValue()); break; default: logger.debug("Received unhandled status update from Onkyo Receiver @{}: data={}", connection.getConnectionName(), data); } } catch (Exception ex) { logger.warn("Exception in statusUpdateReceived for Onkyo Receiver @{}. Cause: {}, data received: {}", connection.getConnectionName(), ex.getMessage(), data); } } private void processInfo(String infoXML) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); try (StringReader sr = new StringReader(infoXML)) { InputSource is = new InputSource(sr); Document doc = builder.parse(is); NodeList selectableInputs = doc.getDocumentElement().getElementsByTagName("selector"); populateInputs(selectableInputs); } } catch (ParserConfigurationException | SAXException | IOException e) { logger.debug("Error occured during Info XML parsing.", e); } } @Override public void connectionError(String ip, String errorMsg) { logger.debug("Connection error occurred to Onkyo Receiver @{}", ip); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, errorMsg); } private State convertDeviceValueToOpenHabState(String data, Class<?> classToConvert) { State state = UnDefType.UNDEF; try { int index; if (data.contentEquals("N/A")) { state = UnDefType.UNDEF; } else if (classToConvert == OnOffType.class) { index = Integer.parseInt(data, 16); state = index == 0 ? OnOffType.OFF : OnOffType.ON; } else if (classToConvert == DecimalType.class) { index = Integer.parseInt(data, 16); state = new DecimalType(index); } else if (classToConvert == PercentType.class) { index = Integer.parseInt(data, 16); state = new PercentType(index); } else if (classToConvert == StringType.class) { state = new StringType(data); } } catch (Exception e) { logger.debug("Cannot convert value '{}' to data type {}", data, classToConvert); } logger.debug("Converted data '{}' to openHAB state '{}' ({})", data, state, classToConvert); return state; } private void handleNetMenuCommand(String cmdName) { if ("Up".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_UP); } else if ("Down".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_DOWN); } else if ("Select".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_SELECT); } else if ("PageUp".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_LEFT); } else if ("PageDown".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_RIGHT); } else if ("Back".equals(cmdName)) { sendCommand(EiscpCommand.NETUSB_OP_RETURN); } else if (cmdName.matches("Select[0-9]")) { int pos = Integer.parseInt(cmdName.substring(6)); sendCommand(EiscpCommand.NETUSB_MENU_SELECT, new DecimalType(pos)); } else { logger.debug("Received unknown menucommand {}", cmdName); } } private void selectInput(int inputId) { sendCommand(EiscpCommand.SOURCE_SET, new DecimalType(inputId)); currentInput = inputId; } @SuppressWarnings("unused") private void onInputChanged(int newInput) { currentInput = newInput; if (newInput != NET_USB_ID) { resetNetMenu(); updateState(CHANNEL_ARTIST, UnDefType.UNDEF); updateState(CHANNEL_ALBUM, UnDefType.UNDEF); updateState(CHANNEL_TITLE, UnDefType.UNDEF); updateState(CHANNEL_CURRENTPLAYINGTIME, UnDefType.UNDEF); } } private void updateAlbumArt(String data) { onkyoAlbumArt.addFrame(data); if (onkyoAlbumArt.isAlbumCoverReady()) { try { byte[] imgData = onkyoAlbumArt.getAlbumArt(); if (imgData != null && imgData.length > 0) { String mimeType = onkyoAlbumArt.getAlbumArtMimeType(); if (mimeType.isEmpty()) { mimeType = guessMimeTypeFromData(imgData); } updateState(CHANNEL_ALBUM_ART, new RawType(imgData, mimeType)); } else { updateState(CHANNEL_ALBUM_ART, UnDefType.UNDEF); } } catch (IllegalArgumentException e) { updateState(CHANNEL_ALBUM_ART, UnDefType.UNDEF); } onkyoAlbumArt.clearAlbumArt(); } if (data.startsWith("2-")) { updateState(CHANNEL_ALBUM_ART_URL, new StringType(data.substring(2, data.length()))); } else if (data.startsWith("n-")) { updateState(CHANNEL_ALBUM_ART_URL, UnDefType.UNDEF); } else { logger.debug("Not supported album art URL type: {}", data.substring(0, 2)); updateState(CHANNEL_ALBUM_ART_URL, UnDefType.UNDEF); } } private void updateNetTitle(String data) { // first 2 characters is service type int type = Integer.parseInt(data.substring(0, 2), 16); ServiceType service = ServiceType.getType(type); String title = ""; if (data.length() > 21) { title = data.substring(22, data.length()); } updateState(CHANNEL_NET_MENU_TITLE, new StringType(service.toString() + ((title.length() > 0) ? ": " + title : ""))); } private void updateNetMenu(String data) { switch (data.charAt(0)) { case 'U': String itemData = data.substring(3, data.length()); switch (data.charAt(1)) { case '0': updateState(CHANNEL_NET_MENU0, new StringType(itemData)); break; case '1': updateState(CHANNEL_NET_MENU1, new StringType(itemData)); break; case '2': updateState(CHANNEL_NET_MENU2, new StringType(itemData)); break; case '3': updateState(CHANNEL_NET_MENU3, new StringType(itemData)); break; case '4': updateState(CHANNEL_NET_MENU4, new StringType(itemData)); break; case '5': updateState(CHANNEL_NET_MENU5, new StringType(itemData)); break; case '6': updateState(CHANNEL_NET_MENU6, new StringType(itemData)); break; case '7': updateState(CHANNEL_NET_MENU7, new StringType(itemData)); break; case '8': updateState(CHANNEL_NET_MENU8, new StringType(itemData)); break; case '9': updateState(CHANNEL_NET_MENU9, new StringType(itemData)); break; } break; case 'C': updateMenuPosition(data); break; } } private void updateMenuPosition(String data) { char position = data.charAt(1); int pos = Character.getNumericValue(position); logger.debug("Updating menu position to {}", pos); if (pos == -1) { updateState(CHANNEL_NET_MENU_SELECTION, UnDefType.UNDEF); } else { updateState(CHANNEL_NET_MENU_SELECTION, new DecimalType(pos)); } if (data.endsWith("P")) { resetNetMenu(); } } private void resetNetMenu() { logger.debug("Reset net menu"); updateState(CHANNEL_NET_MENU0, new StringType("-")); updateState(CHANNEL_NET_MENU1, new StringType("-")); updateState(CHANNEL_NET_MENU2, new StringType("-")); updateState(CHANNEL_NET_MENU3, new StringType("-")); updateState(CHANNEL_NET_MENU4, new StringType("-")); updateState(CHANNEL_NET_MENU5, new StringType("-")); updateState(CHANNEL_NET_MENU6, new StringType("-")); updateState(CHANNEL_NET_MENU7, new StringType("-")); updateState(CHANNEL_NET_MENU8, new StringType("-")); updateState(CHANNEL_NET_MENU9, new StringType("-")); } private State convertNetUsbPlayStatus(String data) { State state = UnDefType.UNDEF; switch (data.charAt(0)) { case 'P': state = PlayPauseType.PLAY; break; case 'p': case 'S': state = PlayPauseType.PAUSE; break; case 'F': state = RewindFastforwardType.FASTFORWARD; break; case 'R': state = RewindFastforwardType.REWIND; break; } return state; } public void sendRawCommand(String command, String value) { if (connection != null) { connection.send(command, value); } else { logger.debug("Cannot send command to onkyo receiver since the onkyo binding is not initialized"); } } private void sendCommand(EiscpCommand deviceCommand) { if (connection != null) { connection.send(deviceCommand.getCommand(), deviceCommand.getValue()); } else { logger.debug("Connect send command to onkyo receiver since the onkyo binding is not initialized"); } } private void sendCommand(EiscpCommand deviceCommand, Command command) { if (connection != null) { final String cmd = deviceCommand.getCommand(); String valTemplate = deviceCommand.getValue(); String val; if (command instanceof OnOffType) { val = String.format(valTemplate, command == OnOffType.ON ? 1 : 0); } else if (command instanceof StringType) { val = String.format(valTemplate, command); } else if (command instanceof DecimalType) { val = String.format(valTemplate, ((DecimalType) command).intValue()); } else if (command instanceof PercentType) { val = String.format(valTemplate, ((DecimalType) command).intValue()); } else { val = valTemplate; } logger.debug("Sending command '{}' with value '{}' to Onkyo Receiver @{}", cmd, val, connection.getConnectionName()); connection.send(cmd, val); } else { logger.debug("Connect send command to onkyo receiver since the onkyo binding is not initialized"); } } /** * Check the status of the AVR. * * @return */ private void checkStatus() { sendCommand(EiscpCommand.POWER_QUERY); if (connection != null && connection.isConnected()) { sendCommand(EiscpCommand.VOLUME_QUERY); sendCommand(EiscpCommand.SOURCE_QUERY); sendCommand(EiscpCommand.MUTE_QUERY); sendCommand(EiscpCommand.NETUSB_TITLE_QUERY); sendCommand(EiscpCommand.LISTEN_MODE_QUERY); sendCommand(EiscpCommand.INFO_QUERY); if (isChannelAvailable(CHANNEL_POWERZONE2)) { sendCommand(EiscpCommand.ZONE2_POWER_QUERY); sendCommand(EiscpCommand.ZONE2_VOLUME_QUERY); sendCommand(EiscpCommand.ZONE2_SOURCE_QUERY); sendCommand(EiscpCommand.ZONE2_MUTE_QUERY); } if (isChannelAvailable(CHANNEL_POWERZONE3)) { sendCommand(EiscpCommand.ZONE3_POWER_QUERY); sendCommand(EiscpCommand.ZONE3_VOLUME_QUERY); sendCommand(EiscpCommand.ZONE3_SOURCE_QUERY); sendCommand(EiscpCommand.ZONE3_MUTE_QUERY); } } else { updateStatus(ThingStatus.OFFLINE); } } private boolean isChannelAvailable(String channel) { List<Channel> channels = getThing().getChannels(); for (Channel c : channels) { if (c.getUID().getId().equals(channel)) { return true; } } return false; } private void handleVolumeSet(EiscpCommand.Zone zone, final State currentValue, final Command command) { if (command instanceof PercentType) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_SET), downScaleVolume((PercentType) command)); } else if (command.equals(IncreaseDecreaseType.INCREASE)) { if (currentValue instanceof PercentType) { if (((DecimalType) currentValue).intValue() < configuration.volumeLimit) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_UP)); } else { logger.info("Volume level is limited to {}, ignore volume up command.", configuration.volumeLimit); } } } else if (command.equals(IncreaseDecreaseType.DECREASE)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_DOWN)); } else if (command.equals(OnOffType.OFF)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.MUTE_SET), command); } else if (command.equals(OnOffType.ON)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.MUTE_SET), command); } else if (command.equals(RefreshType.REFRESH)) { sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_QUERY)); sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.MUTE_QUERY)); } } private State handleReceivedVolume(State volume) { if (volume instanceof DecimalType) { return upScaleVolume(((DecimalType) volume)); } return volume; } private PercentType upScaleVolume(DecimalType volume) { PercentType newVolume = scaleVolumeFromReceiver(volume); if (configuration.volumeLimit < 100) { double scaleCoefficient = 100d / configuration.volumeLimit; PercentType unLimitedVolume = newVolume; newVolume = new PercentType(((Double) (newVolume.doubleValue() * scaleCoefficient)).intValue()); logger.debug("Up scaled volume level '{}' to '{}'", unLimitedVolume, newVolume); } return newVolume; } private DecimalType downScaleVolume(PercentType volume) { PercentType limitedVolume = volume; if (configuration.volumeLimit < 100) { double scaleCoefficient = configuration.volumeLimit / 100d; limitedVolume = new PercentType(((Double) (volume.doubleValue() * scaleCoefficient)).intValue()); logger.debug("Limited volume level '{}' to '{}'", volume, limitedVolume); } return scaleVolumeForReceiver(limitedVolume); } private DecimalType scaleVolumeForReceiver(PercentType volume) { return new DecimalType(((Double) (volume.doubleValue() * configuration.volumeScale)).intValue()); } private PercentType scaleVolumeFromReceiver(DecimalType volume) { return new PercentType(((Double) (volume.intValue() / configuration.volumeScale)).intValue()); } @Override public PercentType getVolume() throws IOException { if (volumeLevelZone1 instanceof PercentType) { return (PercentType) volumeLevelZone1; } throw new IOException(); } @Override public void setVolume(PercentType volume) throws IOException { handleVolumeSet(EiscpCommand.Zone.ZONE1, volumeLevelZone1, downScaleVolume(volume)); } private String guessMimeTypeFromData(byte[] data) { String mimeType = HttpUtil.guessContentTypeFromData(data); logger.debug("Mime type guess from content: {}", mimeType); if (mimeType == null) { mimeType = RawType.DEFAULT_MIME_TYPE; } logger.debug("Mime type: {}", mimeType); return mimeType; } @Override public Collection<Class<? extends ThingHandlerService>> getServices() { return Collections.singletonList(OnkyoThingActionsService.class); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_17
crossvul-java_data_bad_1910_10
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.gce.internal.model; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.openhab.binding.gce.internal.handler.Ipx800EventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * This class takes care of interpreting the status.xml file * * @author Gaël L'hopital - Initial contribution */ @NonNullByDefault public class StatusFileInterpreter { private static final String URL_TEMPLATE = "http://%s/globalstatus.xml"; private final Logger logger = LoggerFactory.getLogger(StatusFileInterpreter.class); private final String hostname; private @Nullable Document doc; private final Ipx800EventListener listener; public static enum StatusEntry { VERSION, CONFIG_MAC; } public StatusFileInterpreter(String hostname, Ipx800EventListener listener) { this.hostname = hostname; this.listener = listener; } public void read() { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); String statusPage = HttpUtil.executeUrl("GET", String.format(URL_TEMPLATE, hostname), 5000); InputStream inputStream = new ByteArrayInputStream(statusPage.getBytes()); Document document = builder.parse(inputStream); document.getDocumentElement().normalize(); doc = document; pushDatas(); inputStream.close(); } catch (IOException | SAXException | ParserConfigurationException e) { logger.warn("Unable to read IPX800 status page : {}", e.getMessage()); doc = null; } } private void pushDatas() { Element root = getRoot(); if (root != null) { PortDefinition.asStream().forEach(portDefinition -> { List<Node> xmlNodes = getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName()); xmlNodes.forEach(xmlNode -> { String sPortNum = xmlNode.getNodeName().replace(portDefinition.getNodeName(), ""); int portNum = Integer.parseInt(sPortNum) + 1; double value = Double.parseDouble(xmlNode.getTextContent().replace("dn", "1").replace("up", "0")); listener.dataReceived(String.format("%s%d", portDefinition.getPortName(), portNum), value); }); }); } } public String getElement(StatusEntry entry) { Element root = getRoot(); if (root != null) { return root.getElementsByTagName(entry.name().toLowerCase()).item(0).getTextContent(); } else { return ""; } } private List<Node> getMatchingNodes(NodeList nodeList, String criteria) { return IntStream.range(0, nodeList.getLength()).boxed().map(nodeList::item) .filter(node -> node.getNodeName().startsWith(criteria)) .sorted(Comparator.comparing(o -> o.getNodeName())).collect(Collectors.toList()); } public int getMaxNumberofNodeType(PortDefinition portDefinition) { Element root = getRoot(); if (root != null) { List<Node> filteredNodes = getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName()); return filteredNodes.size(); } return 0; } private @Nullable Element getRoot() { if (doc == null) { read(); } if (doc != null) { return doc.getDocumentElement(); } return null; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_10
crossvul-java_data_bad_1910_14
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.insteon.internal.device; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.insteon.internal.device.DeviceType.FeatureGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Reads the device types from an xml file. * * @author Daniel Pfrommer - Initial contribution * @author Bernd Pfrommer - openHAB 1 insteonplm binding * @author Rob Nielsen - Port to openHAB 2 insteon binding */ @NonNullByDefault @SuppressWarnings("null") public class DeviceTypeLoader { private static final Logger logger = LoggerFactory.getLogger(DeviceTypeLoader.class); private HashMap<String, DeviceType> deviceTypes = new HashMap<>(); private @Nullable static DeviceTypeLoader deviceTypeLoader = null; private DeviceTypeLoader() { } // private so nobody can call it /** * Finds the device type for a given product key * * @param aProdKey product key to search for * @return the device type, or null if not found */ public @Nullable DeviceType getDeviceType(String aProdKey) { return (deviceTypes.get(aProdKey)); } /** * Must call loadDeviceTypesXML() before calling this function! * * @return currently known device types */ public HashMap<String, DeviceType> getDeviceTypes() { return (deviceTypes); } /** * Reads the device types from input stream and stores them in memory for * later access. * * @param is the input stream from which to read */ public void loadDeviceTypesXML(InputStream in) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(in); doc.getDocumentElement().normalize(); Node root = doc.getDocumentElement(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("device")) { processDevice((Element) node); } } } /** * Reads the device types from file and stores them in memory for later access. * * @param aFileName The name of the file to read from * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public void loadDeviceTypesXML(String aFileName) throws ParserConfigurationException, SAXException, IOException { File file = new File(aFileName); InputStream in = new FileInputStream(file); loadDeviceTypesXML(in); } /** * Process device node * * @param e name of the element to process * @throws SAXException */ private void processDevice(Element e) throws SAXException { String productKey = e.getAttribute("productKey"); if (productKey.equals("")) { throw new SAXException("device in device_types file has no product key!"); } if (deviceTypes.containsKey(productKey)) { logger.warn("overwriting previous definition of device {}", productKey); deviceTypes.remove(productKey); } DeviceType devType = new DeviceType(productKey); NodeList nodes = e.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } Element subElement = (Element) node; if (subElement.getNodeName().equals("model")) { devType.setModel(subElement.getTextContent()); } else if (subElement.getNodeName().equals("description")) { devType.setDescription(subElement.getTextContent()); } else if (subElement.getNodeName().equals("feature")) { processFeature(devType, subElement); } else if (subElement.getNodeName().equals("feature_group")) { processFeatureGroup(devType, subElement); } deviceTypes.put(productKey, devType); } } private String processFeature(DeviceType devType, Element e) throws SAXException { String name = e.getAttribute("name"); if (name.equals("")) { throw new SAXException("feature " + e.getNodeName() + " has feature without name!"); } if (!name.equals(name.toLowerCase())) { throw new SAXException("feature name '" + name + "' must be lower case"); } if (!devType.addFeature(name, e.getTextContent())) { throw new SAXException("duplicate feature: " + name); } return (name); } private String processFeatureGroup(DeviceType devType, Element e) throws SAXException { String name = e.getAttribute("name"); if (name.equals("")) { throw new SAXException("feature group " + e.getNodeName() + " has no name attr!"); } String type = e.getAttribute("type"); if (type.equals("")) { throw new SAXException("feature group " + e.getNodeName() + " has no type attr!"); } FeatureGroup fg = new FeatureGroup(name, type); NodeList nodes = e.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } Element subElement = (Element) node; if (subElement.getNodeName().equals("feature")) { fg.addFeature(processFeature(devType, subElement)); } else if (subElement.getNodeName().equals("feature_group")) { fg.addFeature(processFeatureGroup(devType, subElement)); } } if (!devType.addFeatureGroup(name, fg)) { throw new SAXException("duplicate feature group " + name); } return (name); } /** * Helper function for debugging */ private void logDeviceTypes() { for (Entry<String, DeviceType> dt : getDeviceTypes().entrySet()) { String msg = String.format("%-10s->", dt.getKey()) + dt.getValue(); logger.debug("{}", msg); } } /** * Singleton instance function, creates DeviceTypeLoader * * @return DeviceTypeLoader singleton reference */ @Nullable public static synchronized DeviceTypeLoader instance() { if (deviceTypeLoader == null) { deviceTypeLoader = new DeviceTypeLoader(); InputStream input = DeviceTypeLoader.class.getResourceAsStream("/device_types.xml"); try { deviceTypeLoader.loadDeviceTypesXML(input); } catch (ParserConfigurationException e) { logger.warn("parser config error when reading device types xml file: ", e); } catch (SAXException e) { logger.warn("SAX exception when reading device types xml file: ", e); } catch (IOException e) { logger.warn("I/O exception when reading device types xml file: ", e); } logger.debug("loaded {} devices: ", deviceTypeLoader.getDeviceTypes().size()); deviceTypeLoader.logDeviceTypes(); } return deviceTypeLoader; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_14
crossvul-java_data_bad_1910_20
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.tellstick.internal.live; import java.math.BigDecimal; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.AsyncHttpClientConfig; import org.asynchttpclient.DefaultAsyncHttpClient; import org.asynchttpclient.DefaultAsyncHttpClientConfig; import org.asynchttpclient.DefaultAsyncHttpClientConfig.Builder; import org.asynchttpclient.Response; import org.asynchttpclient.oauth.ConsumerKey; import org.asynchttpclient.oauth.OAuthSignatureCalculator; import org.asynchttpclient.oauth.RequestToken; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.State; import org.openhab.binding.tellstick.internal.TelldusBindingException; import org.openhab.binding.tellstick.internal.handler.TelldusDeviceController; import org.openhab.binding.tellstick.internal.live.xml.TelldusLiveResponse; import org.openhab.binding.tellstick.internal.live.xml.TellstickNetDevice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tellstick.JNA; import org.tellstick.device.TellstickDevice; import org.tellstick.device.TellstickDeviceEvent; import org.tellstick.device.TellstickException; import org.tellstick.device.TellstickSensorEvent; import org.tellstick.device.iface.Device; import org.tellstick.device.iface.DeviceChangeListener; import org.tellstick.device.iface.SensorListener; import org.tellstick.device.iface.SwitchableDevice; /** * {@link TelldusLiveDeviceController} is the communication with Telldus Live service (Tellstick.NET and ZNET) * This controller uses XML based Rest API to communicate with Telldus Live. * * @author Jarle Hjortland - Initial contribution */ public class TelldusLiveDeviceController implements DeviceChangeListener, SensorListener, TelldusDeviceController { private final Logger logger = LoggerFactory.getLogger(TelldusLiveDeviceController.class); private long lastSend = 0; public static final long DEFAULT_INTERVAL_BETWEEN_SEND = 250; static final int REQUEST_TIMEOUT_MS = 5000; private AsyncHttpClient client; static final String HTTP_API_TELLDUS_COM_XML = "http://api.telldus.com/xml/"; static final String HTTP_TELLDUS_CLIENTS = HTTP_API_TELLDUS_COM_XML + "clients/list"; static final String HTTP_TELLDUS_DEVICES = HTTP_API_TELLDUS_COM_XML + "devices/list?supportedMethods=19"; static final String HTTP_TELLDUS_SENSORS = HTTP_API_TELLDUS_COM_XML + "sensors/list?includeValues=1&includeScale=1&includeUnit=1"; static final String HTTP_TELLDUS_SENSOR_INFO = HTTP_API_TELLDUS_COM_XML + "sensor/info"; static final String HTTP_TELLDUS_DEVICE_DIM = HTTP_API_TELLDUS_COM_XML + "device/dim?id=%d&level=%d"; static final String HTTP_TELLDUS_DEVICE_TURNOFF = HTTP_API_TELLDUS_COM_XML + "device/turnOff?id=%d"; static final String HTTP_TELLDUS_DEVICE_TURNON = HTTP_API_TELLDUS_COM_XML + "device/turnOn?id=%d"; private static final int MAX_RETRIES = 3; public TelldusLiveDeviceController() { } @Override public void dispose() { try { client.close(); } catch (Exception e) { logger.error("Failed to close client", e); } } void connectHttpClient(String publicKey, String privateKey, String token, String tokenSecret) { ConsumerKey consumer = new ConsumerKey(publicKey, privateKey); RequestToken user = new RequestToken(token, tokenSecret); OAuthSignatureCalculator calc = new OAuthSignatureCalculator(consumer, user); this.client = new DefaultAsyncHttpClient(createAsyncHttpClientConfig()); try { this.client.setSignatureCalculator(calc); Response response = client.prepareGet(HTTP_TELLDUS_CLIENTS).execute().get(); logger.debug("Response {} statusText {}", response.getResponseBody(), response.getStatusText()); } catch (InterruptedException | ExecutionException e) { logger.error("Failed to connect", e); } } private AsyncHttpClientConfig createAsyncHttpClientConfig() { Builder builder = new DefaultAsyncHttpClientConfig.Builder(); builder.setConnectTimeout(REQUEST_TIMEOUT_MS); return builder.build(); } @Override public void handleSendEvent(Device device, int resendCount, boolean isdimmer, Command command) throws TellstickException { logger.info("Send {} to {}", command, device); if (device instanceof TellstickNetDevice) { if (command == OnOffType.ON) { turnOn(device); } else if (command == OnOffType.OFF) { turnOff(device); } else if (command instanceof PercentType) { dim(device, (PercentType) command); } else if (command instanceof IncreaseDecreaseType) { increaseDecrease(device, ((IncreaseDecreaseType) command)); } } else if (device instanceof SwitchableDevice) { if (command == OnOffType.ON) { if (isdimmer) { logger.debug("Turn off first in case it is allready on"); turnOff(device); } turnOn(device); } else if (command == OnOffType.OFF) { turnOff(device); } } else { logger.warn("Cannot send to {}", device); } } private void increaseDecrease(Device dev, IncreaseDecreaseType increaseDecreaseType) throws TellstickException { String strValue = ((TellstickDevice) dev).getData(); double value = 0; if (strValue != null) { value = Double.valueOf(strValue); } int percent = (int) Math.round((value / 255) * 100); if (IncreaseDecreaseType.INCREASE == increaseDecreaseType) { percent = Math.min(percent + 10, 100); } else if (IncreaseDecreaseType.DECREASE == increaseDecreaseType) { percent = Math.max(percent - 10, 0); } dim(dev, new PercentType(percent)); } private void dim(Device dev, PercentType command) throws TellstickException { double value = command.doubleValue(); // 0 means OFF and 100 means ON if (value == 0 && dev instanceof TellstickNetDevice) { turnOff(dev); } else if (value == 100 && dev instanceof TellstickNetDevice) { turnOn(dev); } else if (dev instanceof TellstickNetDevice && (((TellstickNetDevice) dev).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) { long tdVal = Math.round((value / 100) * 255); TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_DIM, dev.getId(), tdVal), TelldusLiveResponse.class); handleResponse((TellstickNetDevice) dev, response); } else { throw new TelldusBindingException("Cannot send DIM to " + dev); } } private void turnOff(Device dev) throws TellstickException { if (dev instanceof TellstickNetDevice) { TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNOFF, dev.getId()), TelldusLiveResponse.class); handleResponse((TellstickNetDevice) dev, response); } else { throw new TelldusBindingException("Cannot send OFF to " + dev); } } private void handleResponse(TellstickNetDevice device, TelldusLiveResponse response) throws TellstickException { if (response == null || (response.status == null && response.error == null)) { throw new TelldusBindingException("No response " + response); } else if (response.error != null) { if (response.error.equals("The client for this device is currently offline")) { device.setOnline(false); device.setUpdated(true); } throw new TelldusBindingException("Error " + response.error); } else if (!response.status.trim().equals("success")) { throw new TelldusBindingException("Response " + response.status); } } private void turnOn(Device dev) throws TellstickException { if (dev instanceof TellstickNetDevice) { TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNON, dev.getId()), TelldusLiveResponse.class); handleResponse((TellstickNetDevice) dev, response); } else { throw new TelldusBindingException("Cannot send ON to " + dev); } } @Override public State calcState(Device dev) { TellstickNetDevice device = (TellstickNetDevice) dev; State st = null; if (device.getOnline()) { switch (device.getState()) { case JNA.CLibrary.TELLSTICK_TURNON: st = OnOffType.ON; break; case JNA.CLibrary.TELLSTICK_TURNOFF: st = OnOffType.OFF; break; case JNA.CLibrary.TELLSTICK_DIM: BigDecimal dimValue = new BigDecimal(device.getStatevalue()); if (dimValue.intValue() == 0) { st = OnOffType.OFF; } else if (dimValue.intValue() >= 255) { st = OnOffType.ON; } else { st = OnOffType.ON; } break; default: logger.warn("Could not handle {} for {}", device.getState(), device); } } return st; } @Override public BigDecimal calcDimValue(Device device) { BigDecimal dimValue = new BigDecimal(0); switch (((TellstickNetDevice) device).getState()) { case JNA.CLibrary.TELLSTICK_TURNON: dimValue = new BigDecimal(100); break; case JNA.CLibrary.TELLSTICK_TURNOFF: break; case JNA.CLibrary.TELLSTICK_DIM: dimValue = new BigDecimal(((TellstickNetDevice) device).getStatevalue()); dimValue = dimValue.multiply(new BigDecimal(100)); dimValue = dimValue.divide(new BigDecimal(255), 0, BigDecimal.ROUND_HALF_UP); break; default: logger.warn("Could not handle {} for {}", (((TellstickNetDevice) device).getState()), device); } return dimValue; } public long getLastSend() { return lastSend; } public void setLastSend(long currentTimeMillis) { lastSend = currentTimeMillis; } @Override public void onRequest(TellstickSensorEvent newDevices) { setLastSend(newDevices.getTimestamp()); } @Override public void onRequest(TellstickDeviceEvent newDevices) { setLastSend(newDevices.getTimestamp()); } <T> T callRestMethod(String uri, Class<T> response) throws TelldusLiveException { T resultObj = null; try { for (int i = 0; i < MAX_RETRIES; i++) { try { resultObj = innerCallRest(uri, response); break; } catch (TimeoutException e) { logger.warn("TimeoutException error in get", e); } catch (InterruptedException e) { logger.warn("InterruptedException error in get", e); } } } catch (JAXBException e) { logger.warn("Encoding error in get", e); logResponse(uri, e); throw new TelldusLiveException(e); } catch (XMLStreamException e) { logger.warn("Communication error in get", e); logResponse(uri, e); throw new TelldusLiveException(e); } catch (ExecutionException e) { logger.warn("ExecutionException error in get", e); throw new TelldusLiveException(e); } return resultObj; } private <T> T innerCallRest(String uri, Class<T> response) throws InterruptedException, ExecutionException, TimeoutException, JAXBException, FactoryConfigurationError, XMLStreamException { Future<Response> future = client.prepareGet(uri).execute(); Response resp = future.get(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS); // TelldusLiveHandler.logger.info("Devices" + resp.getResponseBody()); JAXBContext jc = JAXBContext.newInstance(response); XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(resp.getResponseBodyAsStream()); // xsr = new PropertyRenamerDelegate(xsr); @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xsr); if (logger.isTraceEnabled()) { logger.trace("Request [{}] Response:{}", uri, resp.getResponseBody()); } return obj; } private void logResponse(String uri, Exception e) { if (e != null) { logger.warn("Request [{}] Failure:{}", uri, e.getMessage()); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_20
crossvul-java_data_bad_4175_0
package org.mapfish.print.map.style; import org.geotools.factory.CommonFactoryFinder; import org.geotools.styling.DefaultResourceLocator; import org.geotools.styling.Style; import org.geotools.xml.styling.SLDParser; import org.locationtech.jts.util.Assert; import org.mapfish.print.Constants; import org.mapfish.print.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Optional; import java.util.function.Function; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Basic implementation for loading and parsing an SLD style. */ public class SLDParserPlugin implements StyleParserPlugin { /** * The separator between the path or url segment for loading the sld and an index of the style to obtain. * <p> * SLDs can contains multiple styles. Because of this there needs to be a way to indicate which style is * referred to. That is the purpose of the style index. */ public static final String STYLE_INDEX_REF_SEPARATOR = "##"; @Override public final Optional<Style> parseStyle( @Nullable final Configuration configuration, @Nonnull final ClientHttpRequestFactory clientHttpRequestFactory, @Nonnull final String styleString) { // try to load xml final Optional<Style> styleOptional = tryLoadSLD( styleString.getBytes(Constants.DEFAULT_CHARSET), null, clientHttpRequestFactory); if (styleOptional.isPresent()) { return styleOptional; } final Integer styleIndex = lookupStyleIndex(styleString).orElse(null); final String styleStringWithoutIndexReference = removeIndexReference(styleString); Function<byte[], Optional<Style>> loadFunction = input -> tryLoadSLD(input, styleIndex, clientHttpRequestFactory); return ParserPluginUtils.loadStyleAsURI(clientHttpRequestFactory, styleStringWithoutIndexReference, loadFunction); } private String removeIndexReference(final String styleString) { int styleIdentifier = styleString.lastIndexOf(STYLE_INDEX_REF_SEPARATOR); if (styleIdentifier > 0) { return styleString.substring(0, styleIdentifier); } return styleString; } private Optional<Integer> lookupStyleIndex(final String ref) { int styleIdentifier = ref.lastIndexOf(STYLE_INDEX_REF_SEPARATOR); if (styleIdentifier > 0) { return Optional.of(Integer.parseInt(ref.substring(styleIdentifier + 2)) - 1); } return Optional.empty(); } private Optional<Style> tryLoadSLD( final byte[] bytes, final Integer styleIndex, final ClientHttpRequestFactory clientHttpRequestFactory) { Assert.isTrue(styleIndex == null || styleIndex > -1, "styleIndex must be > -1 but was: " + styleIndex); final Style[] styles; try { // check if the XML is valid // this is only done in a separate step to avoid that fatal errors show up in the logs // by setting a custom error handler. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler()); db.parse(new ByteArrayInputStream(bytes)); // then read the styles final SLDParser sldParser = new SLDParser(CommonFactoryFinder.getStyleFactory()); sldParser.setOnLineResourceLocator(new DefaultResourceLocator() { @Override public URL locateResource(final String uri) { try { final URL theUrl = super.locateResource(uri); final URI theUri; if (theUrl != null) { theUri = theUrl.toURI(); } else { theUri = URI.create(uri); } if (theUri.getScheme().startsWith("http")) { final ClientHttpRequest request = clientHttpRequestFactory.createRequest( theUri, HttpMethod.GET); return request.getURI().toURL(); } return null; } catch (IOException | URISyntaxException e) { return null; } } }); sldParser.setInput(new ByteArrayInputStream(bytes)); styles = sldParser.readXML(); } catch (Throwable e) { return Optional.empty(); } if (styleIndex != null) { Assert.isTrue(styleIndex < styles.length, String.format("There where %s styles in file but " + "requested index was: %s", styles.length, styleIndex + 1)); } else { Assert.isTrue(styles.length < 2, String.format("There are %s therefore the styleRef must " + "contain an index identifying the style." + " The index starts at 1 for the first " + "style.\n" + "\tExample: thinline.sld##1", styles.length)); } if (styleIndex == null) { return Optional.of(styles[0]); } else { return Optional.of(styles[styleIndex]); } } /** * A default error handler to avoid that error messages like "[Fatal Error] :1:1: Content is not allowed * in prolog." are directly printed to STDERR. */ public static class ErrorHandler extends DefaultHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ErrorHandler.class); /** * @param e Exception */ public final void error(final SAXParseException e) throws SAXException { LOGGER.debug("XML error: {}", e.getLocalizedMessage()); super.error(e); } /** * @param e Exception */ public final void fatalError(final SAXParseException e) throws SAXException { LOGGER.debug("XML fatal error: {}", e.getLocalizedMessage()); super.fatalError(e); } /** * @param e Exception */ public final void warning(final SAXParseException e) { //ignore } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4175_0
crossvul-java_data_good_298_0
/* * Copyright 2008-2017 by Emeric Vernat * * This file is part of Java Melody. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bull.javamelody; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.regex.Pattern; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import net.bull.javamelody.internal.common.LOG; //20091201 dhartford GWTRequestWrapper //20100519 dhartford adjustments for UTF-8, however did not have an impact so removed. //20100520 dhartford adjustments for reader/inputstream. //20110206 evernat refactoring //20131111 roy.paterson SOAP request wrapper //20131111 evernat refactoring /** * Simple Wrapper class to inspect payload for name. * @author dhartford, roy.paterson, evernat */ public class PayloadNameRequestWrapper extends HttpServletRequestWrapper { private static final Pattern GWT_RPC_SEPARATOR_CHAR_PATTERN = Pattern .compile(Pattern.quote("|")); /** * Name of request, or null if we don't know based on payload @null */ private String name; /** * Type of request if name != null, or null if we don't know based on the payload @null */ private String requestType; private BufferedInputStream bufferedInputStream; private ServletInputStream inputStream; private BufferedReader reader; /** * Constructor. * @param request the original HttpServletRequest */ public PayloadNameRequestWrapper(HttpServletRequest request) { super(request); } protected void initialize() throws IOException { //name on a best-effort basis name = null; requestType = null; final HttpServletRequest request = (HttpServletRequest) getRequest(); final String contentType = request.getContentType(); if (contentType == null) { //don't know how to handle this content type return; } if (!"POST".equalsIgnoreCase(request.getMethod())) { //no payload return; } //Try look for name in payload on a best-effort basis... try { if (contentType.startsWith("text/x-gwt-rpc")) { //parse GWT-RPC method name name = parseGwtRpcMethodName(getBufferedInputStream(), getCharacterEncoding()); requestType = "GWT-RPC"; } else if (contentType.startsWith("application/soap+xml") //SOAP 1.2 || contentType.startsWith("text/xml") //SOAP 1.1 && request.getHeader("SOAPAction") != null) { //parse SOAP method name name = parseSoapMethodName(getBufferedInputStream(), getCharacterEncoding()); requestType = "SOAP"; } else { //don't know how to name this request based on payload //(don't parse if text/xml for XML-RPC, because it is obsolete) name = null; requestType = null; } } catch (final Exception e) { LOG.debug("Error trying to parse payload content for request name", e); //best-effort - couldn't figure it out name = null; requestType = null; } finally { //reset stream so application is unaffected resetBufferedInputStream(); } } protected BufferedInputStream getBufferedInputStream() throws IOException { if (bufferedInputStream == null) { //workaround Tomcat issue with form POSTs //see http://stackoverflow.com/questions/18489399/read-httpservletrequests-post-body-and-then-call-getparameter-in-tomcat final ServletRequest request = getRequest(); request.getParameterMap(); //buffer the payload so we can inspect it bufferedInputStream = new BufferedInputStream(request.getInputStream()); // and mark to allow the stream to be reset bufferedInputStream.mark(Integer.MAX_VALUE); } return bufferedInputStream; } protected void resetBufferedInputStream() throws IOException { if (bufferedInputStream != null) { bufferedInputStream.reset(); } } /** * Try to parse GWT-RPC method name from request body stream. Does not close the stream. * * @param stream GWT-RPC request body stream @nonnull * @param charEncoding character encoding of stream, or null for platform default @null * @return GWT-RPC method name, or null if unable to parse @null */ @SuppressWarnings("resource") private static String parseGwtRpcMethodName(InputStream stream, String charEncoding) { //commented out code uses GWT-user library for a more 'proper' approach. //GWT-user library approach is more future-proof, but requires more dependency management. // RPCRequest decodeRequest = RPC.decodeRequest(readLine); // gwtmethodname = decodeRequest.getMethod().getName(); try { final Scanner scanner; if (charEncoding == null) { scanner = new Scanner(stream); } else { scanner = new Scanner(stream, charEncoding); } scanner.useDelimiter(GWT_RPC_SEPARATOR_CHAR_PATTERN); //AbstractSerializationStream.RPC_SEPARATOR_CHAR //AbstractSerializationStreamReader.prepareToRead(...) scanner.next(); //stream version number scanner.next(); //flags //ServerSerializationStreamReader.deserializeStringTable() scanner.next(); //type name count //ServerSerializationStreamReader.preapreToRead(...) scanner.next(); //module base URL scanner.next(); //strong name //RPC.decodeRequest(...) scanner.next(); //service interface name return "." + scanner.next(); //service method name //note we don't close the scanner because we don't want to close the underlying stream } catch (final NoSuchElementException e) { LOG.debug("Unable to parse GWT-RPC request", e); //code above is best-effort - we were unable to parse GWT payload so //treat as a normal HTTP request return null; } } /** * Scan xml for tag child of the current element * * @param reader reader, must be at "start element" @nonnull * @param tagName name of child tag to find @nonnull * @return if found tag * @throws XMLStreamException on error */ static boolean scanForChildTag(XMLStreamReader reader, String tagName) throws XMLStreamException { assert reader.isStartElement(); int level = -1; while (reader.hasNext()) { //keep track of level so we only search children, not descendants if (reader.isStartElement()) { level++; } else if (reader.isEndElement()) { level--; } if (level < 0) { //end parent tag - no more children break; } reader.next(); if (level == 0 && reader.isStartElement() && reader.getLocalName().equals(tagName)) { return true; //found } } return false; //got to end of parent element and not found } /** * Try to parse SOAP method name from request body stream. Does not close the stream. * * @param stream SOAP request body stream @nonnull * @param charEncoding character encoding of stream, or null for platform default @null * @return SOAP method name, or null if unable to parse @null */ private static String parseSoapMethodName(InputStream stream, String charEncoding) { try { // newInstance() et pas newFactory() pour java 1.5 (issue 367) final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // disable DTDs entirely for that factory factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); // disable external entities final XMLStreamReader xmlReader; if (charEncoding != null) { xmlReader = factory.createXMLStreamReader(stream, charEncoding); } else { xmlReader = factory.createXMLStreamReader(stream); } //best-effort parsing //start document, go to first tag xmlReader.nextTag(); //expect first tag to be "Envelope" if (!"Envelope".equals(xmlReader.getLocalName())) { LOG.debug("Unexpected first tag of SOAP request: '" + xmlReader.getLocalName() + "' (expected 'Envelope')"); return null; //failed } //scan for body tag if (!scanForChildTag(xmlReader, "Body")) { LOG.debug("Unable to find SOAP 'Body' tag"); return null; //failed } xmlReader.nextTag(); //tag is method name return "." + xmlReader.getLocalName(); } catch (final XMLStreamException e) { LOG.debug("Unable to parse SOAP request", e); //failed return null; } } /** {@inheritDoc} */ @Override public BufferedReader getReader() throws IOException { if (bufferedInputStream == null) { return super.getReader(); } if (reader == null) { // use character encoding as said in the API final String characterEncoding = this.getCharacterEncoding(); if (characterEncoding == null) { reader = new BufferedReader(new InputStreamReader(this.getInputStream())); } else { reader = new BufferedReader( new InputStreamReader(this.getInputStream(), characterEncoding)); } } return reader; } /** {@inheritDoc} */ @Override public ServletInputStream getInputStream() throws IOException { final ServletInputStream requestInputStream = super.getInputStream(); if (bufferedInputStream == null) { return requestInputStream; } if (inputStream == null) { final BufferedInputStream myBufferedInputStream = bufferedInputStream; //CHECKSTYLE:OFF inputStream = new ServletInputStream() { //CHECKSTYLE:ON @Override public int read() throws IOException { return myBufferedInputStream.read(); } @Override public boolean isFinished() { return requestInputStream.isFinished(); } @Override public boolean isReady() { return requestInputStream.isReady(); } @Override public void setReadListener(ReadListener readListener) { requestInputStream.setReadListener(readListener); } }; } return inputStream; } /** * @return name of request, or null if we can't figure out a good name based on * the request payload @null */ public String getPayloadRequestName() { return name; } /** * Get type of request. If {@link #getPayloadRequestName()} returns non-null then * this method also returns non-null. * * @return type of request if or null if don't know @null */ public String getPayloadRequestType() { return requestType; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_298_0
crossvul-java_data_bad_2449_10
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.platformlambda.services; import org.platformlambda.core.exception.AppException; import org.platformlambda.core.models.EventEnvelope; import org.platformlambda.core.models.LambdaFunction; import org.platformlambda.core.system.Platform; import org.platformlambda.models.ObjectWithGenericType; import org.platformlambda.models.SamplePoJo; import java.io.IOException; import java.util.Date; import java.util.Map; public class HelloGeneric implements LambdaFunction { @Override public Object handleEvent(Map<String, String> headers, Object body, int instance) throws AppException, IOException { String id = headers.get("id"); if (id == null) { throw new IllegalArgumentException("Missing parameter 'id'"); } if (id.equals("1")) { // to set status, key-values or parametric types, we can use EventEnvelope as a result wrapper EventEnvelope result = new EventEnvelope(); ObjectWithGenericType<SamplePoJo> genericObject = new ObjectWithGenericType<>(); // return some place-holder values to demonstrate the PoJo can be transported over the network SamplePoJo mock = new SamplePoJo(1, "Class with generic type resolved at run-time to be SamplePoJo", "200 World Blvd, Planet Earth"); // set current timestamp to indicate that the object is a new one mock.setDate(new Date()); // set instance count and service origin ID to show that the object comes from a different instance mock.setInstance(instance); mock.setOrigin(Platform.getInstance().getOrigin()); genericObject.setId(101); genericObject.setContent(mock); result.setBody(genericObject); result.setParametricType(SamplePoJo.class); return result; } else { throw new AppException(404, "Not found. Try id = 1"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_2449_10
crossvul-java_data_bad_1910_2
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.avmfritz.internal.util; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.avmfritz.internal.dto.DeviceListModel; import org.openhab.binding.avmfritz.internal.dto.templates.TemplateListModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation for a static use of JAXBContext as singleton instance. * * @author Christoph Weitkamp - Initial contribution */ @NonNullByDefault public class JAXBUtils { private static final Logger LOGGER = LoggerFactory.getLogger(JAXBUtils.class); public static final @Nullable JAXBContext JAXBCONTEXT_DEVICES = initJAXBContextDevices(); public static final @Nullable JAXBContext JAXBCONTEXT_TEMPLATES = initJAXBContextTemplates(); private static @Nullable JAXBContext initJAXBContextDevices() { try { return JAXBContext.newInstance(DeviceListModel.class); } catch (JAXBException e) { LOGGER.error("Exception creating JAXBContext for devices: {}", e.getLocalizedMessage(), e); return null; } } private static @Nullable JAXBContext initJAXBContextTemplates() { try { return JAXBContext.newInstance(TemplateListModel.class); } catch (JAXBException e) { LOGGER.error("Exception creating JAXBContext for templates: {}", e.getLocalizedMessage(), e); return null; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_2
crossvul-java_data_good_1577_0
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.selector.filter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.StringReader; import org.apache.xpath.CachedXPathAPI; import org.apache.xpath.objects.XObject; import org.w3c.dom.Document; import org.w3c.dom.traversal.NodeIterator; import org.xml.sax.InputSource; public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { private final String xpath; public XalanXPathEvaluator(String xpath) { this.xpath = xpath; } public boolean evaluate(Filterable m) throws FilterException { String stringBody = m.getBodyAs(String.class); if (stringBody != null) { return evaluate(stringBody); } return false; } protected boolean evaluate(String text) { return evaluate(new InputSource(new StringReader(text))); } protected boolean evaluate(InputSource inputSource) { try { DocumentBuilder dbuilder = createDocumentBuilder(); Document doc = dbuilder.parse(inputSource); //An XPath expression could return a true or false value instead of a node. //eval() is a better way to determine the boolean value of the exp. //For compliance with legacy behavior where selecting an empty node returns true, //selectNodeIterator is attempted in case of a failure. CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); XObject result = cachedXPathAPI.eval(doc, xpath); if (result.bool()) return true; else { NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); return (iterator.nextNode() != null); } } catch (Throwable e) { return false; } } private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); return factory.newDocumentBuilder(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1577_0
crossvul-java_data_bad_4033_2
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.ds.common; import org.postgresql.PGProperty; import org.postgresql.jdbc.AutoSave; import org.postgresql.jdbc.PreferQueryMode; import org.postgresql.util.ExpressionProperties; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.util.URLCoder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Arrays; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.NamingException; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; import javax.sql.CommonDataSource; /** * Base class for data sources and related classes. * * @author Aaron Mulder (ammulder@chariotsolutions.com) */ public abstract class BaseDataSource implements CommonDataSource, Referenceable { private static final Logger LOGGER = Logger.getLogger(BaseDataSource.class.getName()); // Standard properties, defined in the JDBC 2.0 Optional Package spec private String[] serverNames = new String[] {"localhost"}; private String databaseName = ""; private String user; private String password; private int[] portNumbers = new int[] {0}; // Map for all other properties private Properties properties = new Properties(); /* * Ensure the driver is loaded as JDBC Driver might be invisible to Java's ServiceLoader. * Usually, {@code Class.forName(...)} is not required as {@link DriverManager} detects JDBC drivers * via {@code META-INF/services/java.sql.Driver} entries. However there might be cases when the driver * is located at the application level classloader, thus it might be required to perform manual * registration of the driver. */ static { try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { throw new IllegalStateException( "BaseDataSource is unable to load org.postgresql.Driver. Please check if you have proper PostgreSQL JDBC Driver jar on the classpath", e); } } /** * Gets a connection to the PostgreSQL database. The database is identified by the DataSource * properties serverName, databaseName, and portNumber. The user to connect as is identified by * the DataSource properties user and password. * * @return A valid database connection. * @throws SQLException Occurs when the database connection cannot be established. */ public Connection getConnection() throws SQLException { return getConnection(user, password); } /** * Gets a connection to the PostgreSQL database. The database is identified by the DataSource * properties serverName, databaseName, and portNumber. The user to connect as is identified by * the arguments user and password, which override the DataSource properties by the same name. * * @param user user * @param password password * @return A valid database connection. * @throws SQLException Occurs when the database connection cannot be established. */ public Connection getConnection(String user, String password) throws SQLException { try { Connection con = DriverManager.getConnection(getUrl(), user, password); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Created a {0} for {1} at {2}", new Object[] {getDescription(), user, getUrl()}); } return con; } catch (SQLException e) { LOGGER.log(Level.FINE, "Failed to create a {0} for {1} at {2}: {3}", new Object[] {getDescription(), user, getUrl(), e}); throw e; } } /** * This implementation don't use a LogWriter. */ @Override public PrintWriter getLogWriter() { return null; } /** * This implementation don't use a LogWriter. * * @param printWriter Not used */ @Override public void setLogWriter(PrintWriter printWriter) { // NOOP } /** * Gets the name of the host the PostgreSQL database is running on. * * @return name of the host the PostgreSQL database is running on * @deprecated use {@link #getServerNames()} */ @Deprecated public String getServerName() { return serverNames[0]; } /** * Gets the name of the host(s) the PostgreSQL database is running on. * * @return name of the host(s) the PostgreSQL database is running on */ public String[] getServerNames() { return serverNames; } /** * Sets the name of the host the PostgreSQL database is running on. If this is changed, it will * only affect future calls to getConnection. The default value is {@code localhost}. * * @param serverName name of the host the PostgreSQL database is running on * @deprecated use {@link #setServerNames(String[])} */ @Deprecated public void setServerName(String serverName) { this.setServerNames(new String[] { serverName }); } /** * Sets the name of the host(s) the PostgreSQL database is running on. If this is changed, it will * only affect future calls to getConnection. The default value is {@code localhost}. * * @param serverNames name of the host(s) the PostgreSQL database is running on */ public void setServerNames(String[] serverNames) { if (serverNames == null || serverNames.length == 0) { this.serverNames = new String[] {"localhost"}; } else { serverNames = Arrays.copyOf(serverNames, serverNames.length); for (int i = 0; i < serverNames.length; i++) { if (serverNames[i] == null || serverNames[i].equals("")) { serverNames[i] = "localhost"; } } this.serverNames = serverNames; } } /** * Gets the name of the PostgreSQL database, running on the server identified by the serverName * property. * * @return name of the PostgreSQL database */ public String getDatabaseName() { return databaseName; } /** * Sets the name of the PostgreSQL database, running on the server identified by the serverName * property. If this is changed, it will only affect future calls to getConnection. * * @param databaseName name of the PostgreSQL database */ public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } /** * Gets a description of this DataSource-ish thing. Must be customized by subclasses. * * @return description of this DataSource-ish thing */ public abstract String getDescription(); /** * Gets the user to connect as by default. If this is not specified, you must use the * getConnection method which takes a user and password as parameters. * * @return user to connect as by default */ public String getUser() { return user; } /** * Sets the user to connect as by default. If this is not specified, you must use the * getConnection method which takes a user and password as parameters. If this is changed, it will * only affect future calls to getConnection. * * @param user user to connect as by default */ public void setUser(String user) { this.user = user; } /** * Gets the password to connect with by default. If this is not specified but a password is needed * to log in, you must use the getConnection method which takes a user and password as parameters. * * @return password to connect with by default */ public String getPassword() { return password; } /** * Sets the password to connect with by default. If this is not specified but a password is needed * to log in, you must use the getConnection method which takes a user and password as parameters. * If this is changed, it will only affect future calls to getConnection. * * @param password password to connect with by default */ public void setPassword(String password) { this.password = password; } /** * Gets the port which the PostgreSQL server is listening on for TCP/IP connections. * * @return The port, or 0 if the default port will be used. * @deprecated use {@link #getPortNumbers()} */ @Deprecated public int getPortNumber() { if (portNumbers == null || portNumbers.length == 0) { return 0; } return portNumbers[0]; } /** * Gets the port(s) which the PostgreSQL server is listening on for TCP/IP connections. * * @return The port(s), or 0 if the default port will be used. */ public int[] getPortNumbers() { return portNumbers; } /** * Sets the port which the PostgreSQL server is listening on for TCP/IP connections. Be sure the * -i flag is passed to postmaster when PostgreSQL is started. If this is not set, or set to 0, * the default port will be used. * * @param portNumber port which the PostgreSQL server is listening on for TCP/IP * @deprecated use {@link #setPortNumbers(int[])} */ @Deprecated public void setPortNumber(int portNumber) { setPortNumbers(new int[] { portNumber }); } /** * Sets the port(s) which the PostgreSQL server is listening on for TCP/IP connections. Be sure the * -i flag is passed to postmaster when PostgreSQL is started. If this is not set, or set to 0, * the default port will be used. * * @param portNumbers port(s) which the PostgreSQL server is listening on for TCP/IP */ public void setPortNumbers(int[] portNumbers) { if (portNumbers == null || portNumbers.length == 0) { portNumbers = new int[] { 0 }; } this.portNumbers = Arrays.copyOf(portNumbers, portNumbers.length); } /** * @return command line options for this connection */ public String getOptions() { return PGProperty.OPTIONS.get(properties); } /** * Set command line options for this connection * * @param options string to set options to */ public void setOptions(String options) { PGProperty.OPTIONS.set(properties, options); } /** * @return login timeout * @see PGProperty#LOGIN_TIMEOUT */ @Override public int getLoginTimeout() { return PGProperty.LOGIN_TIMEOUT.getIntNoCheck(properties); } /** * @param loginTimeout login timeout * @see PGProperty#LOGIN_TIMEOUT */ @Override public void setLoginTimeout(int loginTimeout) { PGProperty.LOGIN_TIMEOUT.set(properties, loginTimeout); } /** * @return connect timeout * @see PGProperty#CONNECT_TIMEOUT */ public int getConnectTimeout() { return PGProperty.CONNECT_TIMEOUT.getIntNoCheck(properties); } /** * @param connectTimeout connect timeout * @see PGProperty#CONNECT_TIMEOUT */ public void setConnectTimeout(int connectTimeout) { PGProperty.CONNECT_TIMEOUT.set(properties, connectTimeout); } /** * @return protocol version * @see PGProperty#PROTOCOL_VERSION */ public int getProtocolVersion() { if (!PGProperty.PROTOCOL_VERSION.isPresent(properties)) { return 0; } else { return PGProperty.PROTOCOL_VERSION.getIntNoCheck(properties); } } /** * @param protocolVersion protocol version * @see PGProperty#PROTOCOL_VERSION */ public void setProtocolVersion(int protocolVersion) { if (protocolVersion == 0) { PGProperty.PROTOCOL_VERSION.set(properties, null); } else { PGProperty.PROTOCOL_VERSION.set(properties, protocolVersion); } } /** * @return receive buffer size * @see PGProperty#RECEIVE_BUFFER_SIZE */ public int getReceiveBufferSize() { return PGProperty.RECEIVE_BUFFER_SIZE.getIntNoCheck(properties); } /** * @param nbytes receive buffer size * @see PGProperty#RECEIVE_BUFFER_SIZE */ public void setReceiveBufferSize(int nbytes) { PGProperty.RECEIVE_BUFFER_SIZE.set(properties, nbytes); } /** * @return send buffer size * @see PGProperty#SEND_BUFFER_SIZE */ public int getSendBufferSize() { return PGProperty.SEND_BUFFER_SIZE.getIntNoCheck(properties); } /** * @param nbytes send buffer size * @see PGProperty#SEND_BUFFER_SIZE */ public void setSendBufferSize(int nbytes) { PGProperty.SEND_BUFFER_SIZE.set(properties, nbytes); } /** * @param count prepare threshold * @see PGProperty#PREPARE_THRESHOLD */ public void setPrepareThreshold(int count) { PGProperty.PREPARE_THRESHOLD.set(properties, count); } /** * @return prepare threshold * @see PGProperty#PREPARE_THRESHOLD */ public int getPrepareThreshold() { return PGProperty.PREPARE_THRESHOLD.getIntNoCheck(properties); } /** * @return prepared statement cache size (number of statements per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_QUERIES */ public int getPreparedStatementCacheQueries() { return PGProperty.PREPARED_STATEMENT_CACHE_QUERIES.getIntNoCheck(properties); } /** * @param cacheSize prepared statement cache size (number of statements per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_QUERIES */ public void setPreparedStatementCacheQueries(int cacheSize) { PGProperty.PREPARED_STATEMENT_CACHE_QUERIES.set(properties, cacheSize); } /** * @return prepared statement cache size (number of megabytes per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_SIZE_MIB */ public int getPreparedStatementCacheSizeMiB() { return PGProperty.PREPARED_STATEMENT_CACHE_SIZE_MIB.getIntNoCheck(properties); } /** * @param cacheSize statement cache size (number of megabytes per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_SIZE_MIB */ public void setPreparedStatementCacheSizeMiB(int cacheSize) { PGProperty.PREPARED_STATEMENT_CACHE_SIZE_MIB.set(properties, cacheSize); } /** * @return database metadata cache fields size (number of fields cached per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS */ public int getDatabaseMetadataCacheFields() { return PGProperty.DATABASE_METADATA_CACHE_FIELDS.getIntNoCheck(properties); } /** * @param cacheSize database metadata cache fields size (number of fields cached per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS */ public void setDatabaseMetadataCacheFields(int cacheSize) { PGProperty.DATABASE_METADATA_CACHE_FIELDS.set(properties, cacheSize); } /** * @return database metadata cache fields size (number of megabytes per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS_MIB */ public int getDatabaseMetadataCacheFieldsMiB() { return PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.getIntNoCheck(properties); } /** * @param cacheSize database metadata cache fields size (number of megabytes per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS_MIB */ public void setDatabaseMetadataCacheFieldsMiB(int cacheSize) { PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.set(properties, cacheSize); } /** * @param fetchSize default fetch size * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ public void setDefaultRowFetchSize(int fetchSize) { PGProperty.DEFAULT_ROW_FETCH_SIZE.set(properties, fetchSize); } /** * @return default fetch size * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ public int getDefaultRowFetchSize() { return PGProperty.DEFAULT_ROW_FETCH_SIZE.getIntNoCheck(properties); } /** * @param unknownLength unknown length * @see PGProperty#UNKNOWN_LENGTH */ public void setUnknownLength(int unknownLength) { PGProperty.UNKNOWN_LENGTH.set(properties, unknownLength); } /** * @return unknown length * @see PGProperty#UNKNOWN_LENGTH */ public int getUnknownLength() { return PGProperty.UNKNOWN_LENGTH.getIntNoCheck(properties); } /** * @param seconds socket timeout * @see PGProperty#SOCKET_TIMEOUT */ public void setSocketTimeout(int seconds) { PGProperty.SOCKET_TIMEOUT.set(properties, seconds); } /** * @return socket timeout * @see PGProperty#SOCKET_TIMEOUT */ public int getSocketTimeout() { return PGProperty.SOCKET_TIMEOUT.getIntNoCheck(properties); } /** * @param seconds timeout that is used for sending cancel command * @see PGProperty#CANCEL_SIGNAL_TIMEOUT */ public void setCancelSignalTimeout(int seconds) { PGProperty.CANCEL_SIGNAL_TIMEOUT.set(properties, seconds); } /** * @return timeout that is used for sending cancel command in seconds * @see PGProperty#CANCEL_SIGNAL_TIMEOUT */ public int getCancelSignalTimeout() { return PGProperty.CANCEL_SIGNAL_TIMEOUT.getIntNoCheck(properties); } /** * @param enabled if SSL is enabled * @see PGProperty#SSL */ public void setSsl(boolean enabled) { if (enabled) { PGProperty.SSL.set(properties, true); } else { PGProperty.SSL.set(properties, false); } } /** * @return true if SSL is enabled * @see PGProperty#SSL */ public boolean getSsl() { // "true" if "ssl" is set but empty return PGProperty.SSL.getBoolean(properties) || "".equals(PGProperty.SSL.get(properties)); } /** * @param classname SSL factory class name * @see PGProperty#SSL_FACTORY */ public void setSslfactory(String classname) { PGProperty.SSL_FACTORY.set(properties, classname); } /** * @return SSL factory class name * @see PGProperty#SSL_FACTORY */ public String getSslfactory() { return PGProperty.SSL_FACTORY.get(properties); } /** * @return SSL mode * @see PGProperty#SSL_MODE */ public String getSslMode() { return PGProperty.SSL_MODE.get(properties); } /** * @param mode SSL mode * @see PGProperty#SSL_MODE */ public void setSslMode(String mode) { PGProperty.SSL_MODE.set(properties, mode); } /** * @return SSL mode * @see PGProperty#SSL_FACTORY_ARG */ public String getSslFactoryArg() { return PGProperty.SSL_FACTORY_ARG.get(properties); } /** * @param arg argument forwarded to SSL factory * @see PGProperty#SSL_FACTORY_ARG */ public void setSslFactoryArg(String arg) { PGProperty.SSL_FACTORY_ARG.set(properties, arg); } /** * @return argument forwarded to SSL factory * @see PGProperty#SSL_HOSTNAME_VERIFIER */ public String getSslHostnameVerifier() { return PGProperty.SSL_HOSTNAME_VERIFIER.get(properties); } /** * @param className SSL hostname verifier * @see PGProperty#SSL_HOSTNAME_VERIFIER */ public void setSslHostnameVerifier(String className) { PGProperty.SSL_HOSTNAME_VERIFIER.set(properties, className); } /** * @return className SSL hostname verifier * @see PGProperty#SSL_CERT */ public String getSslCert() { return PGProperty.SSL_CERT.get(properties); } /** * @param file SSL certificate * @see PGProperty#SSL_CERT */ public void setSslCert(String file) { PGProperty.SSL_CERT.set(properties, file); } /** * @return SSL certificate * @see PGProperty#SSL_KEY */ public String getSslKey() { return PGProperty.SSL_KEY.get(properties); } /** * @param file SSL key * @see PGProperty#SSL_KEY */ public void setSslKey(String file) { PGProperty.SSL_KEY.set(properties, file); } /** * @return SSL root certificate * @see PGProperty#SSL_ROOT_CERT */ public String getSslRootCert() { return PGProperty.SSL_ROOT_CERT.get(properties); } /** * @param file SSL root certificate * @see PGProperty#SSL_ROOT_CERT */ public void setSslRootCert(String file) { PGProperty.SSL_ROOT_CERT.set(properties, file); } /** * @return SSL password * @see PGProperty#SSL_PASSWORD */ public String getSslPassword() { return PGProperty.SSL_PASSWORD.get(properties); } /** * @param password SSL password * @see PGProperty#SSL_PASSWORD */ public void setSslPassword(String password) { PGProperty.SSL_PASSWORD.set(properties, password); } /** * @return SSL password callback * @see PGProperty#SSL_PASSWORD_CALLBACK */ public String getSslPasswordCallback() { return PGProperty.SSL_PASSWORD_CALLBACK.get(properties); } /** * @param className SSL password callback class name * @see PGProperty#SSL_PASSWORD_CALLBACK */ public void setSslPasswordCallback(String className) { PGProperty.SSL_PASSWORD_CALLBACK.set(properties, className); } /** * @param applicationName application name * @see PGProperty#APPLICATION_NAME */ public void setApplicationName(String applicationName) { PGProperty.APPLICATION_NAME.set(properties, applicationName); } /** * @return application name * @see PGProperty#APPLICATION_NAME */ public String getApplicationName() { return PGProperty.APPLICATION_NAME.get(properties); } /** * @param targetServerType target server type * @see PGProperty#TARGET_SERVER_TYPE */ public void setTargetServerType(String targetServerType) { PGProperty.TARGET_SERVER_TYPE.set(properties, targetServerType); } /** * @return target server type * @see PGProperty#TARGET_SERVER_TYPE */ public String getTargetServerType() { return PGProperty.TARGET_SERVER_TYPE.get(properties); } /** * @param loadBalanceHosts load balance hosts * @see PGProperty#LOAD_BALANCE_HOSTS */ public void setLoadBalanceHosts(boolean loadBalanceHosts) { PGProperty.LOAD_BALANCE_HOSTS.set(properties, loadBalanceHosts); } /** * @return load balance hosts * @see PGProperty#LOAD_BALANCE_HOSTS */ public boolean getLoadBalanceHosts() { return PGProperty.LOAD_BALANCE_HOSTS.isPresent(properties); } /** * @param hostRecheckSeconds host recheck seconds * @see PGProperty#HOST_RECHECK_SECONDS */ public void setHostRecheckSeconds(int hostRecheckSeconds) { PGProperty.HOST_RECHECK_SECONDS.set(properties, hostRecheckSeconds); } /** * @return host recheck seconds * @see PGProperty#HOST_RECHECK_SECONDS */ public int getHostRecheckSeconds() { return PGProperty.HOST_RECHECK_SECONDS.getIntNoCheck(properties); } /** * @param enabled if TCP keep alive should be enabled * @see PGProperty#TCP_KEEP_ALIVE */ public void setTcpKeepAlive(boolean enabled) { PGProperty.TCP_KEEP_ALIVE.set(properties, enabled); } /** * @return true if TCP keep alive is enabled * @see PGProperty#TCP_KEEP_ALIVE */ public boolean getTcpKeepAlive() { return PGProperty.TCP_KEEP_ALIVE.getBoolean(properties); } /** * @param enabled if binary transfer should be enabled * @see PGProperty#BINARY_TRANSFER */ public void setBinaryTransfer(boolean enabled) { PGProperty.BINARY_TRANSFER.set(properties, enabled); } /** * @return true if binary transfer is enabled * @see PGProperty#BINARY_TRANSFER */ public boolean getBinaryTransfer() { return PGProperty.BINARY_TRANSFER.getBoolean(properties); } /** * @param oidList list of OIDs that are allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_ENABLE */ public void setBinaryTransferEnable(String oidList) { PGProperty.BINARY_TRANSFER_ENABLE.set(properties, oidList); } /** * @return list of OIDs that are allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_ENABLE */ public String getBinaryTransferEnable() { return PGProperty.BINARY_TRANSFER_ENABLE.get(properties); } /** * @param oidList list of OIDs that are not allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_DISABLE */ public void setBinaryTransferDisable(String oidList) { PGProperty.BINARY_TRANSFER_DISABLE.set(properties, oidList); } /** * @return list of OIDs that are not allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_DISABLE */ public String getBinaryTransferDisable() { return PGProperty.BINARY_TRANSFER_DISABLE.get(properties); } /** * @return string type * @see PGProperty#STRING_TYPE */ public String getStringType() { return PGProperty.STRING_TYPE.get(properties); } /** * @param stringType string type * @see PGProperty#STRING_TYPE */ public void setStringType(String stringType) { PGProperty.STRING_TYPE.set(properties, stringType); } /** * @return true if column sanitizer is disabled * @see PGProperty#DISABLE_COLUMN_SANITISER */ public boolean isColumnSanitiserDisabled() { return PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(properties); } /** * @return true if column sanitizer is disabled * @see PGProperty#DISABLE_COLUMN_SANITISER */ public boolean getDisableColumnSanitiser() { return PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(properties); } /** * @param disableColumnSanitiser if column sanitizer should be disabled * @see PGProperty#DISABLE_COLUMN_SANITISER */ public void setDisableColumnSanitiser(boolean disableColumnSanitiser) { PGProperty.DISABLE_COLUMN_SANITISER.set(properties, disableColumnSanitiser); } /** * @return current schema * @see PGProperty#CURRENT_SCHEMA */ public String getCurrentSchema() { return PGProperty.CURRENT_SCHEMA.get(properties); } /** * @param currentSchema current schema * @see PGProperty#CURRENT_SCHEMA */ public void setCurrentSchema(String currentSchema) { PGProperty.CURRENT_SCHEMA.set(properties, currentSchema); } /** * @return true if connection is readonly * @see PGProperty#READ_ONLY */ public boolean getReadOnly() { return PGProperty.READ_ONLY.getBoolean(properties); } /** * @param readOnly if connection should be readonly * @see PGProperty#READ_ONLY */ public void setReadOnly(boolean readOnly) { PGProperty.READ_ONLY.set(properties, readOnly); } /** * @return The behavior when set read only * @see PGProperty#READ_ONLY_MODE */ public String getReadOnlyMode() { return PGProperty.READ_ONLY_MODE.get(properties); } /** * @param mode the behavior when set read only * @see PGProperty#READ_ONLY_MODE */ public void setReadOnlyMode(String mode) { PGProperty.READ_ONLY_MODE.set(properties, mode); } /** * @return true if driver should log unclosed connections * @see PGProperty#LOG_UNCLOSED_CONNECTIONS */ public boolean getLogUnclosedConnections() { return PGProperty.LOG_UNCLOSED_CONNECTIONS.getBoolean(properties); } /** * @param enabled true if driver should log unclosed connections * @see PGProperty#LOG_UNCLOSED_CONNECTIONS */ public void setLogUnclosedConnections(boolean enabled) { PGProperty.LOG_UNCLOSED_CONNECTIONS.set(properties, enabled); } /** * @return true if driver should log include detail in server error messages * @see PGProperty#LOG_SERVER_ERROR_DETAIL */ public boolean getLogServerErrorDetail() { return PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(properties); } /** * @param enabled true if driver should include detail in server error messages * @see PGProperty#LOG_SERVER_ERROR_DETAIL */ public void setLogServerErrorDetail(boolean enabled) { PGProperty.LOG_SERVER_ERROR_DETAIL.set(properties, enabled); } /** * @return assumed minimal server version * @see PGProperty#ASSUME_MIN_SERVER_VERSION */ public String getAssumeMinServerVersion() { return PGProperty.ASSUME_MIN_SERVER_VERSION.get(properties); } /** * @param minVersion assumed minimal server version * @see PGProperty#ASSUME_MIN_SERVER_VERSION */ public void setAssumeMinServerVersion(String minVersion) { PGProperty.ASSUME_MIN_SERVER_VERSION.set(properties, minVersion); } /** * @return JAAS application name * @see PGProperty#JAAS_APPLICATION_NAME */ public String getJaasApplicationName() { return PGProperty.JAAS_APPLICATION_NAME.get(properties); } /** * @param name JAAS application name * @see PGProperty#JAAS_APPLICATION_NAME */ public void setJaasApplicationName(String name) { PGProperty.JAAS_APPLICATION_NAME.set(properties, name); } /** * @return true if perform JAAS login before GSS authentication * @see PGProperty#JAAS_LOGIN */ public boolean getJaasLogin() { return PGProperty.JAAS_LOGIN.getBoolean(properties); } /** * @param doLogin true if perform JAAS login before GSS authentication * @see PGProperty#JAAS_LOGIN */ public void setJaasLogin(boolean doLogin) { PGProperty.JAAS_LOGIN.set(properties, doLogin); } /** * @return Kerberos server name * @see PGProperty#KERBEROS_SERVER_NAME */ public String getKerberosServerName() { return PGProperty.KERBEROS_SERVER_NAME.get(properties); } /** * @param serverName Kerberos server name * @see PGProperty#KERBEROS_SERVER_NAME */ public void setKerberosServerName(String serverName) { PGProperty.KERBEROS_SERVER_NAME.set(properties, serverName); } /** * @return true if use SPNEGO * @see PGProperty#USE_SPNEGO */ public boolean getUseSpNego() { return PGProperty.USE_SPNEGO.getBoolean(properties); } /** * @param use true if use SPNEGO * @see PGProperty#USE_SPNEGO */ public void setUseSpNego(boolean use) { PGProperty.USE_SPNEGO.set(properties, use); } /** * @return GSS mode: auto, sspi, or gssapi * @see PGProperty#GSS_LIB */ public String getGssLib() { return PGProperty.GSS_LIB.get(properties); } /** * @param lib GSS mode: auto, sspi, or gssapi * @see PGProperty#GSS_LIB */ public void setGssLib(String lib) { PGProperty.GSS_LIB.set(properties, lib); } /** * @return SSPI service class * @see PGProperty#SSPI_SERVICE_CLASS */ public String getSspiServiceClass() { return PGProperty.SSPI_SERVICE_CLASS.get(properties); } /** * @param serviceClass SSPI service class * @see PGProperty#SSPI_SERVICE_CLASS */ public void setSspiServiceClass(String serviceClass) { PGProperty.SSPI_SERVICE_CLASS.set(properties, serviceClass); } /** * @return if connection allows encoding changes * @see PGProperty#ALLOW_ENCODING_CHANGES */ public boolean getAllowEncodingChanges() { return PGProperty.ALLOW_ENCODING_CHANGES.getBoolean(properties); } /** * @param allow if connection allows encoding changes * @see PGProperty#ALLOW_ENCODING_CHANGES */ public void setAllowEncodingChanges(boolean allow) { PGProperty.ALLOW_ENCODING_CHANGES.set(properties, allow); } /** * @return socket factory class name * @see PGProperty#SOCKET_FACTORY */ public String getSocketFactory() { return PGProperty.SOCKET_FACTORY.get(properties); } /** * @param socketFactoryClassName socket factory class name * @see PGProperty#SOCKET_FACTORY */ public void setSocketFactory(String socketFactoryClassName) { PGProperty.SOCKET_FACTORY.set(properties, socketFactoryClassName); } /** * @return socket factory argument * @see PGProperty#SOCKET_FACTORY_ARG */ public String getSocketFactoryArg() { return PGProperty.SOCKET_FACTORY_ARG.get(properties); } /** * @param socketFactoryArg socket factory argument * @see PGProperty#SOCKET_FACTORY_ARG */ public void setSocketFactoryArg(String socketFactoryArg) { PGProperty.SOCKET_FACTORY_ARG.set(properties, socketFactoryArg); } /** * @param replication set to 'database' for logical replication or 'true' for physical replication * @see PGProperty#REPLICATION */ public void setReplication(String replication) { PGProperty.REPLICATION.set(properties, replication); } /** * @return 'select', "callIfNoReturn', or 'call' * @see PGProperty#ESCAPE_SYNTAX_CALL_MODE */ public String getEscapeSyntaxCallMode() { return PGProperty.ESCAPE_SYNTAX_CALL_MODE.get(properties); } /** * @param callMode the call mode to use for JDBC escape call syntax * @see PGProperty#ESCAPE_SYNTAX_CALL_MODE */ public void setEscapeSyntaxCallMode(String callMode) { PGProperty.ESCAPE_SYNTAX_CALL_MODE.set(properties, callMode); } /** * @return null, 'database', or 'true * @see PGProperty#REPLICATION */ public String getReplication() { return PGProperty.REPLICATION.get(properties); } /** * @return Logger Level of the JDBC Driver * @see PGProperty#LOGGER_LEVEL */ public String getLoggerLevel() { return PGProperty.LOGGER_LEVEL.get(properties); } /** * @param loggerLevel of the JDBC Driver * @see PGProperty#LOGGER_LEVEL */ public void setLoggerLevel(String loggerLevel) { PGProperty.LOGGER_LEVEL.set(properties, loggerLevel); } /** * @return File output of the Logger. * @see PGProperty#LOGGER_FILE */ public String getLoggerFile() { ExpressionProperties exprProps = new ExpressionProperties(properties, System.getProperties()); return PGProperty.LOGGER_FILE.get(exprProps); } /** * @param loggerFile File output of the Logger. * @see PGProperty#LOGGER_LEVEL */ public void setLoggerFile(String loggerFile) { PGProperty.LOGGER_FILE.set(properties, loggerFile); } /** * Generates a {@link DriverManager} URL from the other properties supplied. * * @return {@link DriverManager} URL from the other properties supplied */ public String getUrl() { StringBuilder url = new StringBuilder(100); url.append("jdbc:postgresql://"); for (int i = 0; i < serverNames.length; i++) { if (i > 0) { url.append(","); } url.append(serverNames[i]); if (portNumbers != null && portNumbers.length >= i && portNumbers[i] != 0) { url.append(":").append(portNumbers[i]); } } url.append("/").append(URLCoder.encode(databaseName)); StringBuilder query = new StringBuilder(100); for (PGProperty property : PGProperty.values()) { if (property.isPresent(properties)) { if (query.length() != 0) { query.append("&"); } query.append(property.getName()); query.append("="); query.append(URLCoder.encode(property.get(properties))); } } if (query.length() > 0) { url.append("?"); url.append(query); } return url.toString(); } /** * Generates a {@link DriverManager} URL from the other properties supplied. * * @return {@link DriverManager} URL from the other properties supplied */ public String getURL() { return getUrl(); } /** * Sets properties from a {@link DriverManager} URL. * * @param url properties to set */ public void setUrl(String url) { Properties p = org.postgresql.Driver.parseURL(url, null); if (p == null) { throw new IllegalArgumentException("URL invalid " + url); } for (PGProperty property : PGProperty.values()) { if (!this.properties.containsKey(property.getName())) { setProperty(property, property.get(p)); } } } /** * Sets properties from a {@link DriverManager} URL. * Added to follow convention used in other DBMS. * * @param url properties to set */ public void setURL(String url) { setUrl(url); } public String getProperty(String name) throws SQLException { PGProperty pgProperty = PGProperty.forName(name); if (pgProperty != null) { return getProperty(pgProperty); } else { throw new PSQLException(GT.tr("Unsupported property name: {0}", name), PSQLState.INVALID_PARAMETER_VALUE); } } public void setProperty(String name, String value) throws SQLException { PGProperty pgProperty = PGProperty.forName(name); if (pgProperty != null) { setProperty(pgProperty, value); } else { throw new PSQLException(GT.tr("Unsupported property name: {0}", name), PSQLState.INVALID_PARAMETER_VALUE); } } public String getProperty(PGProperty property) { return property.get(properties); } public void setProperty(PGProperty property, String value) { if (value == null) { return; } switch (property) { case PG_HOST: setServerNames(value.split(",")); break; case PG_PORT: String[] ps = value.split(","); int[] ports = new int[ps.length]; for (int i = 0 ; i < ps.length; i++) { try { ports[i] = Integer.parseInt(ps[i]); } catch (NumberFormatException e) { ports[i] = 0; } } setPortNumbers(ports); break; case PG_DBNAME: setDatabaseName(value); break; case USER: setUser(value); break; case PASSWORD: setPassword(value); break; default: properties.setProperty(property.getName(), value); } } /** * Generates a reference using the appropriate object factory. * * @return reference using the appropriate object factory */ protected Reference createReference() { return new Reference(getClass().getName(), PGObjectFactory.class.getName(), null); } public Reference getReference() throws NamingException { Reference ref = createReference(); StringBuilder serverString = new StringBuilder(); for (int i = 0; i < serverNames.length; i++) { if (i > 0) { serverString.append(","); } String serverName = serverNames[i]; serverString.append(serverName); } ref.add(new StringRefAddr("serverName", serverString.toString())); StringBuilder portString = new StringBuilder(); for (int i = 0; i < portNumbers.length; i++) { if (i > 0) { portString.append(","); } int p = portNumbers[i]; portString.append(Integer.toString(p)); } ref.add(new StringRefAddr("portNumber", portString.toString())); ref.add(new StringRefAddr("databaseName", databaseName)); if (user != null) { ref.add(new StringRefAddr("user", user)); } if (password != null) { ref.add(new StringRefAddr("password", password)); } for (PGProperty property : PGProperty.values()) { if (property.isPresent(properties)) { ref.add(new StringRefAddr(property.getName(), property.get(properties))); } } return ref; } public void setFromReference(Reference ref) { databaseName = getReferenceProperty(ref, "databaseName"); String portNumberString = getReferenceProperty(ref, "portNumber"); if (portNumberString != null) { String[] ps = portNumberString.split(","); int[] ports = new int[ps.length]; for (int i = 0; i < ps.length; i++) { try { ports[i] = Integer.parseInt(ps[i]); } catch (NumberFormatException e) { ports[i] = 0; } } setPortNumbers(ports); } else { setPortNumbers(null); } setServerNames(getReferenceProperty(ref, "serverName").split(",")); for (PGProperty property : PGProperty.values()) { setProperty(property, getReferenceProperty(ref, property.getName())); } } private static String getReferenceProperty(Reference ref, String propertyName) { RefAddr addr = ref.get(propertyName); if (addr == null) { return null; } return (String) addr.getContent(); } protected void writeBaseObject(ObjectOutputStream out) throws IOException { out.writeObject(serverNames); out.writeObject(databaseName); out.writeObject(user); out.writeObject(password); out.writeObject(portNumbers); out.writeObject(properties); } protected void readBaseObject(ObjectInputStream in) throws IOException, ClassNotFoundException { serverNames = (String[]) in.readObject(); databaseName = (String) in.readObject(); user = (String) in.readObject(); password = (String) in.readObject(); portNumbers = (int[]) in.readObject(); properties = (Properties) in.readObject(); } public void initializeFrom(BaseDataSource source) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); source.writeBaseObject(oos); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); readBaseObject(ois); } /** * @return preferred query execution mode * @see PGProperty#PREFER_QUERY_MODE */ public PreferQueryMode getPreferQueryMode() { return PreferQueryMode.of(PGProperty.PREFER_QUERY_MODE.get(properties)); } /** * @param preferQueryMode extended, simple, extendedForPrepared, or extendedCacheEverything * @see PGProperty#PREFER_QUERY_MODE */ public void setPreferQueryMode(PreferQueryMode preferQueryMode) { PGProperty.PREFER_QUERY_MODE.set(properties, preferQueryMode.value()); } /** * @return connection configuration regarding automatic per-query savepoints * @see PGProperty#AUTOSAVE */ public AutoSave getAutosave() { return AutoSave.of(PGProperty.AUTOSAVE.get(properties)); } /** * @param autoSave connection configuration regarding automatic per-query savepoints * @see PGProperty#AUTOSAVE */ public void setAutosave(AutoSave autoSave) { PGProperty.AUTOSAVE.set(properties, autoSave.value()); } /** * see PGProperty#CLEANUP_SAVEPOINTS * * @return boolean indicating property set */ public boolean getCleanupSavepoints() { return PGProperty.CLEANUP_SAVEPOINTS.getBoolean(properties); } /** * see PGProperty#CLEANUP_SAVEPOINTS * * @param cleanupSavepoints will cleanup savepoints after a successful transaction */ public void setCleanupSavepoints(boolean cleanupSavepoints) { PGProperty.CLEANUP_SAVEPOINTS.set(properties, cleanupSavepoints); } /** * @return boolean indicating property is enabled or not. * @see PGProperty#REWRITE_BATCHED_INSERTS */ public boolean getReWriteBatchedInserts() { return PGProperty.REWRITE_BATCHED_INSERTS.getBoolean(properties); } /** * @param reWrite boolean value to set the property in the properties collection * @see PGProperty#REWRITE_BATCHED_INSERTS */ public void setReWriteBatchedInserts(boolean reWrite) { PGProperty.REWRITE_BATCHED_INSERTS.set(properties, reWrite); } /** * @return boolean indicating property is enabled or not. * @see PGProperty#HIDE_UNPRIVILEGED_OBJECTS */ public boolean getHideUnprivilegedObjects() { return PGProperty.HIDE_UNPRIVILEGED_OBJECTS.getBoolean(properties); } /** * @param hideUnprivileged boolean value to set the property in the properties collection * @see PGProperty#HIDE_UNPRIVILEGED_OBJECTS */ public void setHideUnprivilegedObjects(boolean hideUnprivileged) { PGProperty.HIDE_UNPRIVILEGED_OBJECTS.set(properties, hideUnprivileged); } public String getMaxResultBuffer() { return PGProperty.MAX_RESULT_BUFFER.get(properties); } public void setMaxResultBuffer(String maxResultBuffer) { PGProperty.MAX_RESULT_BUFFER.set(properties, maxResultBuffer); } //#if mvn.project.property.postgresql.jdbc.spec >= "JDBC4.1" @Override //#endif public java.util.logging.Logger getParentLogger() { return Logger.getLogger("org.postgresql"); } /* * Alias methods below, these are to help with ease-of-use with other database tools / frameworks * which expect normal java bean getters / setters to exist for the property names. */ public boolean isSsl() { return getSsl(); } public String getSslfactoryarg() { return getSslFactoryArg(); } public void setSslfactoryarg(final String arg) { setSslFactoryArg(arg); } public String getSslcert() { return getSslCert(); } public void setSslcert(final String file) { setSslCert(file); } public String getSslmode() { return getSslMode(); } public void setSslmode(final String mode) { setSslMode(mode); } public String getSslhostnameverifier() { return getSslHostnameVerifier(); } public void setSslhostnameverifier(final String className) { setSslHostnameVerifier(className); } public String getSslkey() { return getSslKey(); } public void setSslkey(final String file) { setSslKey(file); } public String getSslrootcert() { return getSslRootCert(); } public void setSslrootcert(final String file) { setSslRootCert(file); } public String getSslpasswordcallback() { return getSslPasswordCallback(); } public void setSslpasswordcallback(final String className) { setSslPasswordCallback(className); } public String getSslpassword() { return getSslPassword(); } public void setSslpassword(final String sslpassword) { setSslPassword(sslpassword); } public int getRecvBufferSize() { return getReceiveBufferSize(); } public void setRecvBufferSize(final int nbytes) { setReceiveBufferSize(nbytes); } public boolean isAllowEncodingChanges() { return getAllowEncodingChanges(); } public boolean isLogUnclosedConnections() { return getLogUnclosedConnections(); } public boolean isTcpKeepAlive() { return getTcpKeepAlive(); } public boolean isReadOnly() { return getReadOnly(); } public boolean isDisableColumnSanitiser() { return getDisableColumnSanitiser(); } public boolean isLoadBalanceHosts() { return getLoadBalanceHosts(); } public boolean isCleanupSavePoints() { return getCleanupSavepoints(); } public void setCleanupSavePoints(final boolean cleanupSavepoints) { setCleanupSavepoints(cleanupSavepoints); } public boolean isReWriteBatchedInserts() { return getReWriteBatchedInserts(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4033_2
crossvul-java_data_bad_3875_0
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.StringReader; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.dom4j.io.SAXReader; import org.dom4j.rule.Pattern; import org.jaxen.VariableContext; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * <code>DocumentHelper</code> is a collection of helper methods for using * DOM4J. * * @author <a href="mailto:jstrachan@apache.org">James Strachan </a> * @version $Revision: 1.26 $ */ @SuppressWarnings("unused") public final class DocumentHelper { private DocumentHelper() { } private static DocumentFactory getDocumentFactory() { return DocumentFactory.getInstance(); } // Static helper methods public static Document createDocument() { return getDocumentFactory().createDocument(); } public static Document createDocument(Element rootElement) { return getDocumentFactory().createDocument(rootElement); } public static Element createElement(QName qname) { return getDocumentFactory().createElement(qname); } public static Element createElement(String name) { return getDocumentFactory().createElement(name); } public static Attribute createAttribute(Element owner, QName qname, String value) { return getDocumentFactory().createAttribute(owner, qname, value); } public static Attribute createAttribute(Element owner, String name, String value) { return getDocumentFactory().createAttribute(owner, name, value); } public static CDATA createCDATA(String text) { return DocumentFactory.getInstance().createCDATA(text); } public static Comment createComment(String text) { return DocumentFactory.getInstance().createComment(text); } public static Text createText(String text) { return DocumentFactory.getInstance().createText(text); } public static Entity createEntity(String name, String text) { return DocumentFactory.getInstance().createEntity(name, text); } public static Namespace createNamespace(String prefix, String uri) { return DocumentFactory.getInstance().createNamespace(prefix, uri); } public static ProcessingInstruction createProcessingInstruction(String pi, String d) { return getDocumentFactory().createProcessingInstruction(pi, d); } public static ProcessingInstruction createProcessingInstruction(String pi, Map<String, String> data) { return getDocumentFactory().createProcessingInstruction(pi, data); } public static QName createQName(String localName, Namespace namespace) { return getDocumentFactory().createQName(localName, namespace); } public static QName createQName(String localName) { return getDocumentFactory().createQName(localName); } /** * <p> * <code>createXPath</code> parses an XPath expression and creates a new * XPath <code>XPath</code> instance using the singleton {@link * DocumentFactory}. * </p> * * @param xpathExpression * is the XPath expression to create * * @return a new <code>XPath</code> instance * * @throws InvalidXPathException * if the XPath expression is invalid */ public static XPath createXPath(String xpathExpression) throws InvalidXPathException { return getDocumentFactory().createXPath(xpathExpression); } /** * <p> * <code>createXPath</code> parses an XPath expression and creates a new * XPath <code>XPath</code> instance using the singleton {@link * DocumentFactory}. * </p> * * @param xpathExpression * is the XPath expression to create * @param context * is the variable context to use when evaluating the XPath * * @return a new <code>XPath</code> instance * * @throws InvalidXPathException * if the XPath expression is invalid */ public static XPath createXPath(String xpathExpression, VariableContext context) throws InvalidXPathException { return getDocumentFactory().createXPath(xpathExpression, context); } /** * <p> * <code>createXPathFilter</code> parses a NodeFilter from the given XPath * filter expression using the singleton {@link DocumentFactory}. XPath * filter expressions occur within XPath expressions such as * <code>self::node()[ filterExpression ]</code> * </p> * * @param xpathFilterExpression * is the XPath filter expression to create * * @return a new <code>NodeFilter</code> instance */ public static NodeFilter createXPathFilter(String xpathFilterExpression) { return getDocumentFactory().createXPathFilter(xpathFilterExpression); } /** * <p> * <code>createPattern</code> parses the given XPath expression to create * an XSLT style {@link Pattern}instance which can then be used in an XSLT * processing model. * </p> * * @param xpathPattern * is the XPath pattern expression to create * * @return a new <code>Pattern</code> instance */ public static Pattern createPattern(String xpathPattern) { return getDocumentFactory().createPattern(xpathPattern); } /** * <p> * <code>selectNodes</code> performs the given XPath expression on the * {@link List}of {@link Node}instances appending all the results together * into a single list. * </p> * * @param xpathFilterExpression * is the XPath filter expression to evaluate * @param nodes * is the list of nodes on which to evalute the XPath * * @return the results of all the XPath evaluations as a single list */ public static List<Node> selectNodes(String xpathFilterExpression, List<Node> nodes) { XPath xpath = createXPath(xpathFilterExpression); return xpath.selectNodes(nodes); } /** * <p> * <code>selectNodes</code> performs the given XPath expression on the * {@link List}of {@link Node}instances appending all the results together * into a single list. * </p> * * @param xpathFilterExpression * is the XPath filter expression to evaluate * @param node * is the Node on which to evalute the XPath * * @return the results of all the XPath evaluations as a single list */ public static List<Node> selectNodes(String xpathFilterExpression, Node node) { XPath xpath = createXPath(xpathFilterExpression); return xpath.selectNodes(node); } /** * <p> * <code>sort</code> sorts the given List of Nodes using an XPath * expression as a {@link java.util.Comparator}. * </p> * * @param list * is the list of Nodes to sort * @param xpathExpression * is the XPath expression used for comparison */ public static void sort(List<Node> list, String xpathExpression) { XPath xpath = createXPath(xpathExpression); xpath.sort(list); } /** * <p> * <code>sort</code> sorts the given List of Nodes using an XPath * expression as a {@link java.util.Comparator}and optionally removing * duplicates. * </p> * * @param list * is the list of Nodes to sort * @param expression * is the XPath expression used for comparison * @param distinct * if true then duplicate values (using the sortXPath for * comparisions) will be removed from the List */ public static void sort(List<Node> list, String expression, boolean distinct) { XPath xpath = createXPath(expression); xpath.sort(list, distinct); } /** * <p> * <code>parseText</code> parses the given text as an XML document and * returns the newly created Document. * </p> * * Loading external DTD and entities is disabled (if it is possible) for security reasons. * * @param text * the XML text to be parsed * * @return a newly parsed Document * * @throws DocumentException * if the document could not be parsed */ public static Document parseText(String text) throws DocumentException { SAXReader reader = new SAXReader(); try { reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (SAXException e) { //Parse with external resources downloading allowed. } String encoding = getEncoding(text); InputSource source = new InputSource(new StringReader(text)); source.setEncoding(encoding); Document result = reader.read(source); // if the XML parser doesn't provide a way to retrieve the encoding, // specify it manually if (result.getXMLEncoding() == null) { result.setXMLEncoding(encoding); } return result; } private static String getEncoding(String text) { String result = null; String xml = text.trim(); if (xml.startsWith("<?xml")) { int end = xml.indexOf("?>"); String sub = xml.substring(0, end); StringTokenizer tokens = new StringTokenizer(sub, " =\"\'"); while (tokens.hasMoreTokens()) { String token = tokens.nextToken(); if ("encoding".equals(token)) { if (tokens.hasMoreTokens()) { result = tokens.nextToken(); } break; } } } return result; } /** * <p> * makeElement * </p> * a helper method which navigates from the given Document or Element node * to some Element using the path expression, creating any necessary * elements along the way. For example the path <code>a/b/c</code> would * get the first child &lt;a&gt; element, which would be created if it did * not exist, then the next child &lt;b&gt; and so on until finally a * &lt;c&gt; element is returned. * * @param source * is the Element or Document to start navigating from * @param path * is a simple path expression, seperated by '/' which denotes * the path from the source to the resulting element such as * a/b/c * * @return the first Element on the given path which either already existed * on the path or were created by this method. */ public static Element makeElement(Branch source, String path) { StringTokenizer tokens = new StringTokenizer(path, "/"); Element parent; if (source instanceof Document) { Document document = (Document) source; parent = document.getRootElement(); // lets throw a NoSuchElementException // if we are given an empty path String name = tokens.nextToken(); if (parent == null) { parent = document.addElement(name); } } else { parent = (Element) source; } Element element = null; while (tokens.hasMoreTokens()) { String name = tokens.nextToken(); if (name.indexOf(':') > 0) { element = parent.element(parent.getQName(name)); } else { element = parent.element(name); } if (element == null) { element = parent.addElement(name); } parent = element; } return element; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-611/java/bad_3875_0
crossvul-java_data_good_497_0
/* * Distributed as part of c3p0 v.0.9.5.2 * * Copyright (C) 2015 Machinery For Change, Inc. * * Author: Steve Waldman <swaldman@mchange.com> * * This library is free software; you can redistribute it and/or modify * it under the terms of EITHER: * * 1) The GNU Lesser General Public License (LGPL), version 2.1, as * published by the Free Software Foundation * * OR * * 2) The Eclipse Public License (EPL), version 1.0 * * You may choose which license to accept if you wish to redistribute * or modify this work. You may offer derivatives of this work * under the license you have chosen, or you may provide the same * choice of license which you have been offered here. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received copies of both LGPL v2.1 and EPL v1.0 * along with this software; see the files LICENSE-EPL and LICENSE-LGPL. * If not, the text of these licenses are currently available at * * LGPL v2.1: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * EPL v1.0: http://www.eclipse.org/org/documents/epl-v10.php * */ package com.mchange.v2.c3p0.cfg; import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.w3c.dom.*; import com.mchange.v2.log.*; import com.mchange.v1.xml.DomParseUtils; public final class C3P0ConfigXmlUtils { public final static String XML_CONFIG_RSRC_PATH = "/c3p0-config.xml"; final static MLogger logger = MLog.getLogger( C3P0ConfigXmlUtils.class ); public final static String LINESEP; private final static String[] MISSPELL_PFXS = {"/c3p0", "/c3pO", "/c3po", "/C3P0", "/C3PO"}; private final static char[] MISSPELL_LINES = {'-', '_'}; private final static String[] MISSPELL_CONFIG = {"config", "CONFIG"}; private final static String[] MISSPELL_XML = {"xml", "XML"}; // its an ugly way to do this, but since resources are not listable... // // this is only executed once, and does about 40 tests (for now) // should I care about the cost in initialization time? // // should only be run if we've checked for the correct file, but // not found it private final static void warnCommonXmlConfigResourceMisspellings() { if (logger.isLoggable( MLevel.WARNING) ) { for (int a = 0, lena = MISSPELL_PFXS.length; a < lena; ++a) { StringBuffer sb = new StringBuffer(16); sb.append( MISSPELL_PFXS[a] ); for (int b = 0, lenb = MISSPELL_LINES.length; b < lenb; ++b) { sb.append(MISSPELL_LINES[b]); for (int c = 0, lenc = MISSPELL_CONFIG.length; c < lenc; ++c) { sb.append(MISSPELL_CONFIG[c]); sb.append('.'); for (int d = 0, lend = MISSPELL_XML.length; d < lend; ++d) { sb.append(MISSPELL_XML[d]); String test = sb.toString(); if (!test.equals(XML_CONFIG_RSRC_PATH)) { Object hopefullyNull = C3P0ConfigXmlUtils.class.getResource( test ); if (hopefullyNull != null) { logger.warning("POSSIBLY MISSPELLED c3p0-conf.xml RESOURCE FOUND. " + "Please ensure the file name is c3p0-config.xml, all lower case, " + "with the digit 0 (NOT the letter O) in c3p0. It should be placed " + " in the top level of c3p0's effective classpath."); return; } } } } } } } } static { String ls; try { ls = System.getProperty("line.separator", "\r\n"); } catch (Exception e) { ls = "\r\n"; } LINESEP = ls; } public static C3P0Config extractXmlConfigFromDefaultResource() throws Exception { InputStream is = null; try { is = C3P0ConfigUtils.class.getResourceAsStream(XML_CONFIG_RSRC_PATH); if ( is == null ) { warnCommonXmlConfigResourceMisspellings(); return null; } else return extractXmlConfigFromInputStream( is ); } finally { try { if (is != null) is.close(); } catch (Exception e) { if ( logger.isLoggable( MLevel.FINE ) ) logger.log(MLevel.FINE,"Exception on resource InputStream close.", e); } } } public static C3P0Config extractXmlConfigFromInputStream(InputStream is) throws Exception { DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setExpandEntityReferences(false); DocumentBuilder db = fact.newDocumentBuilder(); Document doc = db.parse( is ); return extractConfigFromXmlDoc(doc); } public static C3P0Config extractConfigFromXmlDoc(Document doc) throws Exception { Element docElem = doc.getDocumentElement(); if (docElem.getTagName().equals("c3p0-config")) { NamedScope defaults; HashMap configNamesToNamedScopes = new HashMap(); Element defaultConfigElem = DomParseUtils.uniqueChild( docElem, "default-config" ); if (defaultConfigElem != null) defaults = extractNamedScopeFromLevel( defaultConfigElem ); else defaults = new NamedScope(); NodeList nl = DomParseUtils.immediateChildElementsByTagName(docElem, "named-config"); for (int i = 0, len = nl.getLength(); i < len; ++i) { Element namedConfigElem = (Element) nl.item(i); String configName = namedConfigElem.getAttribute("name"); if (configName != null && configName.length() > 0) { NamedScope namedConfig = extractNamedScopeFromLevel( namedConfigElem ); configNamesToNamedScopes.put( configName, namedConfig); } else logger.warning("Configuration XML contained named-config element without name attribute: " + namedConfigElem); } return new C3P0Config( defaults, configNamesToNamedScopes ); } else throw new Exception("Root element of c3p0 config xml should be 'c3p0-config', not '" + docElem.getTagName() + "'."); } private static NamedScope extractNamedScopeFromLevel(Element elem) { HashMap props = extractPropertiesFromLevel( elem ); HashMap userNamesToOverrides = new HashMap(); NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "user-overrides"); for (int i = 0, len = nl.getLength(); i < len; ++i) { Element perUserConfigElem = (Element) nl.item(i); String userName = perUserConfigElem.getAttribute("user"); if (userName != null && userName.length() > 0) { HashMap userProps = extractPropertiesFromLevel( perUserConfigElem ); userNamesToOverrides.put( userName, userProps ); } else logger.warning("Configuration XML contained user-overrides element without user attribute: " + LINESEP + perUserConfigElem); } HashMap extensions = extractExtensionsFromLevel( elem ); return new NamedScope(props, userNamesToOverrides, extensions); } private static HashMap extractExtensionsFromLevel(Element elem) { HashMap out = new HashMap(); NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "extensions"); for (int i = 0, len = nl.getLength(); i < len; ++i) { Element extensionsElem = (Element) nl.item(i); out.putAll( extractPropertiesFromLevel( extensionsElem ) ); } return out; } private static HashMap extractPropertiesFromLevel(Element elem) { // System.err.println( "extractPropertiesFromLevel()" ); HashMap out = new HashMap(); try { NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "property"); int len = nl.getLength(); for (int i = 0; i < len; ++i) { Element propertyElem = (Element) nl.item(i); String propName = propertyElem.getAttribute("name"); if (propName != null && propName.length() > 0) { String propVal = DomParseUtils.allTextFromElement(propertyElem, true); out.put( propName, propVal ); //System.err.println( propName + " -> " + propVal ); } else logger.warning("Configuration XML contained property element without name attribute: " + LINESEP + propertyElem); } } catch (Exception e) { logger.log( MLevel.WARNING, "An exception occurred while reading config XML. " + "Some configuration information has probably been ignored.", e ); } return out; } private C3P0ConfigXmlUtils() {} }
./CrossVul/dataset_final_sorted/CWE-611/java/good_497_0
crossvul-java_data_good_1910_18
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.samsungtv.internal.service; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link SamsungTvUtils} provides some utilities for internal use. * * @author Pauli Anttila - Initial contribution */ @NonNullByDefault public class SamsungTvUtils { /** * Build {@link String} type {@link HashMap} from variable number of * {@link String}s. * * @param data * Variable number of {@link String} parameters which will be * added to hash map. */ public static HashMap<String, String> buildHashMap(String... data) { HashMap<String, String> result = new HashMap<>(); if (data.length % 2 != 0) { throw new IllegalArgumentException("Odd number of arguments"); } String key = null; Integer step = -1; for (String value : data) { step++; switch (step % 2) { case 0: if (value == null) { throw new IllegalArgumentException("Null key value"); } key = value; continue; case 1: if (key != null) { result.put(key, value); } break; } } return result; } /** * Build {@link Document} from {@link String} which contains XML content. * * @param xml * {@link String} which contains XML content. * @return {@link Document} or null if convert has failed. */ public static @Nullable Document loadXMLFromString(String xml) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); return builder.parse(is); } catch (ParserConfigurationException | SAXException | IOException e) { // Silently ignore exception and return null. } return null; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_18
crossvul-java_data_bad_1736_1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.milton.http.webdav; import io.milton.common.ReadingException; import io.milton.common.StreamUtils; import io.milton.common.WritingException; import java.io.ByteArrayInputStream; import org.apache.commons.io.output.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import javax.xml.namespace.QName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * * @author brad */ public class DefaultPropPatchParser implements PropPatchRequestParser { private final static Logger log = LoggerFactory.getLogger( DefaultPropPatchParser.class ); @Override public PropPatchParseResult getRequestedFields( InputStream in ) { log.debug( "getRequestedFields" ); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); StreamUtils.readTo( in, bout, false, true ); byte[] arr = bout.toByteArray(); return parseContent( arr ); } catch( SAXException ex ) { throw new RuntimeException( ex ); } catch( ReadingException ex ) { throw new RuntimeException( ex ); } catch( WritingException ex ) { throw new RuntimeException( ex ); } catch( IOException ex ) { throw new RuntimeException( ex ); } } private PropPatchParseResult parseContent( byte[] arr ) throws IOException, SAXException { if( arr.length > 0 ) { log.debug( "processing content" ); ByteArrayInputStream bin = new ByteArrayInputStream( arr ); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); PropPatchSaxHandler handler = new PropPatchSaxHandler(); reader.setContentHandler( handler ); reader.parse( new InputSource( bin ) ); log.debug( "toset: " + handler.getAttributesToSet().size()); return new PropPatchParseResult( handler.getAttributesToSet(), handler.getAttributesToRemove().keySet() ); } else { log.debug( "empty content" ); return new PropPatchParseResult( new HashMap<QName, String>(), new HashSet<QName>() ); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1736_1
crossvul-java_data_good_4290_2
/* * file: UnmarshalHelper.java * author: Jon Iles * copyright: (c) Packwood Software 2020 * date: 29/08/2020 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.common; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.UnmarshallerHandler; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; /** * Utility methods wrapping JAXB unmarshal. */ public final class UnmarshalHelper { /** * Unmarshal from an input stream. * * @param context JAXB context * @param stream input stream * @return Unmarshalled root node */ public static final Object unmarshal(JAXBContext context, InputStream stream) throws JAXBException, SAXException, ParserConfigurationException { return context.createUnmarshaller().unmarshal(new SAXSource(XmlReaderHelper.createXmlReader(), new InputSource(stream))); } /** * Unmarshall from an input stream and apply a filter. * * @param context JAXB context * @param stream input stream * @param filter XMLFilter instance * @return Unmarshalled root node */ public static final Object unmarshal(JAXBContext context, InputStream stream, XMLFilter filter) throws JAXBException, SAXException, ParserConfigurationException, IOException { return unmarshal(context, new InputSource(stream), filter, false); } /** * Unmarshall from an input source and apply a filter, optionally ignore validation errors. * * @param context JAXB context * @param source input source * @param filter XMLFilter instance * @param ignoreValidationErrors true if validation errors are ignored * @return Unmarshalled root node */ public static final Object unmarshal(JAXBContext context, InputSource source, XMLFilter filter, boolean ignoreValidationErrors) throws JAXBException, SAXException, ParserConfigurationException, IOException { Unmarshaller unmarshaller = context.createUnmarshaller(); if (ignoreValidationErrors) { unmarshaller.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { return true; } }); } UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); filter.setParent(XmlReaderHelper.createXmlReader()); filter.setContentHandler(unmarshallerHandler); filter.parse(source); return unmarshallerHandler.getResult(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4290_2
crossvul-java_data_good_1910_12
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.hpprinter.internal.api; import java.io.IOException; import java.io.StringReader; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpMethod; import org.openhab.binding.hpprinter.internal.api.HPServerResult.RequestStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link HPWebServerClient} is responsible for handling reading of data from the HP Embedded Web Server. * * @author Stewart Cossey - Initial contribution */ @NonNullByDefault public class HPWebServerClient { public static final int REQUEST_TIMEOUT_SEC = 10; private final Logger logger = LoggerFactory.getLogger(HPWebServerClient.class); private final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); private final HttpClient httpClient; private final String serverAddress; /** * Creates a new HP Web Server Client object. * * @param httpClient {HttpClient} The HttpClient to use for HTTP requests. * @param address The address for the Embedded Web Server. */ public HPWebServerClient(HttpClient httpClient, String address) { this.httpClient = httpClient; serverAddress = "http://" + address; logger.debug("Create printer connection {}", serverAddress); } /** * Gets the Status information from the Embedded Web Server. * * @return The status information. */ public HPServerResult<HPStatus> getStatus() { return fetchData(serverAddress + HPStatus.ENDPOINT, (HPStatus::new)); } public HPServerResult<HPProductUsageFeatures> getProductFeatures() { return fetchData(serverAddress + HPProductUsageFeatures.ENDPOINT, (HPProductUsageFeatures::new)); } public HPServerResult<HPFeatures> getProductUsageFeatures() { return fetchData(serverAddress + HPFeatures.ENDPOINT, (HPFeatures::new)); } public HPServerResult<HPScannerStatusFeatures> getScannerFeatures() { return fetchData(serverAddress + HPScannerStatusFeatures.ENDPOINT, (HPScannerStatusFeatures::new)); } /** * Gets the Usage information from the Embedded Web Server. * * @return The usage information. */ public HPServerResult<HPUsage> getUsage() { return fetchData(serverAddress + HPUsage.ENDPOINT, (HPUsage::new)); } public HPServerResult<HPScannerStatus> getScannerStatus() { return fetchData(serverAddress + HPScannerStatus.ENDPOINT, (HPScannerStatus::new)); } public HPServerResult<HPProperties> getProperties() { return fetchData(serverAddress + HPProperties.ENDPOINT, (HPProperties::new)); } private <T> HPServerResult<T> fetchData(String endpoint, Function<Document, T> function) { try { logger.trace("HTTP Client Load {}", endpoint); ContentResponse cr = httpClient.newRequest(endpoint).method(HttpMethod.GET) .timeout(REQUEST_TIMEOUT_SEC, TimeUnit.SECONDS).send(); String contentAsString = cr.getContentAsString(); logger.trace("HTTP Client Result {} Size {}", cr.getStatus(), contentAsString.length()); return new HPServerResult<>(function.apply(getDocument(contentAsString))); } catch (TimeoutException ex) { logger.trace("HTTP Client Timeout Exception {}", ex.getMessage()); return new HPServerResult<>(RequestStatus.TIMEOUT, ex.getMessage()); } catch (InterruptedException | ExecutionException | ParserConfigurationException | SAXException | IOException ex) { logger.trace("HTTP Client Exception {}", ex.getMessage()); return new HPServerResult<>(RequestStatus.ERROR, ex.getMessage()); } } private synchronized Document getDocument(String contentAsString) throws ParserConfigurationException, SAXException, IOException { // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource source = new InputSource(new StringReader(contentAsString)); return builder.parse(source); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_12
crossvul-java_data_good_4290_3
/* * file: XmlReaderHelper.java * author: Jon Iles * copyright: (c) Packwood Software 2020 * date: 29/08/2020 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.common; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * Utility methods for working with XmlReader. */ public final class XmlReaderHelper { /** * Create a new XmlReader instance. * * @return XmlReader instance */ public static final XMLReader createXmlReader() throws SAXException, ParserConfigurationException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setNamespaceAware(true); SAXParser saxParser = factory.newSAXParser(); return saxParser.getXMLReader(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4290_3
crossvul-java_data_good_1910_10
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.gce.internal.model; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.openhab.binding.gce.internal.handler.Ipx800EventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * This class takes care of interpreting the status.xml file * * @author Gaël L'hopital - Initial contribution */ @NonNullByDefault public class StatusFileInterpreter { private static final String URL_TEMPLATE = "http://%s/globalstatus.xml"; private final Logger logger = LoggerFactory.getLogger(StatusFileInterpreter.class); private final String hostname; private @Nullable Document doc; private final Ipx800EventListener listener; public static enum StatusEntry { VERSION, CONFIG_MAC; } public StatusFileInterpreter(String hostname, Ipx800EventListener listener) { this.hostname = hostname; this.listener = listener; } public void read() { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); String statusPage = HttpUtil.executeUrl("GET", String.format(URL_TEMPLATE, hostname), 5000); InputStream inputStream = new ByteArrayInputStream(statusPage.getBytes()); Document document = builder.parse(inputStream); document.getDocumentElement().normalize(); doc = document; pushDatas(); inputStream.close(); } catch (IOException | SAXException | ParserConfigurationException e) { logger.warn("Unable to read IPX800 status page : {}", e.getMessage()); doc = null; } } private void pushDatas() { Element root = getRoot(); if (root != null) { PortDefinition.asStream().forEach(portDefinition -> { List<Node> xmlNodes = getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName()); xmlNodes.forEach(xmlNode -> { String sPortNum = xmlNode.getNodeName().replace(portDefinition.getNodeName(), ""); int portNum = Integer.parseInt(sPortNum) + 1; double value = Double.parseDouble(xmlNode.getTextContent().replace("dn", "1").replace("up", "0")); listener.dataReceived(String.format("%s%d", portDefinition.getPortName(), portNum), value); }); }); } } public String getElement(StatusEntry entry) { Element root = getRoot(); if (root != null) { return root.getElementsByTagName(entry.name().toLowerCase()).item(0).getTextContent(); } else { return ""; } } private List<Node> getMatchingNodes(NodeList nodeList, String criteria) { return IntStream.range(0, nodeList.getLength()).boxed().map(nodeList::item) .filter(node -> node.getNodeName().startsWith(criteria)) .sorted(Comparator.comparing(o -> o.getNodeName())).collect(Collectors.toList()); } public int getMaxNumberofNodeType(PortDefinition portDefinition) { Element root = getRoot(); if (root != null) { List<Node> filteredNodes = getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName()); return filteredNodes.size(); } return 0; } private @Nullable Element getRoot() { if (doc == null) { read(); } if (doc != null) { return doc.getDocumentElement(); } return null; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_10
crossvul-java_data_good_4290_4
/* * file: ConceptDrawProjectReader.java * author: Jon Iles * copyright: (c) Packwood Software 2018 * date: 9 July 2018 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.conceptdraw; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import net.sf.mpxj.DateRange; import net.sf.mpxj.Duration; import net.sf.mpxj.EventManager; import net.sf.mpxj.MPXJException; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectConfig; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.ProjectProperties; import net.sf.mpxj.Rate; import net.sf.mpxj.Relation; import net.sf.mpxj.RelationType; import net.sf.mpxj.Resource; import net.sf.mpxj.ResourceAssignment; import net.sf.mpxj.Task; import net.sf.mpxj.TimeUnit; import net.sf.mpxj.common.AlphanumComparator; import net.sf.mpxj.common.UnmarshalHelper; import net.sf.mpxj.conceptdraw.schema.Document; import net.sf.mpxj.conceptdraw.schema.Document.Calendars.Calendar; import net.sf.mpxj.conceptdraw.schema.Document.Calendars.Calendar.ExceptedDays.ExceptedDay; import net.sf.mpxj.conceptdraw.schema.Document.Calendars.Calendar.WeekDays.WeekDay; import net.sf.mpxj.conceptdraw.schema.Document.Links.Link; import net.sf.mpxj.conceptdraw.schema.Document.Projects.Project; import net.sf.mpxj.conceptdraw.schema.Document.WorkspaceProperties; import net.sf.mpxj.listener.ProjectListener; import net.sf.mpxj.reader.AbstractProjectReader; /** * This class creates a new ProjectFile instance by reading a ConceptDraw Project file. */ public final class ConceptDrawProjectReader extends AbstractProjectReader { /** * {@inheritDoc} */ @Override public void addProjectListener(ProjectListener listener) { if (m_projectListeners == null) { m_projectListeners = new ArrayList<>(); } m_projectListeners.add(listener); } /** * {@inheritDoc} */ @Override public ProjectFile read(InputStream stream) throws MPXJException { try { if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_calendarMap = new HashMap<>(); m_taskIdMap = new HashMap<>(); ProjectConfig config = m_projectFile.getProjectConfig(); config.setAutoResourceUniqueID(false); config.setAutoResourceID(false); m_projectFile.getProjectProperties().setFileApplication("ConceptDraw PROJECT"); m_projectFile.getProjectProperties().setFileType("CDP"); m_eventManager.addProjectListeners(m_projectListeners); Document cdp = (Document) UnmarshalHelper.unmarshal(CONTEXT, stream, new NamespaceFilter()); readProjectProperties(cdp); readCalendars(cdp); readResources(cdp); readTasks(cdp); readRelationships(cdp); // // Ensure that the unique ID counters are correct // config.updateUniqueCounters(); return m_projectFile; } catch (ParserConfigurationException ex) { throw new MPXJException("Failed to parse file", ex); } catch (JAXBException ex) { throw new MPXJException("Failed to parse file", ex); } catch (SAXException ex) { throw new MPXJException("Failed to parse file", ex); } catch (IOException ex) { throw new MPXJException("Failed to parse file", ex); } finally { m_projectFile = null; m_eventManager = null; m_projectListeners = null; m_calendarMap = null; m_taskIdMap = null; } } /** * Extracts project properties from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readProjectProperties(Document cdp) { WorkspaceProperties props = cdp.getWorkspaceProperties(); ProjectProperties mpxjProps = m_projectFile.getProjectProperties(); mpxjProps.setSymbolPosition(props.getCurrencyPosition()); mpxjProps.setCurrencyDigits(props.getCurrencyDigits()); mpxjProps.setCurrencySymbol(props.getCurrencySymbol()); mpxjProps.setDaysPerMonth(props.getDaysPerMonth()); mpxjProps.setMinutesPerDay(props.getHoursPerDay()); mpxjProps.setMinutesPerWeek(props.getHoursPerWeek()); m_workHoursPerDay = mpxjProps.getMinutesPerDay().doubleValue() / 60.0; } /** * Extracts calendar data from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readCalendars(Document cdp) { for (Calendar calendar : cdp.getCalendars().getCalendar()) { readCalendar(calendar); } for (Calendar calendar : cdp.getCalendars().getCalendar()) { ProjectCalendar child = m_calendarMap.get(calendar.getID()); ProjectCalendar parent = m_calendarMap.get(calendar.getBaseCalendarID()); if (parent == null) { m_projectFile.setDefaultCalendar(child); } else { child.setParent(parent); } } } /** * Read a calendar. * * @param calendar ConceptDraw PROJECT calendar */ private void readCalendar(Calendar calendar) { ProjectCalendar mpxjCalendar = m_projectFile.addCalendar(); mpxjCalendar.setName(calendar.getName()); m_calendarMap.put(calendar.getID(), mpxjCalendar); for (WeekDay day : calendar.getWeekDays().getWeekDay()) { readWeekDay(mpxjCalendar, day); } for (ExceptedDay day : calendar.getExceptedDays().getExceptedDay()) { readExceptionDay(mpxjCalendar, day); } } /** * Reads a single day for a calendar. * * @param mpxjCalendar ProjectCalendar instance * @param day ConceptDraw PROJECT week day */ private void readWeekDay(ProjectCalendar mpxjCalendar, WeekDay day) { if (day.isIsDayWorking()) { ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day.getDay()); for (Document.Calendars.Calendar.WeekDays.WeekDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod()) { hours.addRange(new DateRange(period.getFrom(), period.getTo())); } } } /** * Read an exception day for a calendar. * * @param mpxjCalendar ProjectCalendar instance * @param day ConceptDraw PROJECT exception day */ private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day) { ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate()); if (day.isIsDayWorking()) { for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod()) { mpxjException.addRange(new DateRange(period.getFrom(), period.getTo())); } } } /** * Reads resource data from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readResources(Document cdp) { for (Document.Resources.Resource resource : cdp.getResources().getResource()) { readResource(resource); } } /** * Reads a single resource from a ConceptDraw PROJECT file. * * @param resource ConceptDraw PROJECT resource */ private void readResource(Document.Resources.Resource resource) { Resource mpxjResource = m_projectFile.addResource(); mpxjResource.setName(resource.getName()); mpxjResource.setResourceCalendar(m_calendarMap.get(resource.getCalendarID())); mpxjResource.setStandardRate(new Rate(resource.getCost(), resource.getCostTimeUnit())); mpxjResource.setEmailAddress(resource.getEMail()); mpxjResource.setGroup(resource.getGroup()); //resource.getHyperlinks() mpxjResource.setUniqueID(resource.getID()); //resource.getMarkerID() mpxjResource.setNotes(resource.getNote()); mpxjResource.setID(Integer.valueOf(resource.getOutlineNumber())); //resource.getStyleProject() mpxjResource.setType(resource.getSubType() == null ? resource.getType() : resource.getSubType()); } /** * Read the projects from a ConceptDraw PROJECT file as top level tasks. * * @param cdp ConceptDraw PROJECT file */ private void readTasks(Document cdp) { // // Sort the projects into the correct order // List<Project> projects = new ArrayList<>(cdp.getProjects().getProject()); final AlphanumComparator comparator = new AlphanumComparator(); Collections.sort(projects, new Comparator<Project>() { @Override public int compare(Project o1, Project o2) { return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber()); } }); for (Project project : cdp.getProjects().getProject()) { readProject(project); } } /** * Read a project from a ConceptDraw PROJECT file. * * @param project ConceptDraw PROJECT project */ private void readProject(Project project) { Task mpxjTask = m_projectFile.addTask(); //project.getAuthor() mpxjTask.setBaselineCost(project.getBaselineCost()); mpxjTask.setBaselineFinish(project.getBaselineFinishDate()); mpxjTask.setBaselineStart(project.getBaselineStartDate()); //project.getBudget(); //project.getCompany() mpxjTask.setFinish(project.getFinishDate()); //project.getGoal() //project.getHyperlinks() //project.getMarkerID() mpxjTask.setName(project.getName()); mpxjTask.setNotes(project.getNote()); mpxjTask.setPriority(project.getPriority()); // project.getSite() mpxjTask.setStart(project.getStartDate()); // project.getStyleProject() // project.getTask() // project.getTimeScale() // project.getViewProperties() String projectIdentifier = project.getID().toString(); mpxjTask.setGUID(UUID.nameUUIDFromBytes(projectIdentifier.getBytes())); // // Sort the tasks into the correct order // List<Document.Projects.Project.Task> tasks = new ArrayList<>(project.getTask()); final AlphanumComparator comparator = new AlphanumComparator(); Collections.sort(tasks, new Comparator<Document.Projects.Project.Task>() { @Override public int compare(Document.Projects.Project.Task o1, Document.Projects.Project.Task o2) { return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber()); } }); Map<String, Task> map = new HashMap<>(); map.put("", mpxjTask); for (Document.Projects.Project.Task task : tasks) { readTask(projectIdentifier, map, task); } } /** * Read a task from a ConceptDraw PROJECT file. * * @param projectIdentifier parent project identifier * @param map outline number to task map * @param task ConceptDraw PROJECT task */ private void readTask(String projectIdentifier, Map<String, Task> map, Document.Projects.Project.Task task) { Task parentTask = map.get(getParentOutlineNumber(task.getOutlineNumber())); Task mpxjTask = parentTask.addTask(); TimeUnit units = task.getBaseDurationTimeUnit(); mpxjTask.setCost(task.getActualCost()); mpxjTask.setDuration(getDuration(units, task.getActualDuration())); mpxjTask.setFinish(task.getActualFinishDate()); mpxjTask.setStart(task.getActualStartDate()); mpxjTask.setBaselineDuration(getDuration(units, task.getBaseDuration())); mpxjTask.setBaselineFinish(task.getBaseFinishDate()); mpxjTask.setBaselineCost(task.getBaselineCost()); // task.getBaselineFinishDate() // task.getBaselineFinishTemplateOffset() // task.getBaselineStartDate() // task.getBaselineStartTemplateOffset() mpxjTask.setBaselineStart(task.getBaseStartDate()); // task.getCallouts() mpxjTask.setPercentageComplete(task.getComplete()); mpxjTask.setDeadline(task.getDeadlineDate()); // task.getDeadlineTemplateOffset() // task.getHyperlinks() // task.getMarkerID() mpxjTask.setName(task.getName()); mpxjTask.setNotes(task.getNote()); mpxjTask.setPriority(task.getPriority()); // task.getRecalcBase1() // task.getRecalcBase2() mpxjTask.setType(task.getSchedulingType()); // task.getStyleProject() // task.getTemplateOffset() // task.getValidatedByProject() if (task.isIsMilestone()) { mpxjTask.setMilestone(true); mpxjTask.setDuration(Duration.getInstance(0, TimeUnit.HOURS)); mpxjTask.setBaselineDuration(Duration.getInstance(0, TimeUnit.HOURS)); } String taskIdentifier = projectIdentifier + "." + task.getID(); m_taskIdMap.put(task.getID(), mpxjTask); mpxjTask.setGUID(UUID.nameUUIDFromBytes(taskIdentifier.getBytes())); map.put(task.getOutlineNumber(), mpxjTask); for (Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment : task.getResourceAssignments().getResourceAssignment()) { readResourceAssignment(mpxjTask, assignment); } } /** * Read resource assignments. * * @param task Parent task * @param assignment ConceptDraw PROJECT resource assignment */ private void readResourceAssignment(Task task, Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment) { Resource resource = m_projectFile.getResourceByUniqueID(assignment.getResourceID()); if (resource != null) { ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource); mpxjAssignment.setUniqueID(assignment.getID()); mpxjAssignment.setWork(Duration.getInstance(assignment.getManHour().doubleValue() * m_workHoursPerDay, TimeUnit.HOURS)); mpxjAssignment.setUnits(assignment.getUse()); } } /** * Read all task relationships from a ConceptDraw PROJECT file. * * @param cdp ConceptDraw PROJECT file */ private void readRelationships(Document cdp) { for (Link link : cdp.getLinks().getLink()) { readRelationship(link); } } /** * Read a task relationship. * * @param link ConceptDraw PROJECT task link */ private void readRelationship(Link link) { Task sourceTask = m_taskIdMap.get(link.getSourceTaskID()); Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID()); if (sourceTask != null && destinationTask != null) { Duration lag = getDuration(link.getLagUnit(), link.getLag()); RelationType type = link.getType(); Relation relation = destinationTask.addPredecessor(sourceTask, type, lag); relation.setUniqueID(link.getID()); } } /** * Read a duration. * * @param units duration units * @param duration duration value * @return Duration instance */ private Duration getDuration(TimeUnit units, Double duration) { Duration result = null; if (duration != null) { double durationValue = duration.doubleValue() * 100.0; switch (units) { case MINUTES: { durationValue *= MINUTES_PER_DAY; break; } case HOURS: { durationValue *= HOURS_PER_DAY; break; } case DAYS: { durationValue *= 3.0; break; } case WEEKS: { durationValue *= 0.6; break; } case MONTHS: { durationValue *= 0.15; break; } default: { throw new IllegalArgumentException("Unsupported time units " + units); } } durationValue = Math.round(durationValue) / 100.0; result = Duration.getInstance(durationValue, units); } return result; } /** * Return the parent outline number, or an empty string if * we have a root task. * * @param outlineNumber child outline number * @return parent outline number */ private String getParentOutlineNumber(String outlineNumber) { String result; int index = outlineNumber.lastIndexOf('.'); if (index == -1) { result = ""; } else { result = outlineNumber.substring(0, index); } return result; } private ProjectFile m_projectFile; private EventManager m_eventManager; private List<ProjectListener> m_projectListeners; private Map<Integer, ProjectCalendar> m_calendarMap; private Map<Integer, Task> m_taskIdMap; private double m_workHoursPerDay; private static final int HOURS_PER_DAY = 24; private static final int MINUTES_PER_DAY = HOURS_PER_DAY * 60; /** * Cached context to minimise construction cost. */ private static JAXBContext CONTEXT; /** * Note any error occurring during context construction. */ private static JAXBException CONTEXT_EXCEPTION; static { try { // // JAXB RI property to speed up construction // System.setProperty("com.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot", "true"); // // Construct the context // CONTEXT = JAXBContext.newInstance("net.sf.mpxj.conceptdraw.schema", ConceptDrawProjectReader.class.getClassLoader()); } catch (JAXBException ex) { CONTEXT_EXCEPTION = ex; CONTEXT = null; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4290_4