Пример #1
0
 @RequestMapping(
     value = {"/", "/index"},
     method = RequestMethod.GET)
 public String home(Model model) {
   // Two Test Dataset from datehub.io
   InputStream in2005 =
       servletContext.getResourceAsStream("/WEB-INF/content/ibm-publications-2005.rdf");
   InputStream in2006 =
       servletContext.getResourceAsStream("/WEB-INF/content/ibm-publications-2006.rdf");
   try {
     ArrayList<RdfModel> rms2005 = RdfProcess.processRDF(in2005);
     Boolean b = rms2005.addAll(RdfProcess.processRDF(in2006));
     for (int i = 0; i < rms2005.size(); i++)
       jc.execute(
           new Delete.Builder(String.valueOf(i))
               .index("publications")
               .type("publication")
               .build());
     RdfSearch.Indexing(jc, rms2005);
     model.addAttribute("rdfModel", new RdfModel());
   } catch (Exception e) {
     e.printStackTrace();
   }
   return "index";
 }
Пример #2
0
  private void initializeApplicationVersion(final ServletContext servletContext) {
    Properties properties = new Properties();
    InputStream inputStream =
        servletContext.getResourceAsStream("/WEB-INF/classes/version.properties");

    if (inputStream == null) {
      LOGGER.warn("  version.properties not found, no version information available");
      ApplicationVersionHolder.INSTANCE.initialize("unknown", "unknown", "unknown", "unknown");
      return;
    }

    try {
      properties.load(inputStream);
      ApplicationVersionHolder.INSTANCE.initializeFromProperties(properties);
    } catch (Exception e) {
      ApplicationVersionHolder.INSTANCE.initialize("unknown", "unknown", "unknown", "unknown");
      e.printStackTrace();
    }

    LOGGER.info(
        "  Version: " + ApplicationVersionHolder.INSTANCE.getApplicationVersion().getVersion());
    LOGGER.info(
        "  Build date: "
            + ApplicationVersionHolder.INSTANCE.getApplicationVersion().getBuildDate());
  }
  protected InputStream getWSSE(ServletContext context) {
    if (context == null)
      throw new RuntimeException(ErrorCodes.NULL_VALUE + "Servlet Context is null");

    InputStream is = context.getResourceAsStream("/WEB-INF/jboss-wsse.xml");
    return is;
  }
Пример #4
0
  /*
   * Scans the web application's sub-directory identified by startPath,
   * along with its sub-directories, for TLDs and adds an implicit map entry
   * to the taglib map for any TLD that has a <uri> element.
   *
   * Initially, rootPath equals /WEB-INF/. The /WEB-INF/classes and
   * /WEB-INF/lib sub-directories are excluded from the search, as per the
   * JSP 2.0 spec.
   *
   * Keep code in sync with o.a.c.startup.TldConfig
   */
  private void tldScanResourcePaths(String startPath) throws Exception {

    Set<String> dirList = ctxt.getResourcePaths(startPath);
    if (dirList != null) {
      Iterator<String> it = dirList.iterator();
      while (it.hasNext()) {
        String path = it.next();
        if (!path.endsWith(TLD_EXT)
            && (path.startsWith(WEB_INF_LIB) || path.startsWith("/WEB-INF/classes/"))) {
          continue;
        }
        if (path.endsWith(TLD_EXT)) {
          if (path.startsWith("/WEB-INF/tags/") && !path.endsWith("implicit.tld")) {
            continue;
          }
          InputStream stream = ctxt.getResourceAsStream(path);
          try {
            tldScanStream(path, null, stream);
          } finally {
            if (stream != null) {
              try {
                stream.close();
              } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
              }
            }
          }
        } else {
          tldScanResourcePaths(path);
        }
      }
    }
  }
Пример #5
0
  /**
   * Calculate and return an absolute pathname to the XML file to contain our persistent storage
   * information.
   *
   * @throws Exception if an input/output error occurs
   */
  private String calculatePath() throws Exception {

    // Can we access the database via file I/O?
    String path = context.getRealPath(pathname);
    if (path != null) {
      return (path);
    }

    // Does a copy of this file already exist in our temporary directory
    File dir = (File) context.getAttribute("javax.servlet.context.tempdir");
    File file = new File(dir, "struts-example-database.xml");
    if (file.exists()) {
      return (file.getAbsolutePath());
    }

    // Copy the static resource to a temporary file and return its path
    InputStream is = context.getResourceAsStream(pathname);
    BufferedInputStream bis = new BufferedInputStream(is, 1024);
    FileOutputStream os = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(os, 1024);
    byte buffer[] = new byte[1024];
    while (true) {
      int n = bis.read(buffer);
      if (n <= 0) {
        break;
      }
      bos.write(buffer, 0, n);
    }
    bos.close();
    bis.close();
    return (file.getAbsolutePath());
  }
