I have a non-Java project that produces a versioned build artifact, and I want to upload this to a Nexus repository. Because the project isn't Java, it doesn't use Maven for builds. And I'd rather not introduce Maven/POM files just to get files into Nexus.
The links on blogs to the Nexus REST API all end up at a sign-in wall, with no "create user" link that I can see.
So, what's the best (or any reasonable) way to upload build artifacts to a Nexus repository without Maven? "bash + curl" would be great, or even a Python script.
Have you considering using the Maven command-line to upload files?
mvn deploy:deploy-file \
-Durl=$REPO_URL \
-DrepositoryId=$REPO_ID \
-DgroupId=org.myorg \
-DartifactId=myproj \
-Dversion=1.2.3 \
-Dpackaging=zip \
-Dfile=myproj.zip
This will automatically generate the Maven POM for the artifact.
Update
The following Sonatype article states that the "deploy-file" maven plugin is the easiest solution, but it also provides some examples using curl:
https://support.sonatype.com/entries/22189106-How-can-I-programatically-upload-an-artifact-into-Nexus-
Using curl:
curl -v \
-F "r=releases" \
-F "g=com.acme.widgets" \
-F "a=widget" \
-F "v=0.1-1" \
-F "p=tar.gz" \
-F "file=#./widget-0.1-1.tar.gz" \
-u myuser:mypassword \
http://localhost:8081/nexus/service/local/artifact/maven/content
You can see what the parameters mean here: https://support.sonatype.com/entries/22189106-How-can-I-programatically-upload-an-artifact-into-Nexus-
To make the permissions for this work, I created a new role in the admin GUI and I added two privileges to that role: Artifact Download and Artifact Upload. The standard "Repo: All Maven Repositories (Full Control)"-role is not enough.
You won't find this in the REST API documentation that comes bundled with the Nexus server, so these parameters might change in the future.
On a Sonatype JIRA issue, it was mentioned that they "are going to overhaul the REST API (and the way it's documentation is generated) in an upcoming release, most likely later this year".
You can ABSOLUTELY do this without using anything MAVEN related. I personally use the NING HttpClient (v1.8.16, to support java6).
For whatever reason, Sonatype makes it incredibly difficulty to figure out what the correct URLs, headers, and payloads are supposed to be; and I had to sniff the traffic and guess... There are some barely useful blogs/documentation there, however it is either irrelevant to oss.sonatype.org, or it's XML based (and I found out it doesn't even work). Crap documentation on their part, IMHO, and hopefully future seekers can find this answer useful. Many thanks to https://stackoverflow.com/a/33414423/2101812 for their post, as it helped a lot.
If you release somewhere other than oss.sonatype.org, just replace it with whatever the correct host is.
Here is the (CC0 licensed) code I wrote to accomplish this. Where profile is your sonatype/nexus profileID (such as 4364f3bbaf163) and repo (such as comdorkbox-1003) are parsed from the response when you upload your initial POM/Jar.
Close repo:
/**
* Closes the repo and (the server) will verify everything is correct.
* #throws IOException
*/
private static
String closeRepo(final String authInfo, final String profile, final String repo, final String nameAndVersion) throws IOException {
String repoInfo = "{'data':{'stagedRepositoryId':'" + repo + "','description':'Closing " + nameAndVersion + "'}}";
RequestBuilder builder = new RequestBuilder("POST");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/profiles/" + profile + "/finish")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.setBody(repoInfo.getBytes(OS.UTF_8))
.build();
return sendHttpRequest(request);
}
Promote repo:
/**
* Promotes (ie: release) the repo. Make sure to drop when done
* #throws IOException
*/
private static
String promoteRepo(final String authInfo, final String profile, final String repo, final String nameAndVersion) throws IOException {
String repoInfo = "{'data':{'stagedRepositoryId':'" + repo + "','description':'Promoting " + nameAndVersion + "'}}";
RequestBuilder builder = new RequestBuilder("POST");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/profiles/" + profile + "/promote")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.setBody(repoInfo.getBytes(OS.UTF_8))
.build();
return sendHttpRequest(request);
}
Drop repo:
/**
* Drops the repo
* #throws IOException
*/
private static
String dropRepo(final String authInfo, final String profile, final String repo, final String nameAndVersion) throws IOException {
String repoInfo = "{'data':{'stagedRepositoryId':'" + repo + "','description':'Dropping " + nameAndVersion + "'}}";
RequestBuilder builder = new RequestBuilder("POST");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/profiles/" + profile + "/drop")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.setBody(repoInfo.getBytes(OS.UTF_8))
.build();
return sendHttpRequest(request);
}
Delete signature turds:
/**
* Deletes the extra .asc.md5 and .asc.sh1 'turds' that show-up when you upload the signature file. And yes, 'turds' is from sonatype
* themselves. See: https://issues.sonatype.org/browse/NEXUS-4906
* #throws IOException
*/
private static
void deleteSignatureTurds(final String authInfo, final String repo, final String groupId_asPath, final String name,
final String version, final File signatureFile)
throws IOException {
String delURL = "https://oss.sonatype.org/service/local/repositories/" + repo + "/content/" +
groupId_asPath + "/" + name + "/" + version + "/" + signatureFile.getName();
RequestBuilder builder;
Request request;
builder = new RequestBuilder("DELETE");
request = builder.setUrl(delURL + ".sha1")
.addHeader("Authorization", "Basic " + authInfo)
.build();
sendHttpRequest(request);
builder = new RequestBuilder("DELETE");
request = builder.setUrl(delURL + ".md5")
.addHeader("Authorization", "Basic " + authInfo)
.build();
sendHttpRequest(request);
}
File uploads:
public
String upload(final File file, final String extension, String classification) throws IOException {
final RequestBuilder builder = new RequestBuilder("POST");
final RequestBuilder requestBuilder = builder.setUrl(uploadURL);
requestBuilder.addHeader("Authorization", "Basic " + authInfo)
.addBodyPart(new StringPart("r", repo))
.addBodyPart(new StringPart("g", groupId))
.addBodyPart(new StringPart("a", name))
.addBodyPart(new StringPart("v", version))
.addBodyPart(new StringPart("p", "jar"))
.addBodyPart(new StringPart("e", extension))
.addBodyPart(new StringPart("desc", description));
if (classification != null) {
requestBuilder.addBodyPart(new StringPart("c", classification));
}
requestBuilder.addBodyPart(new FilePart("file", file));
final Request request = requestBuilder.build();
return sendHttpRequest(request);
}
EDIT1:
How to get the activity/status for a repo
/**
* Gets the activity information for a repo. If there is a failure during verification/finish -- this will provide what it was.
* #throws IOException
*/
private static
String activityForRepo(final String authInfo, final String repo) throws IOException {
RequestBuilder builder = new RequestBuilder("GET");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/repository/" + repo + "/activity")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.build();
return sendHttpRequest(request);
}
No need to use these commands .. you can directly use the nexus web Interface in order to upload your JAR using GAV parameters.
So it is very simple.
The calls that you need to make against Nexus are REST api calls.
The maven-nexus-plugin is a Maven plugin that you can use to make these calls. You could create a dummy pom with the necessary properties and make those calls through the Maven plugin.
Something like:
mvn -DserverAuthId=sonatype-nexus-staging -Dauto=true nexus:staging-close
Assumed things:
You have defined a server in your ~/.m2/settings.xml named sonatype-nexus-staging with your sonatype user and password set up - you will probably already have done this if you are deploying snapshots. But you can find more info here.
Your local settings.xml includes the nexus plugins as specified here.
The pom.xml sitting in your current directory has the correct Maven coordinates in its definition. If not, you can specify the groupId, artifactId, and version on the command line.
The -Dauto=true will turn off the interactive prompts so you can script this.
Ultimately, all this is doing is creating REST calls into Nexus. There is a full Nexus REST api but I have had little luck finding documentation for it that's not behind a paywall. You can turn on the debug mode for the plugin above and figure it out however by using -Dnexus.verboseDebug=true -X.
You could also theoretically go into the UI, turn on the Firebug Net panel, and watch for /service POSTs and deduce a path there as well.
In ruby https://github.com/RiotGames/nexus_cli A CLI wrapper around Sonatype Nexus REST calls.
Usage Example:
nexus-cli push_artifact com.mycompany.artifacts:myartifact:tgz:1.0.0 ~/path/to/file/to/push/myartifact.tgz
Configuration is done via the .nexus_cli file.
url: "http://my-nexus-server/nexus/"
repository: "my-repository-id"
username: "username"
password: "password"
You can also use the direct deploy method using curl. You don't need a pom for your file for it but it will not be generated as well so if you want one, you will have to upload it separately.
Here is the command:
version=1.2.3
artifact="myartifact"
repoId=yourrepository
groupId=org.myorg
REPO_URL=http://localhost:8081/nexus
curl -u nexususername:nexuspassword --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artifact/$version/$artifact-$version.tgz
for those who need it in Java, using apache httpcomponents 4.0:
public class PostFile {
protected HttpPost httppost ;
protected MultipartEntity mpEntity;
protected File filePath;
public PostFile(final String fullUrl, final String filePath){
this.httppost = new HttpPost(fullUrl);
this.filePath = new File(filePath);
this.mpEntity = new MultipartEntity();
}
public void authenticate(String user, String password){
String encoding = new String(Base64.encodeBase64((user+":"+password).getBytes()));
httppost.setHeader("Authorization", "Basic " + encoding);
}
private void addParts() throws UnsupportedEncodingException{
mpEntity.addPart("r", new StringBody("repository id"));
mpEntity.addPart("g", new StringBody("group id"));
mpEntity.addPart("a", new StringBody("artifact id"));
mpEntity.addPart("v", new StringBody("version"));
mpEntity.addPart("p", new StringBody("packaging"));
mpEntity.addPart("e", new StringBody("extension"));
mpEntity.addPart("file", new FileBody(this.filePath));
}
public String post() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
addParts();
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println(httppost.getEntity().getContentLength());
HttpEntity resEntity = response.getEntity();
String statusLine = response.getStatusLine().toString();
System.out.println(statusLine);
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
return statusLine;
}
}
If you need a convenient command line interface or python API, look at repositorytools
Using it, you can upload artifact to nexus with command
artifact upload foo-1.2.3.ext releases com.fooware
To make it work, you will also need to set some environment variables
export REPOSITORY_URL=https://repo.example.com
export REPOSITORY_USER=admin
export REPOSITORY_PASSWORD=mysecretpassword
For recent versions of Nexus OSS (>= 3.9.0)
https://support.sonatype.com/hc/en-us/articles/115006744008-How-can-I-programmatically-upload-files-into-Nexus-3-
Example for versions 3.9.0 to 3.13.0:
curl -D - -u user:pass -X POST "https://nexus.domain/nexus/service/rest/beta/components?repository=somerepo" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "raw.directory=/test/" -F "raw.asset1=#test.txt;type=application/json" -F "raw.asset1.filename=test.txt"
You can manually upload the artifact's by clicking on upload artifacts button in the Nexus server and provide the necessary GAV properties for uploading(it's generally the file structure for storing the artifact)
#Adam Vandenberg For Java code to POST to Nexus.
https://github.com/manbalagan/nexusuploader
public class NexusRepository implements RepoTargetFactory {
String DIRECTORY_KEY= "raw.directory";
String ASSET_KEY= "raw.asset1";
String FILENAME_KEY= "raw.asset1.filename";
String repoUrl;
String userName;
String password;
#Override
public void setRepoConfigurations(String repoUrl, String userName, String password) {
this.repoUrl = repoUrl;
this.userName = userName;
this.password = password;
}
public String pushToRepository() {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(repoUrl) ;
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
String authHeader = "Basic " + new String(encodedAuth);
postRequest.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
try
{
byte[] packageBytes = "Hello. This is my file content".getBytes();
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
InputStream packageStream = new ByteArrayInputStream(packageBytes);
InputStreamBody inputStreamBody = new InputStreamBody(packageStream, ContentType.APPLICATION_OCTET_STREAM);
multipartEntityBuilder.addPart(DIRECTORY_KEY, new StringBody("DIRECTORY"));
multipartEntityBuilder.addPart(FILENAME_KEY, new StringBody("MyFile.txt"));
multipartEntityBuilder.addPart(ASSET_KEY, inputStreamBody);
HttpEntity entity = multipartEntityBuilder.build();
postRequest.setEntity(entity); ;
HttpResponse response = httpclient.execute(postRequest) ;
if (response != null)
{
System.out.println(response.getStatusLine().getStatusCode());
}
}
catch (Exception ex)
{
ex.printStackTrace() ;
}
return null;
}
}
You can use curl instead.
version=1.2.3
artifact="artifact"
repoId=repositoryId
groupId=org/myorg
REPO_URL=http://localhost:8081/nexus
curl -u username:password --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artifact/$version/$artifact-$version.tgz
Related
I am trying to clone a git repository using JGit.
public static void main(String[] args) throws IOException, InvalidRemoteException, GitAPIException {
String name = "username";
String password = "password";
remotePath = "https://user#stash.gto.intranet.db.com:8081/scm/paragon/paragongit.git";
CredentialsProvider cp = new UsernamePasswordCredentialsProvider(name, password);
File localPath = new File("C:/Users/13 dec/");
if (!localPath.delete()) {
throw new IOException("Could not delete temporary file" + localPath);
}
System.out.println("localPath " + localPath.getAbsolutePath());
System.out.println("Cloning from" + remotePath + "to" + localPath);
Git git = Git.init().setDirectory(localPath).call();
System.out.println("The End");
Git result = Git.cloneRepository().setURI(remotePath).setDirectory(localPath).setCredentialsProvider(cp).call();
System.out.println("The end of program");
}
But I am getting JGitInternalException
Error->Exception in thread "main" org.eclipse.jgit.api.errors.JGitInternalException: Destination path "13 dec" already exists and is not an empty directory
at org.eclipse.jgit.api.CloneCommand.verifyDirectories(CloneCommand.java:253)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:189)
at testInAction.main(testInAction.java:39)
The error message is telling you that you are trying to clone a git repo over the top of an existing non-empty directory.
You can't do that. And you can't do that by running git clone from the command line either; see the comments on https://stackoverflow.com/a/42561781/139985
Basically, git is trying to stop you from shooting yourself in the foot.
when we create a directory in C:\Users then it is created a read only and we would need admin privilege to delete it even using normal delete from windows.
I have this controller which create an empty sheet and I want to return the excel file to the navigator. The problem is, the excel file is corrupted.
If I create the file on my computer the file isn't corrupted, so my HSSFWorkbook is valid. Seems a problem of encodage/encapsulation added by the spring context ?
#Controller
public class ExportController {
#RequestMapping(value = "/export/test/excel", method = RequestMethod.POST)
public void downloadExcelTestFile(
HttpServletRequest request,
HttpServletResponse response) throws IOException {
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
//response.reset();
//response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=test.xls");
OutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
wb.close();
}
The download start well, I receive the file test.xls, but I can't open it. Is there a Spring way to achiev a proper download inside a #Controller ?
I use Spring 4.2.4
UPDATE 1
I tried a Spring way but it's not working better
HSSFWorkbook wb = new HSSFWorkbook();
wb.createSheet("Sheet1");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
} finally {
bos.close();
}
byte[] bytes = bos.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/vnd.ms-excel;");
headers.set("content-length",Integer.toString(bytes.length));
headers.set("Content-Disposition", "attachment; filename=test.xls");
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
UPDATE 3
I found a reason but I don't understand why.
If I build my war file and deploy it manually in the very same tomcat 7.0.70 it works. My Excel is not corrupted.
If I download from the dev environnement in eclipse, it doesn't work. Seems a tomcat + eclipse issue.
Ok that wasn't a Spring issue, not even a tomcat issue.
The problem was from my grunt-connect-proxy, when I run my front throught localhost:9000 : files that I downloaded were corrupted. If I build the project in a war file or run the front from localhost:8080 ( same port than the server ) without "grunt serve" and so without the proxy it works.
I have not fix the problem with grunt ... I just ignore it, but this answer can save your time.
Sample Spring Backed Code to create an excel and return it using Spring REST. The input parameters may change as per your requirement
#RequestMapping(value = "/convertFlatFileToExcel.do", method = RequestMethod.POST)
public HttpEntity<byte[]> convertFlatFileToExcel(#RequestParam(value="file") MultipartFile file,#RequestParam(value="jobid") String jobid) {
ByteArrayOutputStream archivo = new ByteArrayOutputStream();
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.write(archivo);
if(null!=workbook && null!=archivo) {
workbook.close();
archivo.close();
}
byte[] documentContent = archivo.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"myexcelfile.xls\"");
headers.setContentLength(documentContent.length);
response = new ResponseEntity<byte[]>(documentContent, headers, HttpStatus.OK);
}
**Sample UI Code:
Below is the sample code to call to Rest Service using Angular JS. Import the FileSaver js file using https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js
This will have the method saveAs() to save the given excel blob data with a given name.
**
$http.post(urlBase+'/convertFlatFileToExcel.do', formData,{
transformRequest : angular.identity,
responseType: 'arraybuffer',
headers : {
'Content-Type' : undefined,
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}})
.then(
function (response) {
$window.sessionStorage.showProgress = "";
var file = new Blob([response.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
saveAs(file, jobid.toUpperCase()+'.xlsx');
},
function (errResponse) {
$window.sessionStorage.showProgress = "";
$mdDialog.show($mdDialog.alert({title: 'Invalid Job ID!',textContent: 'Please enter a valid Job ID. For any issues, please contact the admin!',ok: 'GOT IT!'}));
deferred.reject(errResponse);
});
This is driving me crazy! I'm trying to serve a JPG image. I am sure this method was working fine the other day, so I don't know what's changed. I've tried many different things to get it to work but I can't seem to get past the exception.
Basically I'm trying to serve an image from the database.
I thought maybe the actual bytes are corrupt so I wrote them to a file, and checked the file content. Just in Finder on Mac, the file in the temp directory looks fine in the preview application so I'm pretty sure it's not the content itself causing the problem.
This is the controller method:
#RequestMapping(value="/binaries/**", method = RequestMethod.GET, produces={MediaType.APPLICATION_JSON_VALUE, MediaType.IMAGE_GIF_VALUE,
MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE, "application/javascript"})
public #ResponseBody
ResponseEntity<byte[]> serveResource(WebRequest webRequest, HttpServletResponse response, String uri) throws IOException {
String path = (String)request.getAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE );
BinaryFile bf = binaryService.findByUri(path);
String tmpdir = System.getProperty("java.io.tmpdir");
File dest = new File(tmpdir + File.separator + bf.getFileName());
FileUtils.writeByteArrayToFile(dest, bf.getResource());
logger.debug("file written: " + dest.getAbsolutePath());
// response.addHeader("Cache-Control", "public, max-age=3600");
if (webRequest.checkNotModified(bf.getLastModifiedDate().toDate().getTime()))
{
return null;
};
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(bf.getResource());
}
This is the exception:
Request: http://localhost:8080/binaries/products/shortcode_1/test_image2.jpg raised org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
Anyone have any ideas? It's Spring 4.1.4.RELEASE
Oh never mind, I figured out what changed. I'd overridden the MessageConverters because I was working on some Jackson stuff, so the fix was that I needed to manually add back the ByteArrayHttpMessageConverter.
#Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter(){
ByteArrayHttpMessageConverter bam = new ByteArrayHttpMessageConverter();
List<org.springframework.http.MediaType> mediaTypes = new LinkedList<org.springframework.http.MediaType>();
mediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON);
mediaTypes.add(org.springframework.http.MediaType.IMAGE_JPEG);
mediaTypes.add(org.springframework.http.MediaType.IMAGE_PNG);
mediaTypes.add(org.springframework.http.MediaType.IMAGE_GIF);
mediaTypes.add(org.springframework.http.MediaType.TEXT_PLAIN);
bam.setSupportedMediaTypes(mediaTypes);
return bam;
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter mapper = new MappingJackson2HttpMessageConverter();
ObjectMapper om = new ObjectMapper();
om.registerModule(new JodaModule());
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setObjectMapper(om);
converters.add(mapper);
converters.add(byteArrayHttpMessageConverter());
super.configureMessageConverters(converters);
}
I'm trying to perform an basic auth to the login-module which runs on my jboss using REST. I already found an StackOverflow topic which explains how to authenticate with credentials.
RESTEasy client framework authentication credentials
This does not work. Analysing the established connection with Wireshark I was not able to see an HTTP package with Authorization: Basic. After more research I found this article, http://docs.jboss.org/resteasy/docs/2.3.3.Final/userguide/html/RESTEasy_Client_Framework.html which describes how to append basic auth to ApacheHttpClient4Executor from resteasy.
// Configure HttpClient to authenticate preemptively
// by prepopulating the authentication data cache.
// 1. Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// 2. Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put("com.bluemonkeydiamond.sippycups", basicAuth);
// 3. Add AuthCache to the execution context
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
// 4. Create client executor and proxy
httpClient = new DefaultHttpClient();
ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext);
client = ProxyFactory.create(BookStoreService.class, url, executor);
But this does not work either. There is no description how to append username and passwort for basic auth to the construct. Why is that information not associated with any class from httpcomponent?
One can use org.jboss.resteasy.client.jaxrs.BasicAuthentication which is packaged with resteasy-client 3.x and is meant specifically for basic authentication.
Client client = ClientBuilder.newClient();
ResteasyWebTarget resteasyWebTarget = (ResteasyWebTarget)client.target("http://mywebservice/rest/api");
resteasyWebTarget.register(new BasicAuthentication("username", "passwd"));
You can add a raw authorization header to your REST client by invoking .header(HttpHeaders.AUTHORIZATION, authHeader) in your client configuration.
The credentials must be packed in authorization header in the format of "user:pass", encoded as base64 byte array and then appended to the string "Basic " which identifies basic auth.
This is the whole snippet (inspired by this post on baeldung)
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
String authHeader = "Basic " + new String(encodedAuth);
authToken = restClient.target(restApiUrl + loginPath)
.request()
.accept(MediaType.TEXT_PLAIN)
.header(HttpHeaders.AUTHORIZATION, authHeader)
.get(String.class);
This worked for me in a Resteasy client. For information, when testing this with wget I had to use the --auth-no-challenge flag.
Consider the solution from Adam Bien:
You can attach an ClientRequestFilter to the RESTEasy Client, which adds the Authorization header to the request:
public class Authenticator implements ClientRequestFilter {
private final String user;
private final String password;
public Authenticator(String user, String password) {
this.user = user;
this.password = password;
}
public void filter(ClientRequestContext requestContext) throws IOException {
MultivaluedMap<String, Object> headers = requestContext.getHeaders();
final String basicAuthentication = getBasicAuthentication();
headers.add("Authorization", basicAuthentication);
}
private String getBasicAuthentication() {
String token = this.user + ":" + this.password;
try {
return "Basic " +
DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
} catch (UnsupportedEncodingException ex) {
throw new IllegalStateException("Cannot encode with UTF-8", ex);
}
}
}
Client client = ClientBuilder.newClient()
.register(new Authenticator(user, password));
I recently upgraded to resteasy-client:4.0.0.Final to deal with some Jackson upgrade issues, and I noticed that setting headers seem to work differently (I was getting 401: Authorization Errors for every authenticated request that previously worked). I also couldn't find much documentation, (the 4.0.0.Final release is only a month old and has some dependency issues, if my experience is representative of the broader case).
The code previously injected headers into the ClientRequestContext:
public AddAuthHeadersRequestFilter(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public void filter(ClientRequestContext requestContext) throws IOException {
String token = username + ":" + password;
String base64Token = Base64.encodeString(token);
requestContext.getHeaders().add("Authorization", "Basic " + base64Token);
}
}
then we set the filter on the ResteasyClient like so:
ResteasyClient client = new ResteasyClientBuilder()
.sslContext(buildSSLContext())
.hostnameVerifier(buildHostVerifier())
.build();
client.register(new AddAuthHeadersRequestFilter(user, pass));
However, this appears not to set the HeaderDelegate, which is where headers are retrieved in 4.x(?) and possibly earlier versions.
The trick was to register that filter on the ResteasyWebTarget instead of the client in the 4.0.0.Final version (you may notice the clientBuilder works a little differently now too).
ResteasyClient client = (ResteasyClient)ResteasyClientBuilder.newBuilder()
.sslContext(buildSSLContext())
.hostnameVerifier(buildHostVerifier())
.build();
ResteasyWebTarget target = client.target(url);
target.register(new AddAuthHeadersRequestFilter(user, pass));
How do I use AWS SDK for ASP.NET to upload a file to a specific folder? - I was able to upload files by specifying the bucket name (request.WithBucketName), but I want to be able to upload a file to a specific folder within the bucket itself.
This is the code that I use to upload a file to a single bucket:
public bool UploadFileToS3(string uploadAsFileName, Stream ImageStream, S3CannedACL filePermission, S3StorageClass storageType, string toWhichBucketName)
{
try
{
client = Amazon.AWSClientFactory.CreateAmazonS3Client(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY);
PutObjectRequest request = new PutObjectRequest();
request.WithKey(uploadAsFileName);
request.WithInputStream(ImageStream);
request.WithBucketName(toWhichBucketName);
request.CannedACL = filePermission;
request.StorageClass = storageType;
client.PutObject(request);
client.Dispose();
}
catch
{
return false;
}
return true;
}
Hope that this code will help you out.
To add a file to a folder in a bucket, you need to update the Key of the PutObjectRequest to include the folder before the file name.
public bool UploadFileToS3(string uploadAsFileName, Stream ImageStream, S3CannedACL filePermission, S3StorageClass storageType, string toWhichBucketName)
{
try
{
using(client = Amazon.AWSClientFactory.CreateAmazonS3Client(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY))
{
PutObjectRequest request = new PutObjectRequest();
request.WithKey( "folder" + "/" + uploadAsFileName );
request.WithInputStream(ImageStream);
request.WithBucketName(toWhichBucketName);
request.CannedACL = filePermission;
request.StorageClass = storageType;
client.PutObject(request);
}
}
catch
{
return false;
}
return true;
}
This post that talks about uploading files to folder. They are using a TransferUtilityUploadRequest though, but it should work with the PutObjectRequest. Scroll to the bottom for the relevant example.
This post shows how to create a folder without uploading a file to it.
Hope this is helpful
Edit:
Updated the code to use a using block instead of calling Dispose per best practices.
Look Like Following functionlity
1.Create an AmazonS3 object
2.Create a bucket
3.Add a new file to Amazon S3
4.Get a file from Amazon S3
5.Delete a file from Amazon S3
Amazon
super easy way:
using System;
using System.Web;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System.Configuration;
/// <summary>
/// Summary description for AWShandler
/// </summary>
public static class AWSHandler
{
public static void sendFileToS3(string fileName, string storeLocation)
{
try
{
AmazonS3Client client = new AmazonS3Client(RegionEndpoint.EUWest1);
PutObjectRequest request = new PutObjectRequest();
request.BucketName = ConfigurationManager.AppSettings["AWSBucket"].ToString();
request.FilePath = fileName;
request.Key = storeLocation + fileName;
request.ContentType = MimeMapping.GetMimeMapping(fileName);
PutObjectResponse response = client.PutObject(request);
}
catch (Exception ex)
{
// use a logger and handle it
}
}
}
you just need to put your keys in the web/app.config file:
<add key="AWSAccessKey" Value="yourKey" />
<add key="AWSSecretKey" Value="yourSecret" />
These can be obtained from you account page in the AWS console. They must use the names quoted here too, as they are pre-defined by the AWS library.