jersey client failed with ClientResponse status 400 - jersey-2.0

I am trying to upload a file to cloud using jersey client. But here I am getting below response.
InboundJaxrsResponse{context=ClientResponse{method=POST, uri=http://test.net/hello, status=400, reason=400}}
and the source is as below.
final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
final JsonObjectBuilder formJson = Json.createObjectBuilder();
formJson.add("name", fileName);
formJson.add("parent", 0);
String jsonStr = formJson.build().toString();
final FileDataBodyPart filePart = new FileDataBodyPart("file", new File(fileLocation));
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final FormDataMultiPart multiPart = (FormDataMultiPart) formDataMultiPart
.field(jsonStr, MediaType.MULTIPART_FORM_DATA).bodyPart(filePart);
multiPart.setContentDisposition(FormDataContentDisposition.name("file").fileName(fileLocation).build());
final WebTarget target = client.target("http://test.net/hello");
final Response response = target.request().header("Content-Type", "multipart/form-data")
.header("instanceid", "b05642c8-d231-48fe-a163-d978a6208d98")
.post(Entity.entity(multiPart, "multipart/form-data"));
Can any one help me to out this issue.
Thanks,

Related

invalid_client error calling sign in with apple rest API

We have begun implementing Sign in with Apple in our mobile app but cannot seem to call the token endpoint successfully (https://appleid.apple.com/auth/token). The response we get is 400 with the body [{"error":"invalid_client"}]. I have read and re-read the details on how to generate the client-secret. We are using a java backend and specifically the nimbus library to create the signed JWT.
final JWSHeader clientSecretHeader =
new JWSHeader.Builder(JWSAlgorithm.ES256)
.keyID("7N5XJ*****")
.build();
final Date issuedAtTime = Date.from(Instant.now());
final Date expirationTime = Date.from(Instant.now().plusSeconds(3600));
final JWTClaimsSet clientSecretClaims =
new JWTClaimsSet.Builder()
.issuer("HL46P*****")
.issueTime(issuedAtTime)
.expirationTime(expirationTime)
.audience("https://appleid.apple.com")
.subject("com.company.app")
.build();
final byte[] keyBytes = ...private key loaded from p8 file...;
final KeyFactory keyFactory = KeyFactory.getInstance("EC");
final ECPrivateKey privateKey =
(ECPrivateKey)keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
final JWSSigner jwtSigner = new ECDSASigner(signingKey);
final SignedJWT clientSecretJwt = new SignedJWT(clientSecretHeader, clientSecretClaims);
clientSecretJwt.sign(jwtSigner);
final MultiValueMap<string, string=""> map= new LinkedMultiValueMap<>();
map.add("grant_type", "authorization_code");
map.add("client_id", "HL46P*****");
map.add("client_secret", clientSecretJwt.serialize());
map.add("code", "code receiged from app...");
/* if User-Agent is not set, request fails with 400 invalid_client */
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set(HttpHeaders.USER_AGENT, "My App");
final HttpEntity<multivaluemap<string, string="">> request = new HttpEntity<>(map, headers);
final RestTemplate restTemplate = new RestTemplateBuilder().build();
final ResponseEntity response = response = restTemplate.postForEntity(
"https://appleid.apple.com/auth/token",
request,
GetTokenResponse.class
);
The resulting JWT looks like the following:
Header
{
"kid": "7N5XJ*****",
"alg": "ES256"
}
Claims
{
"aud": "https://appleid.apple.com",
"sub": "com.company.app",
"iss": "HL46P.....",
"exp": 1585583898,
"iat": 1585580298
}
In the end, we determined that if the User-Agent header is not set, the apple API will fail with a 400 response code and invalid_client as the error. That error is completely misleading, but setting the User-Agent header resolves it.

attach file from DAM to send mail in cq/AEM

i was trying to send a mail from cq-DAM but failed.
i can send files from my own pc, i want to get the files from DAM
here is the code ::
#SuppressWarnings("unchecked")
final Enumeration<String> parameterNames = request.getParameterNames();
final Map<String, String> parameters = new HashMap<String, String>();
while (parameterNames.hasMoreElements()) {
final String key = parameterNames.nextElement();
parameters.put(key, request.getParameter(key));
}
Resource templateRsrc = request.getResourceResolver().getResource("/etc/notification/send-email.html");
String mailId = request.getParameter("mailId");
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("/media/intelligrape/MyFiles/Xtra/Crafting/Paper Work/images.jpg");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
attachment.setName("John");
int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
try {
final MailTemplate mailTemplate = MailTemplate.create(templateRsrc.getPath(), templateRsrc.getResourceResolver().adaptTo(Session.class));
final HtmlEmail email = mailTemplate.getEmail(StrLookup.mapLookup(parameters), HtmlEmail.class);
logger.error("PROPERTIES**************************** "+parameters);
email.addTo(mailId);
email.attach(attachment);
URL url = new URL("<any URL except localhost>");
String cid = email.embed(url, "Apache logo");
email.setHtmlMsg("<html><body>The ig logo - <img src=\"cid:"+cid+"\"></body></html>");
email.setTextMsg("Your email client does not support HTML messages");
messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
messageGateway.send(email);
thanks in advance..:)
You can get InputStream of the DAM image and convert it to ByteArrayDataSource and then use attach(datasource,name,description) method to attach the DAM image to email.
Node contentNode = imageNode.getNode("jcr:content");
Binary imageBinary = contentNode.getProperty("jcr:data").getBinary();
InputStream imageStream = imageBinary.getStream();
ByteArrayDataSource imageDS = new ByteArrayDataSource(imageStream,"image/jpeg");
email.attach(imageDS,"Some Image","Some Description");

How to add new header to jersey client to upload multipart file

Please find below jersey client code to upload multipart file:
String url = "http://localhost:7070"
Client client = Client.create();
WebResource webresource = client.resource(url);
File file = new File("C://Data//image1.jpg");
File thumbnail = new File("C://Data/image2.jpg");
InputStream isthumbnail = new FileInputStream(thumbnail);
InputStream isfile = new FileInputStream(file);
FormDataMultiPart multiPart = new FormDataMultiPart();
FormDataBodyPart bodyPart1 = new FormDataBodyPart(FormDataContentDisposition.name("Thumbnail").fileName("thumbnail").build(), isthumbnail, MediaType.APPLICATION_OCTET_STREAM_TYPE);
FormDataBodyPart bodyPart2 = new FormDataBodyPart(FormDataContentDisposition.name("File").fileName("file").build(), isfile, MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(bodyPart);
multiPart.bodyPart(bodyPart1);
//New Headers
String fileContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
String thumbnailContentLength = "form-data; contentLength=\""+Long.toString(file.length())+ "\"";
final ClientResponse clientResp = webresource.type(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_XML).post(ClientResponse.class, multiPart);
System.out.println("File Upload Success with Response"+clientResp.getStatus());
I need to add the String fileContentLength and thumbnailContentLength as header
Content-Length.
How do i add the headers as part of multipart and post the request?Any help would be appreciated
Use a FormDataContentDisposition as an argument to FormDataBodyPart(FormDataContentDisposition formDataContentDisposition, Object entity, MediaType mediaType).
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
final String value = "Hello World";
final FormDataContentDisposition dispo = FormDataContentDisposition
.name("file")
.fileName("test.txt")
.size(value.getBytes().length)
.build();
final FormDataBodyPart bodyPart = new FormDataBodyPart(dispo, value);
formDataMultiPart.bodyPart(bodyPart);

Upload local file to SharePoint Online using HttpWebRequest

I'm trying to upload a file to a SharePoint online site that I have permissions for, I have tried using an HttpWebRequest to get an XDocument to allow me to upload a file but when I call an HttpWebResponse I get the error "The underlying connection was closed: An unexpected error occurred on a receive."
I'm unable to use SharePoint client object model as this app is to be used on PCs that don't have a SharePoint installation.
You will need to create a digest:
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
var response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
JsonObject val = JsonValue.Parse(content).GetObject();
JsonObject d = val.GetNamedObject("d");
JsonObject wi = d.GetNamedObject("GetContextWebInformation");
retVal = wi.GetNamedString("FormDigestValue");
}
Then you can use the following example to upload the file and retrieve its metadata from the http response:
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true");
IRandomAccessStream fileStream = await path.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
Byte[] content = new byte[fileStream.Size];
reader.ReadBytes(content);
ByteArrayContent file = new ByteArrayContent(content);
HttpResponseMessage response = await client.PostAsync(String.Concat("_api/web/lists/getByTitle('Project Photos')/RootFolder/Files/add(url='", filename, ".jpg',overwrite='true')?$expand=ListItemAllFields"), file);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var info = response.Content.ReadAsStringAsync();
JsonObject d = JsonValue.Parse(info.Result).GetObject();
string id = d["d"].GetObject()["ListItemAllFields"].GetObject().GetNamedValue("ID").Stringify();
}

HTTP Status 500 - org.springframework.web.client.HttpClientErrorException: 404 /

I am using RestTemplate, but when i call postFor function i get following exception, Below are the code for showing detail:
Controller
#Controller
#RequestMapping("/data")
public class DataController {
#RequestMapping(value = "/{id}", method = RequestMethod.POST)
public ResponseEntity<ManagementResource> postData(#PathVariable("id") String id,#RequestBody Data1 data) {
RSResponse<Data1> response = new RSResponse<Data1>();
response.setStatus(RSResponse.Status.SUCCESS);
response.setData(data);
return new ResponseEntity<ManagementResource>(HttpStatus.CREATED);
}
}
client code:
RestTemplate rt = new RestTemplate();
Data1 d = new Data1();
d.setEmp_id(1);
d.setEmp_name("abc");
d.setEmp_salary(10000);
Map<String, String> vars = new HashMap<String, String>();
vars.put("id", "JS01");
String url = "http://localhost:8090/JSFFaceletsTutorial/data/{id}";
ResponseEntity<Data1> response = rt.postForEntity(url,d,Data1.class,vars);
Data1 data = response.getBody();
please tell if anyone knows it.
Thanks
Does your service need headers? If so, you can pass like this,
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Accept", "application/json");
HttpEntity<Data1> request = new HttpEntity<Data1>(d, headers);
ResponseEntity<Data1> response = rt.postForEntity(url,request,Data1.class,vars);
Data1 data = response.getBody();