Пример #6
0
  public boolean doGet(String path, ServletContext ctx, HttpServletResponse resp)
      throws ServletException, IOException {
    if (path != null && path.length() > 0) {
      for (Application runtime : runtimes) {
        Iterable<ResourceResolver> resolvers = runtime.resolveBeans(ResourceResolver.class);
        for (ResourceResolver resolver : resolvers) {
          // For now we only have resource of URL type ...
          URL content = resolver.resolve(path);
          InputStream in;
          if (content != null) {
            in = content.openStream();
          } else {
            // It could be a server resource like an image
            in = ctx.getResourceAsStream(path);
          }

          if (in != null) {
            int pos = path.lastIndexOf('/');
            String name = pos == -1 ? path : path.substring(pos + 1);
            String contentType = ctx.getMimeType(name);
            if (contentType != null) {
              resp.setContentType(contentType);
            }
            Tools.copy(in, resp.getOutputStream());
            return true;
          }
        }
      }
    }
    return false;
  }
Пример #7
0
 public InputStream getResourceAsStream(String resourceName) throws IOException {
   InputStream resourceStream = context.getResourceAsStream("/" + resourceName);
   if (resourceStream == null) {
     throw new IOException("Cannot find resource: " + resourceName);
   }
   return resourceStream;
 }
Пример #8
0
 private Document getNativeRecord(String path) {
   Document nativeRecord = null;
   //        HashMap recordMap = null;
   if (datestampMap.containsKey(path)) {
     //            recordMap = new HashMap();
     //            File file = localIdentifier2File(path);
     try {
       InputStream is = context.getResourceAsStream(path);
       //                FileInputStream fis = new FileInputStream(file);
       nativeRecord = OAIUtil.parse(is);
       //                Node node = XPathAPI.selectSingleNode(doc, "/record/header");
       //                String header = OAIUtil.toString(node);
       //                recordMap.put("headerNode", node);
       //                FileInputStream fis = new FileInputStream(file);
       //                BufferedInputStream bis = new BufferedInputStream(fis);
       //                byte[] buffer = new byte[(int)file.length()];
       //                bis.read(buffer, 0, (int)file.length());
       //                recordMap.put("recordBytes", buffer);
       //                bis.close();
       //                fis.close();
       //                return recordMap;
     } catch (Exception e) {
       e.printStackTrace();
       return null;
     }
   }
   return nativeRecord;
 }
  public Source resolve(String href, String base) throws TransformerException {
    if (manager.isUseDb()) {
      return new StreamSource(new ByteArrayInputStream(manager.getCategoryPage(href)));
    }

    return new StreamSource(context.getResourceAsStream(href));
  }
Пример #10
0
  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    servletContext = servletConfig.getServletContext();

    try {
      SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
      con = scf.createConnection();
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Unable to open a SOAPConnection", e);
    }

    InputStream in = servletContext.getResourceAsStream("/WEB-INF/address.properties");

    if (in != null) {
      Properties props = new Properties();

      try {
        props.load(in);

        to = props.getProperty("to");
        data = props.getProperty("data");
      } catch (IOException ex) {
        // Ignore
      }
    }
  }
Пример #11
0
 protected InputStream getServletContextInputStream() {
   String servletContextPath = path;
   if (!servletContextPath.startsWith("/")) {
     servletContextPath = "/" + servletContextPath;
   }
   return servletContext.getResourceAsStream(servletContextPath);
 }
Пример #12
0
  public static String getVersion(ServletContext application) {
    String defaultVersion = "";
    try {
      InputStream inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF");
      Manifest manifest = new Manifest(inputStream);
      Attributes attributes = manifest.getMainAttributes();
      String version = attributes.getValue("Application-Version");
      String builtTime = attributes.getValue("HudsonBuildId");
      String revision = attributes.getValue("HudsonBuildNumber");

      if (version != null
          && version != ""
          && builtTime != null
          && builtTime != ""
          && revision != null
          && revision != "") {

        String versionTmp = "";
        if (version.contains("SNAPSHOT")) {
          versionTmp = version.substring(0, version.indexOf("-"));
        } else {
          versionTmp = version;
        }

        return versionTmp + " Build " + builtTime.substring(0, 10) + " Rev:" + revision;
      }
    } catch (IOException e) {
    }
    return defaultVersion;
  }
  /* (non-Javadoc)
   * @see net.jawr.web.resource.handler.stream.StreamResourceReader#getResourceAsStream(java.lang.String, boolean)
   */
  public InputStream getResourceAsStream(String resourceName, boolean processingBundle) {

    InputStream is = null;
    if (!resourceName.contains(":") && isAccessPermitted(resourceName)) {
      is = context.getResourceAsStream(resourceName);
    }
    return is;
  }
