小编gip*_*ani的帖子

Android HttpUrlConnection:发布Multipart

我正在尝试将测试文件发布到使用Android部署在tomcat上的spring rest servlet.我正在开发Android 4.1.2,但我已经在4.0.3上验证了同样的问题.

问题是文件上传需要很长时间(对于4MB文件大约需要70秒),也在本地网络中.使用3g连接可以节省时间.我已经排除它可能是服务器问题:使用curl执行相同的调用需要1/2秒,并且使用apache作为后端结果是相同的.

使用HttpClient工作正常.

我正在使用Spring Android RestClient 1.0.1.RELEASE,并且考虑到Android版本以及我没有覆盖默认行为的事实,它使用HttpUrlConnection而不是HttpClient来发出http请求.

我还实现了我的自定义ClientHttpRequestFactory,以便操纵SSL连接的一些细节,我已经定义了自己的ClientHttpRequestInterceptor实现,以便修改身份验证头.

我也设置setBufferRequestBody(false)为了避免OutOfMemoryException大文件.但是这个属性对所需的时间没有影响.

MyClientHttpRequestFactory:

public class MyClientHttpRequestFactory extends SimpleClientHttpRequestFactory{

    @Override
    protected void prepareConnection(HttpURLConnection connection,  String httpMethod) throws IOException {
        super.prepareConnection(connection, httpMethod);
        connection.setConnectTimeout(240 * 1000);
        connection.setReadTimeout(240 * 1000);


        if ("post".equals(httpMethod.toLowerCase())) {
            setBufferRequestBody(false);
        }else {
            setBufferRequestBody(true);
        }
    }

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    final HttpURLConnection httpUrlConnection = super.openConnection(url, proxy);

