Пример #1
0
  public void init() throws javax.servlet.ServletException {
    super.init();

    org.slf4j.Logger logServerStartup = org.slf4j.LoggerFactory.getLogger("serverStartup");
    logServerStartup.info(
        getClass().getName() + " initialization start - " + UsageLog.setupNonRequestContext());

    this.ascLimit = ThreddsConfig.getInt("Opendap.ascLimit", ascLimit);
    this.binLimit = ThreddsConfig.getInt("Opendap.binLimit", binLimit);

    this.odapVersionString = ThreddsConfig.get("Opendap.serverVersion", odapVersionString);
    logServerStartup.info(
        getClass().getName()
            + " version= "
            + odapVersionString
            + " ascLimit = "
            + ascLimit
            + " binLimit = "
            + binLimit);

    // debugging actions
    makeDebugActions();

    logServerStartup.info(
        getClass().getName()
            + " initialization done - "
            + UsageLog.closingMessageNonRequestContext());
  }
Пример #2
0
  public void create(Project project) {
    Assert.isNull(
        projectService.findProject(project.getName()),
        "project  [" + project.getName() + "] has exist");
    MongoTemplate template = project.fetchMongoTemplate();
    Assert.notNull(template, "mongo uri is not access");
    Assert.notNull(template.getDb(), "mongo uri is not access");
    Assert.isTrue(
        project.fetchMongoTemplate().collectionExists(project.getLogCollection()),
        " [" + project.getLogCollection() + "] 日志表不存在");
    try {
      List<Task> taskList = Lists.newArrayList();
      logger.debug("init task count:{}", project.getTasks().size());
      for (Task _task : project.getTasks()) {

        Task task = getTemplateTask(_task);
        Task tempTask = renderTemplateTask(task, project);
        if (tempTask != null) taskList.add(tempTask);
      }
      project.setTasks(taskList);
    } catch (Exception e) {
      logger.error("", e);
      throw new IllegalArgumentException("自动添加监控脚本错误:" + e.getMessage());
    }
    projectService.saveProject(project);
  }
Пример #3
0
  /**
   * Looks for the parameter table which matches the center, subcenter and table version from the
   * tables array. If this is the first time asking for this table, then the parameters for this
   * table have not been read in yet, so this is done as well.
   *
   * @param center - integer from PDS octet 5, representing Center.
   * @param subcenter - integer from PDS octet 26, representing Subcenter
   * @param tableVersion - integer from PDS octet 4, representing Parameter Table Version
   * @return GribPDSParamTable matching center, subcenter, and number
   * @throws NotSupportedException no table found
   */
  public static GribPDSParamTable getParameterTable(int center, int subcenter, int tableVersion)
      throws NotSupportedException {

    String key = center + "_" + subcenter + "_" + tableVersion;
    if (center == -1) { // non existent table
      logger.error("GribPDSParamTable: non existent table for center, subcenter, table = " + key);
      return null;
    }

    GribPDSParamTable table = tableMap.get(key);
    if (table != null) return table;

    table = readParameterTable(center, subcenter, tableVersion, true);

    if (table == null) {
      logger.error("GribPDSParamTable: cannot find table for center, subcenter, table " + key);
      throw new NotSupportedException(
          "Could not find a table entry for GRIB file with center: "
              + center
              + " subCenter: "
              + subcenter
              + " number: "
              + tableVersion);
    }

    tableMap.put(key, table);
    return table;
  }
 private boolean verifySignature(
     Principal principal,
     byte[] dataToSign,
     String signature,
     ContainerRequestContext requestContext) {
   try {
     final byte[] signatureData = StringUtils.base64Decode(signature);
     if (logger.isDebugEnabled()) {
       logger.debug(
           "Verifying REST request - principal: "
               + principal
               + " data: "
               + fingerprint(dataToSign)
               + " signature: "
               + fingerprint(signatureData));
     }
     SignatureVerificationKey key = findVerificationKey(principal);
     if (key == null) {
       return false;
     }
     try {
       cryptoEngine.verifySignature(key, digestAlgorithm, dataToSign, signatureData);
       return true;
     } catch (InvalidKeyException e) {
       logServerError(
           "Invalid key found while verifying signature: " + e.getMessage(), e, requestContext);
       throw new WebApplicationException(INTERNAL_SERVER_ERROR);
     } catch (SignatureException e) {
       return false;
     }
   } catch (BackendAccessException e) {
     logServerError("Unexpected BackendAccessException: " + e.getMessage(), e, requestContext);
     throw new WebApplicationException(INTERNAL_SERVER_ERROR);
   }
 }
