| /******************************************************************************** |
| * Copyright (c) 2018 Mettenmeier GmbH |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0 |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ********************************************************************************/ |
| package org.eclipse.openk.core.controller; |
| |
| import java.io.File; |
| import java.util.Arrays; |
| import java.util.HashMap; |
| import java.util.List; |
| import java.util.Map; |
| |
| import javax.ws.rs.WebApplicationException; |
| import javax.ws.rs.core.MediaType; |
| import javax.ws.rs.core.Response; |
| import javax.ws.rs.core.Response.ResponseBuilder; |
| import javax.ws.rs.core.StreamingOutput; |
| |
| import org.apache.log4j.Logger; |
| import org.eclipse.openk.auth2.util.JwtHelper; |
| import org.eclipse.openk.common.JsonGeneratorBase; |
| import org.eclipse.openk.core.exceptions.HttpStatusException; |
| import org.eclipse.openk.sp.exceptions.SPExceptionParser; |
| import org.eclipse.openk.sp.exceptions.SpErrorEntry; |
| import org.eclipse.openk.sp.exceptions.SpException; |
| import org.eclipse.openk.sp.exceptions.SpExceptionEnum; |
| import org.eclipse.openk.sp.exceptions.SpExceptionMapper; |
| import org.eclipse.openk.sp.rest.reports.ReportRestService; |
| import org.eclipse.openk.sp.util.FileHelper; |
| import org.eclipse.openk.sp.util.FileStreamingOutput; |
| import org.springframework.http.HttpStatus; |
| import org.springframework.transaction.TransactionSystemException; |
| |
| public abstract class BaseWebService { |
| |
| protected final FileHelper fileHelper; |
| |
| private final Map<String, Long> currentTimeMeasures = new HashMap<>(); |
| |
| @FunctionalInterface |
| public interface ModifyingInvokable<T> { |
| T invoke(String changeUser) throws SpException; // NOSONAR |
| } |
| |
| protected final Logger logger; |
| |
| protected BaseWebService(Logger logger, FileHelper fileHelper) { |
| this.logger = logger; |
| this.fileHelper = fileHelper; |
| } |
| |
| protected abstract void assertAndRefreshToken(String token, String[] secureType) throws HttpStatusException; |
| |
| protected Response invokeRunnable(String token, String[] arrSecureType, ModifyingInvokable invokable) { |
| try (AutoCloseable ignored = perform(invokable.getClass().getName() + ".Invoke()")) { // NOSONAR |
| String changeUserName = ""; |
| |
| assertAndRefreshToken(token, arrSecureType); |
| changeUserName = JwtHelper.getJwtPayload(token).getPreferredUsername(); |
| |
| Object o = invokable.invoke(changeUserName); |
| |
| String jsonStr = JsonGeneratorBase.getGson().toJson(o); |
| |
| return Response.ok(jsonStr).build(); |
| |
| } catch (SpException spException) { |
| Integer[] lsConflictIds = { 1001 }; |
| List<Integer> arr = Arrays.asList(lsConflictIds); |
| spException.setStackTrace(new StackTraceElement[0]); |
| logger.error(spException); |
| if (arr.contains(spException.getHttpStatus())) { |
| return Response.status(HttpStatus.CONFLICT.value()).entity(spException).build(); |
| } else { |
| return Response.status(HttpStatus.BAD_REQUEST.value()).entity(spException).build(); |
| } |
| } catch (HttpStatusException e) { |
| SpErrorEntry ee = null; |
| switch (e.getHttpStatus()) { |
| case 401: |
| ee = SpExceptionEnum.HTTP_UNAUTHERIZED_EXCEPTION.getEntry(); |
| break; |
| case 404: |
| ee = SpExceptionEnum.HTTP_UNAUTHERIZED_EXCEPTION.getEntry(); |
| break; |
| case 500: |
| ee = SpExceptionEnum.HTTP_INTERNAL_SERVER_EXCEPTION.getEntry(); |
| break; |
| default: |
| ee = SpExceptionEnum.DEFAULT_EXCEPTION.getEntry(); |
| break; |
| } |
| // ee.setE(e); |
| SpException spException = new SpException(ee); |
| logger.error(spException.getLocalizedMessage()); |
| spException.setStackTrace(new StackTraceElement[0]); |
| return Response.status(spException.getHttpStatus()).entity(spException).build(); |
| |
| } catch (TransactionSystemException e) { |
| String errorString = SPExceptionParser.parseSQLExceptions(e.getCause().getMessage()); |
| SpErrorEntry ee = SpExceptionEnum.DB_TRANSACTIONAL_EXCEPTION.getEntry(); |
| // TransactionSystemException is not serializable |
| SpException spe = new SpException(500, SpExceptionMapper.getExceptionStacktrace(e), null); |
| |
| SpException spException = new SpException(ee.getCode(), spe, errorString); |
| logger.error(errorString, spException); |
| spException.setStackTrace(new StackTraceElement[0]); |
| return Response.status(spException.getHttpStatus()).entity(spException).build(); |
| |
| } catch (Exception e) { |
| SpErrorEntry ee = SpExceptionEnum.DEFAULT_EXCEPTION.getEntry(); |
| SpException spException = new SpException(ee); |
| spException.setStackTrace(new StackTraceElement[0]); |
| return Response.status(500).entity(spException).build(); |
| } |
| } |
| |
| protected Response invokeRunnableStreaming(String token, String[] arrSecureType, ModifyingInvokable invokable) { |
| try (AutoCloseable ignored = perform(invokable.getClass().getName() + ".Invoke()")) { // NOSONAR |
| String changeUserName = ""; |
| |
| assertAndRefreshToken(token, arrSecureType); |
| changeUserName = JwtHelper.getJwtPayload(token).getPreferredUsername(); |
| Object o = invokable.invoke(changeUserName); |
| File f = (File) o; |
| |
| String[] arrString = f.getName().split("\\."); |
| String fileType = arrString[arrString.length - 1]; |
| String mediaType = this.getMediaTypeForFile(fileType); |
| |
| ResponseBuilder responseBuilder = Response.status(200).entity(f).type(mediaType); |
| Response response = responseBuilder.build(); |
| |
| response.getHeaders().putSingle("Content-Length", f.length()); |
| response.getHeaders().putSingle("Content-Disposition", "attachment; filename=" + f.getName()); |
| response.getHeaders().putSingle("Content-Type", "application/octet-stream"); |
| |
| |
| return response; |
| |
| } catch (HttpStatusException e) { |
| SpErrorEntry ee = SpExceptionEnum.DEFAULT_EXCEPTION.getEntry(); |
| ee.setE(e); |
| SpException spException = new SpException(ee); |
| logger.info(e.getHttpStatus(), spException); |
| throw new WebApplicationException(Response.Status.BAD_REQUEST); |
| |
| } catch (Exception e) { |
| SpErrorEntry ee = SpExceptionEnum.DEFAULT_EXCEPTION.getEntry(); |
| SpException spException = new SpException(ee); |
| throw new WebApplicationException(Response.Status.BAD_REQUEST); |
| } |
| } |
| |
| protected StreamingOutput invokeRunnableStream(String token, String[] arrSecureType, ModifyingInvokable invokable) { |
| try (AutoCloseable ignored = perform(invokable.getClass().getName() + ".Invoke()")) { // NOSONAR |
| String changeUserName = ""; |
| |
| assertAndRefreshToken(token, arrSecureType); |
| changeUserName = JwtHelper.getJwtPayload(token).getPreferredUsername(); |
| Object o = invokable.invoke(changeUserName); |
| File f = (File) o; |
| |
| return new FileStreamingOutput(f); |
| |
| } catch (HttpStatusException e) { |
| SpErrorEntry ee = SpExceptionEnum.DEFAULT_EXCEPTION.getEntry(); |
| ee.setE(e); |
| SpException spException = new SpException(ee); |
| logger.info(e.getHttpStatus(), spException); |
| throw new WebApplicationException(Response.Status.BAD_REQUEST); |
| |
| } catch (Exception e) { |
| SpErrorEntry ee = SpExceptionEnum.DEFAULT_EXCEPTION.getEntry(); |
| SpException spException = new SpException(ee); |
| throw new WebApplicationException(Response.Status.BAD_REQUEST); |
| } |
| } |
| |
| private void startProcessing(String methodName) { |
| Long lStartingTime = System.currentTimeMillis(); |
| String lookupName = buildLookupId(methodName); |
| currentTimeMeasures.put(lookupName, lStartingTime); |
| |
| logger.info(this.getClass().getName() + "." + lookupName + ": Start processing..."); |
| } |
| |
| protected AutoCloseable perform(final String methodName) { |
| startProcessing(methodName); |
| return () -> endProcessing(methodName); |
| } |
| |
| private String buildLookupId(String func) { |
| return func + "@@" + Thread.currentThread().getId(); |
| } |
| |
| private void endProcessing(String methodName) { |
| String lookupName = buildLookupId(methodName); |
| if (currentTimeMeasures.containsKey(lookupName)) { |
| Long lStartingTime = currentTimeMeasures.get(lookupName); |
| currentTimeMeasures.remove(lookupName); |
| logger.info(this.getClass().getName() + "." + lookupName + ": Finished processing in " |
| + (System.currentTimeMillis() - lStartingTime) + " ms"); |
| } |
| |
| } |
| |
| /** |
| * @return the fileHelper |
| */ |
| public FileHelper getFileHelper() { |
| return fileHelper; |
| } |
| |
| /** |
| * Method to get the correct media type for the current file. |
| * |
| * @param f pdf or xlsx |
| * @return |
| */ |
| private String getMediaTypeForFile(String fileType) { |
| String mediaType = ""; |
| if (fileType.equalsIgnoreCase("xlsx")) { |
| //mediaType = ReportRestService.EXCEL_MEDIA_TYPE; |
| mediaType="application/octet-stream"; |
| } else if (fileType.equalsIgnoreCase("pdf")) { |
| mediaType = MediaType.APPLICATION_JSON; |
| } |
| return mediaType; |
| |
| } |
| |
| } |