Skip to content

Commit

Permalink
Fixed saving of temporary files (uploaded when deploying)
Browse files Browse the repository at this point in the history
- previous state caused an unsupported archive exception
  • Loading branch information
dmatej committed Apr 12, 2022
1 parent 812bc8d commit 8262ac4
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 58 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
* Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
Expand Down Expand Up @@ -43,13 +44,9 @@
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.sse.SseFeature;

import static org.glassfish.admin.rest.resources.TemplateExecCommand.localStrings;

/**
*
* @author ludovic champenois ludo@dev.java.net Code moved from generated classes to here. Gen code inherits from this
* template class that contains the logic for mapped commands RS Resources
*
*/
@Produces({ "text/html", MediaType.APPLICATION_JSON + ";qs=0.5", MediaType.APPLICATION_XML + ";qs=0.5" })
public class TemplateCommandPostResource extends TemplateExecCommand {
Expand Down Expand Up @@ -175,20 +172,18 @@ private static ParameterMap createDataBasedOnForm(FormDataMultiPart formData) {
formData = new FormDataMultiPart();
}
try {
/* data passed to the generic command running
*
* */

// data passed to the generic command running
Map<String, List<FormDataBodyPart>> m1 = formData.getFields();

Set<String> ss = m1.keySet();
for (String fieldName : ss) {
for (FormDataBodyPart bodyPart : formData.getFields(fieldName)) {

if (bodyPart.getContentDisposition().getFileName() != null) {//we have a file
if (bodyPart.getContentDisposition().getFileName() == null) {
data.add(fieldName, bodyPart.getValue());
} else {
//save it and mark it as delete on exit.
InputStream fileStream = bodyPart.getValueAs(InputStream.class);
String mimeType = bodyPart.getMediaType().toString();

//Use just the filename without complete path. File creation
//in case of remote deployment failing because fo this.
Expand All @@ -201,12 +196,9 @@ private static ParameterMap createDataBasedOnForm(FormDataMultiPart formData) {
}
}

File f = Util.saveFile(fileName, mimeType, fileStream);
f.deleteOnExit();
File f = Util.saveTemporaryFile(fileName, fileStream);
//put only the local path of the file in the same field.
data.add(fieldName, f.getAbsolutePath());
} else {
data.add(fieldName, bodyPart.getValue());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
* Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
Expand Down Expand Up @@ -86,7 +87,7 @@ public class TemplateRestResource extends AbstractResource implements OptionsCap
protected ConfigModel childModel; //good model even if the child entity is null
protected String childID; // id of the current child if part of a list, might be null
public final static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(TemplateRestResource.class);
final private static List<String> attributesToSkip = new ArrayList<String>() {
final private static List<String> attributesToSkip = new ArrayList<>() {

{
add("parent");
Expand Down Expand Up @@ -118,7 +119,7 @@ public Map<String, String> getEntity(@QueryParam("expandLevel") @DefaultValue("1
throw new WebApplicationException(Response.Status.NOT_FOUND);
}

return getAttributes((ConfigBean) getEntity());
return getAttributes(getEntity());
}

@POST
Expand Down Expand Up @@ -183,7 +184,7 @@ public RestResourceMetadata options() {
*/
protected RestActionReporter doCreateOrUpdate(HashMap<String, String> data) {
if (data == null) {
data = new HashMap<String, String>();
data = new HashMap<>();
}
try {
//data.remove("submit");
Expand Down Expand Up @@ -226,7 +227,7 @@ protected RestActionReporter doCreateOrUpdate(HashMap<String, String> data) {

protected ExitCode doDelete(HashMap<String, String> data) {
if (data == null) {
data = new HashMap<String, String>();
data = new HashMap<>();
}
if (entity == null) {//wrong resource
// return Response.status(404).entity(ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo)).build();
Expand Down Expand Up @@ -372,18 +373,19 @@ private String buildPath(Dom node) {
* local location on the server side (ie. just the path)
*/
public static HashMap<String, String> createDataBasedOnForm(FormDataMultiPart formData) {
HashMap<String, String> data = new HashMap<String, String>();
HashMap<String, String> data = new HashMap<>();
try {
//data passed to the generic command running
Map<String, List<FormDataBodyPart>> m1 = formData.getFields();

Set<String> ss = m1.keySet();
for (String fieldName : ss) {
for (FormDataBodyPart bodyPart : formData.getFields(fieldName)) {
if (bodyPart.getContentDisposition().getFileName() != null) {//we have a file
if (bodyPart.getContentDisposition().getFileName() == null) {
data.put(fieldName, bodyPart.getValue());
} else {
//save it and mark it as delete on exit.
InputStream fileStream = bodyPart.getValueAs(InputStream.class);
String mimeType = bodyPart.getMediaType().toString();

//Use just the filename without complete path. File creation
//in case of remote deployment failing because fo this.
Expand All @@ -396,13 +398,9 @@ public static HashMap<String, String> createDataBasedOnForm(FormDataMultiPart fo
}
}

File f = Util.saveFile(fileName, mimeType, fileStream);
f.deleteOnExit();
File f = Util.saveTemporaryFile(fileName, fileStream);
//put only the local path of the file in the same field.
data.put(fieldName, f.getAbsolutePath());

} else {
data.put(fieldName, bodyPart.getValue());
}
}
}
Expand Down Expand Up @@ -448,7 +446,7 @@ public void setBeanByKey(List<Dom> parentList, String id, String tag) {

String keyvalue = c.attribute(keyAttributeName.toLowerCase(Locale.US));
if (keyvalue.equals(childID)) {
setEntity((ConfigBean) c);
setEntity(c);
}
}
}
Expand Down Expand Up @@ -565,7 +563,7 @@ private String getResourceName(String absoluteName, String delimiter) {

//******************************************************************************************************************
private Map<String, String> getAttributes(Dom entity) {
Map<String, String> result = new TreeMap<String, String>();
Map<String, String> result = new TreeMap<>();
Set<String> attributeNames = entity.model.getAttributeNames();
for (String attributeName : attributeNames) {
result.put(eleminateHypen(attributeName), entity.attribute(attributeName));
Expand All @@ -575,7 +573,7 @@ private Map<String, String> getAttributes(Dom entity) {
}

private Map<String, MethodMetaData> getMethodMetaData() {
Map<String, MethodMetaData> map = new TreeMap<String, MethodMetaData>();
Map<String, MethodMetaData> map = new TreeMap<>();
//GET meta data
map.put("GET", new MethodMetaData());

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
* Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
Expand Down Expand Up @@ -44,8 +45,6 @@
import jakarta.ws.rs.core.HttpHeaders;
import org.glassfish.admin.rest.Constants;
import org.glassfish.admin.rest.RestLogging;
import org.glassfish.admin.rest.model.ResponseBody;

import org.glassfish.admin.rest.utils.xml.RestActionReporter;
import org.glassfish.admin.restconnector.RestConfig;
import org.glassfish.api.ActionReport.MessagePart;
Expand Down Expand Up @@ -330,7 +329,7 @@ public static Map<String, String> getCurrentValues(String basePath, Subject subj
}

public static Map<String, String> getCurrentValues(String basePath, ServiceLocator habitat, Subject subject) {
Map<String, String> values = new HashMap<String, String>();
Map<String, String> values = new HashMap<>();
final String path = (basePath.endsWith(".")) ? basePath.substring(0, basePath.length() - 1) : basePath;
RestActionReporter gr = ResourceUtil.runCommand("get", new ParameterMap() {
{
Expand Down Expand Up @@ -442,7 +441,6 @@ public static String getMethodParameterList(CommandModel cm, boolean withType, b
String sep = "";
for (CommandModel.ParamModel model : params) {
Param param = model.getParam();
boolean include = true;
if (param.optional() && !includeOptional) {
continue;
}
Expand All @@ -467,38 +465,38 @@ public static String getMethodParameterList(CommandModel cm, boolean withType, b
return sb.toString();
}

public static File saveFile(String fileName, String mimeType, InputStream fileStream) {
BufferedOutputStream out = null;
File f = null;
public static File saveTemporaryFile(String fileName, InputStream fileStream) {
File file;
try {
if (fileName.contains(".")) {
//String prefix = fileName.substring(0, fileName.indexOf("."));
// String suffix = fileName.substring(fileName.indexOf("."), fileName.length());
//if (prefix.length() < 3) {
// prefix = "glassfish" + prefix;
//}
f = new File(new File(System.getProperty("java.io.tmpdir")), fileName);
}

out = new BufferedOutputStream(new FileOutputStream(f));
String[] parts = getNameAndSuffix(fileName);
file = File.createTempFile(parts[0], parts[1]);
} catch (IOException e) {
throw new IllegalStateException("Could not create a temp file for " + fileName, e);
}
try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
while ((bytesRead = fileStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
return f;
} catch (IOException ex) {
RestLogging.restLogger.log(Level.SEVERE, RestLogging.IO_EXCEPTION, ex.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
RestLogging.restLogger.log(Level.SEVERE, RestLogging.IO_EXCEPTION, ex.getMessage());
}
return file;
} catch (IOException e) {
throw new IllegalStateException("Could not write to a temp file " + file, e);
}
return null;
}


private static String[] getNameAndSuffix(String fileName) {
if (fileName == null) {
return new String[2];
}
int dotPosition = fileName.lastIndexOf('.');
if (dotPosition < 1) {
// on Linux: files with dots as the first char mean hidden files.
// or the dot wasn't found at all
return new String[] {fileName, null};
}
return new String[] {fileName.substring(0, dotPosition), fileName.substring(dotPosition)};
}

public static boolean isGenericType(Type type) {
Expand Down

0 comments on commit 8262ac4

Please sign in to comment.