1

I am writing with my friends app, which collects JobOffer and can manually apply on them.

For example, I am getting CSRF token from this page Click cause I need CSRF to upload file.

But when i'm trying to execute restTemplate.exchange() i am getting error: "Caused by: java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String ".

Here is my class:

@Data
@Service
class StackOverflowComAcceptor implements JobOfferService {

    private final static String BASE_URL = "http://stackoverflow.com";
    private final ConnectionService2 connectionService2;
    private final StackOverflowComFactory stackOverflowComFactory;
    private final RestTemplate restTemplate;

    @Autowired
    private CVProvider cvProvider;



    @Override
    @SneakyThrows
    public void accept(JobOffer jobOffer) {
        //List<Connection.KeyVal> templateDataEntries = stackOverflowComFactory.create();

        ConnectionRequest connectionRequest = ConnectionRequest
                .builder()
                //url is in joboffer
                .url("http://stackoverflow.com/jobs/apply/110247")
                .method(Connection.Method.GET)
                .data(new ArrayList<Connection.KeyVal>() )
                .build();


        ConnectionResponse submit1 = connectionService2.submit(connectionRequest);
        Document document = submit1.getDocument();

        String csrf = extractCSRF(document);
        String cvurl = "http://stackoverflow.com/jobs/apply/upload-resume";
        //String cvurl = "http://stackoverflow.com/jobs/apply/upload-resume?jobId=110247&fkey=" + csrf;
        InputStream inputStream = cvProvider.asInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);

        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("fkey", csrf);
        uriVariables.put("jobId", "110247");


        HttpHeaders partHeaders = new HttpHeaders();
        partHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ByteArrayResource byteArrayResource = new ByteArrayResource(bytes, "test.pdf");

        MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
        data.add("qqfile", byteArrayResource);

        HttpEntity<MultiValueMap<String, Object>> requestEntity =
                new HttpEntity<>(data, partHeaders);

        ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
//        byteArrayHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(new MediaType[]{MediaType
//                .APPLICATION_OCTET_STREAM}));
        FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        formHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(
                new MediaType[]{MediaType.APPLICATION_OCTET_STREAM}));

        //restTemplate.getMessageConverters().add(byteArrayHttpMessageConverter);
        restTemplate.getMessageConverters().add(formHttpMessageConverter);

        ResponseEntity<Object> model = restTemplate.exchange(cvurl, HttpMethod.POST, requestEntity, Object.class ,
                uriVariables);

        System.out.println(model);


    }

    private String extractCSRF(Document document) {
        String s = document.getElementsByTag("script").get(0).toString();
        Pattern p = Pattern.compile("Careers.XSRF_KEY = \\\"([a-z0-9]{32})\\\""); // Regex for the value of the key
        Matcher m = p.matcher(s);
        String csrf = null;
        while( m.find() )
        {
            csrf = m.group(1); // value only
        }
        System.out.println(csrf);
        return csrf;
    }



}

Here is my stacktrace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testStacka' defined in file [D:\WWW\Epomis\epomis\build\classes\main\net\elenx\epomis\service\com\stackoverflow\Test.class]: Invocation of init method failed; nested exception is java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-1.4.1.BUILD-SNAPSHOT.jar:1.4.1.BUILD-SNAPSHOT]
    at net.elenx.Epomis.main(Epomis.java:22) [main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_74]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_74]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_74]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_74]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: java.lang.ClassCastException: org.springframework.core.io.ByteArrayResource cannot be cast to java.lang.String
    at org.springframework.http.converter.FormHttpMessageConverter.writeForm(FormHttpMessageConverter.java:292) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:254) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:89) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:849) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:617) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:588) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:507) ~[spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at net.elenx.epomis.service.com.stackoverflow.StackOverflowComAcceptor.accept(StackOverflowComAcceptor.java:99) ~[main/:na]
    at net.elenx.epomis.service.com.stackoverflow.Test.afterPropertiesSet(Test.java:40) ~[main/:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    ... 19 common frames omitted


Process finished with exit code 1   

Any ideas how to solve the problem?

1 Answer 1

3

It's obviously some problem with casting, you're trying to cast FileMessageResource to String. It's not necessarily happening explicitly. Can you add the stack trace?

Ok so I have an answear for you, even two of them, choose the one that you like best.

  1. You don't need to use HttpEntity<MultiValueMap<String, Object>>, as there is a constructor allowing to pass any object so you may consider using simply HttpEntity<byte[]>, remember to pass byteArrayResource.getByteArray() if you decide to take this approach.
  2. I've taken a look into the Spring api and there is a slight difference for multipart / other content types in FormHttpMessageConverter. You can use MultiValueMap<String, Object> only for Multipart content type. Otherwise the map is being cast to MultiValueMap<String, String>, hence the error while running your application. To get rid of it just change the content type from partHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); to partHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.