Пример #5
0
 /**
  * Method to get a resource. href:
  * http://howtodoinjava.com/spring/spring-core/how-to-load-external-resources-files-into-spring-context/
  *
  * @param fileNameOrUri the {@link Object} to convert to {@link Resource} must be a {@link
  *     File},{@link URI},{@link URL},{@link Path},{@link String},{@link InputStream}
  * @param clazz the {@link Class} for reference to the resource folder.
  * @param classLoader the {@link ClassLoader} for load the resources.
  * @return the {@link Resource}.
  */
 private static Resource getResourceSpringAsResource(
     Object fileNameOrUri, @Nullable Class<?> clazz, @Nullable ClassLoader classLoader) {
   try {
     Resource yourfile;
     // if File
     if (fileNameOrUri instanceof File && ((File) fileNameOrUri).exists()) {
       yourfile = new org.springframework.core.io.FileSystemResource(((File) fileNameOrUri));
     }
     // if URL
     else if (org.springframework.util.ResourceUtils.isUrl(String.valueOf(fileNameOrUri))
         || fileNameOrUri instanceof URL) {
       if (fileNameOrUri instanceof URL) {
         yourfile = new org.springframework.core.io.UrlResource((URL) fileNameOrUri);
       } else {
         yourfile = new org.springframework.core.io.UrlResource(String.valueOf(fileNameOrUri));
       }
       // if Path or URI
     } else if (fileNameOrUri instanceof Path || fileNameOrUri instanceof URI) {
       if (fileNameOrUri instanceof Path && Files.exists((Path) fileNameOrUri)) {
         yourfile = new org.springframework.core.io.PathResource((Path) fileNameOrUri);
       } else {
         yourfile = new org.springframework.core.io.PathResource((URI) fileNameOrUri);
       }
       /*  }else if(fileNameOrUri instanceof Class){
       org.springframework.core.io.ClassRelativeResourceLoader relativeResourceLoader =
               new org.springframework.core.io.ClassRelativeResourceLoader((Class<?>) fileNameOrUri);
       yourfile = relativeResourceLoader.getResource("")
       */
       // if InputStream
     } else if (fileNameOrUri instanceof InputStream) {
       yourfile = new org.springframework.core.io.InputStreamResource((InputStream) fileNameOrUri);
     } else if (fileNameOrUri instanceof byte[]) {
       yourfile = new org.springframework.core.io.ByteArrayResource((byte[]) fileNameOrUri);
       // if String path toa file or String of a URI
     } else if (fileNameOrUri instanceof String) {
       if (classLoader != null) {
         yourfile =
             new org.springframework.core.io.ClassPathResource(
                 String.valueOf(fileNameOrUri), classLoader);
       } else if (clazz != null) {
         yourfile =
             new org.springframework.core.io.ClassPathResource(
                 String.valueOf(fileNameOrUri), clazz);
       } else {
         yourfile =
             new org.springframework.core.io.ClassPathResource(String.valueOf(fileNameOrUri));
       }
     } else {
       logger.error(
           "Can't load the resource for the Object with Class:"
               + fileNameOrUri.getClass().getName());
       return null;
     }
     return yourfile;
   } catch (IOException e) {
     logger.error(e.getMessage(), e);
     return null;
   }
 }
