GVKun编程网logo

Tomcat错误:在ExternalContext中找不到资源(tomcat找不到或无法加载主类)

22

在这篇文章中,我们将带领您了解Tomcat错误:在ExternalContext中找不到资源的全貌,包括tomcat找不到或无法加载主类的相关情况。同时,我们还将为您介绍有关apachejena-te

在这篇文章中,我们将带领您了解Tomcat错误:在ExternalContext中找不到资源的全貌,包括tomcat找不到或无法加载主类的相关情况。同时,我们还将为您介绍有关apache jena-text full text search with external content、applicationContext.xml中的区别、com.itextpdf.text.pdf.security.ExternalSignature的实例源码、Context.getExternalFilesDir()和Context.getExternalCacheDir()方法的知识,以帮助您更好地理解这个主题。

本文目录一览:

Tomcat错误:在ExternalContext中找不到资源(tomcat找不到或无法加载主类)

Tomcat错误:在ExternalContext中找不到资源(tomcat找不到或无法加载主类)

当我尝试通过http://localhost/home/index.html访问开发站点时收到此错误,该站点重定向到http://localhost/home/views/main/index.xhtml:

java.io.FileNotFoundException: /views/main/index*.xhtml Not Found in ExternalContext as a Resource

我正在将Tomcat 7.0.8和Mojarra JSF 2.0.4与Eclipse
Helios结合使用。我已经检查了WAR部署文件中的index.xhtml文件,并且该文件位于WAR文件中。我还检查了../wtpwebapps/home/views/main目录,可以看到Eclipse已经部署了index.xhtml文件。

我得到的stacktrace是:

    07/02/2011 3:58:53 AM org.apache.catalina.core.StandardWrapperValve invokeSEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/home] threw exceptionjava.lang.NullPointerException    at com.sun.faces.lifecycle.RestoreViewPhase.notifyAfter(RestoreViewPhase.java:301)    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:114)    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:383)    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:288)    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)    at java.lang.Thread.run(Thread.java:662)

我不确定为什么会出现上述错误。有人可以帮忙吗?

答案1

小编典典

我解决了问题:这只是web.xml的配置问题。

我在web.xml中将webapp版本声明为2.0,而对于Tomcat 7,则声明为3.0。

apache jena-text full text search with external content

Introduction

According to document Jena Full Text Search, it is possible that the indexed text is content external to the RDF store with only additional triples in the RDF store. The subject URI returned as a search result may then be considered to refer via the indexed property to the external content.

To work with external content, the maintenance of the index is external to the RDF data store too. The key of the index is: building an URI field from indexed document''s path.

When the text search is performed, the URIs returned as the search result will be used for matching the subject URI in the SPARQL query.

In this tutorial, we create lucene index for external text documents, perform a full text search in SPARQL using jena-text, then return the highlighting results.

The example code is available on github.

Create Maven project

The example project uses jena-text 3.9.0 and lucene 6.4.2(the lucene dependencey is already specified in the jena-text library).

Add the following depedecies to you pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.atjiang.jena</groupId>
  <artifactId>jena-text-full-text-search-with-external-content</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>jena-text-full-text-search-with-external-content</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <phase>install</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.jena</groupId>
      <artifactId>apache-jena-libs</artifactId>
      <type>pom</type>
      <version>3.9.0</version>
    </dependency>

    <dependency>
      <groupId>org.apache.jena</groupId>
      <artifactId>jena-cmds</artifactId>
      <version>3.9.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.jena/jena-text -->
    <dependency>
      <groupId>org.apache.jena</groupId>
      <artifactId>jena-text</artifactId>
      <version>3.9.0</version>
    </dependency>


    <!-- Testing support -->
    <dependency>
      <groupId>org.apache.jena</groupId>
      <artifactId>jena-base</artifactId>
      <version>3.9.0</version>
      <classifier>tests</classifier>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
    <dependency>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.8.0</version>
    </dependency>
  </dependencies>
</project>

Example data

The turtle file called data.ttl is stored in the root directory of the project, which is searched in SPARQL.

@prefix email: <http://atjiang.com/data/email/> .