Пример #14
0
 public static final InputStream getConfigFile(ServletContext servletContext, String fileName)
     throws ResourceNotFoundException {
   String resourceName = CONFIG_DIR + "/" + fileName;
   InputStream in = servletContext.getResourceAsStream(resourceName);
   if (in == null) {
     throw new ResourceNotFoundException("resource not found : " + resourceName);
   }
   return in;
 }
  public void init(ServletConfig config) throws ServletException {
    System.out.println("CabServer Log4JInitServlet is initializing log4j");
    String log4jLocation = config.getInitParameter("log4j-properties-location");

    ServletContext sc = config.getServletContext();

    if (log4jLocation == null) {
      System.err.println(
          "*** CabServer No log4j-properties-location init param, "
              + "so initializing log4j with BasicConfigurator");
      BasicConfigurator.configure();
    } else {
      String webAppPath = sc.getRealPath("/");
      String log4jProp = webAppPath + log4jLocation;
      File yoMamaYesThisSaysYoMama = new File(log4jProp);
      if (yoMamaYesThisSaysYoMama.exists()) {
        System.out.println("CabServer Initializing log4j with: " + log4jProp);
        PropertyConfigurator.configure(log4jProp);
      } else {
        System.err.println(
            "*** CabServer "
                + log4jProp
                + " file not found, so "
                + "initializing log4j with BasicConfigurator");
        BasicConfigurator.configure();
      }
    }
    super.init(config);

    String constantsLocation = config.getInitParameter("constants-properties-location");

    try {

      Properties props = new Properties();
      InputStream stream = sc.getResourceAsStream(constantsLocation);
      props.load(stream);
      stream.close();

      Iterator keyIterator = props.keySet().iterator();
      while (keyIterator.hasNext()) {
        String key = (String) keyIterator.next();
        String value = (String) props.getProperty(key);
        // System.out.println("key:" + key + " value: " + value);
        ConfigDetails.constants.put(key, value);
      }

      Iterator it = ConfigDetails.constants.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry) it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #16
0
  public static final InputStream getStaticComponentResource(
      ServletContext application, String componentType, String resource)
      throws FileNotFoundException {
    String fullName = STATIC_COMPONENT_DIR + "/" + componentType + "/" + resource;
    InputStream res = application.getResourceAsStream(fullName);
    if (res == null) {
      throw new FileNotFoundException("file not found : " + fullName);
    }

    return res;
  }
  /* (non-Javadoc)
   * @see net.jawr.web.resource.handler.ResourceReader#getResource(java.lang.String, boolean)
   */
  public Reader getResource(String resourceName, boolean processingBundle) {

    Reader rd = null;
    if (!resourceName.contains(":")) {
      InputStream is = context.getResourceAsStream(resourceName);
      if (is != null) {
        rd = new InputStreamReader(is, charset);
      }
    }
    return rd;
  }
Пример #18
0
  @GET
  @Produces(MediaType.TEXT_HTML)
  public Response executeQueryXml(
      @Context HttpServletRequest req) // , @Context HttpServletResponse res)
      throws Exception {

    requireService();

    InputStream r = servletContext.getResourceAsStream("/resources/snorql/index.html");
    System.out.println("Resource is " + r);
    return Response.ok(r, MediaType.TEXT_HTML).build();
  }
  /**
   * @param contextPath HttpServletRequest context path
   * @param outputStream - OutputStream
   * @param resourcesToMerge list of resources to merge
   * @param autoCorrectUrlsInCSS whether to correct image urls in merged css files response.
   * @return number of non existing, unprocessed resources
   */
  private int processResources(
      String contextPath,
      OutputStream outputStream,
      List<String> resourcesToMerge,
      boolean autoCorrectUrlsInCSS) {

    int resourcesNotFound = 0;

    for (String resourcePath : resourcesToMerge) {

      LOGGER.trace("Processing resource : {}", resourcePath);

      InputStream is = null;

      try {
        is = context.getResourceAsStream(resourcePath);
        if (is == null) {
          resourcesNotFound++;
          continue;
        }
        if (resourcePath.endsWith(EXT_CSS)
            && autoCorrectUrlsInCSS) { // Need to deal with images url in CSS

          this.processCSS(contextPath, resourcePath, is, outputStream);

        } else {
          byte[] buffer = new byte[128];
          int c;
          while ((c = is.read(buffer)) != -1) {
            outputStream.write(buffer, 0, c);
          }
        }
      } catch (IOException e) {
        LOGGER.error("Error while reading resource : {}", resourcePath);
        LOGGER.error("IOException :", e);
      }

      if (is != null) {
        try {
          is.close();
        } catch (IOException ex) {
          LOGGER.warn("Failed to close stream: {}", ex);
        }
        try {
          outputStream.flush();
        } catch (IOException ex) {
          LOGGER.error("Failed to flush out:{}", outputStream);
        }
      }
    }
    return resourcesNotFound;
  }
Пример #20
0
 public static String getContent(ServletContext context, String name) {
   String htmlContent = null;
   try {
     InputStream is = context.getResourceAsStream("/WEB-INF/views/" + name + ".html");
     try {
       htmlContent = new java.util.Scanner(is).useDelimiter("\\A").next();
     } catch (java.util.NoSuchElementException e) {
     }
     is.close();
   } catch (Exception ex) {
   }
   return htmlContent;
 }
 private InputStream getConfigInputStream(ServletContext servletContext) {
   InputStream is = getJSONFromServletContext(servletContext);
   if (is == null) {
     String path = servletContext.getInitParameter("keycloak.config.file");
     if (path == null) {
       is = servletContext.getResourceAsStream("/WEB-INF/keycloak-saml.xml");
     } else {
       try {
         is = new FileInputStream(path);
       } catch (FileNotFoundException e) {
         throw new RuntimeException(e);
       }
     }
   }
   return is;
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("application/pdf");

    OutputStream out = response.getOutputStream();
    ServletContext sc = getServletContext();
    InputStream in = sc.getResourceAsStream("/wcd.pdf");
    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = in.read(bytes)) != -1) {
      out.write(bytes, 0, read);
    }
    out.flush();
    out.close();
  }
  protected void copyJar(ServletContext servletContext, String dir, String jarName)
      throws Exception {

    String servletContextName = servletContext.getServletContextName();

    String jarFullName = "/WEB-INF/" + jarName + "/" + jarName + ".jar";

    InputStream is = servletContext.getResourceAsStream(jarFullName);

    if (is == null) {
      throw new HotDeployException(jarFullName + " does not exist");
    }

    String newJarFullName = dir + "ext-" + servletContextName + jarName.substring(3) + ".jar";

    StreamUtil.transfer(is, new FileOutputStream(new File(newJarFullName)));
  }