Пример #6
0
  public boolean load(String abspath) {
    abspath = abspath.replace('\\', '/');
    File rcFile = new File(abspath);
    if (!rcFile.exists() || !rcFile.canRead()) {
      return false;
    }
    if (showlog) log.debug("Loading rc file: " + abspath);
    try (BufferedReader rdr =
        new BufferedReader(new InputStreamReader(new FileInputStream(rcFile), CDM.UTF8))) {
      for (int lineno = 1; ; lineno++) {
        URL url = null;
        String line = rdr.readLine();
        if (line == null) break;
        // trim leading blanks
        line = line.trim();
        if (line.length() == 0) continue; // empty line
        if (line.charAt(0) == '#') continue; // check for comment
        // parse the line
        if (line.charAt(0) == LTAG) {
          int rindex = line.indexOf(RTAG);
          if (rindex < 0) return false;
          if (showlog) log.error("Malformed [url] at " + abspath + "." + lineno);
          String surl = line.substring(1, rindex);
          try {
            url = new URL(surl);
          } catch (MalformedURLException mue) {
            if (showlog) log.error("Malformed [url] at " + abspath + "." + lineno);
          }
          line = line.substring(rindex + 1);
          // trim again
          line = line.trim();
        }
        // Get the key,value part
        String[] pieces = line.split("\\s*=\\s*");
        assert (pieces.length == 1 || pieces.length == 2);
        // Create the triple
        String value = "1";
        if (pieces.length == 2) value = pieces[1].trim();
        Triple triple = new Triple(pieces[0].trim(), value, url);
        List<Triple> list = triplestore.get(triple.key);
        if (list == null) list = new ArrayList<Triple>();
        Triple prev = addtriple(list, triple);
        triplestore.put(triple.key, list);
      }

    } catch (FileNotFoundException fe) {
      if (showlog) log.debug("Loading rc file: " + abspath);
      return false;

    } catch (IOException ioe) {
      if (showlog) log.error("File " + abspath + ": IO exception: " + ioe.getMessage());
      return false;
    }
    return true;
  }
Пример #7
0
 /**
  * Utility to save the string content to a file
  *
  * @param filename String
  * @param content
  */
 public static void saveFileContent(String filename, String content) {
   try (OutputStreamWriter w =
       new OutputStreamWriter(new FileOutputStream(filename), "ISO-8859-1")) {
     w.write(content);
     w.flush();
   } catch (IOException ioe) {
     logger.error("", ioe);
   } catch (Exception ex) {
     logger.error("", ex);
   }
 }
Пример #8
0
 private void checkSize(ServerDDS dds, boolean isAscii) throws Exception {
   long size = computeSize(dds, isAscii);
   // System.err.printf("total (constrained) size=%s\n", size);
   log.debug("total (constrained) size={}", size);
   double dsize = size / (1000 * 1000);
   double maxSize = isAscii ? ascLimit : binLimit; // Mbytes
   if (dsize > maxSize) {
     log.info("Reject request size = {} Mbytes", dsize);
     throw new UnsupportedOperationException(
         "Request too big=" + dsize + " Mbytes, max=" + maxSize);
   }
 }
