use of javax.ws.rs.DefaultValue in project mycore by MyCoRe-Org.
the class MCRSessionResource method list.
/**
* Lists all {@link MCRSession}'s in json format.
*
* @param resolveHostname (false) if the host names are resolved. Resolving host names takes some
* time, so this is deactivated by default
* @return list of sessions
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("list")
public Response list(@DefaultValue("false") @QueryParam("resolveHostname") Boolean resolveHostname) {
// check permissions
MCRJerseyUtil.checkPermission("manage-sessions");
// get all sessions
JsonArray rootJSON = new ArrayList<>(MCRSessionMgr.getAllSessions().values()).parallelStream().map(s -> generateSessionJSON(s, resolveHostname)).collect(JsonArray::new, JsonArray::add, JsonArray::addAll);
return Response.status(Status.OK).entity(rootJSON.toString()).build();
}
use of javax.ws.rs.DefaultValue in project alluxio by Alluxio.
the class AlluxioWorkerRestServiceHandler method getWebUILogs.
/**
* Gets web ui logs page data.
*
* @param requestPath the request path
* @param requestOffset the request offset
* @param requestEnd the request end
* @param requestLimit the request limit
* @return the response object
*/
@GET
@Path(WEBUI_LOGS)
public Response getWebUILogs(@DefaultValue("") @QueryParam("path") String requestPath, @DefaultValue("0") @QueryParam("offset") String requestOffset, @QueryParam("end") String requestEnd, @DefaultValue("20") @QueryParam("limit") String requestLimit) {
return RestUtils.call(() -> {
FilenameFilter filenameFilter = (dir, name) -> name.toLowerCase().endsWith(".log");
WorkerWebUILogs response = new WorkerWebUILogs();
if (!ServerConfiguration.getBoolean(PropertyKey.WEB_FILE_INFO_ENABLED)) {
return response;
}
response.setDebug(ServerConfiguration.getBoolean(PropertyKey.DEBUG)).setInvalidPathError("").setViewingOffset(0).setCurrentPath("");
// response.setDownloadLogFile(1);
// response.setBaseUrl("./browseLogs");
// response.setShowPermissions(false);
String logsPath = ServerConfiguration.getString(PropertyKey.LOGS_DIR);
File logsDir = new File(logsPath);
String requestFile = requestPath;
if (requestFile == null || requestFile.isEmpty()) {
// List all log files in the log/ directory.
List<UIFileInfo> fileInfos = new ArrayList<>();
File[] logFiles = logsDir.listFiles(filenameFilter);
if (logFiles != null) {
for (File logFile : logFiles) {
String logFileName = logFile.getName();
fileInfos.add(new UIFileInfo(new UIFileInfo.LocalFileInfo(logFileName, logFileName, logFile.length(), UIFileInfo.LocalFileInfo.EMPTY_CREATION_TIME, logFile.lastModified(), logFile.isDirectory()), ServerConfiguration.global(), new WorkerStorageTierAssoc().getOrderedStorageAliases()));
}
}
Collections.sort(fileInfos, UIFileInfo.PATH_STRING_COMPARE);
response.setNTotalFile(fileInfos.size());
try {
int offset = Integer.parseInt(requestOffset);
int limit = Integer.parseInt(requestLimit);
limit = offset == 0 && limit > fileInfos.size() ? fileInfos.size() : limit;
limit = offset + limit > fileInfos.size() ? fileInfos.size() - offset : limit;
int sum = Math.addExact(offset, limit);
fileInfos = fileInfos.subList(offset, sum);
response.setFileInfos(fileInfos);
} catch (NumberFormatException e) {
response.setFatalError("Error: offset or limit parse error, " + e.getLocalizedMessage());
return response;
} catch (ArithmeticException e) {
response.setFatalError("Error: offset or offset + limit is out of bound, " + e.getLocalizedMessage());
return response;
} catch (IllegalArgumentException e) {
response.setFatalError(e.getLocalizedMessage());
return response;
}
} else {
// Request a specific log file.
// Only allow filenames as the path, to avoid arbitrary local path lookups.
requestFile = new File(requestFile).getName();
response.setCurrentPath(requestFile);
File logFile = new File(logsDir, requestFile);
try {
long fileSize = logFile.length();
String offsetParam = requestOffset;
long relativeOffset = 0;
long offset;
try {
if (offsetParam != null) {
relativeOffset = Long.parseLong(offsetParam);
}
} catch (NumberFormatException e) {
relativeOffset = 0;
}
String endParam = requestEnd;
// relative to the end of the file.
if (endParam == null) {
offset = relativeOffset;
} else {
offset = fileSize - relativeOffset;
}
if (offset < 0) {
offset = 0;
} else if (offset > fileSize) {
offset = fileSize;
}
String fileData;
try (InputStream is = new FileInputStream(logFile)) {
fileSize = logFile.length();
int len = (int) Math.min(5L * Constants.KB, fileSize - offset);
byte[] data = new byte[len];
long skipped = is.skip(offset);
if (skipped < 0) {
// Nothing was skipped.
fileData = "Unable to traverse to offset; is file empty?";
} else if (skipped < offset) {
// Couldn't skip all the way to offset.
fileData = "Unable to traverse to offset; is offset larger than the file?";
} else {
// Read may not read up to len, so only convert what was read.
int read = is.read(data, 0, len);
if (read < 0) {
// Stream couldn't read anything, skip went to EOF?
fileData = "Unable to read file";
} else {
fileData = WebUtils.convertByteArrayToStringWithoutEscape(data, 0, read);
}
}
}
response.setFileData(fileData).setViewingOffset(offset);
} catch (IOException e) {
response.setInvalidPathError("Error: File " + logFile + " is not available " + e.getMessage());
}
}
return response;
}, ServerConfiguration.global());
}
use of javax.ws.rs.DefaultValue in project component-runtime by Talend.
the class ActionResource method getIndex.
/**
* This endpoint returns the list of available actions for a certain family and potentially filters the "
* output limiting it to some families and types of actions.
*
* @param types the types of actions (optional).
* @param families the families (optional).
* @param language the language to use (optional).
* @return the list of actions matching the requested filters or all if none are set.
*/
@GET
// add an index if needed or too slow
@Path("index")
public ActionList getIndex(@QueryParam("type") final String[] types, @QueryParam("family") final String[] families, @QueryParam("language") @DefaultValue("en") final String language) {
final Predicate<ServiceMeta.ActionMeta> typeMatcher = new Predicate<ServiceMeta.ActionMeta>() {
private final Collection<String> accepted = new HashSet<>(asList(types));
@Override
public boolean test(final ServiceMeta.ActionMeta actionMeta) {
return accepted.isEmpty() || accepted.contains(actionMeta.getType());
}
};
final Predicate<ServiceMeta.ActionMeta> componentMatcher = new Predicate<ServiceMeta.ActionMeta>() {
private final Collection<String> accepted = new HashSet<>(asList(families));
@Override
public boolean test(final ServiceMeta.ActionMeta actionMeta) {
return accepted.isEmpty() || accepted.contains(actionMeta.getFamily());
}
};
final Locale locale = localeMapper.mapLocale(language);
return new ActionList(manager.find(c -> c.get(ContainerComponentRegistry.class).getServices().stream().map(s -> s.getActions().stream()).flatMap(identity()).filter(typeMatcher.and(componentMatcher)).map(s -> new ActionItem(s.getFamily(), s.getType(), s.getAction(), propertiesService.buildProperties(s.getParameters(), c.getLoader(), locale, null).collect(toList())))).collect(toList()));
}
use of javax.ws.rs.DefaultValue in project component-runtime by Talend.
the class DocumentationResource method getDocumentation.
/**
* Returns an asciidoctor version of the documentation for the component represented by its identifier `id`.
*
* Format can be either asciidoc or html - if not it will fallback on asciidoc - and if html is selected you get
* a partial document.
*
* IMPORTANT: it is recommended to use asciidoc format and handle the conversion on your side if you can,
* the html flavor handles a limited set of the asciidoc syntax only like plain arrays, paragraph and titles.
*
* The documentation will likely be the family documentation but you can use anchors to access a particular
* component (_componentname_inlowercase).
*
* @param id the component identifier.
* @param language the expected language for the documentation (default to en if not found).
* @param format the expected format (asciidoc or html).
* @return the documentation for that component.
*/
@GET
@Path("component/{id}")
@Produces(MediaType.APPLICATION_JSON)
public DocumentationContent getDocumentation(@PathParam("id") final String id, @QueryParam("language") @DefaultValue("en") final String language, @QueryParam("format") @DefaultValue("asciidoc") final String format) {
final Locale locale = localeMapper.mapLocale(language);
final Container container = ofNullable(componentDao.findById(id)).map(meta -> manager.findPlugin(meta.getParent().getPlugin()).orElseThrow(() -> new WebApplicationException(Response.status(NOT_FOUND).entity(new ErrorPayload(ErrorDictionary.PLUGIN_MISSING, "No plugin '" + meta.getParent().getPlugin() + "'")).build()))).orElseThrow(() -> new WebApplicationException(Response.status(NOT_FOUND).entity(new ErrorPayload(ErrorDictionary.COMPONENT_MISSING, "No component '" + id + "'")).build()));
// rendering to html can be slow so do it lazily and once
DocumentationCache cache = container.get(DocumentationCache.class);
if (cache == null) {
synchronized (container) {
cache = container.get(DocumentationCache.class);
if (cache == null) {
cache = new DocumentationCache();
container.set(DocumentationCache.class, cache);
}
}
}
return cache.documentations.computeIfAbsent(new DocKey(id, language, format), key -> {
// todo: handle i18n properly, for now just fallback on not suffixed version and assume the dev put it
// in the comp
final String content = Stream.of("documentation_" + locale.getLanguage() + ".adoc", "documentation_" + language + ".adoc", "documentation.adoc").map(name -> container.getLoader().getResource("TALEND-INF/" + name)).filter(Objects::nonNull).findFirst().map(url -> {
try (final BufferedReader stream = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
return stream.lines().collect(joining("\n"));
} catch (final IOException e) {
throw new WebApplicationException(Response.status(INTERNAL_SERVER_ERROR).entity(new ErrorPayload(ErrorDictionary.UNEXPECTED, e.getMessage())).build());
}
}).map(value -> {
switch(format) {
case "html":
case "html5":
return adoc.toHtml(value);
case "asciidoc":
case "adoc":
default:
return value;
}
}).orElseThrow(() -> new WebApplicationException(Response.status(NOT_FOUND).entity(new ErrorPayload(ErrorDictionary.COMPONENT_MISSING, "No component '" + id + "'")).build()));
return new DocumentationContent(format, content);
});
}
use of javax.ws.rs.DefaultValue in project component-runtime by Talend.
the class ExecutionResource method read.
/**
* Read inputs from an instance of mapper. The number of returned records if enforced to be limited to 1000.
* The format is a JSON based format where each like is a json record.
*
* @param family the component family.
* @param component the component name.
* @param size the maximum number of records to read.
* @param configuration the component configuration as key/values.
*/
@POST
@Deprecated
@Produces("talend/stream")
@Path("read/{family}/{component}")
public void read(@Suspended final AsyncResponse response, @Context final Providers providers, @PathParam("family") final String family, @PathParam("component") final String component, @QueryParam("size") @DefaultValue("50") final long size, final Map<String, String> configuration) {
final long maxSize = Math.min(size, MAX_RECORDS);
response.setTimeoutHandler(asyncResponse -> log.warn("Timeout on dataset retrieval"));
response.setTimeout(appConfiguration.datasetRetrieverTimeout(), SECONDS);
executorService.submit(() -> {
final Optional<Mapper> mapperOptional = manager.findMapper(family, component, getConfigComponentVersion(configuration), configuration);
if (!mapperOptional.isPresent()) {
response.resume(new WebApplicationException(Response.status(BAD_REQUEST).entity(new ErrorPayload(COMPONENT_MISSING, "Didn't find the input component")).build()));
return;
}
final Mapper mapper = mapperOptional.get();
mapper.start();
try {
final Input input = mapper.create();
try {
input.start();
response.resume((StreamingOutput) output -> {
Object data;
int current = 0;
while (current++ < maxSize && (data = input.next()) != null) {
if (CharSequence.class.isInstance(data) || Number.class.isInstance(data) || Boolean.class.isInstance(data)) {
final PrimitiveWrapper wrapper = new PrimitiveWrapper();
wrapper.setValue(data);
data = wrapper;
}
inlineStreamingMapper.toJson(data, output);
output.write(EOL);
}
});
} finally {
input.stop();
}
} finally {
mapper.stop();
}
});
}
Aggregations