<http://atjiang.com/data/email/id/id1> email:content "no_matter_what.txt" .
<http://atjiang.com/data/email/id/id2> email:content "no_matter_what.txt" .

The text files under directory to_index are the external files which will be used to create a Lucene index. File name of each text file is the email id, corresponding to the email id in the turtle file.

$ ls -la to_index/
total 16
drwxrwxr-x 2 hy hy 4096 12月  6 08:44 .
drwxrwxr-x 7 hy hy 4096 12月 13 15:06 ..
-rw-rw-r-- 1 hy hy   30 12月  6 08:44 id1
-rw-rw-r-- 1 hy hy   28 12月  6 08:44 id2

$ cat to_index/id1
context 
good luck
background

$ cat to_index/id2
context
bad luck
background

Code example explained

The lucene index and search code are based on Lucene''s demo code IndexFiles.java and SearchFiles.java.

Create lucene index

// in file IndexFiles.java
  /** Indexes a single document */
  static void indexDoc(IndexWriter writer, Path file, long lastModified) throws IOException {
    try (InputStream stream = Files.newInputStream(file)) {
      // make a new, empty document
      Document doc = new Document();
      
      // Add the path of the file as a field named "path".  Use a
      // field that is indexed (i.e. searchable), but don''t tokenize 
      // the field into separate words and don''t index term frequency
      // or positional information:
      Field pathField = new StringField("uri", App.EMAIL_URI_PREFIX + "id/" + file.getFileName().toString(), Field.Store.YES);
      doc.add(pathField);
      
      // Add the last modified date of the file a field named "modified".
      // Use a LongPoint that is indexed (i.e. efficiently filterable with
      // PointRangeQuery).  This indexes to milli-second resolution, which
      // is often too fine.  You could instead create a number based on
      // year/month/day/hour/minutes/seconds, down the resolution you require.
      // For example the long value 2011021714 would mean
      // February 17, 2011, 2-3 PM.
      doc.add(new LongPoint("modified", lastModified));
      
      // Add the contents of the file to a field named "contents".  Specify a Reader,
      // so that the text of the file is tokenized and indexed, but not stored.
      // Note that FileReader expects the file to be in UTF-8 encoding.
      // If that''s not the case searching for special characters will fail.
      //doc.add(new TextField("text", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))));
      doc.add(new TextField("text", new String(Files.readAllBytes(file)), Field.Store.YES));


      if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
        // New index, so we just add the document (no old document can be there):
        System.out.println("adding " + file);
        writer.addDocument(doc);
      } else {
        // Existing index (an old copy of this document may have been indexed) so 
        // we use updateDocument instead to replace the old one matching the exact 
        // path, if present:
        System.out.println("updating " + file);
        writer.updateDocument(new Term("path", file.toString()), doc);
      }
    }
  }
}

With in line Field pathField = new StringField("uri", App.EMAIL_URI_PREFIX + "id/" + file.getFileName().toString(), Field.Store.YES);, we create a StringField uri from the external text file''s name. And Field.Store.YES indicates the text file''s content will be stored in the index, which is used for working with jena-text''s full text search highlighting feature.

Load dataset and define the index mapping

// in file JenaTextSearch.java

public static Dataset createCode() 
{
    // Base data
    Dataset ds1 = DatasetFactory.create() ;
    Model defaultModel = ModelFactory.createDefaultModel();
    defaultModel.read("data.ttl", "N-TRIPLES");
    ds1.setDefaultModel(defaultModel);

    // Define the index mapping
    EntityDefinition entDef = new EntityDefinition( "uri", "text", ResourceFactory.createProperty( App.EMAIL_URI_PREFIX, "content" ) );

    Directory dir = null;
    try {
        dir = new SimpleFSDirectory(Paths.get("index")); // lucene index directory
    }
    catch( IOException e){
        e.printStackTrace();
    }

    // Join together into a dataset
    Dataset ds = TextDatasetFactory.createLucene( ds1, dir, new TextIndexConfig(entDef) ) ;
    
    return ds ;
}

We define the index mapping according to the index we built. The index itself is maintained by the main app, see code in below.