Пример #9
0
  // any time the server needs access to the dataset, it gets a "GuardedDataset" which allows us to
  // add caching
  // optionally, a session may be established, which allows us to reserve the dataset for that
  // session.
  protected GuardedDataset getDataset(ReqState preq) throws Exception {
    HttpServletRequest req = preq.getRequest();
    String reqPath = preq.getDataSet();

    // see if the client wants sessions
    boolean acceptSession = false;
    String s = req.getHeader("X-Accept-Session");
    if (s != null && s.equalsIgnoreCase("true") && allowSessions) acceptSession = true;

    HttpSession session = null;
    if (acceptSession) {
      // see if theres already a session established, create one if not
      session = req.getSession();
      if (!session.isNew()) {
        GuardedDataset gdataset = (GuardedDataset) session.getAttribute(reqPath);
        if (null != gdataset) {
          if (debugSession)
            System.out.printf(" found gdataset %s in session %s %n", reqPath, session.getId());
          if (log.isDebugEnabled())
            log.debug(" found gdataset " + gdataset + " in session " + session.getId());
          return gdataset;
        }
      }
    }

    NetcdfFile ncd = DatasetHandler.getNetcdfFile(req, preq.getResponse(), reqPath);
    if (null == ncd) return null;

    GuardedDataset gdataset = new GuardedDatasetCacheAndClone(reqPath, ncd, acceptSession);
    // GuardedDataset gdataset = new GuardedDatasetImpl(reqPath, ncd, acceptSession);

    if (acceptSession) {
      String cookiePath = req.getRequestURI();
      String suffix = "." + preq.getRequestSuffix();
      if (cookiePath.endsWith(suffix)) // snip off the suffix
      cookiePath = cookiePath.substring(0, cookiePath.length() - suffix.length());
      session.setAttribute(reqPath, gdataset);
      session.setAttribute(CookieFilter.SESSION_PATH, cookiePath);
      // session.setAttribute("dataset", ncd.getLocation());  // for UsageValve
      // session.setMaxInactiveInterval(30); // 30 second timeout !!
      if (debugSession)
        System.out.printf(
            " added gdataset %s in session %s cookiePath %s %n",
            reqPath, session.getId(), cookiePath);
      if (log.isDebugEnabled())
        log.debug(" added gdataset " + gdataset + " in session " + session.getId());
    } /* else {
        session = req.getSession();
        session.setAttribute("dataset", ncd.getLocation()); // for UsageValve
      } */

    return gdataset;
  }
Пример #10
0
  /**
   * Send given content string as the HTTP response.
   *
   * @param contents the string to return as the HTTP response.
   * @param res the HttpServletResponse
   * @throws IOException if an I/O error occurs while writing the response.
   */
  public static void returnString(String contents, HttpServletResponse res) throws IOException {

    try {
      ServletOutputStream out = res.getOutputStream();
      IO.copy(new ByteArrayInputStream(contents.getBytes()), out);
      log.info(
          UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contents.length()));
    } catch (IOException e) {
      log.error(" IOException sending string: ", e);
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending string: " + e.getMessage());
    }
  }
Пример #11
0
  /**
   * Write a file to the response stream. Handles Range requests.
   *
   * @param servlet called from here
   * @param req the request
   * @param res the response
   * @param file to serve
   * @param contentType content type, if null, will try to guess
   * @throws IOException on write error
   */
  public static void returnFile(
      HttpServlet servlet,
      HttpServletRequest req,
      HttpServletResponse res,
      File file,
      String contentType)
      throws IOException {

    // No file, nothing to view
    if (file == null) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // check that it exists
    if (!file.exists()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // not a directory
    if (!file.isFile()) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, 0));
      res.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    // Set the type of the file
    String filename = file.getPath();
    if (null == contentType) {
      if (filename.endsWith(".html")) contentType = "text/html; charset=iso-8859-1";
      else if (filename.endsWith(".xml")) contentType = "text/xml; charset=iso-8859-1";
      else if (filename.endsWith(".txt") || (filename.endsWith(".log"))) contentType = CONTENT_TEXT;
      else if (filename.indexOf(".log.") > 0) contentType = CONTENT_TEXT;
      else if (filename.endsWith(".nc")) contentType = "application/x-netcdf";
      else contentType = servlet.getServletContext().getMimeType(filename);

      if (contentType == null) contentType = "application/octet-stream";
    }

    returnFile(req, res, file, contentType);
  }