Пример #24
0
  @Override
  public TriggerEvent generateInterEntityCompareRule(InterEntityCompareRule icmp) {
    trigger = new TriggerEvent();
    String string = "";
    BufferedReader fis = null;
    try {
      fis =
          new BufferedReader(
              new InputStreamReader(
                  context.getResourceAsStream(
                      "/WEB-INF/data/oracleTrigger/interEntityCompare.txt")));

      StringBuilder builder = new StringBuilder();
      int content;
      while ((content = fis.read()) != -1) {
        builder.append((char) content);
      }
      Map<String, String> values = new HashMap<String, String>();
      values.put("NAME", icmp.getName());
      values.put("WHEN", "INSERT OR UPDATE");
      values.put("TABLENAME", icmp.getColumn().getTable().getName());
      values.put("SECONDCOLUMN", icmp.getSecondcolumn().getName());
      values.put("SECONDTABLE", icmp.getSecondcolumn().getTable().getName());
      values.put("SECONDPK", icmp.getSecondpk().getName());
      values.put("PK", icmp.getPk_identifier().getName());
      values.put("COLUMN", icmp.getColumn().getName());
      values.put("OPERATOR", icmp.getOperator());

      values.put("REVOPERATOR", getReverseOperator(icmp.getOperator()));
      values.put("ERRORMESSAGE", icmp.getErrormessage());
      String s = builder.toString();
      for (Map.Entry<String, String> e : values.entrySet()) {
        s = s.replaceAll("\\{" + e.getKey() + "\\}", e.getValue());
      }
      string = s;
    } catch (IOException e) {
      e.printStackTrace();
    }
    trigger.setColumn(icmp.getColumn());
    trigger.setTable(icmp.getColumn().getTable());
    trigger.setTriggerSourceCode(string);
    trigger.setName(icmp.getName());
    trigger.setRule(icmp);

    return trigger;
  }