    if (url.getProtocol().toLowerCase().equals("https")
        &&
        settings.selfSignedCert().get())
    {
        try {
            ((HttpsURLConnection)httpUrlConnection).setSSLSocketFactory(getSSLSocketFactory());
            ((HttpsURLConnection)httpUrlConnection).setHostnameVerifier(new NullHostnameVerifier());
        } catch …
Run Code Online (Sandbox Code Playgroud)

performance spring android httpurlconnection android-networking

12
推荐指数
1
解决办法
4018
查看次数

Spring MVC框架:使用PUT方法的MultipartResolver

我正在使用框架3.2.3.RELEASE开发一个spring mvc应用程序

在我的应用程序中,我使用StandardServletMultipartResolver处理Multipart,但是使用apache commons-fileupload 1.3,事情是相同的.

我想知道为什么isMultipart方法的实现只考虑POST方法,而不考虑PUT方法.如果我想更新实体和相关文件,我必须使用POST.

查看org.springframework.web.multipart.support.Standard ServletMultipartResolver:

public boolean isMultipart(HttpServletRequest request) {
    // Same check as in Commons FileUpload...
    if (!"post".equals(request.getMethod().toLowerCase()) ) {
        return false;
    }
    String contentType = request.getContentType();
    return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
}
Run Code Online (Sandbox Code Playgroud)

而在org.apache.commons.fileupload.servlet.ServletFileU pload我有:

public static final boolean isMultipartContent(HttpServletRequest request) {
    if (!POST_METHOD.equalsIgnoreCase(request.getMethod() )) {
        return false;
    }
    return FileUploadBase.isMultipartContent(new ServletRequestContext(request));
}
Run Code Online (Sandbox Code Playgroud)

不是一件至关重要的事情,事实上只是使用PUT工作的POST方法.但我想承认为什么PUT不被考虑在内!

谢谢你回复Marco

spring multipartform-data spring-mvc apache-commons-fileupload

8
推荐指数
1
解决办法
3456
查看次数

Spring @Async:LAZY集合上的null hibernate会话

我在@Async服务层方法上使用注释.

当我EAGERLY加载@OneToMany集合字段时,一切正常,但是当我尝试访问LAZY加载的元素时,我发现Hibernate SessionImplementor对象session为null.这显然给了我一个例外:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:
....    
Run Code Online (Sandbox Code Playgroud)

这是我的收藏领域:

@OneToMany(mappedBy="abc", fetch=FetchType.LAZY, cascade=CascadeType.REMOVE)
@OrderBy(value="xsd asc")
@JsonIgnore
private Set<Item> items = new HashSet<Item>();
Run Code Online (Sandbox Code Playgroud)

如何绑定hibernate会话以便LAZELY在@Async上下文中加载我的对象?

编辑

这是我的trancactionManager/entityManager配置

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="emf"/>
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter">

    </property>
    <property name="packagesToScan" value="it.domain"/>

    <property name="persistenceUnitName" value="persistenceUnit"/>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
            <!--${hibernate.format_sql} -->
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <!-- ${hibernate.show_sql} -->
            <prop …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate hibernate-session

8
推荐指数
2
解决办法
7734
查看次数

Spring抛出JpaSystemException而不是DuplicateKeyException

我遇到了DataAccessException处理的麻烦.

当违反了uniquess键约束时,我得到了一个JpaSystemException,而不是DuplicateKeyException!

我找到了一些线索谈论这个问题,但没有人帮我解决问题.如何映射到具体的org.springframework.dao异常?

我的persistence.xml文件如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>        
        <class>...</class>
        <class>...</class>
        ...
        <exclude-unlisted-classes />
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/> 
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
            <property name="hibernate.connection.charSet" value="UTF-8"/>
            <property name="hibernate.show.sql" value="true"/>

            <property name="hibernate.ejb.event.post-insert" value="org.hibernate.ejb.event.EJB3PostInsertEventListener,org.hibernate.envers.event.AuditEventListener" />
        <property name="hibernate.ejb.event.post-update" value="org.hibernate.ejb.event.EJB3PostUpdateEventListener,org.hibernate.envers.event.AuditEventListener" />
        <property name="hibernate.ejb.event.post-delete" value="org.hibernate.ejb.event.EJB3PostDeleteEventListener,org.hibernate.envers.event.AuditEventListener" />
        <property name="hibernate.ejb.event.pre-collection-update" value="org.hibernate.envers.event.AuditEventListener" />
            <property name="hibernate.ejb.event.pre-collection-remove" value="org.hibernate.envers.event.AuditEventListener" />
        <property name="hibernate.ejb.event.post-collection-recreate" value="org.hibernate.envers.event.AuditEventListener" />
    </properties>         
    </persistence-unit>    
    <persistence-unit name="persistenceUnitI24" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>...</class>
        <class>...</class>
        <exclude-unlisted-classes />
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate"/> …
Run Code Online (Sandbox Code Playgroud)

spring hibernate jpa unique-constraint

7
推荐指数
1
解决办法
5020
查看次数

JPA 2.1/Hibernate 4.3弃用警告

我正在使用JPA 2.1示例应用程序Hibernate 4.3.x实现.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="unit1">

        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>net.roseindia.model.Product</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/common"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="root"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>

    </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

pom.xml我有以下依赖.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.3.5.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

示例命令行应用程序正常工作(非常简单)但是在启动它时会收到以下警告消息.

Apr 13, 2014 1:12:43 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Run Code Online (Sandbox Code Playgroud)

那么,这是我的错误配置问题(我可以避免它吗?),或者它是Hibernate实现中的问题?

更新

这是我使用的代码:

import net.roseindia.model.Product;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory; …
Run Code Online (Sandbox Code Playgroud)

java hibernate jpa jpa-2.1

7
推荐指数
1
解决办法
2万
查看次数

创建自定义方法安全表达式的最佳方法

我正在尝试创建自己的方法安全表达式,我想在其中使用@PreFilter@PostFilter注释.

在搜索教程和类似问题时,我发现了两种方法.

第一种是扩展DefaultMethodSecurityExpressionHandler和覆盖createSecurityExpressionRoot,以便进行定制SecurityExpressionRoot.

@PreAuthorize('isOwner(#someEntity)') 
Run Code Online (Sandbox Code Playgroud)

第二种方法是简单地使用@Component类和@Pre/ @Postfilter访问其方法@bean.method()

@PreAuthorize("@mySecurityService.isOwner('#someEntityl')")
Run Code Online (Sandbox Code Playgroud)

我的问题是:哪种方式首选?如果两者都可以,为什么选择另一个?

谢谢Marco

java spring spring-security

6
推荐指数
1
解决办法
2676
查看次数

Android - 终结器抛出的未捕获异常

我有一段代码,它接受服务器响应并将其写入文件。

该文件包含 json 数据。我将响应写入文件,以便按顺序扫描 json 并避免在列表中加载大的 json 数据!

我认为此方法会引发异常,但我不确定!

public File getData(final String url) throws URISyntaxException, AuthenticationException, IOException, ClientProtocolException, HttpResponseException {
    final HttpGet getRequest = new HttpGet(new URI(url));

    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    getRequest.addHeader(new BasicScheme().authenticate(creds, getRequest));
    getRequest.setHeader("Content-Type", "application/json");
    final ResponseHandler<byte[]> responseHandler = new ByteArrayResponseHandler();
    final byte[] responseBody = mClient.execute(getRequest, responseHandler);

    final File output = new File(FileConfig.TEMP_PATH + System.currentTimeMillis()+".json");
    final FileOutputStream fos = new FileOutputStream(output.getPath()); 

    fos.write(responseBody);
    fos.close();
    return output;
}
Run Code Online (Sandbox Code Playgroud)

但我注意到最近(我不知道为什么)我得到了这个例外:

01-22 07:45:51.809: E/System(9055): Uncaught exception thrown by finalizer …
Run Code Online (Sandbox Code Playgroud)

android fileoutputstream apache-httpclient-4.x

5
推荐指数
1
解决办法
1万
查看次数

Spring Data JPA聚合函数与QueryDsl谓词

我有一个Spring Data Jpa存储库,扩展了PagingAndSortingRepositoryQueryDslPredicateExecutor

它指向一个表,该表包含我想用聚合函数详细说明的元素。我想每一次读取m.field1MIN m.field2

所以这是我在@Query方法注释中的查询:

select new x.xx.MyClass(m.field1, MIN(m.field2))
from MyClass m
group by m.field1, m.field2
Run Code Online (Sandbox Code Playgroud)

这是我的存储库接口方法:

Page<MyClass> findMyClass(Predicate predicate, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)

即使这个查询很烂,并且有更好的方法也可以,它仍然有效。

但是,当我尝试使用谓词时,即使使用空谓词,我也会得到:

org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1; 
    nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. 
    Remember that ordinal parameters are 1-based! Position: 1
Run Code Online (Sandbox Code Playgroud)

那么有可能使此工作正常进行,还是我不得不采用另一种实现方式?

java spring hibernate querydsl spring-data

5
推荐指数
0
解决办法
1613
查看次数

Spring:通过java配置在Controller层中启用全局方法安全性

我正在尝试将我的xml servlet配置迁移到java配置.

以下配置是我的servlet配置,它在Controller层上启用自定义安全注释.

<security:global-method-security pre-post-annotations="enabled">
    <security:expression-handler ref="expressionHandler"/>
</security:global-method-security>

<bean id="expressionHandler" class="yyy.MyMethodSecurityExpressionHandler" />
Run Code Online (Sandbox Code Playgroud)

我还有一个工作的spring security xml配置,这是为了被java配置替换,但现在不是.这里有一些我的安全配置:

<bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <property name="userDetailsService" ref="userDetailsService" />
    </bean>

<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
    <constructor-arg>
         <ref bean="authenticationProvider"/>
    </constructor-arg>
</bean>

<security:authentication-manager>
    <security:authentication-provider user-service-ref="userDetailsService" />
</security:authentication-manager>

<security:global-method-security pre-post-annotations="enabled" />
Run Code Online (Sandbox Code Playgroud)

我想开始迁移我的servlet配置@PreAuthorize,@PostAuthorize在Controller层中启用安全性和标记.

我发现了这个注释:@EnableGlobalMethodSecurity(prePostEnabled=true)但是把它放在我的servlet配置上:

@Configuration
@ComponentScan(basePackages= {
        "....."         
})
@EnableGlobalMethodSecurity(prePostEnabled=true)

public class WebappServletConfig extends WebMvcConfigurationSupport {
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
Run Code Online (Sandbox Code Playgroud)

而且我不知道如何设置我的自定义表达式处理程序!

有人提示吗?谢谢

java spring spring-mvc spring-security spring-java-config

5
推荐指数
2
解决办法
2万
查看次数

角度保存/恢复组件状态

我正在开发一个具有多标签布局的 angular 7 应用程序。每个选项卡都包含一个组件,可以引用其他嵌套组件。

当用户选择一个新的/另一个选项卡时,当前选项卡上显示的组件将被销毁(我不只是隐藏它们,而且我遵循了这种模式,因为打开的选项卡可能很多,这对我来说似乎是一个更快的解决方案) . 由于加载组件的成本可能很高(可能从 API 中检索到大量数据),因此我尝试将每个组件状态保存在选项卡容器中(它在整个应用程序生命周期内都保持活动状态)。

一切都按预期工作,但我想我已经使用了很多代码来满足我的需求,我希望一切都可以更简单(并且更不容易出错)。

下面是关于我如何设法做到这一点的摘录。首先,我创建了一个抽象类,选项卡中的每个组件都应扩展该类。

export abstract class TabbedComponent implements OnInit, OnDestroy {
  abstract get componentName(): string;

  tab: LimsTab;
  host: TabComponent;
  private _componentInitialized = false;

  constructor(
    private _host: TabComponent,
  ) {
    this.host = _host;
  }

  get componentInitialized(): boolean {
    return this._componentInitialized;
  }

  ngOnInit(): void {
    this.tab = this.host.tab;
    this.loadDataContext();
    this._componentInitialized = true;
  }

  ngOnDestroy(): void {
    this.saveDataContext();
  }

  get dataContext() {
    return this.tab.dataContext;
  }

  protected abstract saveDataContext(): void;
  protected abstract loadDataContext(): void;
}
Run Code Online (Sandbox Code Playgroud)

loadDataContext …

angular

5
推荐指数
1
解决办法
2980
查看次数