Пример #12
0
  public void createSelf() {
    Project project = new Project();
    project.setAlias("闪电狗");
    project.setName("flash_dog");
    setMongoInfoByLog4j(project);

    if (projectService.findProject(project.getName()) == null) {
      logger.debug("try create a monitor project for flash-dog {}", project);
      project.setTasks(initTasks);
      create(project);

    } else {
      logger.debug("projectName={} has exist ,skip create ", project.getName());
    }
  }
Пример #13
0
  public static boolean saveFile(
      HttpServlet servlet,
      String contentPath,
      String path,
      HttpServletRequest req,
      HttpServletResponse res) {

    // @todo Need to use logServerAccess() below here.
    boolean debugRequest = Debug.isSet("SaveFile");
    if (debugRequest) log.debug(" saveFile(): path= " + path);

    String filename = contentPath + path; // absolute path
    File want = new File(filename);

    // backup current version if it exists
    int version = getBackupVersion(want.getParent(), want.getName());
    String fileSave = filename + "~" + version;
    File file = new File(filename);
    if (file.exists()) {
      try {
        IO.copyFile(filename, fileSave);
      } catch (IOException e) {
        log.error(
            "saveFile(): Unable to save copy of file "
                + filename
                + " to "
                + fileSave
                + "\n"
                + e.getMessage());
        return false;
      }
    }

    // save new file
    try {
      OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
      IO.copy(req.getInputStream(), out);
      out.close();
      if (debugRequest) log.debug("saveFile(): ok= " + filename);
      res.setStatus(HttpServletResponse.SC_CREATED);
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_CREATED, -1));
      return true;
    } catch (IOException e) {
      log.error(
          "saveFile(): Unable to PUT file " + filename + " to " + fileSave + "\n" + e.getMessage());
      return false;
    }
  }
Пример #14
0
  private void initRSTA(String syntaxstyle) {

    rsTextArea.setCodeFoldingEnabled(true);
    rsTextArea.setAntiAliasingEnabled(true);
    // rsTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
    rsTextArea.setSyntaxEditingStyle(syntaxstyle);

    rTextScrollPane1.setFoldIndicatorEnabled(true);
    rTextScrollPane1.setLineNumbersEnabled(true);

    // Create a toolbar with searching options.
    nextButton.setActionCommand("FindNext");
    nextButton.addActionListener(this);
    searchField.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            nextButton.doClick(0);
          }
        });
    prevButton.setActionCommand("FindPrev");
    prevButton.addActionListener(this);

    try {
      //           Theme theme =
      // Theme.load(getClass().getResourceAsStream("/jeplus/gui/themes/eclipse.xml"));
      Theme theme = Theme.load(new FileInputStream("RSyntaxTheme.xml"));
      theme.apply(rsTextArea);
    } catch (IOException ioe) { // Never happens
      logger.error("Failed to apply theme from RSyntaxTheme.xml. Default is used.", ioe);
    }
    setFont(rsTextArea, rsTextArea.getFont().deriveFont(13f));
  }
Пример #15
0
 /**
  * Method use OpenCsv Library for
  *
  * @param fileInputCsv the File CSV to parse.
  * @param separator the char separator.
  * @return the List of Bean parsed from the CSV file.
  */
 public static List<String[]> parseCSVFileAsList(File fileInputCsv, char separator) {
   try {
     List<String[]> records;
     // read all lines at once
     try ( // create CSVReader object
     CSVReader reader = new CSVReader(new FileReader(fileInputCsv), separator)) {
       // read all lines at once
       records = reader.readAll();
       Iterator<String[]> iterator = records.iterator();
       records.clear();
       // skip header row
       iterator.next();
       while (iterator.hasNext()) {
         String[] record = iterator.next();
         records.add(record);
       }
     }
     return records;
   } catch (IOException e) {
     logger.error(
         "Can't parse the CSV file:" + fileInputCsv.getAbsolutePath() + " -> " + e.getMessage(),
         e);
     return new ArrayList<>();
   }
 }