Пример #25
0
  private void init(ErrorDispatcher err) throws JasperException {
    if (initialized) return;

    InputStream is = ctxt.getResourceAsStream(TAG_PLUGINS_XML);
    if (is == null) return;

    TreeNode root = (new ParserUtils()).parseXMLDocument(TAG_PLUGINS_XML, is);
    if (root == null) {
      return;
    }

    if (!TAG_PLUGINS_ROOT_ELEM.equals(root.getName())) {
      err.jspError("jsp.error.plugin.wrongRootElement", TAG_PLUGINS_XML, TAG_PLUGINS_ROOT_ELEM);
    }

    tagPlugins = new HashMap();
    Iterator pluginList = root.findChildren("tag-plugin");
    while (pluginList.hasNext()) {
      TreeNode pluginNode = (TreeNode) pluginList.next();
      TreeNode tagClassNode = pluginNode.findChild("tag-class");
      if (tagClassNode == null) {
        // Error
        return;
      }
      String tagClass = tagClassNode.getBody().trim();
      TreeNode pluginClassNode = pluginNode.findChild("plugin-class");
      if (pluginClassNode == null) {
        // Error
        return;
      }

      String pluginClassStr = pluginClassNode.getBody();
      TagPlugin tagPlugin = null;
      try {
        Class pluginClass = Class.forName(pluginClassStr);
        tagPlugin = (TagPlugin) pluginClass.newInstance();
      } catch (Exception e) {
        throw new JasperException(e);
      }
      if (tagPlugin == null) {
        return;
      }
      tagPlugins.put(tagClass, tagPlugin);
    }
    initialized = true;
  }
 public static void readOntologyFilesInPathSet(String path, ServletContext ctx, Model model) {
   log.debug("Reading ontology files from '" + path + "'");
   Set<String> paths = ctx.getResourcePaths(path);
   if (paths != null) {
     for (String p : paths) {
       String format = getRdfFormat(p);
       log.info("Loading ontology file at " + p + " as format " + format);
       InputStream ontologyInputStream = ctx.getResourceAsStream(p);
       try {
         model.read(ontologyInputStream, null, format);
         log.debug("...successful");
       } catch (Throwable t) {
         log.error("Failed to load ontology file at '" + p + "' as format " + format, t);
       }
     }
   }
 }
  private void readPropertiesWithContext(
      Properties properties, ServletContext context, String path, Logger log) {

    Reader reader = null;
    try {

      reader = new InputStreamReader(context.getResourceAsStream(path), "UTF-8");
      properties.load(reader);

    } catch (Exception e) {

      log.warn("Failed to load " + path);
    } finally {

      IOUtils.closeQuietly(reader);
    }
  }
Пример #28
0
 /**
  * Returns the designer version from the manifest.
  *
  * @param context
  * @return version
  */
 private static String readDesignerVersion(ServletContext context) {
   String retStr = "";
   try {
     InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF");
     BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
     String line;
     while ((line = br.readLine()) != null) {
       if (line.startsWith(BUNDLE_VERSION)) {
         retStr = line.substring(BUNDLE_VERSION.length() + 1);
         retStr = retStr.trim();
       }
     }
     inputStream.close();
   } catch (IOException e) {
     _logger.error(e.getMessage(), e);
   }
   return retStr;
 }
Пример #29
0
  @RequestMapping(method = RequestMethod.GET)
  public void viewSource(
      @RequestParam("file") String file, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (!enabled) {
      throw (new OpenLegacyRuntimeException("View source controller is not enabled"));
    }

    ServletContext servletContext = request.getSession().getServletContext();

    InputStream resource = servletContext.getResourceAsStream(file);
    if (resource == null) {
      throw (new OpenLegacyRuntimeException("Specified resource doesn''t exists"));
    }
    String content = IOUtils.toString(resource);
    content = HtmlUtils.htmlEscape(content);
    response.getWriter().write(MessageFormat.format(htmlOutput, content));
  }
Пример #30
0
  private void readFromPropertiesFile(ServletConfig config) {
    ServletContext ctx = config.getServletContext();
    Properties props = new Properties();
    try {
      props.load(ctx.getResourceAsStream("/WEB-INF/ibk.properties"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    Set<Object> keys = props.keySet();
    String key = null;

    Iterator<Object> itr = keys.iterator();
    while (itr.hasNext()) {
      key = (String) itr.next();
      ctx.setAttribute(key, props.getProperty(key));
    }
  }