jena-text query

public static void queryData(Dataset dataset)
{
    String prefix = "PREFIX email: <" + App.EMAIL_URI_PREFIX + "> " +
            "PREFIX text: <http://jena.apache.org/text#> ";

    long startTime = System.nanoTime() ;
    System.out.println("Email''s content contains ''good''");
    String query = "SELECT * WHERE " +
            "{ ?s text:query (email:content ''good'') ." +
            "  ?s email:content ?text . " +
            " }";

    dataset.begin(ReadWrite.READ) ;
    try {
        Query q = QueryFactory.create(prefix+"\n"+query) ;
        QueryExecution qexec = QueryExecutionFactory.create(q , dataset) ;
        QueryExecUtils.executeQuery(q, qexec) ;
    } finally { dataset.end() ; }
    long finishTime = System.nanoTime() ;
    double time = (finishTime-startTime)/1.0e6 ;
    System.out.println("Query " + String.format("FINISH - %.2fms", time)) ;

    startTime = System.nanoTime() ;
    System.out.println("Email''s content contains ''bad''");
    query = "SELECT * WHERE " +
            "{ (?s ?score ?lit) text:query (email:content ''bad'' \"highlight:s:<emhiLite''> | e:</em>\") ." +
            "  ?s email:content ?text . " +
            " }";

    dataset.begin(ReadWrite.READ) ;
    try {
        Query q = QueryFactory.create(prefix+"\n"+query) ;
        QueryExecution qexec = QueryExecutionFactory.create(q , dataset) ;
        QueryExecUtils.executeQuery(q, qexec) ;
    } finally { dataset.end() ; }
    finishTime = System.nanoTime() ;
    time = (finishTime-startTime)/1.0e6 ;
    System.out.println("Query " + String.format("FINISH - %.2fms", time)) ;
}

The main entry

// in file App.java
public class App
{
    static String EMAIL_URI_PREFIX = "http://atjiang.com/data/email/";
    public static void main( String[] args ) {

        testJenaText();
    }

    public static void testJenaText() {
        IndexFiles.testIndex();
        try {
            SearchFiles.testSearch();
        } catch (Exception e){

            System.out.println(e.toString());
        }

        JenaTextSearch.main();
    }
}

Compile and run