Пример #16
0
 /**
  * _more_
  *
  * @param aTableList _more_
  * @param aTables _more_
  * @return Was read successful
  * @throws IOException On badness
  */
 private static boolean readTableEntries(String aTableList, ArrayList<GribPDSParamTable> aTables)
     throws IOException {
   InputStream inputStream = GribResourceReader.getInputStream(aTableList);
   if (inputStream == null) {
     logger.debug("Could not open table file:" + aTableList);
     return false;
   }
   return readTableEntries(inputStream, aTableList, aTables);
 }
Пример #17
0
 public static File getResourceSpringAsFile(String pathRelativeToFileOnResourceFolder) {
   try {
     //noinspection ConstantConditions
     return getResourceSpringAsResource(pathRelativeToFileOnResourceFolder, null, null).getFile();
   } catch (IOException e) {
     logger.error(e.getMessage(), e);
     return null;
   }
 }
Пример #18
0
 /**
  * Utility to load content of a file into a String object
  *
  * @param filename String
  * @return String
  */
 public static String getFileContent(String filename) {
   String content = null;
   try (BufferedReader r =
       new BufferedReader(new InputStreamReader(new FileInputStream(filename), "ISO-8859-1"))) {
     String line = r.readLine();
     StringBuilder buf = new StringBuilder();
     while (line != null) {
       buf.append(line).append('\n');
       line = r.readLine();
     }
     content = buf.toString();
   } catch (IOException ioe) {
     logger.error("", ioe);
   } catch (Exception ex) {
     logger.error("", ex);
   }
   return content;
 }
Пример #19
0
  /**
   * Write a file to the response stream.
   *
   * @param servlet called from here
   * @param contentPath file root path
   * @param path file path reletive to the root
   * @param req the request
   * @param res the response
   * @param contentType content type, or null
   * @throws IOException on write error
   */
  public static void returnFile(
      HttpServlet servlet,
      String contentPath,
      String path,
      HttpServletRequest req,
      HttpServletResponse res,
      String contentType)
      throws IOException {

    String filename = ServletUtil.formFilename(contentPath, path);

    log.debug("returnFile(): returning file <" + filename + ">.");
    // No file, nothing to view
    if (filename == null) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0));
      res.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // dontallow ..
    if (filename.indexOf("..") != -1) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_FORBIDDEN, 0));
      res.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    // dont allow access to WEB-INF or META-INF
    String upper = filename.toUpperCase();
    if (upper.indexOf("WEB-INF") != -1 || upper.indexOf("META-INF") != -1) {
      log.info(
          "returnFile(): "
              + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_FORBIDDEN, 0));
      res.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }

    returnFile(servlet, req, res, new File(filename), contentType);
  }
Пример #20
0
  /**
   * Forward this request to the CatalogServices servlet ("/catalog.html").
   *
   * @param req request
   * @param res response
   * @throws IOException on IO error
   * @throws ServletException other error
   */
  public static void forwardToCatalogServices(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    String reqs = "catalog=" + getReletiveURL(req);
    String query = req.getQueryString();
    if (query != null) reqs = reqs + "&" + query;
    log.info("forwardToCatalogServices(): request string = \"/catalog.html?" + reqs + "\"");

    // dispatch to CatalogHtml servlet
    RequestForwardUtils.forwardRequestRelativeToCurrentContext("/catalog.html?" + reqs, req, res);
  }
Пример #21
0
 /**
  * Method to get the String array of the columns of a CSV File.
  *
  * @param contentWithHeaders the {@link List} of {@link String} array of the content of the csv.
  * @return a String Array of the columns.
  */
 public static String[] getHeaders(List<String[]> contentWithHeaders) {
   String[] columns = new String[0];
   try {
     String[] headers = contentWithHeaders.get(0);
     if (headers.length <= 1) {
       throw new Exception("Can't find the delimiter with openCSV try with Univicity method.");
     }
   } catch (Exception e) {
     logger.error("Can't find the Headers on the content", e);
   }
   return columns;
 }