$ mvn install
$ mvn compile
$ java -cp target/jena-text-full-text-search-with-external-content-1.0-SNAPSHOT.jar:target/lib/* com.atjiang.jena.App


Indexing to directory ''index''...
adding to_index/id1
adding to_index/id2
357 total milliseconds
Searching for: luck
2 total matching documents
1. http://atjiang.com/data/email/id/id1
2. http://atjiang.com/data/email/id/id2
log4j:WARN No appenders could be found for logger (org.apache.jena.util.FileManager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Email''s content contains ''good''
-----------------------------------------------------------------
| s                                      | text                 |
=================================================================
| <http://atjiang.com/data/email/id/id1> | "no_matter_what.txt" |
-----------------------------------------------------------------
Query FINISH - 159.10ms
Email''s content contains ''bad''
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| s                                      | score                                                 | lit                                                       | text                 |
=====================================================================================================================================================================================
| <http://atjiang.com/data/email/id/id2> | "0.6931472"^^<http://www.w3.org/2001/XMLSchema#float> | "context\n<emhiLite''>bad</em> luck\nbackground\n" | "no_matter_what.txt" |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Query FINISH - 17.91ms

Lucene index tools

You can analyze the Lucene index using the Luke toolbox. With this toolbox, you can see how many terms are indexed, with what frequency they occur.

Resources

  • Jena Full Text Search
  • Apache Lucene - Building and Installing the Basic Demo
  • Full text search in SPARQL using Apache Lucene
  • https://github.com/DmitryKey/...

applicationContext.xml中<context:annotation-config> 和 <context:component-scan>的区别

applicationContext.xml中的区别

Difference between <context:annotation-config> vs <context:component-scan>

<context:annotation-config>是用于激活那些已经在spring容器里注册过的bean(无论是通过xml的方式还是通过package sanning的方式)上面的注解。

<context:component-scan>除了具有<context:annotation-config>的功能之外,<context:component-scan>还可以在指定的package下扫描以及注册javabean。

下面我们通过例子来详细查看他们的区别,

有三个class A,B,C,并且B,C的对象被注入到A中.

package com.xxx;
public class B {
  public B() {
    System.out.println("creating bean B: " + this);
  }
}

package com.xxx;
public class C {
  public C() {
    System.out.println("creating bean C: " + this);
  }
}

package com.yyy;
import com.xxx.B;
import com.xxx.C;
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc; 
  }
}

在applicationContext.xml中加入下面的配置 :

<bean id="bBean"class="com.xxx.B"/><bean id="cBean"class="com.xxx.C"/><bean id="aBean"class="com.yyy.A"><property name="bbb" ref="bBean"/><property name="ccc" ref="cBean"/></bean>

加载applicationContext.xml配置文件,将得到下面的结果:

creating bean B: com.xxx.B@c2ff5 creating bean C: com.xxx.C@1e8a1f6 creating bean A: com.yyy.A@1e152c5 setting A.bbb with com.xxx.B@c2ff5 setting A.ccc with com.xxx.C@1e8a1f6

OK,这个结果没什么好说的,就是完全通过xml的方式,不过太过时了,下面通过注解的方式来简化我们的xml配置文件

首先,我们使用autowire的方式将对象bbb和ccc注入到A中:

package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxx.B;
import com.xxx.C;
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  @Autowired
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  @Autowired
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc;
  }
}

然后,我们就可以从applicationContext.xml中移除下面的配置

<property name="bbb" ref="bBean"/><property name="ccc" ref="cBean"/>

移除之后,我们的applicationContext.xml配置文件就简化为下面的样子了

<bean id="bBean"class="com.xxx.B"/><bean id="cBean"class="com.xxx.C"/><bean id="aBean"class="com.yyy.A"/>

当我们加载applicationContext.xml配置文件之后,将得到下面的结果:

creating bean B: com.xxx.B@5e5a50 creating bean C: com.xxx.C@54a328 creating bean A: com.yyy.A@a3d4cf
ottom: 1em; border: 0px; vertical-align: baseline; clear: both; font-family: Arial,结果是错误的的,究竟是因为什么呢?为什么我们的属性没有被注入进去呢?

是因为注解本身并不能够做任何事情,它们只是最基本的组成部分,我们需要能够处理这些注解的处理工具来处理这些注解

这就是<context:annotation-config>所做的事情

我们将applicationContext.xml配置文件作如下修改:

<context:annotation-config /><bean id="bBean"class="com.xxx.B"/><bean id="cBean"class="com.xxx.C"/><bean id="aBean"class="com.yyy.A"/>

creating bean B: com.xxx.B@15663a2 creating bean C: com.xxx.C@cd5f8b creating bean A: com.yyy.A@157aa53 setting A.bbb with com.xxx.B@15663a2 setting A.ccc with com.xxx.C@cd5f8b
ottom: 1em; border: 0px; vertical-align: baseline; clear: both; font-family: Arial,结果正确了

但是如果我们将代码作如下修改:

package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class B {
  public B() {
    System.out.println("creating bean B: " + this);
  }
}

package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class C {
  public C() {
    System.out.println("creating bean C: " + this);
  }
}

package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xxx.B;
import com.xxx.C;
@Component
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  @Autowired
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  @Autowired
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc;
  }
}

applicationContext.xml配置文件修改为:

<context:annotation-config />

当我们加载applicationContext.xml配置文件之后,却没有任何输出,这是为什么呢?

那是因为<context:annotation-config />仅能够在已经在已经注册过的bean上面起作用。对于没有在spring容器中注册的bean,它并不能执行任何操作。

但是不用担心,<context:component-scan>除了具有<context:annotation-config />的功能之外,还具有自动将带有@component,@service,@Repository等注解的对象注册到spring容器中的功能。

<context:component-scan base-package="com.xxx"/>

当我们加载applicationContext.xml的时候,会得到下面的结果:

creating bean B: com.xxx.B@1be0f0a creating bean C: com.xxx.C@80d1ff

这是什么原因呢?

是因为我们仅仅扫描了com.xxx包及其子包的类,而class A是在com.yyy包下,所以就扫描不到了

下面我们在applicationContext.xml中把com.yyy也加入进来:

<context:component-scan basepackage="com.xxx,com.yyy"/><context:component-scan base-package="com.xxx"/> 
然后加载applicationContext.xml就会得到下面的结果:
creating bean B: com.xxx.B@cd5f8b creating bean C: com.xxx.C@15ac3c9 creating bean A: com.yyy.A@ec4a87 setting A.bbb with com.xxx.B@cd5f8b setting A.ccc with com.xxx.C@15ac3c9

哇,结果正确啦 !

回头看下我们的applicationContext.xml文件,已经简化为:

/><context:component-scan base-package="com.xxx"/>

了。

那如果我们在applicationContext.xml手动加上下面的配置,也就是说既在applicationContext.xml中手动的注册了A的实例对象,同时,通过component-scan去扫描并注册B,C的对象

<context:component-scan base-package="com.xxx"/><bean id="aBean"class="com.yyy.A"/>

结果仍是正确的:

creating bean B: com.xxx.B@157aa53 creating bean C: com.xxx.C@ec4a87 creating bean A: com.yyy.A@1d64c37 setting A.bbb with com.xxx.B@157aa53 setting A.ccc with com.xxx.C@ec4a87

虽然class A并不是通过扫描的方式注册到容器中的 ,但是<context:component-scan>所产生的的处理那些注解的处理器工具,会处理所有绑定到容器上面的bean,不管是通过xml手动注册的还是通过scanning扫描注册的。

那么,如果我们通过下面的方式呢?我们既配置了<context:annotation-config />,又配置了<context:component-scan base-package="com.xxx" />,它们都具有处理在容器中注册的bean里面的注解的功能。会不会出现重复注入的情况呢?

<context:annotation-config /><context:component-scan base-package="com.xxx"/><bean id="aBean"class="com.yyy.A"/>

不用担心,不会出现的:

因为<context:annotation-config />和<context:component-scan>同时存在的时候,前者会被忽略。也就是那些@autowire,@resource等注入注解只会被注入一次

哪怕是你手动的注册了多个处理器,spring仍然只会处理一次:

<context:annotation-config />
<context:component-scan base-package="com.xxx" />
<bean id="aBean"/>
<bean id="bla"/>
<bean id="bla1"/>
<bean id="bla2"/>
<bean id="bla3"/>

结果仍是正确的:

creating bean B: com.xxx.B@157aa53 creating bean C: com.xxx.C@ec4a87 creating bean A: com.yyy.A@25d2b2 setting A.bbb with com.xxx.B@157aa53 setting A.ccc with com.xxx.C@ec4a87

com.itextpdf.text.pdf.security.ExternalSignature的实例源码

com.itextpdf.text.pdf.security.ExternalSignature的实例源码

项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void sign50MBrunoAppend() throws IOException,DocumentException,GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER,"50m-signedBrunoAppend.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,os,'\0',RESULT_FOLDER,true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36,748,144,780),1,"sig");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk,digestAlgorithm,"BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance,digest,pks,chain,null,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
/**
 * <a href="http://stackoverflow.com/questions/30449348/signing-pdf-memory-consumption">
 * Signing PDF - memory consumption
 * </a>
 * <br>
 * <a href="http://50mpdf.tk/50m.pdf">50m.pdf</a>
 * <p>
 * {@link #sign50MNaive()} tests the naive approach,* {@link #sign50MBruno()} tests Bruno's original approach,* {@link #sign50MBrunopartial()} tests Bruno's approach with partial reading,* {@link #sign50MBrunoAppend()} tests Bruno's approach with append mode,and
 * {@link #sign50MBrunopartialAppend()} tests Bruno's approach with partial reading and append mode.
 * </p>
 */