Пример #22
0
  /**
   * ************************************************************************ Sends an error to the
   * client.
   *
   * @param t The exception that caused the problem.
   * @param res The <code>HttpServletResponse</code> for the client.
   */
  public static void handleException(Throwable t, HttpServletResponse res) {
    try {
      String message = t.getMessage();
      if (message == null) message = "NULL message " + t.getClass().getName();
      if (Debug.isSet("trustedMode")) { // security issue: only show stack if trusted
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        t.printStackTrace(ps);
        message = new String(bs.toByteArray());
      }
      log.info(
          UsageLog.closingMessageForRequestContext(
              HttpServletResponse.SC_BAD_REQUEST, message.length()));
      log.error("handleException", t);
      t.printStackTrace(); // debugging - log.error not showing stack trace !!
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_BAD_REQUEST, message);

    } catch (Throwable e) {
      log.error("handleException() had problem reporting Exception", e);
      t.printStackTrace();
    }
  }
Пример #23
0
 /**
  * Method to get the content of a comma separated file (.csv,.input,.txt)
  *
  * @param CSV the File comma separated.
  * @param noHeaders if true jump the first line of the content.
  * @return the List of Array of the content of the File comma separated.
  */
 public static List<String[]> parseCSVFileAsList(File CSV, boolean noHeaders) {
   List<String[]> content;
   try {
     CSVReader reader1 = new CSVReader(new FileReader(CSV));
     content = reader1.readAll();
     /* List<String[]> myDatas = reader1.readAll();
     String[] lineI = myDatas.get(i);
     for (String[] line : myDatas) {
         for (String value : line) {
             //do stuff with value
         }
     }*/
     if (noHeaders) content.remove(0);
     if (content.get(0).length <= 1) {
       logger.warn(
           "Attention: You haven't parsed correctly the CSV file with OpenCSV API try with Univocity Method");
     }
     return content;
   } catch (IOException e) {
     logger.error("Can't find the CSV File:" + e.getMessage(), e);
     return null;
   }
 }
 public RESTAuthenticationFilter(
     CryptoEngine cryptoEngine,
     Long contentMaxSize,
     DigestAlgorithm digestAlgorithm,
     long expiry,
     ReplayAttackValidator replayAttackValidator) {
   this.cryptoEngine = cryptoEngine;
   this.contentMaxSize = contentMaxSize;
   this.digestAlgorithm = digestAlgorithm;
   this.expiry = expiry;
   this.replayAttackValidator = replayAttackValidator;
   logger.debug(
       "REST Authentication filter using crypto engine: " + cryptoEngine.getClass().getName());
 }
Пример #25
0
 /**
  * Method use OpenCsv Library for
  *
  * @param clazz the Class of the Bean.
  * @param fileInputCsv the File CSV to parse.
  * @param separator the char separator.
  * @param <T> the generic variable.
  * @return the List of Bean parsed from the CSV file.
  */
 public static <T> List<T> parseCSVFileAsList(Class<T> clazz, File fileInputCsv, char separator) {
   try {
     List<T> beans;
     try ( // create CSVReader object
     CSVReader reader = new CSVReader(new FileReader(fileInputCsv), separator)) {
       beans = new ArrayList<>();
       // read line by line
       String[] record;
       // skip header row
       String[] headers = reader.readNext();
       // read content
       while ((record = reader.readNext()) != null) {
         T t = ReflectionUtilities.invokeConstructor(clazz);
         for (int i = 0; i < record.length; i++) {
           String nameMethod = "set" + org.apache.commons.lang3.StringUtils.capitalize(headers[i]);
           // invoke setter method
           if (ReflectionUtilities.checkMethod(clazz, nameMethod)) {
             ReflectionUtilities.invokeSetter(t, nameMethod, record[i]);
           } else {
             logger.warn(
                 "Not exists the Method with name:"
                     + nameMethod
                     + " on the Bean:"
                     + t.getClass().getName());
           }
         }
         beans.add(t);
       }
     }
     return beans;
   } catch (IOException e) {
     logger.error(
         "Can't parse the CSV file:" + fileInputCsv.getAbsolutePath() + " -> " + e.getMessage(),
         e);
     return new ArrayList<>();
   }
 }
  private double getTime(StructureMembers.Member timeVar, StructureData sdata) {
    if (timeVar == null) return 0.0;

    if ((timeVar.getDataType() == DataType.CHAR) || (timeVar.getDataType() == DataType.STRING)) {
      String time = sdata.getScalarString(timeVar);
      CalendarDate date = CalendarDateFormatter.isoStringToCalendarDate(null, time);
      if (date == null) {
        log.error("Cant parse date - not ISO formatted, = " + time);
        return 0.0;
      }
      return date.getMillis() / 1000.0;

    } else {
      return sdata.convertScalarDouble(timeVar);
    }
  }