// runs with -Xmx240m,fails with -Xmx230m
@Test
public void sign50MNaive() throws IOException,"50m-signednaive.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,'\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void sign50MBruno() throws IOException,"50m-signedBruno.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,false);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void sign50MBrunopartial() throws IOException,GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/50m.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath,true);
    FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER,"50m-signedBrunopartial.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void sign50MBrunopartialAppend() throws IOException,"50m-signedBrunopartialAppend.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
/**
 * <a href="http://stackoverflow.com/questions/30526254/sign-concatenated-pdf-in-append-mode-with-certified-no-changes-allowed">
 * Sign concatenated PDF in append mode with CERTIFIED_NO_CHANGES_ALLOWED
 * </a>
 * <br>
 * <a href="https://www.dropBox.com/s/lea6r9fup6th44c/test_pdf.zip?dl=0">test_pdf.zip</a>
 * 
 * {@link #signCertifyG()} certifies g.pdf,OK
 * {@link #sign2g()} merely signs 2g.pdf,OK
 * {@link #signCertify2gNoAppend()} certifies 2g.pdf but not in append mode,OK
 * {@link #tidySignCertify2g()} first tidies,then certifies 2g.pdf,OK
 * {@link #signCertify2g()} certifies 2g.pdf,Adobe says invalid
 * {@link #signCertify2gFix()} certifies 2g-fix.pdf,OK!
 * 
 * 2g-fix.pdf is a patched version of 2g.pdf with a valid /Size trailer entry
 * and a valid,single-sectioned cross reference table 
 */