Пример #27
0
 /**
  * Method to write a CSV List of Array of String to System Console..
  *
  * @param content the List of Array of String to convert.
  * @param separator the char separator.
  */
 public static void writeCSVDataToConsole(List<String[]> content, char separator) {
   try {
     Writer writer = new OutputStreamWriter(System.out, StringUtilities.UTF_8);
     CSVWriter csvWriter;
     if (StringUtilities.NULL_CHAR2 == separator) {
       csvWriter =
           new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
     } else {
       csvWriter = new CSVWriter(writer, separator, CSVWriter.NO_QUOTE_CHARACTER);
     }
     csvWriter.writeAll(content, false);
     csvWriter.close();
   } catch (IOException e) {
     logger.error("Can't write the CSV to Console -> " + e.getMessage(), e);
   }
 }
Пример #28
0
  // read or create index
  private void readOrCreateIndex(CollectionManager.Force ff, Formatter f) throws IOException {

    // force new index or test for new index needed
    boolean force =
        ((ff == CollectionManager.Force.always)
            || (ff == CollectionManager.Force.test && needsUpdate()));

    // otherwise, we're good as long as the index file exists
    File idx = gc.getIndexFile();
    if (force || !idx.exists() || !readIndex(idx.getPath())) {
      logger.info("GribCollection {}: createIndex {}", gc.getName(), idx.getPath());
      createIndex(idx, ff, f); // write out index
      gc.rafLocation = idx.getPath();
      gc.setRaf(new RandomAccessFile(idx.getPath(), "r"));
      readIndex(gc.getRaf()); // read back in index
    }
  }
Пример #29
0
 public static String readResource(Resource resource) {
   try {
     /* org.springframework.core.io.Resource resource =
     new org.springframework.core.io.ClassPathResource(fileLocationInClasspath);*/
     BufferedReader br =
         new BufferedReader(new InputStreamReader(resource.getInputStream()), 1024);
     StringBuilder stringBuilder = new StringBuilder();
     String line;
     while ((line = br.readLine()) != null) {
       stringBuilder.append(line).append('\n');
     }
     br.close();
     return stringBuilder.toString();
   } catch (Exception e) {
     logger.error(e.getMessage(), e);
     return null;
   }
 }
Пример #30
0
  private void sendErrorResponse(HttpServletResponse response, int errorCode, String errorMessage) {
    try {
      log.info(UsageLog.closingMessageForRequestContext(errorCode, -1));
      response.setStatus(errorCode);
      response.setHeader("Content-Description", "dods-error");
      response.setContentType("text/plain");

      PrintWriter pw = new PrintWriter(response.getOutputStream());
      pw.println("Error {");
      pw.println("    code = " + errorCode + ";");
      pw.println("    message = \"" + errorMessage + "\";");

      pw.println("};");
      pw.flush();
    } catch (Exception e) {
      System.err.println("sendErrorResponse: " + e);
    }
  }