@Test
public void signCertifyG() throws IOException,GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/g.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath,"g-certified.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void sign2g() throws IOException,GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath,"2g-signed.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void signCertify2g() throws IOException,"2g-certified.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void signCertify2gNoAppend() throws IOException,"2g-certified-noAppend.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,RESULT_FOLDER);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature(new Rectangle(36,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
@Test
public void signCertify2gFix() throws IOException,GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/2g-fix.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath,"2g-fix-certified.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
public void C2_01_SignHelloWorld_sign(String src,String dest,Certificate[] chain,PrivateKey pk,String digestAlgorithm,String provider,CryptoStandard subfilter,String reason,String location)
        throws GeneralSecurityException,IOException,DocumentException {
    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(src);
    FileOutputStream os = new FileOutputStream(dest);
    pdfstamper stamper = pdfstamper.createSignature(reader,'\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason(reason);
    appearance.setLocation(location);
    appearance.setVisibleSignature(new Rectangle(36,"sig");
    // Creating the signature
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(pk,provider);
    MakeSignature.signDetached(appearance,signature,subfilter);
}
项目:testarea-itext5    文件:ComplexSignatureFields.java   
@Test
public void sign2274_2007_H_PROVISIONAL_multifield() throws IOException,GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/2274_2007_H_PROVISIONAL - multifield.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath,"2274_2007_H_PROVISIONAL - multifield-signed.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature("IntSig1");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk,subfilter);
}
项目:testarea-itext5    文件:ComplexSignatureFields.java   
/**
 * <a href="http://stackoverflow.com/questions/32818522/itextsharp-setvisiblesignature-not-working-as-expected">
 * ITextSharp SetVisibleSignature not working as expected
 * </a>
 * <p>
 * The issue observed by the OP (user2699460) occurs since iText(Sharp) 5.5.7
 * both of iText and iTextSharp.
 * </p>
 * <p>
 * The file signed in this sample,test-2-user2699460-signed.pdf,has been created
 * as intermediary result using a simplified version of the OP's c# code. 
 * </p>
 */
@Test
public void signTest_2_user2699460() throws IOException,GeneralSecurityException
{
    String filepath = "src/test/resources/mkl/testarea/itext5/signature/test-2-user2699460.pdf";
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(filepath,"test-2-user2699460-signed.pdf"));
    pdfstamper stamper =
        pdfstamper.createSignature(reader,true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    //appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    appearance.setReason("reason");
    appearance.setLocation("location");
    appearance.setVisibleSignature("Bunker");
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk,subfilter);
}
项目:testarea-itext5    文件:CreateSignature.java   
/**
 * <a href="https://stackoverflow.com/questions/45062602/itext-pdfappearence-issue">
 * Text - PDFAppearence issue
 * </a>
 * <p>
 * This test shows how one can create a custom signature layer 2.
 * As the OP of the question at hand mainly wants to generate a
 * pure DESCRIPTION appearance that uses the whole area,we here
 * essentially copy the PdfSignatureAppearance.getAppearance code
 * for generating layer 2 in pure DESCRIPTION mode and apply it
 * to a plain pre-fetched layer 2.
 * </p>
 */
@Test
public void signWithCustomLayer2() throws IOException,GeneralSecurityException
{
    String digestAlgorithm = "SHA512";
    CryptoStandard subfilter = CryptoStandard.CMS;

    try (   InputStream resource = getClass().getResourceAsstream("/mkl/testarea/itext5/extract/test.pdf")  )
    {
        PdfReader reader = new PdfReader(resource);
        FileOutputStream os = new FileOutputStream(new File(RESULT_FOLDER,"test-customLayer2.pdf"));
        pdfstamper stamper = pdfstamper.createSignature(reader,'\0');

        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason("reason");
        appearance.setLocation("location");
        appearance.setVisibleSignature(new Rectangle(36,"sig");

        // This essentially is the PdfSignatureAppearance.getAppearance code
        // for generating layer 2 in pure DESCRIPTION mode applied to a plain
        // pre-fetched layer 2.
        // vvvvv
        PdfTemplate layer2 = appearance.getLayer(2);
        String text = "We're using iText to put a text inside a signature placeholder in a PDF. "
                + "We use a code snippet similar to this to define the Signature Appearence.\n"
                + "Everything works fine,but the signature text does not fill all the signature "
                + "placeholder area as expected by us,but the area filled seems to have an height "
                + "that is approximately the 70% of the available space.\n"
                + "As a result,sometimes especially if the length of the signature text is quite "
                + "big,the signature text does not fit in the placeholder and the text is striped "
                + "away.";
        Font font = new Font();
        float size = font.getSize();
        final float MARGIN = 2;
        Rectangle dataRect = new Rectangle(
                MARGIN,MARGIN,appearance.getRect().getWidth() - MARGIN,appearance.getRect().getHeight() - MARGIN);
        if (size <= 0) {
            Rectangle sr = new Rectangle(dataRect.getWidth(),dataRect.getHeight());
            size = ColumnText.fitText(font,text,sr,12,appearance.getRunDirection());
        }
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(appearance.getRunDirection());
        ct.setSimpleColumn(new Phrase(text,font),dataRect.getLeft(),dataRect.getBottom(),dataRect.getRight(),dataRect.getTop(),size,Element.ALIGN_LEFT);
        ct.go();
        // ^^^^^

        ExternalSignature pks = new PrivateKeySignature(pk,"BC");
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance,subfilter);
    }
}

Context.getExternalFilesDir()和Context.getExternalCacheDir()方法

Context.getExternalFilesDir()和Context.getExternalCacheDir()方法

应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的。
大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中。
这样当该应用被卸载后,这些数据还保留在SDCard中,留下了垃圾数据。
如果你想让你的应用被卸载后,与该应用相关的数据也清除掉,该怎么办呢?

通过Context.getExternalFilesDir()方法可以获取到 SDCard/Android/data/你的应用的包名/files/ 目录,一般放一些长时间保存的数据
通过Context.getExternalCacheDir()方法可以获取到 SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据

如果使用上面的方法,当你的应用在被用户卸载后,SDCard/Android/data/你的应用的包名/ 这个目录下的所有文件都会被删除,不会留下垃圾信息。

而且上面二个目录分别对应 设置->应用->应用详情里面的”清除数据“与”清除缓存“选项


如果要保存下载的内容,就不要放在以上目录下

关于Tomcat错误:在ExternalContext中找不到资源tomcat找不到或无法加载主类的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于apache jena-text full text search with external content、applicationContext.xml中的区别、com.itextpdf.text.pdf.security.ExternalSignature的实例源码、Context.getExternalFilesDir()和Context.getExternalCacheDir()方法的相关信息,请在本站寻找。

本文标签: