target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testEnvironment() throws Exception { SiteImpl site = getSite(); PathInfo path = getPath(site, "/health/environment"); DefaultEnvironment env = getEnv(); MockHttpServletResponse resp = new MockHttpServletResponse(); monitoringHandler.handle(getRequest(ctx), resp, env, site, path); String content = resp.getContentAsString(); Assert.assertTrue(content.contains("JAVA_HOME")); } | public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } MonitoringHandler(); } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } MonitoringHandler(); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env,
Site site, PathInfo pathInfo); } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } MonitoringHandler(); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env,
Site site, PathInfo pathInfo); } |
@Test public void testSizeMin() { assertTrue("sizeMin(foo,3)"); assertFalse("sizeMin(foo,4)"); assertTrue("sizeMin(multifoo,4)"); assertFalse("sizeMin(multifoo,5)"); assertFalse("sizeMin(multibar,5)"); } | public static boolean sizeMin(Object item, int min) { return size(item) >= min; } | RuleValidation { public static boolean sizeMin(Object item, int min) { return size(item) >= min; } } | RuleValidation { public static boolean sizeMin(Object item, int min) { return size(item) >= min; } RuleValidation(Request container); } | RuleValidation { public static boolean sizeMin(Object item, int min) { return size(item) >= min; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); } | RuleValidation { public static boolean sizeMin(Object item, int min) { return size(item) >= min; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; } |
@Test public void testQuality() throws IOException { File targetFile = new File(targetFolder, "desert-quality-10.jpg"); ImageProcessor ip = getSource(targetFile); ip.fitToWidth(384).quality(10d); ip.getImage(); } | public ImageProcessor quality(double quality) { op.quality(quality); return this; } | ImageProcessor { public ImageProcessor quality(double quality) { op.quality(quality); return this; } } | ImageProcessor { public ImageProcessor quality(double quality) { op.quality(quality); return this; } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); } | ImageProcessor { public ImageProcessor quality(double quality) { op.quality(quality); return this; } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } | ImageProcessor { public ImageProcessor quality(double quality) { op.quality(quality); return this; } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } |
@Test public void test() throws Exception { SiteImpl site = getSite(); PathInfo path = getPath(site, "/health"); DefaultEnvironment env = getEnv(); MockHttpServletResponse resp = new MockHttpServletResponse(); MockHttpServletRequest req = getRequest(ctx); monitoringHandler.handle(req, resp, env, site, path); String responseBody = resp.getContentAsString().replaceAll("\\d{10}", "1204768206"); WritingJsonValidator.validate(responseBody, "rest/health.json"); req = getRequest(ctx); req.addParameter("details", "true"); resp = new MockHttpServletResponse(); monitoringHandler.handle(req, resp, env, site, path); responseBody = resp.getContentAsString().replaceAll("\\d{10}", "1204768206"); WritingJsonValidator.validate(responseBody, "rest/health-detailed.json"); } | public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } MonitoringHandler(); } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } MonitoringHandler(); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env,
Site site, PathInfo pathInfo); } | MonitoringHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env, Site site, PathInfo pathInfo) throws ServletException, IOException { servletResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM); if (isAuthenticated(env, servletRequest)) { String pathsegment = pathInfo.getElementAt(2); Object result = null; if (null == pathsegment) { boolean details = "true".equalsIgnoreCase(servletRequest.getParameter("details")); result = getSiteInfo(site, details, servletResponse); } else if ("system".equals(pathsegment)) { result = new TreeMap<>(System.getProperties()); } else if ("environment".equals(pathsegment)) { result = new TreeMap<>(System.getenv()); } else if ("jars".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, site.getName() + "." + EnvironmentKeys.JAR_INFO_MAP); } else if ("platform".equals(pathsegment)) { result = env.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG + "." + JAR_INFO_MAP); } servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); writer.writeValue(servletResponse.getOutputStream(), result); } else { servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value()); } } MonitoringHandler(); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment env,
Site site, PathInfo pathInfo); } |
@Test public void testRedirectToFirstVisibleApplication() throws ServletException, IOException { servletRequest.setSession(session); MockitoAnnotations.initMocks(this); Mockito.when(platformProperties.getString(Platform.Property.VHOST_MODE)) .thenReturn(VHostMode.NAME_BASED.name()); Mockito.when(platformProperties.getString(Platform.Property.TEMPLATE_FOLDER)).thenReturn("template"); Environment initialEnv = DefaultEnvironment.get(servletContext); initialEnv.setAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG, platformProperties); initialEnv.setAttribute(Scope.PLATFORM, Platform.Environment.SITES, new HashMap<>()); DefaultEnvironment env = DefaultEnvironment.get(servletContext, servletRequest); Mockito.when(siteProperties.getString(SiteProperties.TEMPLATE, null)).thenReturn("appng"); Mockito.when(siteProperties.getString(SiteProperties.DEFAULT_APPLICATION)).thenReturn("manager"); Mockito.when(siteProperties.getString(SiteProperties.MANAGER_PATH)).thenReturn("/manager"); Mockito.when(site.getName()).thenReturn("localhost"); Mockito.when(site.getProperties()).thenReturn(siteProperties); Set<Application> applications = new HashSet<>(); applications.add(applicationB); applications.add(application); Mockito.when(site.getApplications()).thenReturn(applications); Mockito.when(application.getName()).thenReturn("someapp"); Mockito.when(applicationB.isHidden()).thenReturn(true); Mockito.when(subject.hasApplication(application)).thenReturn(true); Mockito.when(subject.isAuthenticated()).thenReturn(true); env.setSubject(subject); Map<String, Site> siteMap = new HashMap<>(); env.setAttribute(Scope.PLATFORM, Platform.Environment.SITES, siteMap); PathInfo pathInfo = new PathInfo("localhost", "http: Arrays.asList("/assets"), Arrays.asList("/de"), "/repository", "jsp"); new GuiHandler(null).handle(servletRequest, servletResponse, env, site, pathInfo); Mockito.verify(site).sendRedirect(env, "/manager/localhost/someapp"); } | public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo pathInfo) throws ServletException, IOException { Properties platformProperties = environment.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { String siteRoot = site.getProperties().getString(SiteProperties.SITE_ROOT_DIR); String siteWwwDir = site.getProperties().getString(SiteProperties.WWW_DIR); String templatePrefix = platformProperties.getString(Platform.Property.TEMPLATE_PREFIX); String templateDir = siteRoot + siteWwwDir + templatePrefix; processGui(servletRequest, servletResponse, environment, site, pathInfo, templateDir); } catch (InvalidConfigurationException e) { Site errorSite = e.getSite(); if (null != errorSite && !errorSite.equals(site)) { String guiPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); LOGGER.warn(String.format("application '%s' not found for site '%s', redirecting to %s", e.getApplicationName(), errorSite.getName(), guiPath), e); Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, guiPath); } else { LOGGER.error("error while processing appNG GUI", e); } } Thread.currentThread().setContextClassLoader(contextClassLoader); } | GuiHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo pathInfo) throws ServletException, IOException { Properties platformProperties = environment.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { String siteRoot = site.getProperties().getString(SiteProperties.SITE_ROOT_DIR); String siteWwwDir = site.getProperties().getString(SiteProperties.WWW_DIR); String templatePrefix = platformProperties.getString(Platform.Property.TEMPLATE_PREFIX); String templateDir = siteRoot + siteWwwDir + templatePrefix; processGui(servletRequest, servletResponse, environment, site, pathInfo, templateDir); } catch (InvalidConfigurationException e) { Site errorSite = e.getSite(); if (null != errorSite && !errorSite.equals(site)) { String guiPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); LOGGER.warn(String.format("application '%s' not found for site '%s', redirecting to %s", e.getApplicationName(), errorSite.getName(), guiPath), e); Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, guiPath); } else { LOGGER.error("error while processing appNG GUI", e); } } Thread.currentThread().setContextClassLoader(contextClassLoader); } } | GuiHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo pathInfo) throws ServletException, IOException { Properties platformProperties = environment.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { String siteRoot = site.getProperties().getString(SiteProperties.SITE_ROOT_DIR); String siteWwwDir = site.getProperties().getString(SiteProperties.WWW_DIR); String templatePrefix = platformProperties.getString(Platform.Property.TEMPLATE_PREFIX); String templateDir = siteRoot + siteWwwDir + templatePrefix; processGui(servletRequest, servletResponse, environment, site, pathInfo, templateDir); } catch (InvalidConfigurationException e) { Site errorSite = e.getSite(); if (null != errorSite && !errorSite.equals(site)) { String guiPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); LOGGER.warn(String.format("application '%s' not found for site '%s', redirecting to %s", e.getApplicationName(), errorSite.getName(), guiPath), e); Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, guiPath); } else { LOGGER.error("error while processing appNG GUI", e); } } Thread.currentThread().setContextClassLoader(contextClassLoader); } GuiHandler(File debugFolder); } | GuiHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo pathInfo) throws ServletException, IOException { Properties platformProperties = environment.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { String siteRoot = site.getProperties().getString(SiteProperties.SITE_ROOT_DIR); String siteWwwDir = site.getProperties().getString(SiteProperties.WWW_DIR); String templatePrefix = platformProperties.getString(Platform.Property.TEMPLATE_PREFIX); String templateDir = siteRoot + siteWwwDir + templatePrefix; processGui(servletRequest, servletResponse, environment, site, pathInfo, templateDir); } catch (InvalidConfigurationException e) { Site errorSite = e.getSite(); if (null != errorSite && !errorSite.equals(site)) { String guiPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); LOGGER.warn(String.format("application '%s' not found for site '%s', redirecting to %s", e.getApplicationName(), errorSite.getName(), guiPath), e); Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, guiPath); } else { LOGGER.error("error while processing appNG GUI", e); } } Thread.currentThread().setContextClassLoader(contextClassLoader); } GuiHandler(File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo pathInfo); } | GuiHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo pathInfo) throws ServletException, IOException { Properties platformProperties = environment.getAttribute(Scope.PLATFORM, Platform.Environment.PLATFORM_CONFIG); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { String siteRoot = site.getProperties().getString(SiteProperties.SITE_ROOT_DIR); String siteWwwDir = site.getProperties().getString(SiteProperties.WWW_DIR); String templatePrefix = platformProperties.getString(Platform.Property.TEMPLATE_PREFIX); String templateDir = siteRoot + siteWwwDir + templatePrefix; processGui(servletRequest, servletResponse, environment, site, pathInfo, templateDir); } catch (InvalidConfigurationException e) { Site errorSite = e.getSite(); if (null != errorSite && !errorSite.equals(site)) { String guiPath = site.getProperties().getString(SiteProperties.MANAGER_PATH); LOGGER.warn(String.format("application '%s' not found for site '%s', redirecting to %s", e.getApplicationName(), errorSite.getName(), guiPath), e); Redirect.to(servletResponse, HttpServletResponse.SC_MOVED_PERMANENTLY, guiPath); } else { LOGGER.error("error while processing appNG GUI", e); } } Thread.currentThread().setContextClassLoader(contextClassLoader); } GuiHandler(File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo pathInfo); static final String PLATFORM_MESSAGES; } |
@Test public void testSoap() throws Exception { String servletPath = "/services/site1/appng-demoapplication/soap/personService/personService.wsdl"; setup(servletPath); List<String> emptyList = new ArrayList<>(); PathInfo pathInfo = new PathInfo("localhost", "localhost", "localhost", servletPath, "/ws", "/services", emptyList, emptyList, "", ""); Mockito.when(environment.getAttribute(Scope.REQUEST, EnvironmentKeys.PATH_INFO)).thenReturn(pathInfo); handle(servletRequest, servletResponse, environment, site, pathInfo); Assert.assertEquals("[SOAP-Call] site1 appng-demoapplication", servletResponse.getContentAsString()); } | public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } |
@Test public void testActionUnsupportedMediaType() throws Exception { String servletPath = "/services/localhost/appng-demoapplication/action/foobar/siteEvent/create"; PathInfo setupPath = setupPath(servletPath); handle(servletRequest, servletResponse, environment, site, setupPath); Assert.assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), servletResponse.getStatus()); } | public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } |
@Test public void testWebservice() throws Exception { String servletPath = "/services/localhost/appng-demoapplication/webservice/personService"; PathInfo pathInfo = setupPath(servletPath); handle(servletRequest, servletResponse, environment, site, pathInfo); Assert.assertEquals("Webservice-Call", servletResponse.getContentAsString()); Assert.assertEquals(HttpHeaders.CONTENT_TYPE_TEXT_PLAIN, servletResponse.getContentType()); Assert.assertEquals(HttpStatus.ACCEPTED.value(), servletResponse.getStatus()); } | public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } |
@Test public void testSiteNotStarted() throws Exception { PathInfo pathInfo = setupPath("/services/localhost/foobar"); site.setState(SiteState.STARTING); handle(servletRequest, servletResponse, environment, site, pathInfo); Assert.assertEquals(StringUtils.EMPTY, servletResponse.getContentAsString()); Assert.assertNull(servletResponse.getContentType()); Assert.assertEquals(HttpStatus.SERVICE_UNAVAILABLE.value(), servletResponse.getStatus()); } | public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } | ServiceRequestHandler implements RequestHandler { public void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment, Site site, PathInfo path) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { if (path.isService()) { String siteName = path.getSiteName(); String applicationName = path.getApplicationName(); String serviceType = path.getElementAt(path.getApplicationIndex() + 1); Site siteToUse = RequestUtil.waitForSite(environment, siteName); if (null == siteToUse) { LOGGER.warn("No such site: '{}', returning {} (path: {})", siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } else if (!siteToUse.hasState(SiteState.STARTED)) { LOGGER.warn("Site '{}' is in state {}, returning {} (path: {})", siteName, siteToUse.getState(), HttpStatus.SERVICE_UNAVAILABLE.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value()); return; } URLClassLoader siteClassLoader = siteToUse.getSiteClassLoader(); Thread.currentThread().setContextClassLoader(siteClassLoader); ApplicationProvider application = (ApplicationProvider) ((SiteImpl) siteToUse) .getSiteApplication(applicationName); if (null == application) { LOGGER.warn("No such application '{}' for site '{}' returning {} (path: {})", applicationName, siteName, HttpStatus.NOT_FOUND.value(), path.getServletPath()); servletResponse.setStatus(HttpStatus.NOT_FOUND.value()); return; } ApplicationRequest applicationRequest = application.getApplicationRequest(servletRequest, servletResponse); String result = null; String contenttype = null; boolean applyPermissionsOnServiceRef = site.getProperties().getBoolean("applyPermissionsOnServiceRef", true); if (SERVICE_TYPE_ACTION.equals(serviceType)) { path.checkPathLength(8); String format = path.getElementAt(path.getApplicationIndex() + 2); String eventId = path.getElementAt(path.getApplicationIndex() + 3); String actionId = path.getElementAt(path.getApplicationIndex() + 4); Action action = application.processAction(servletResponse, applyPermissionsOnServiceRef, applicationRequest, actionId, eventId, marshallService); if (null != action) { LOGGER.debug("calling event '{}', action '{}' of application '{}', format: {}", eventId, actionId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(action); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, action); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(action)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("event not present or no permission ('{}', action '{}' of application '{}')", eventId, actionId, applicationName); } } else if (SERVICE_TYPE_DATASOURCE.equals(serviceType)) { path.checkPathLength(7); String format = path.getElementAt(path.getApplicationIndex() + 2); String dataSourceId = path.getElementAt(path.getApplicationIndex() + 3); Datasource datasource = application.processDataSource(servletResponse, applyPermissionsOnServiceRef, applicationRequest, dataSourceId, marshallService); if (null != datasource) { boolean hasErrors = addMessagesToDatasource(environment, site, application, datasource); if (hasErrors) { LOGGER.debug( "Datasource has been processed an error messages found in session. Set return code to 400"); servletResponse.setStatus(HttpStatus.BAD_REQUEST.value()); } LOGGER.debug("calling datasource '{}' of application '{}', format: {}", dataSourceId, applicationName, format); if (FORMAT_XML.equals(format)) { result = marshallService.marshallNonRoot(datasource); contenttype = MediaType.TEXT_XML_VALUE; } else if (FORMAT_HTML.equals(format)) { result = processPlatform(environment, path, siteToUse, application, datasource); contenttype = MediaType.TEXT_HTML_VALUE; } else if (FORMAT_JSON.equals(format)) { result = writeJson(new JsonWrapper(datasource)); contenttype = MediaType.APPLICATION_JSON_VALUE; } else { servletResponse.setStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()); } } else { LOGGER.debug("datasource not present or no permission ('{}' in application '{}')", dataSourceId, applicationName); } } else if (SERVICE_TYPE_WEBSERVICE.equals(serviceType)) { path.checkPathLength(6); String webserviceName = path.getService(); callWebservice(servletRequest, servletResponse, applicationRequest, environment, siteToUse, application, webserviceName); } else if (SERVICE_TYPE_SOAP.equals(serviceType)) { path.checkPathLength(5); handleSoap(siteToUse, application, environment, servletRequest, servletResponse); } else if (SERVICE_TYPE_REST.equals(serviceType)) { path.checkPathLength(6); handleRest(siteToUse, application, environment, servletRequest, servletResponse); } else { LOGGER.warn("unknown service type: {}", serviceType); } if (null != result) { servletResponse.setContentType(contenttype); servletResponse.getOutputStream().write(result.getBytes()); servletResponse.getOutputStream().close(); } } } catch (Exception e) { String queryString = servletRequest.getQueryString(); String pathWithQuery = servletRequest.getServletPath() + (null == queryString ? "" : "?" + queryString); LOGGER.error(String.format("error while processing service-request %s", pathWithQuery), e); servletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); servletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE); servletResponse.getWriter().write("an error occured"); servletResponse.getWriter().close(); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } ServiceRequestHandler(MarshallService marshallService, PlatformTransformer transformer, File debugFolder); void handle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Environment environment,
Site site, PathInfo path); } |
@Test(timeout = 100000) public void test() throws Exception { ClassLoader classLoader = RepositoryWatcherTest.class.getClassLoader(); URL url = classLoader.getResource("repository/manager/www"); String rootDir = FilenameUtils.normalize(new File(url.toURI()).getPath(), true); String urlrewrite = classLoader.getResource("conf/urlrewrite.xml").getFile(); RepositoryWatcher repositoryWatcher = new RepositoryWatcher(); SiteImpl site = new SiteImpl(); site.setHost("localhost"); PropertyHolder siteProps = new PropertyHolder(); siteProps.addProperty(SiteProperties.CACHE_TIME_TO_LIVE, 1800, null, Property.Type.INT); siteProps.addProperty(SiteProperties.CACHE_STATISTICS, true, null, Property.Type.BOOLEAN); site.setProperties(siteProps); CacheService.createCacheManager(HazelcastConfigurer.getInstance(null), false); Cache<String, CachedResponse> cache = CacheService.createCache(site); String fehlerJsp = "/de/fehler.jsp"; String testJsp = "/de/test.jsp"; String keyFehlerJsp = "GET" + fehlerJsp; String keyTestJsp = "GET" + testJsp; int timeToLive = 1800; HttpServletRequest req = new MockHttpServletRequest(); String contentType = "text/plain"; byte[] bytes = "a value".getBytes(); cache.put(keyFehlerJsp, new CachedResponse(keyFehlerJsp, site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); cache.put(keyTestJsp, new CachedResponse(keyTestJsp, site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); cache.put("GET/de/error", new CachedResponse("GET/de/error", site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); cache.put("GET/de/fault", new CachedResponse("GET/de/fault", site, req, 200, contentType, bytes, new HttpHeaders(), timeToLive)); int size = getCacheSize(cache); Assert.assertEquals(4, size); repositoryWatcher.init(cache, rootDir, new File(urlrewrite), RepositoryWatcher.DEFAULT_RULE_SUFFIX, Arrays.asList("de")); Long forwardsUpdatedAt = repositoryWatcher.forwardsUpdatedAt; ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("repositoryWatcher").setDaemon(true).build(); ExecutorService executor = Executors.newSingleThreadExecutor(tf); executor.execute(repositoryWatcher); FileUtils.touch(new File(rootDir, fehlerJsp)); FileUtils.touch(new File(rootDir, testJsp)); FileUtils.touch(new File(urlrewrite)); while (getCacheSize(cache) != 0 || forwardsUpdatedAt == repositoryWatcher.forwardsUpdatedAt) { Thread.sleep(50); } Assert.assertNull(cache.get(keyFehlerJsp)); Assert.assertNull(cache.get(keyTestJsp)); Assert.assertNull(cache.get("GET/de/error")); Assert.assertNull(cache.get("GET/de/fault")); Assert.assertEquals(0, getCacheSize(cache)); Assert.assertTrue(repositoryWatcher.forwardsUpdatedAt > forwardsUpdatedAt); } | void init(Cache<String, CachedResponse> cache, String wwwDir, File configFile, String ruleSourceSuffix, List<String> documentDirs) throws Exception { this.cache = cache; this.watcher = FileSystems.getDefault().newWatchService(); this.wwwDir = FilenameUtils.normalize(wwwDir, true); this.configFile = configFile; this.ruleSourceSuffix = ruleSourceSuffix; readUrlRewrites(configFile); watch(configFile.getParentFile()); for (String docDir : documentDirs) { watch(new File(wwwDir, docDir)); } } | RepositoryWatcher implements Runnable { void init(Cache<String, CachedResponse> cache, String wwwDir, File configFile, String ruleSourceSuffix, List<String> documentDirs) throws Exception { this.cache = cache; this.watcher = FileSystems.getDefault().newWatchService(); this.wwwDir = FilenameUtils.normalize(wwwDir, true); this.configFile = configFile; this.ruleSourceSuffix = ruleSourceSuffix; readUrlRewrites(configFile); watch(configFile.getParentFile()); for (String docDir : documentDirs) { watch(new File(wwwDir, docDir)); } } } | RepositoryWatcher implements Runnable { void init(Cache<String, CachedResponse> cache, String wwwDir, File configFile, String ruleSourceSuffix, List<String> documentDirs) throws Exception { this.cache = cache; this.watcher = FileSystems.getDefault().newWatchService(); this.wwwDir = FilenameUtils.normalize(wwwDir, true); this.configFile = configFile; this.ruleSourceSuffix = ruleSourceSuffix; readUrlRewrites(configFile); watch(configFile.getParentFile()); for (String docDir : documentDirs) { watch(new File(wwwDir, docDir)); } } RepositoryWatcher(Site site, String jspExtension, String ruleSourceSuffix); RepositoryWatcher(); } | RepositoryWatcher implements Runnable { void init(Cache<String, CachedResponse> cache, String wwwDir, File configFile, String ruleSourceSuffix, List<String> documentDirs) throws Exception { this.cache = cache; this.watcher = FileSystems.getDefault().newWatchService(); this.wwwDir = FilenameUtils.normalize(wwwDir, true); this.configFile = configFile; this.ruleSourceSuffix = ruleSourceSuffix; readUrlRewrites(configFile); watch(configFile.getParentFile()); for (String docDir : documentDirs) { watch(new File(wwwDir, docDir)); } } RepositoryWatcher(Site site, String jspExtension, String ruleSourceSuffix); RepositoryWatcher(); void run(); boolean needsToBeWatched(); } | RepositoryWatcher implements Runnable { void init(Cache<String, CachedResponse> cache, String wwwDir, File configFile, String ruleSourceSuffix, List<String> documentDirs) throws Exception { this.cache = cache; this.watcher = FileSystems.getDefault().newWatchService(); this.wwwDir = FilenameUtils.normalize(wwwDir, true); this.configFile = configFile; this.ruleSourceSuffix = ruleSourceSuffix; readUrlRewrites(configFile); watch(configFile.getParentFile()); for (String docDir : documentDirs) { watch(new File(wwwDir, docDir)); } } RepositoryWatcher(Site site, String jspExtension, String ruleSourceSuffix); RepositoryWatcher(); void run(); boolean needsToBeWatched(); static final String DEFAULT_RULE_SUFFIX; } |
@Test public void testPostProcessBeanFactory() { Site site = Mockito.mock(Site.class); Application application = Mockito.mock(Application.class); DatasourceConfigurer datasourceConfigurer = Mockito.mock(DatasourceConfigurer.class); DatabaseConnection databaseConnection = new DatabaseConnection(); ArrayList<String> dictionaryNames = new ArrayList<>(); ApplicationPostProcessor applicationPostProcessor = new ApplicationPostProcessor(site, application, databaseConnection, null, dictionaryNames); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerSingleton("mockConfigurer", datasourceConfigurer); ApplicationCacheManager cacheManager = Mockito.mock(ApplicationCacheManager.class); beanFactory.registerSingleton("cacheManager", cacheManager); ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); beanFactory.registerSingleton("messageSource", messageSource); beanFactory.registerSingleton("additionalMessageSource", new StaticMessageSource()); applicationPostProcessor.postProcessBeanFactory(beanFactory); Mockito.verify(datasourceConfigurer).configure(databaseConnection); Mockito.verify(cacheManager).initialize(site, application, null); Assert.assertEquals(site, beanFactory.getBean("site")); Assert.assertEquals(application, beanFactory.getBean("application")); Assert.assertEquals(site, beanFactory.getBean(Site.class)); Assert.assertEquals(application, beanFactory.getBean(Application.class)); Assert.assertTrue(messageSource.getParentMessageSource() instanceof MessageSourceChain); Assert.assertTrue(dictionaryNames.contains("messages-core")); } | public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerSingleton("site", site); beanFactory.registerSingleton("application", application); beanFactory.getBean(ApplicationCacheManager.class).initialize(site, application, platformCacheManager); try { DatasourceConfigurer datasourceConfigurer = beanFactory.getBean(DatasourceConfigurer.class); if (null != connection) { try { LOGGER.debug("configuring {}", connection); datasourceConfigurer.configure(connection); } catch (Exception e) { throw new BeanCreationException("error while creating DatasourceConfigurer", e); } } else { LOGGER.debug("no connection given, destroying bean '{}'", DATASOURCE_BEAN_NAME); beanFactory.destroyBean(DATASOURCE_BEAN_NAME, datasourceConfigurer); } } catch (NoSuchBeanDefinitionException e) { LOGGER.debug("no DatasourceConfigurer found in bean-factory"); } dictionaryNames.add(MESSAGES_CORE); Map<String, MessageSource> messageSources = beanFactory.getBeansOfType(MessageSource.class); MessageSource messageSource = messageSources.remove("messageSource"); ResourceBundleMessageSource globalMessageSource = (ResourceBundleMessageSource) messageSource; globalMessageSource.setBasenames(dictionaryNames.toArray(new String[dictionaryNames.size()])); if (messageSources.size() > 0) { MessageSource[] msArray = messageSources.values().toArray(new MessageSource[messageSources.size()]); globalMessageSource.setParentMessageSource(new MessageSourceChain(msArray)); } } | ApplicationPostProcessor implements BeanFactoryPostProcessor, Ordered { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerSingleton("site", site); beanFactory.registerSingleton("application", application); beanFactory.getBean(ApplicationCacheManager.class).initialize(site, application, platformCacheManager); try { DatasourceConfigurer datasourceConfigurer = beanFactory.getBean(DatasourceConfigurer.class); if (null != connection) { try { LOGGER.debug("configuring {}", connection); datasourceConfigurer.configure(connection); } catch (Exception e) { throw new BeanCreationException("error while creating DatasourceConfigurer", e); } } else { LOGGER.debug("no connection given, destroying bean '{}'", DATASOURCE_BEAN_NAME); beanFactory.destroyBean(DATASOURCE_BEAN_NAME, datasourceConfigurer); } } catch (NoSuchBeanDefinitionException e) { LOGGER.debug("no DatasourceConfigurer found in bean-factory"); } dictionaryNames.add(MESSAGES_CORE); Map<String, MessageSource> messageSources = beanFactory.getBeansOfType(MessageSource.class); MessageSource messageSource = messageSources.remove("messageSource"); ResourceBundleMessageSource globalMessageSource = (ResourceBundleMessageSource) messageSource; globalMessageSource.setBasenames(dictionaryNames.toArray(new String[dictionaryNames.size()])); if (messageSources.size() > 0) { MessageSource[] msArray = messageSources.values().toArray(new MessageSource[messageSources.size()]); globalMessageSource.setParentMessageSource(new MessageSourceChain(msArray)); } } } | ApplicationPostProcessor implements BeanFactoryPostProcessor, Ordered { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerSingleton("site", site); beanFactory.registerSingleton("application", application); beanFactory.getBean(ApplicationCacheManager.class).initialize(site, application, platformCacheManager); try { DatasourceConfigurer datasourceConfigurer = beanFactory.getBean(DatasourceConfigurer.class); if (null != connection) { try { LOGGER.debug("configuring {}", connection); datasourceConfigurer.configure(connection); } catch (Exception e) { throw new BeanCreationException("error while creating DatasourceConfigurer", e); } } else { LOGGER.debug("no connection given, destroying bean '{}'", DATASOURCE_BEAN_NAME); beanFactory.destroyBean(DATASOURCE_BEAN_NAME, datasourceConfigurer); } } catch (NoSuchBeanDefinitionException e) { LOGGER.debug("no DatasourceConfigurer found in bean-factory"); } dictionaryNames.add(MESSAGES_CORE); Map<String, MessageSource> messageSources = beanFactory.getBeansOfType(MessageSource.class); MessageSource messageSource = messageSources.remove("messageSource"); ResourceBundleMessageSource globalMessageSource = (ResourceBundleMessageSource) messageSource; globalMessageSource.setBasenames(dictionaryNames.toArray(new String[dictionaryNames.size()])); if (messageSources.size() > 0) { MessageSource[] msArray = messageSources.values().toArray(new MessageSource[messageSources.size()]); globalMessageSource.setParentMessageSource(new MessageSourceChain(msArray)); } } ApplicationPostProcessor(Site site, Application application, DatabaseConnection databaseConnection,
CacheManager platformCacheManager, Collection<String> dictionaryNames); } | ApplicationPostProcessor implements BeanFactoryPostProcessor, Ordered { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerSingleton("site", site); beanFactory.registerSingleton("application", application); beanFactory.getBean(ApplicationCacheManager.class).initialize(site, application, platformCacheManager); try { DatasourceConfigurer datasourceConfigurer = beanFactory.getBean(DatasourceConfigurer.class); if (null != connection) { try { LOGGER.debug("configuring {}", connection); datasourceConfigurer.configure(connection); } catch (Exception e) { throw new BeanCreationException("error while creating DatasourceConfigurer", e); } } else { LOGGER.debug("no connection given, destroying bean '{}'", DATASOURCE_BEAN_NAME); beanFactory.destroyBean(DATASOURCE_BEAN_NAME, datasourceConfigurer); } } catch (NoSuchBeanDefinitionException e) { LOGGER.debug("no DatasourceConfigurer found in bean-factory"); } dictionaryNames.add(MESSAGES_CORE); Map<String, MessageSource> messageSources = beanFactory.getBeansOfType(MessageSource.class); MessageSource messageSource = messageSources.remove("messageSource"); ResourceBundleMessageSource globalMessageSource = (ResourceBundleMessageSource) messageSource; globalMessageSource.setBasenames(dictionaryNames.toArray(new String[dictionaryNames.size()])); if (messageSources.size() > 0) { MessageSource[] msArray = messageSources.values().toArray(new MessageSource[messageSources.size()]); globalMessageSource.setParentMessageSource(new MessageSourceChain(msArray)); } } ApplicationPostProcessor(Site site, Application application, DatabaseConnection databaseConnection,
CacheManager platformCacheManager, Collection<String> dictionaryNames); void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory); int getOrder(); } | ApplicationPostProcessor implements BeanFactoryPostProcessor, Ordered { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { beanFactory.registerSingleton("site", site); beanFactory.registerSingleton("application", application); beanFactory.getBean(ApplicationCacheManager.class).initialize(site, application, platformCacheManager); try { DatasourceConfigurer datasourceConfigurer = beanFactory.getBean(DatasourceConfigurer.class); if (null != connection) { try { LOGGER.debug("configuring {}", connection); datasourceConfigurer.configure(connection); } catch (Exception e) { throw new BeanCreationException("error while creating DatasourceConfigurer", e); } } else { LOGGER.debug("no connection given, destroying bean '{}'", DATASOURCE_BEAN_NAME); beanFactory.destroyBean(DATASOURCE_BEAN_NAME, datasourceConfigurer); } } catch (NoSuchBeanDefinitionException e) { LOGGER.debug("no DatasourceConfigurer found in bean-factory"); } dictionaryNames.add(MESSAGES_CORE); Map<String, MessageSource> messageSources = beanFactory.getBeansOfType(MessageSource.class); MessageSource messageSource = messageSources.remove("messageSource"); ResourceBundleMessageSource globalMessageSource = (ResourceBundleMessageSource) messageSource; globalMessageSource.setBasenames(dictionaryNames.toArray(new String[dictionaryNames.size()])); if (messageSources.size() > 0) { MessageSource[] msArray = messageSources.values().toArray(new MessageSource[messageSources.size()]); globalMessageSource.setParentMessageSource(new MessageSourceChain(msArray)); } } ApplicationPostProcessor(Site site, Application application, DatabaseConnection databaseConnection,
CacheManager platformCacheManager, Collection<String> dictionaryNames); void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory); int getOrder(); } |
@Test public void testIsLocked() { SubjectImpl s = new SubjectImpl(); Date now = new Date(); Assert.assertFalse(s.isExpired(now)); s.setExpiryDate(now); Assert.assertFalse(s.isExpired(now)); Assert.assertFalse(s.isExpired(DateUtils.addMinutes(now, -1))); Assert.assertTrue(s.isExpired(DateUtils.addMilliseconds(now, 1))); Assert.assertTrue(s.isExpired(DateUtils.addSeconds(now, 1))); Assert.assertTrue(s.isExpired(DateUtils.addMinutes(now, 1))); } | @Column(name = "locked") public boolean isLocked() { return locked; } | SubjectImpl implements Subject, Auditable<Integer> { @Column(name = "locked") public boolean isLocked() { return locked; } } | SubjectImpl implements Subject, Auditable<Integer> { @Column(name = "locked") public boolean isLocked() { return locked; } } | SubjectImpl implements Subject, Auditable<Integer> { @Column(name = "locked") public boolean isLocked() { return locked; } @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.USERNAME_OR_LDAPGROUP_PATTERN, message = ValidationPatterns.USERNAME_GROUP_MSSG) @Size(max = ValidationPatterns.LENGTH_255, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); @Version Date getVersion(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 2, max = 3, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getLanguage(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) String getRealname(); @Pattern(regexp = ValidationPatterns.EMAIL_PATTERN, message = ValidationMessages.VALIDATION_EMAIL) @Column(name = "email") String getEmail(); void setEmail(String email); String getDigest(); String getSalt(); @ManyToMany(targetEntity = GroupImpl.class) @JoinTable(joinColumns = { @JoinColumn(name = "subject_Id") }, inverseJoinColumns = { @JoinColumn(name = "group_id") }) List<Group> getGroups(); @Column(name = "type") @Enumerated(EnumType.STRING) UserType getUserType(); @Transient boolean isExpired(Date date); @Column(name = "expiry_date") Date getExpiryDate(); @Column(name = "last_login") Date getLastLogin(); @Column(name = "pw_last_changed") Date getPasswordLastChanged(); @Column(name = "locked") boolean isLocked(); @Column(name = "pw_change_policy") PasswordChangePolicy getPasswordChangePolicy(); @Column(name = "login_attempts") Integer getFailedLoginAttempts(); @Transient boolean isAuthenticated(); @Transient boolean hasApplication(Application application); @Transient List<Role> getApplicationroles(Application application); @Override int hashCode(); @Override boolean equals(Object o); boolean isAuthorized(Authorizable<?> authorizable); @Override String toString(); @Column(name = "timezone") String getTimeZone(); @Transient String getAuthName(); @Transient String getTypeName(); @Transient boolean isInactive(Date now, Integer inactiveLockPeriod); } | SubjectImpl implements Subject, Auditable<Integer> { @Column(name = "locked") public boolean isLocked() { return locked; } @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.USERNAME_OR_LDAPGROUP_PATTERN, message = ValidationPatterns.USERNAME_GROUP_MSSG) @Size(max = ValidationPatterns.LENGTH_255, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); @Version Date getVersion(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 2, max = 3, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getLanguage(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) String getRealname(); @Pattern(regexp = ValidationPatterns.EMAIL_PATTERN, message = ValidationMessages.VALIDATION_EMAIL) @Column(name = "email") String getEmail(); void setEmail(String email); String getDigest(); String getSalt(); @ManyToMany(targetEntity = GroupImpl.class) @JoinTable(joinColumns = { @JoinColumn(name = "subject_Id") }, inverseJoinColumns = { @JoinColumn(name = "group_id") }) List<Group> getGroups(); @Column(name = "type") @Enumerated(EnumType.STRING) UserType getUserType(); @Transient boolean isExpired(Date date); @Column(name = "expiry_date") Date getExpiryDate(); @Column(name = "last_login") Date getLastLogin(); @Column(name = "pw_last_changed") Date getPasswordLastChanged(); @Column(name = "locked") boolean isLocked(); @Column(name = "pw_change_policy") PasswordChangePolicy getPasswordChangePolicy(); @Column(name = "login_attempts") Integer getFailedLoginAttempts(); @Transient boolean isAuthenticated(); @Transient boolean hasApplication(Application application); @Transient List<Role> getApplicationroles(Application application); @Override int hashCode(); @Override boolean equals(Object o); boolean isAuthorized(Authorizable<?> authorizable); @Override String toString(); @Column(name = "timezone") String getTimeZone(); @Transient String getAuthName(); @Transient String getTypeName(); @Transient boolean isInactive(Date now, Integer inactiveLockPeriod); } |
@Test public void testIsInactive() { SubjectImpl s = new SubjectImpl(); Date now = new Date(); s.setLastLogin(now); int inactiveLockPeriod = 10; Assert.assertFalse(s.isInactive(now, inactiveLockPeriod)); Assert.assertFalse(s.isInactive(now, inactiveLockPeriod)); Assert.assertFalse(s.isInactive(now, inactiveLockPeriod)); Date plusTenDays = DateUtils.addDays(now, inactiveLockPeriod); Assert.assertFalse(s.isInactive(plusTenDays, inactiveLockPeriod)); Assert.assertTrue(s.isInactive(DateUtils.addMilliseconds(plusTenDays, 1), inactiveLockPeriod)); Assert.assertTrue(s.isInactive(DateUtils.addDays(now, 11), inactiveLockPeriod)); } | @Transient public boolean isInactive(Date now, Integer inactiveLockPeriod) { return null != lastLogin && inactiveLockPeriod > 0 && DateUtils.addDays(lastLogin, inactiveLockPeriod).before(now); } | SubjectImpl implements Subject, Auditable<Integer> { @Transient public boolean isInactive(Date now, Integer inactiveLockPeriod) { return null != lastLogin && inactiveLockPeriod > 0 && DateUtils.addDays(lastLogin, inactiveLockPeriod).before(now); } } | SubjectImpl implements Subject, Auditable<Integer> { @Transient public boolean isInactive(Date now, Integer inactiveLockPeriod) { return null != lastLogin && inactiveLockPeriod > 0 && DateUtils.addDays(lastLogin, inactiveLockPeriod).before(now); } } | SubjectImpl implements Subject, Auditable<Integer> { @Transient public boolean isInactive(Date now, Integer inactiveLockPeriod) { return null != lastLogin && inactiveLockPeriod > 0 && DateUtils.addDays(lastLogin, inactiveLockPeriod).before(now); } @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.USERNAME_OR_LDAPGROUP_PATTERN, message = ValidationPatterns.USERNAME_GROUP_MSSG) @Size(max = ValidationPatterns.LENGTH_255, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); @Version Date getVersion(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 2, max = 3, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getLanguage(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) String getRealname(); @Pattern(regexp = ValidationPatterns.EMAIL_PATTERN, message = ValidationMessages.VALIDATION_EMAIL) @Column(name = "email") String getEmail(); void setEmail(String email); String getDigest(); String getSalt(); @ManyToMany(targetEntity = GroupImpl.class) @JoinTable(joinColumns = { @JoinColumn(name = "subject_Id") }, inverseJoinColumns = { @JoinColumn(name = "group_id") }) List<Group> getGroups(); @Column(name = "type") @Enumerated(EnumType.STRING) UserType getUserType(); @Transient boolean isExpired(Date date); @Column(name = "expiry_date") Date getExpiryDate(); @Column(name = "last_login") Date getLastLogin(); @Column(name = "pw_last_changed") Date getPasswordLastChanged(); @Column(name = "locked") boolean isLocked(); @Column(name = "pw_change_policy") PasswordChangePolicy getPasswordChangePolicy(); @Column(name = "login_attempts") Integer getFailedLoginAttempts(); @Transient boolean isAuthenticated(); @Transient boolean hasApplication(Application application); @Transient List<Role> getApplicationroles(Application application); @Override int hashCode(); @Override boolean equals(Object o); boolean isAuthorized(Authorizable<?> authorizable); @Override String toString(); @Column(name = "timezone") String getTimeZone(); @Transient String getAuthName(); @Transient String getTypeName(); @Transient boolean isInactive(Date now, Integer inactiveLockPeriod); } | SubjectImpl implements Subject, Auditable<Integer> { @Transient public boolean isInactive(Date now, Integer inactiveLockPeriod) { return null != lastLogin && inactiveLockPeriod > 0 && DateUtils.addDays(lastLogin, inactiveLockPeriod).before(now); } @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.USERNAME_OR_LDAPGROUP_PATTERN, message = ValidationPatterns.USERNAME_GROUP_MSSG) @Size(max = ValidationPatterns.LENGTH_255, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); @Version Date getVersion(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 2, max = 3, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getLanguage(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) String getRealname(); @Pattern(regexp = ValidationPatterns.EMAIL_PATTERN, message = ValidationMessages.VALIDATION_EMAIL) @Column(name = "email") String getEmail(); void setEmail(String email); String getDigest(); String getSalt(); @ManyToMany(targetEntity = GroupImpl.class) @JoinTable(joinColumns = { @JoinColumn(name = "subject_Id") }, inverseJoinColumns = { @JoinColumn(name = "group_id") }) List<Group> getGroups(); @Column(name = "type") @Enumerated(EnumType.STRING) UserType getUserType(); @Transient boolean isExpired(Date date); @Column(name = "expiry_date") Date getExpiryDate(); @Column(name = "last_login") Date getLastLogin(); @Column(name = "pw_last_changed") Date getPasswordLastChanged(); @Column(name = "locked") boolean isLocked(); @Column(name = "pw_change_policy") PasswordChangePolicy getPasswordChangePolicy(); @Column(name = "login_attempts") Integer getFailedLoginAttempts(); @Transient boolean isAuthenticated(); @Transient boolean hasApplication(Application application); @Transient List<Role> getApplicationroles(Application application); @Override int hashCode(); @Override boolean equals(Object o); boolean isAuthorized(Authorizable<?> authorizable); @Override String toString(); @Column(name = "timezone") String getTimeZone(); @Transient String getAuthName(); @Transient String getTypeName(); @Transient boolean isInactive(Date now, Integer inactiveLockPeriod); } |
@Test public void testSizeMax() { assertTrue("sizeMax(foo,4)"); assertFalse("sizeMax(foo,2)"); assertTrue("sizeMax(multifoo,4)"); assertFalse("sizeMax(multifoo,3)"); assertTrue("sizeMax(multibar,3)"); } | public static boolean sizeMax(Object item, int max) { return size(item) <= max; } | RuleValidation { public static boolean sizeMax(Object item, int max) { return size(item) <= max; } } | RuleValidation { public static boolean sizeMax(Object item, int max) { return size(item) <= max; } RuleValidation(Request container); } | RuleValidation { public static boolean sizeMax(Object item, int max) { return size(item) <= max; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); } | RuleValidation { public static boolean sizeMax(Object item, int max) { return size(item) <= max; } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; } |
@Test public void testDetermineType() { PropertyImpl booleanProp = new PropertyImpl("booleanProp", "true"); booleanProp.determineType(); Assert.assertEquals(Property.Type.BOOLEAN, booleanProp.getType()); PropertyImpl intProp = new PropertyImpl("intProp", "5"); intProp.determineType(); Assert.assertEquals(Property.Type.INT, intProp.getType()); PropertyImpl decimalProp = new PropertyImpl("decimalProp", "5.42"); decimalProp.determineType(); Assert.assertEquals(Property.Type.DECIMAL, decimalProp.getType()); PropertyImpl multilineProp = new PropertyImpl("multilineProp", null); multilineProp.setClob("textProp"); multilineProp.determineType(); Assert.assertEquals(Property.Type.MULTILINE, multilineProp.getType()); PropertyImpl textProp = new PropertyImpl("textProp", "test"); textProp.determineType(); Assert.assertEquals(Property.Type.TEXT, textProp.getType()); } | @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) public Type getType() { return super.getType(); } | PropertyImpl extends SimpleProperty implements Property, Auditable<String>, Comparable<Property> { @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) public Type getType() { return super.getType(); } } | PropertyImpl extends SimpleProperty implements Property, Auditable<String>, Comparable<Property> { @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) public Type getType() { return super.getType(); } PropertyImpl(); PropertyImpl(String name, String value); PropertyImpl(String name, String value, String defaultValue); } | PropertyImpl extends SimpleProperty implements Property, Auditable<String>, Comparable<Property> { @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) public Type getType() { return super.getType(); } PropertyImpl(); PropertyImpl(String name, String value); PropertyImpl(String name, String value, String defaultValue); @Override @Id @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 3, max = 255, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getName(); @Override boolean isMandatory(); @Override @Transient String getId(); @Override @Version Date getVersion(); @Override @Column(name = "value") String getActualString(); @Override @Column(name = "defaultValue") String getDefaultString(); @Override @Column(name = "description", length = 1024) String getDescription(); @Override @Column(name = "blobValue") @Lob byte[] getBlob(); @Override @Column(name = "clobValue") @Lob String getClob(); @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) Type getType(); @Override int hashCode(); @Override boolean equals(Object o); } | PropertyImpl extends SimpleProperty implements Property, Auditable<String>, Comparable<Property> { @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) public Type getType() { return super.getType(); } PropertyImpl(); PropertyImpl(String name, String value); PropertyImpl(String name, String value, String defaultValue); @Override @Id @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Size(min = 3, max = 255, message = ValidationMessages.VALIDATION_STRING_MIN_MAX) String getName(); @Override boolean isMandatory(); @Override @Transient String getId(); @Override @Version Date getVersion(); @Override @Column(name = "value") String getActualString(); @Override @Column(name = "defaultValue") String getDefaultString(); @Override @Column(name = "description", length = 1024) String getDescription(); @Override @Column(name = "blobValue") @Lob byte[] getBlob(); @Override @Column(name = "clobValue") @Lob String getClob(); @Override @Column(name = "prop_type") @Enumerated(EnumType.STRING) Type getType(); @Override int hashCode(); @Override boolean equals(Object o); } |
@Test public void testSiteInternalRedirect() { site.sendRedirect(environment, "page/foo/bar#anchor", HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals("/ws/foo/page/foo/bar#anchor", response.getHeader(HttpHeaders.LOCATION)); Assert.assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()); } | public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } |
@Test public void testSiteInternalRedirectMSIE() { Mockito.when(environment.getAttribute(REQUEST, HttpHeaders.USER_AGENT)).thenReturn("MSIE"); site.sendRedirect(environment, "page/foo/bar#anchor", HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals("/ws/foo/page/foo/bar?tab=anchor#anchor", response.getHeader(HttpHeaders.LOCATION)); Assert.assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()); } | public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } |
@Test public void testExternalRedirect() { site.sendRedirect(environment, "/some/uri", HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals("/some/uri", response.getHeader(HttpHeaders.LOCATION)); Assert.assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()); } | public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } | SiteImpl implements Site, Auditable<Integer> { public void sendRedirect(Environment env, String target) { sendRedirect(env, target, HttpServletResponse.SC_MOVED_PERMANENTLY); } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } |
@Test public void testCloseClassloader() throws IOException { site.setSiteApplications(new HashSet<>()); site.closeSiteContext(); try { URLClassLoader.class.getMethod("close"); Assert.assertTrue("siteclassloader should be closed", isClosed); } catch (NoSuchMethodException e) { Assert.assertFalse("siteclassloader should not be closed", isClosed); } } | private void closeClassloader() { try { siteClassLoader.close(); } catch (IOException e) { LOGGER.error("error while closing classloader", e); } siteClassLoader = null; } | SiteImpl implements Site, Auditable<Integer> { private void closeClassloader() { try { siteClassLoader.close(); } catch (IOException e) { LOGGER.error("error while closing classloader", e); } siteClassLoader = null; } } | SiteImpl implements Site, Auditable<Integer> { private void closeClassloader() { try { siteClassLoader.close(); } catch (IOException e) { LOGGER.error("error while closing classloader", e); } siteClassLoader = null; } } | SiteImpl implements Site, Auditable<Integer> { private void closeClassloader() { try { siteClassLoader.close(); } catch (IOException e) { LOGGER.error("error while closing classloader", e); } siteClassLoader = null; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } | SiteImpl implements Site, Auditable<Integer> { private void closeClassloader() { try { siteClassLoader.close(); } catch (IOException e) { LOGGER.error("error while closing classloader", e); } siteClassLoader = null; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer getId(); void setId(Integer id); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.NAME_STRICT_PATTERN, message = ValidationPatterns.NAME_STRICT_MSSG) @Size(max = ValidationPatterns.LENGTH_64, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(unique = true) String getName(); void setName(String name); @Size(max = ValidationPatterns.LENGTH_8192, message = ValidationMessages.VALIDATION_STRING_MAX) @Column(length = ValidationPatterns.LENGTH_8192) String getDescription(); void setDescription(String description); @Version Date getVersion(); void setVersion(Date version); @OneToMany(targetEntity = org.appng.core.domain.SiteApplication.class, fetch = FetchType.LAZY, mappedBy = "site") Set<SiteApplication> getSiteApplications(); void setSiteApplications(Set<SiteApplication> applications); @Transient Set<Application> getApplications(); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.HOST_PATTERN, message = ValidationPatterns.HOST_MSSG) @Column(unique = true) String getHost(); void setHost(String host); @NotNull(message = ValidationMessages.VALIDATION_NOT_NULL) @Pattern(regexp = ValidationPatterns.DOMAIN_PATTERN, message = ValidationPatterns.DOMAIN_MSSG) @Column(unique = true) String getDomain(); void setDomain(String domain); boolean isActive(); void setActive(boolean active); @Column(name = "create_repository") boolean isCreateRepository(); void setCreateRepository(boolean createRepository); @Column(name = "reload_count") int getReloadCount(); void setReloadCount(int reloadCount); @Transient Map<String, Application> getApplicationMap(); @Transient Application getApplication(String name); @Transient boolean hasApplication(String name); @Override int hashCode(); @Override boolean equals(Object o); @Transient Properties getProperties(); void setProperties(Properties properties); @Transient SiteClassLoader getSiteClassLoader(); void setSiteClassLoader(SiteClassLoader siteClassLoader); void setSender(Sender sender); boolean sendEvent(Event event); void sendRedirect(Environment env, String target); void sendRedirect(Environment env, String target, Integer statusCode); void sendRedirect(Environment env, String target, Integer statusCode, boolean keepOrigin); File readFile(String relativePath); @Transient Date getStartupTime(); void setStartupTime(Date startupTime); @Override String toString(); void closeSiteContext(); @Transient Set<Named<Integer>> getGroups(); void setGroups(Set<Named<Integer>> groups); void setRootDirectory(File siteRootDirectory); SiteApplication getSiteApplication(String name); @Transient PasswordPolicy getPasswordPolicy(); void setPasswordPolicy(PasswordPolicy policy); @Transient boolean isRunning(); void setRunning(boolean isRunning); @Transient SiteState getState(); void setState(SiteState state); boolean hasState(SiteState... states); int addRequest(); int removeRequest(); @Transient int getRequests(); } |
@Test public void testDeselectAllOptions() { ResponseEntity<Action> actionEntity = new ResponseEntity<>(new Action(), HttpStatus.OK); ActionField field = getSelectionField(); Option a = getOption("a", true); field.getOptions().getEntries().add(a); Option b = getOption("b", true); field.getOptions().getEntries().add(b); Action action = actionEntity.getBody(); action.setFields(new ArrayList<>()); action.getFields().add(field); ActionHelper.create(actionEntity).deselectAllOptions(field.getName()); Assert.assertFalse(a.isSelected()); Assert.assertFalse(b.isSelected()); } | public ActionHelper deselectAllOptions(String name) { Optional<ActionField> field = getField(name); if (field.isPresent() && isSelectionType(field.get())) { field.get().getOptions().getEntries().forEach(o -> o.setSelected(false)); } return this; } | ActionHelper { public ActionHelper deselectAllOptions(String name) { Optional<ActionField> field = getField(name); if (field.isPresent() && isSelectionType(field.get())) { field.get().getOptions().getEntries().forEach(o -> o.setSelected(false)); } return this; } } | ActionHelper { public ActionHelper deselectAllOptions(String name) { Optional<ActionField> field = getField(name); if (field.isPresent() && isSelectionType(field.get())) { field.get().getOptions().getEntries().forEach(o -> o.setSelected(false)); } return this; } ActionHelper(ResponseEntity<Action> action); } | ActionHelper { public ActionHelper deselectAllOptions(String name) { Optional<ActionField> field = getField(name); if (field.isPresent() && isSelectionType(field.get())) { field.get().getOptions().getEntries().forEach(o -> o.setSelected(false)); } return this; } ActionHelper(ResponseEntity<Action> action); static ActionHelper create(ResponseEntity<Action> action); ActionHelper setFieldValue(String name, Object value); ActionHelper setFieldSelectionValue(String name, String value); ActionHelper deselectAllOptions(String name); Optional<ActionField> getField(List<ActionField> fields, String name); Optional<ActionField> getField(String name); } | ActionHelper { public ActionHelper deselectAllOptions(String name) { Optional<ActionField> field = getField(name); if (field.isPresent() && isSelectionType(field.get())) { field.get().getOptions().getEntries().forEach(o -> o.setSelected(false)); } return this; } ActionHelper(ResponseEntity<Action> action); static ActionHelper create(ResponseEntity<Action> action); ActionHelper setFieldValue(String name, Object value); ActionHelper setFieldSelectionValue(String name, String value); ActionHelper deselectAllOptions(String name); Optional<ActionField> getField(List<ActionField> fields, String name); Optional<ActionField> getField(String name); } |
@Test public void testSetFieldValue() { Action action = new Action(); ResponseEntity<Action> actionEntity = new ResponseEntity<>(action, HttpStatus.OK); ActionField field = new ActionField(); field.setName("field"); field.setFieldType(FieldType.TEXT); action.setFields(new ArrayList<>()); action.getFields().add(field); ActionHelper actionHelper = ActionHelper.create(actionEntity); Assert.assertNull(actionHelper.getField("field").get().getValue()); actionHelper.setFieldValue("field", "a"); Assert.assertEquals("a", actionHelper.getField("field").get().getValue()); } | public ActionHelper setFieldValue(String name, Object value) { Optional<ActionField> field = getField(name); if (field.isPresent() && !isSelectionType(field.get())) { field.get().setValue(value); } return this; } | ActionHelper { public ActionHelper setFieldValue(String name, Object value) { Optional<ActionField> field = getField(name); if (field.isPresent() && !isSelectionType(field.get())) { field.get().setValue(value); } return this; } } | ActionHelper { public ActionHelper setFieldValue(String name, Object value) { Optional<ActionField> field = getField(name); if (field.isPresent() && !isSelectionType(field.get())) { field.get().setValue(value); } return this; } ActionHelper(ResponseEntity<Action> action); } | ActionHelper { public ActionHelper setFieldValue(String name, Object value) { Optional<ActionField> field = getField(name); if (field.isPresent() && !isSelectionType(field.get())) { field.get().setValue(value); } return this; } ActionHelper(ResponseEntity<Action> action); static ActionHelper create(ResponseEntity<Action> action); ActionHelper setFieldValue(String name, Object value); ActionHelper setFieldSelectionValue(String name, String value); ActionHelper deselectAllOptions(String name); Optional<ActionField> getField(List<ActionField> fields, String name); Optional<ActionField> getField(String name); } | ActionHelper { public ActionHelper setFieldValue(String name, Object value) { Optional<ActionField> field = getField(name); if (field.isPresent() && !isSelectionType(field.get())) { field.get().setValue(value); } return this; } ActionHelper(ResponseEntity<Action> action); static ActionHelper create(ResponseEntity<Action> action); ActionHelper setFieldValue(String name, Object value); ActionHelper setFieldSelectionValue(String name, String value); ActionHelper deselectAllOptions(String name); Optional<ActionField> getField(List<ActionField> fields, String name); Optional<ActionField> getField(String name); } |
@Test public void testCookies() { Map<String, String> cookies = new HashMap<>(); cookies.put("foo", "bar"); cookies.put("lore", "ipsum"); RestClient restClient = new RestClient("foo", cookies); List<String> cookieList = restClient.getHeaders(false).get(HttpHeaders.COOKIE); Assert.assertTrue(cookieList.contains("foo=bar")); Assert.assertTrue(cookieList.contains("lore=ipsum")); } | protected HttpHeaders getHeaders(boolean acceptAnyType) { HttpHeaders headers = new HttpHeaders(); if (!cookies.isEmpty()) { cookies.keySet().forEach(k -> { String cookie = cookies.get(k); headers.add(HttpHeaders.COOKIE, k + "=" + cookie); LOGGER.debug("sent cookie: {}={}", k, cookies.get(k)); }); } headers.setContentType(MediaType.APPLICATION_JSON_UTF8); List<MediaType> acceptableMediaTypes; if (acceptAnyType) { acceptableMediaTypes = Arrays.asList(MediaType.ALL); } else { acceptableMediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_UTF8); } headers.setAccept(acceptableMediaTypes); headers.set(HttpHeaders.USER_AGENT, "appNG Rest Client"); return headers; } | RestClient { protected HttpHeaders getHeaders(boolean acceptAnyType) { HttpHeaders headers = new HttpHeaders(); if (!cookies.isEmpty()) { cookies.keySet().forEach(k -> { String cookie = cookies.get(k); headers.add(HttpHeaders.COOKIE, k + "=" + cookie); LOGGER.debug("sent cookie: {}={}", k, cookies.get(k)); }); } headers.setContentType(MediaType.APPLICATION_JSON_UTF8); List<MediaType> acceptableMediaTypes; if (acceptAnyType) { acceptableMediaTypes = Arrays.asList(MediaType.ALL); } else { acceptableMediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_UTF8); } headers.setAccept(acceptableMediaTypes); headers.set(HttpHeaders.USER_AGENT, "appNG Rest Client"); return headers; } } | RestClient { protected HttpHeaders getHeaders(boolean acceptAnyType) { HttpHeaders headers = new HttpHeaders(); if (!cookies.isEmpty()) { cookies.keySet().forEach(k -> { String cookie = cookies.get(k); headers.add(HttpHeaders.COOKIE, k + "=" + cookie); LOGGER.debug("sent cookie: {}={}", k, cookies.get(k)); }); } headers.setContentType(MediaType.APPLICATION_JSON_UTF8); List<MediaType> acceptableMediaTypes; if (acceptAnyType) { acceptableMediaTypes = Arrays.asList(MediaType.ALL); } else { acceptableMediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_UTF8); } headers.setAccept(acceptableMediaTypes); headers.set(HttpHeaders.USER_AGENT, "appNG Rest Client"); return headers; } RestClient(String url); RestClient(String url, Map<String, String> cookies); } | RestClient { protected HttpHeaders getHeaders(boolean acceptAnyType) { HttpHeaders headers = new HttpHeaders(); if (!cookies.isEmpty()) { cookies.keySet().forEach(k -> { String cookie = cookies.get(k); headers.add(HttpHeaders.COOKIE, k + "=" + cookie); LOGGER.debug("sent cookie: {}={}", k, cookies.get(k)); }); } headers.setContentType(MediaType.APPLICATION_JSON_UTF8); List<MediaType> acceptableMediaTypes; if (acceptAnyType) { acceptableMediaTypes = Arrays.asList(MediaType.ALL); } else { acceptableMediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_UTF8); } headers.setAccept(acceptableMediaTypes); headers.set(HttpHeaders.USER_AGENT, "appNG Rest Client"); return headers; } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id,
MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable,
MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId,
String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); } | RestClient { protected HttpHeaders getHeaders(boolean acceptAnyType) { HttpHeaders headers = new HttpHeaders(); if (!cookies.isEmpty()) { cookies.keySet().forEach(k -> { String cookie = cookies.get(k); headers.add(HttpHeaders.COOKIE, k + "=" + cookie); LOGGER.debug("sent cookie: {}={}", k, cookies.get(k)); }); } headers.setContentType(MediaType.APPLICATION_JSON_UTF8); List<MediaType> acceptableMediaTypes; if (acceptAnyType) { acceptableMediaTypes = Arrays.asList(MediaType.ALL); } else { acceptableMediaTypes = Arrays.asList(MediaType.APPLICATION_JSON_UTF8); } headers.setAccept(acceptableMediaTypes); headers.set(HttpHeaders.USER_AGENT, "appNG Rest Client"); return headers; } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id,
MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable,
MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId,
String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); } |
@Test public void testSetCookies() { RestClient restClient = new RestClient("foo"); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.SET_COOKIE, "foo=bar"); headers.add(HttpHeaders.SET_COOKIE, "lore=ipsum;"); restClient.setCookies(new ResponseEntity<>(headers, HttpStatus.OK)); Map<String, String> cookies = restClient.getCookies(); Assert.assertEquals("bar", cookies.get("foo")); Assert.assertEquals("ipsum", cookies.get("lore")); } | protected void setCookies(ResponseEntity<?> entity) { List<String> setCookies = entity.getHeaders().get(HttpHeaders.SET_COOKIE); if (null != setCookies) { for (String c : setCookies) { int valueStart = c.indexOf('='); String name = c.substring(0, valueStart); int end = c.indexOf(';'); String value = c.substring(valueStart + 1, end < 0 ? c.length() : end); cookies.put(name, value); LOGGER.debug("received cookie: {}={}", name, value); } } } | RestClient { protected void setCookies(ResponseEntity<?> entity) { List<String> setCookies = entity.getHeaders().get(HttpHeaders.SET_COOKIE); if (null != setCookies) { for (String c : setCookies) { int valueStart = c.indexOf('='); String name = c.substring(0, valueStart); int end = c.indexOf(';'); String value = c.substring(valueStart + 1, end < 0 ? c.length() : end); cookies.put(name, value); LOGGER.debug("received cookie: {}={}", name, value); } } } } | RestClient { protected void setCookies(ResponseEntity<?> entity) { List<String> setCookies = entity.getHeaders().get(HttpHeaders.SET_COOKIE); if (null != setCookies) { for (String c : setCookies) { int valueStart = c.indexOf('='); String name = c.substring(0, valueStart); int end = c.indexOf(';'); String value = c.substring(valueStart + 1, end < 0 ? c.length() : end); cookies.put(name, value); LOGGER.debug("received cookie: {}={}", name, value); } } } RestClient(String url); RestClient(String url, Map<String, String> cookies); } | RestClient { protected void setCookies(ResponseEntity<?> entity) { List<String> setCookies = entity.getHeaders().get(HttpHeaders.SET_COOKIE); if (null != setCookies) { for (String c : setCookies) { int valueStart = c.indexOf('='); String name = c.substring(0, valueStart); int end = c.indexOf(';'); String value = c.substring(valueStart + 1, end < 0 ? c.length() : end); cookies.put(name, value); LOGGER.debug("received cookie: {}={}", name, value); } } } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id,
MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable,
MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId,
String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); } | RestClient { protected void setCookies(ResponseEntity<?> entity) { List<String> setCookies = entity.getHeaders().get(HttpHeaders.SET_COOKIE); if (null != setCookies) { for (String c : setCookies) { int valueStart = c.indexOf('='); String name = c.substring(0, valueStart); int end = c.indexOf(';'); String value = c.substring(valueStart + 1, end < 0 ? c.length() : end); cookies.put(name, value); LOGGER.debug("received cookie: {}={}", name, value); } } } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id,
MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable,
MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId,
String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); } |
@Test public void testDataSource() throws URISyntaxException { RestClient restClient = new RestClient("http: protected <IN, OUT> RestResponseEntity<IN> exchange(URI uri, OUT body, HttpMethod method, Class<IN> returnType) { Assert.assertEquals( "http: uri.toString()); return null; } }; MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("foo", "bar"); parameters.add("47", "11"); Pageable pageable = new Pageable().addSort("foo", OrderEnum.ASC).addSort("bar", OrderEnum.DESC); restClient.datasource("application", "foobar", pageable, parameters); } | public RestResponseEntity<Datasource> datasource(String application, String id) throws URISyntaxException { return datasource(application, id, (Pageable) null); } | RestClient { public RestResponseEntity<Datasource> datasource(String application, String id) throws URISyntaxException { return datasource(application, id, (Pageable) null); } } | RestClient { public RestResponseEntity<Datasource> datasource(String application, String id) throws URISyntaxException { return datasource(application, id, (Pageable) null); } RestClient(String url); RestClient(String url, Map<String, String> cookies); } | RestClient { public RestResponseEntity<Datasource> datasource(String application, String id) throws URISyntaxException { return datasource(application, id, (Pageable) null); } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id,
MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable,
MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId,
String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); } | RestClient { public RestResponseEntity<Datasource> datasource(String application, String id) throws URISyntaxException { return datasource(application, id, (Pageable) null); } RestClient(String url); RestClient(String url, Map<String, String> cookies); RestResponseEntity<Datasource> datasource(String application, String id); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable); RestResponseEntity<Datasource> datasource(String application, String id,
MultiValueMap<String, String> parameters); RestResponseEntity<Datasource> datasource(String application, String id, Pageable pageable,
MultiValueMap<String, String> parameters); RestResponseEntity<Action> getAction(String application, String eventId, String actionId,
String... pathVariables); RestResponseEntity<Action> getAction(Link link); RestResponseEntity<Action> performAction(Action data, Link link); RestResponseEntity<Action> performAction(String application, Action data, String... pathVariables); Map<String, String> getCookies(); RestResponseEntity<byte[]> getBinaryData(Link link); RestResponseEntity<byte[]> getBinaryData(String relativePath); RestResponseEntity<IN> exchange(String path, OUT body, Class<IN> returnType, HttpMethod method); RestResponseEntity<IN> getResource(String path, Class<IN> returnType); } |
@Test public void testSizeMinMax() { assertTrue("sizeMinMax(foo,1,3)"); assertFalse("sizeMinMax(foo,4,5)"); assertTrue("sizeMinMax(multifoo,1,4)"); assertFalse("sizeMinMax(multifoo,1,3)"); assertFalse("sizeMinMax(multifoo,5,7)"); assertFalse("sizeMinMax(multibar,1,3)"); assertFalse("sizeMinMax(multibar,5,7)"); } | public static boolean sizeMinMax(Object item, int min, int max) { return sizeMax(item, max) && sizeMin(item, min); } | RuleValidation { public static boolean sizeMinMax(Object item, int min, int max) { return sizeMax(item, max) && sizeMin(item, min); } } | RuleValidation { public static boolean sizeMinMax(Object item, int min, int max) { return sizeMax(item, max) && sizeMin(item, min); } RuleValidation(Request container); } | RuleValidation { public static boolean sizeMinMax(Object item, int min, int max) { return sizeMax(item, max) && sizeMin(item, min); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); } | RuleValidation { public static boolean sizeMinMax(Object item, int min, int max) { return sizeMax(item, max) && sizeMin(item, min); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; } |
@Test public void testComment() { Assert.assertArrayEquals(new String[0], batch.parseLine("#My first comment")); Assert.assertArrayEquals(new String[0], batch.parseLine("# AnotherOne")); } | protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } |
@Test public void testSysEnvVariables() { OperatingSystem os = OperatingSystem.detect(); String lang = System.getenv("LANG"); LOGGER.info("OS is {} ({}) with LANG {}", os, System.getProperty("os.name"), lang); switch (os) { case LINUX: Assert.assertArrayEquals(new String[0], batch.parseLine("def LANG = ${systemEnv['LANG']}")); String langVar = variables.get("LANG"); Assert.assertEquals(String.format("Expected value %s for variable LANG, but was %s", lang, langVar), lang, langVar); break; case WINDOWS: Assert.assertArrayEquals(new String[0], batch.parseLine("def temp = ${systemEnv['TEMP']}")); Assert.assertTrue(StringUtils.isNotBlank(variables.get("temp"))); break; case MACOSX: Assert.assertArrayEquals(new String[0], batch.parseLine("def HOME = ${systemEnv['HOME']}")); Assert.assertTrue(StringUtils.containsIgnoreCase(variables.get("HOME"), "users")); break; case OTHER: Assert.fail("Unsupported operating system found: " + os); } } | protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } |
@Test public void testCommandParsing() { Assert.assertArrayEquals(new String[0], batch.parseLine("# a comment")); Assert.assertArrayEquals(new String[0], batch.parseLine("def foo = bar")); Assert.assertArrayEquals(new String[0], batch.parseLine("")); Assert.assertArrayEquals(new String[] { "-i", "-f", "-g", "-h" }, batch.parseLine("-i -f -g -h")); Assert.assertArrayEquals(new String[] { "-k", "chunk", "with", "space", "\"in double-quotes\"" }, batch.parseLine("-k chunk with space \"in double-quotes\"")); Assert.assertArrayEquals(new String[] { "-initdatabase" }, batch.parseLine("-initdatabase")); Assert.assertArrayEquals( new String[] { "create-site", "-n", "manager", "-h", "localhost", "-d", "http: batch.parseLine("create-site -n manager -h localhost -d http: Assert.assertArrayEquals(new String[] { "-r", "\"L R\"", "-f" }, batch.parseLine("-r \"L R\" -f")); Assert.assertArrayEquals( new String[] { "import-application", "-n", "appng-authentication", "-v", "1.0-SNAPSHOT", "-r", "\"Local Repository\"", "-f" }, batch.parseLine( "import-application -n appng-authentication -v 1.0-SNAPSHOT -r \"Local Repository\" -f")); } | protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } |
@Test public void testCommandVariables() { checkVariables("def DEPLOY = -f", "DEPLOY", "-f"); checkVariables("def MANAGER_APP =appng-manager ", "MANAGER_APP", "appng-manager"); checkVariables("def MANAGER_VERSION = 1.1-SNAPSHOT", "MANAGER_VERSION", "1.1-SNAPSHOT"); checkVariables("def REPOSITORY=\"Local Repository\"", "REPOSITORY", "\"Local Repository\""); checkVariables("def ADMIN_GROUP=Administrator", "ADMIN_GROUP", "Administrator"); checkVariables("def ADMIN_SUBJECT=admin", "ADMIN_GROUP", "Administrator"); checkVariables("def ROLE_NAME=Platform Administrator", "ROLE_NAME", "\"Platform Administrator\""); Assert.assertArrayEquals(new String[] { "test", "-f" }, batch.parseLine("test ${DEPLOY}")); Assert.assertArrayEquals( new String[] { "import-application", "-n", "appng-manager", "-v", "1.1-SNAPSHOT", "-r", "\"Local Repository\"", "-c", "-f" }, batch.parseLine( "import-application -n ${MANAGER_APP} -v ${MANAGER_VERSION} -r ${REPOSITORY} -c ${DEPLOY}")); Assert.assertArrayEquals( new String[] { "add-applicationrole", "-g", "Administrator", "-p", "appng-manager", "-r", "\"Platform Administrator\"" }, batch.parseLine("add-applicationrole -g ${ADMIN_GROUP} -p ${MANAGER_APP} -r ${ROLE_NAME}")); Assert.assertArrayEquals( new String[] { "create-subject", "-u", "admin", "-p", "tester", "-n", "\"appNG Administrator\"", "-l", "en", "-e", "[email protected]" }, batch.parseLine( "create-subject -u ${ADMIN_SUBJECT} -p tester -n \"appNG Administrator\" -l en -e [email protected]")); } | protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } |
@Test public void testCommandUndeclaredVariables() { Assert.assertArrayEquals(new String[] { "foo", "$BAR" }, batch.parseLine("foo $BAR")); Assert.assertArrayEquals( new String[] { "prefix", "$UNDECLARED_VAR", "suffix", "plus", "\"quotes with space\"" }, batch.parseLine("prefix $UNDECLARED_VAR suffix plus 'quotes with space'")); } | protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } |
@Test public void testQuotes() { Assert.assertArrayEquals(new String[] { "\"foo\"", "\"bar\"" }, batch.parseLine("\"foo\" \"bar\"")); Assert.assertArrayEquals(new String[] { "\"foo\"", "further", "parameters" }, batch.parseLine("\"foo\" further parameters")); Assert.assertArrayEquals(new String[] { "\"foo\"", "\"bar\"" }, batch.parseLine("'foo' 'bar'")); Assert.assertArrayEquals(new String[] { "\"foo\"", "further", "parameters" }, batch.parseLine("'foo' further parameters")); } | protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } | CommandBatch implements ExecutableCliCommand { protected String[] parseLine(String command) { String[] args = new String[0]; if (command.startsWith(COMMENT_PREFIX) || StringUtils.isBlank(command)) { return args; } Map<String, Object> params = new HashMap<>(variables); params.put("systemEnv", System.getenv()); params.put("systemProp", System.getProperties()); ExpressionEvaluator ee = new ExpressionEvaluator(params); String line = ee.evaluate(command, String.class); if (line.startsWith(VAR_DECLARATION)) { int eqIdx = line.indexOf(VAR_ASSIGNMENT); String name = line.substring(VAR_DECLARATION.length() + 1, eqIdx).trim(); String value = line.substring(eqIdx + 1).trim(); if (value.contains(StringUtils.SPACE) && value.charAt(0) != DOUBLE_QUOTE) { value = DOUBLE_QUOTE + value + DOUBLE_QUOTE; } variables.put(name, value); } else { args = parse(line).toArray(); if (args.length == 0 && StringUtils.isNotBlank(line)) { args = line.split(StringUtils.SPACE); } } return args; } void execute(CliEnvironment cle); } |
@Test(expected = BusinessException.class) public void testInvalid() throws BusinessException { new HashPassword("").execute(cliEnv); } | public void execute(CliEnvironment cle) throws BusinessException { boolean passwordSet = StringUtils.isNotBlank(password); if (!(interactive || passwordSet)) { throw new BusinessException("Either password must be given or -i must be set!"); } if (interactive) { runInteractive(cle); return; } String digest = savePasswordForSubject(cle, new SubjectImpl(), password); cle.setResult(digest); } | HashPassword implements ExecutableCliCommand { public void execute(CliEnvironment cle) throws BusinessException { boolean passwordSet = StringUtils.isNotBlank(password); if (!(interactive || passwordSet)) { throw new BusinessException("Either password must be given or -i must be set!"); } if (interactive) { runInteractive(cle); return; } String digest = savePasswordForSubject(cle, new SubjectImpl(), password); cle.setResult(digest); } } | HashPassword implements ExecutableCliCommand { public void execute(CliEnvironment cle) throws BusinessException { boolean passwordSet = StringUtils.isNotBlank(password); if (!(interactive || passwordSet)) { throw new BusinessException("Either password must be given or -i must be set!"); } if (interactive) { runInteractive(cle); return; } String digest = savePasswordForSubject(cle, new SubjectImpl(), password); cle.setResult(digest); } HashPassword(); HashPassword(String password); HashPassword(boolean interactive); } | HashPassword implements ExecutableCliCommand { public void execute(CliEnvironment cle) throws BusinessException { boolean passwordSet = StringUtils.isNotBlank(password); if (!(interactive || passwordSet)) { throw new BusinessException("Either password must be given or -i must be set!"); } if (interactive) { runInteractive(cle); return; } String digest = savePasswordForSubject(cle, new SubjectImpl(), password); cle.setResult(digest); } HashPassword(); HashPassword(String password); HashPassword(boolean interactive); void execute(CliEnvironment cle); } | HashPassword implements ExecutableCliCommand { public void execute(CliEnvironment cle) throws BusinessException { boolean passwordSet = StringUtils.isNotBlank(password); if (!(interactive || passwordSet)) { throw new BusinessException("Either password must be given or -i must be set!"); } if (interactive) { runInteractive(cle); return; } String digest = savePasswordForSubject(cle, new SubjectImpl(), password); cle.setResult(digest); } HashPassword(); HashPassword(String password); HashPassword(boolean interactive); void execute(CliEnvironment cle); } |
@Test public void testAppngHome() { File result = path.getFile(APPNG_ROOT); Mockito.when(cliBootstrapEnvironment.getFileFromEnv(CliBootstrap.APPNG_HOME)).thenReturn(result); Assert.assertEquals(result, CliBootstrap.getPlatformRootPath(cliBootstrapEnvironment)); } | static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } static void main(String[] args); static int run(String[] args); } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } static void main(String[] args); static int run(String[] args); static String CURRENT_COMMAND; static final String APPNG_HOME; } |
@Test public void testAppngHomeUndefined() { try { CliBootstrap.getPlatformRootPath(cliBootstrapEnvironment); Assert.fail("IllegalArgumentException expected, but no exception has been thrown."); } catch (IllegalArgumentException e) { Assert.assertEquals("APPNG_HOME is not defined!", e.getMessage()); } } | static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } static void main(String[] args); static int run(String[] args); } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } static void main(String[] args); static int run(String[] args); static String CURRENT_COMMAND; static final String APPNG_HOME; } |
@Test public void testAppngHomeInvalid() { File result = path.getFile("invalid-path"); Mockito.when(cliBootstrapEnvironment.getFileFromEnv(CliBootstrap.APPNG_HOME)).thenReturn(result); try { CliBootstrap.getPlatformRootPath(cliBootstrapEnvironment); Assert.fail("IllegalArgumentException expected, but no exception has been thrown."); } catch (IllegalArgumentException e) { Assert.assertEquals("The path specified in APPNG_HOME does not exist: " + result, e.getMessage()); } } | static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } static void main(String[] args); static int run(String[] args); } | CliBootstrap { static File getPlatformRootPath(CliBootstrapEnvironment env) { File appngHome = env.getFileFromEnv(APPNG_HOME); return checkFile(APPNG_HOME, appngHome, true); } static void main(String[] args); static int run(String[] args); static String CURRENT_COMMAND; static final String APPNG_HOME; } |
@Test public void testNumber() { assertFalse("number(foo)"); assertTrue("number(bar)"); } | public static boolean number(String string) { return regExp(string, EXP_NUMBER); } | RuleValidation { public static boolean number(String string) { return regExp(string, EXP_NUMBER); } } | RuleValidation { public static boolean number(String string) { return regExp(string, EXP_NUMBER); } RuleValidation(Request container); } | RuleValidation { public static boolean number(String string) { return regExp(string, EXP_NUMBER); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); } | RuleValidation { public static boolean number(String string) { return regExp(string, EXP_NUMBER); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; } |
@Test public void testTabbedEmpty() throws BusinessException { String table = prettyTable.render(true, true); Assert.assertEquals("\nA\tB\tC\n", table); } | public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } PrettyTable(); } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); } |
@Test public void testTabbed() throws BusinessException { prettyTable.addRow(1, null, 3); String table = prettyTable.render(true, true); Assert.assertEquals("\nA\tB\tC\n1\tnull\t3\n", table); } | static String tabbed(String n) { return n + PrettyTable.TAB; } | PrettyTable { static String tabbed(String n) { return n + PrettyTable.TAB; } } | PrettyTable { static String tabbed(String n) { return n + PrettyTable.TAB; } PrettyTable(); } | PrettyTable { static String tabbed(String n) { return n + PrettyTable.TAB; } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); } | PrettyTable { static String tabbed(String n) { return n + PrettyTable.TAB; } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); } |
@Test public void testTableEmpty() throws BusinessException, IOException { String table = prettyTable.render(false, true); URL resource = getClass().getClassLoader().getResource("PrettyTableTest-empty.txt"); String expected = FileUtils.readFileToString(new File(resource.getFile()), Charset.defaultCharset()); Assert.assertEquals(expected, table); } | public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } PrettyTable(); } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); } | PrettyTable { public String render(boolean tabbedValues, boolean beVerbose) { boolean withBorders = !tabbedValues; tableWidth = 0; StringBuilder builder = new StringBuilder(); builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; int noOfColumns = 0; for (TableColumn column : columns) { String col = column.render(withBorders, beVerbose); builder = (null != col) ? builder.append(col) : builder; if (!column.isVerbose() || beVerbose) { tableWidth += column.getCellWidth(); noOfColumns++; } if (!withBorders && column.equals(columns.get(columns.size() - 1))) { builder.deleteCharAt(builder.length() - 1); } } tableWidth += ((noOfColumns + 1) * PrettyTable.VERTICAL_BORDER.length()) + (CELL_MARGIN * noOfColumns * 2); builder = builder.insert(0, newLine(withBorders, DOUBLE_LINE)); builder.append(newLine(withBorders, DOUBLE_LINE)); for (TableRow row : rows) { builder = (withBorders) ? builder.append(PrettyTable.VERTICAL_BORDER) : builder; builder.append(row.render(columns, withBorders, beVerbose)); builder.append(newLine(withBorders, SINGLE_LINE)); } return builder.toString(); } PrettyTable(); void addColumn(String name); void addColumn(String name, boolean isVerbose); void addRow(Object... values); String render(boolean tabbedValues, boolean beVerbose); List<TableRow> getRows(); int getColumnIndex(String id); } |
@Test public void testEditPerson() throws ProcessingException, IOException { CallableAction callableAction = getAction("personEvent", "editPerson").withParam(FORM_ACTION, "editPerson") .withParam("id", "1").getCallableAction(new Person(1, "Luke the Duke", "Skywalker")); callableAction.perform(); WritingXmlValidator.validateXml(callableAction.getAction(), "xml/PersonActionTest-testEditPerson.xml"); } | @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } @Autowired PersonAction(PersonService service); } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } @Autowired PersonAction(PersonService service); @Override void perform(Site site, Application application, Environment environment, Options options, Request request,
Person formBean, FieldProcessor fieldProcessor); } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } @Autowired PersonAction(PersonService service); @Override void perform(Site site, Application application, Environment environment, Options options, Request request,
Person formBean, FieldProcessor fieldProcessor); } |
@Test public void testCreatePerson() throws ProcessingException, IOException { CallableAction callableAction = getAction("personEvent", "createPerson").withParam(FORM_ACTION, "createPerson") .getCallableAction(new Person(null, "Obi Wan", "Kenobi")); callableAction.perform(); WritingXmlValidator.validateXml(callableAction.getAction(), "xml/PersonActionTest-testCreatePerson.xml"); } | @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } @Autowired PersonAction(PersonService service); } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } @Autowired PersonAction(PersonService service); @Override void perform(Site site, Application application, Environment environment, Options options, Request request,
Person formBean, FieldProcessor fieldProcessor); } | PersonAction implements ActionProvider<Person> { @Override public void perform(Site site, Application application, Environment environment, Options options, Request request, Person formBean, FieldProcessor fieldProcessor) { String mode = options.getOptionValue("action", "id"); if ("edit".equals(mode)) { Integer personId = request.convert(options.getOptionValue("action", "person"), Integer.class); formBean.setId(personId); service.updatePerson(formBean); String message = request.getMessage("person.edited"); fieldProcessor.addOkMessage(message); } else if ("create".equals(mode)) { service.createPerson(formBean); String message = request.getMessage("person.created"); fieldProcessor.addOkMessage(message); } } @Autowired PersonAction(PersonService service); @Override void perform(Site site, Application application, Environment environment, Options options, Request request,
Person formBean, FieldProcessor fieldProcessor); } |
@Test public void testUpdateAppNG() throws Exception { target = UpNGizr.appNGHome; Resource resource = getResource("appng-application"); new Updater(new MockServletContext()).updateAppNG(resource, target); assertFolderNotEmpty("WEB-INF"); assertFolderNotEmpty("WEB-INF/classes"); Assert.assertFalse(new File(target, "WEB-INF/conf").exists()); assertFolderNotEmpty("WEB-INF/lib"); } | @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @Autowired Updater(ServletContext context); } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } |
@Test public void testUpdateAppNGizer() throws Exception { target = UpNGizr.appNGizerHome; Resource resource = getResource("appng-appngizer"); new Updater(new MockServletContext()).updateAppNGizer(resource, target); assertFolderNotEmpty("WEB-INF"); File metaInf = assertFolderNotEmpty("META-INF"); Assert.assertTrue(new File(metaInf, "MANIFEST.MF").exists()); assertFolderNotEmpty("WEB-INF/classes/org/appng/appngizer/model/"); assertFolderNotEmpty("WEB-INF/classes/org/appng/appngizer/controller/"); assertFolderNotEmpty("WEB-INF/lib"); } | protected void updateAppNGizer(Resource resource, String appNGizerHome) throws RestClientException, IOException { if (!(resource.exists() && new File(appNGizerHome).exists())) { return; } Path warArchive = Files.createTempFile(null, null); try ( FileOutputStream out = new FileOutputStream(warArchive.toFile()); InputStream is = resource.getInputStream()) { IOUtils.copy(is, out); try (ZipFile zip = new ZipFile(warArchive.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); String folder = name.substring(0, name.lastIndexOf('/') + 1); if (!entry.isDirectory()) { if (folder.startsWith(WEB_INF_CLASSES)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } else { switch (folder) { case WEB_INF: if (!(WEB_INF + "web.xml").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case META_INF: if ((META_INF + "MANIFEST.MF").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case WEB_INF_LIB: writeFile(appNGizerHome, zip.getInputStream(entry), name); break; default: LOGGER.info("Skipping {}", name); break; } } } } } } finally { warArchive.toFile().delete(); } } | Updater { protected void updateAppNGizer(Resource resource, String appNGizerHome) throws RestClientException, IOException { if (!(resource.exists() && new File(appNGizerHome).exists())) { return; } Path warArchive = Files.createTempFile(null, null); try ( FileOutputStream out = new FileOutputStream(warArchive.toFile()); InputStream is = resource.getInputStream()) { IOUtils.copy(is, out); try (ZipFile zip = new ZipFile(warArchive.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); String folder = name.substring(0, name.lastIndexOf('/') + 1); if (!entry.isDirectory()) { if (folder.startsWith(WEB_INF_CLASSES)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } else { switch (folder) { case WEB_INF: if (!(WEB_INF + "web.xml").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case META_INF: if ((META_INF + "MANIFEST.MF").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case WEB_INF_LIB: writeFile(appNGizerHome, zip.getInputStream(entry), name); break; default: LOGGER.info("Skipping {}", name); break; } } } } } } finally { warArchive.toFile().delete(); } } } | Updater { protected void updateAppNGizer(Resource resource, String appNGizerHome) throws RestClientException, IOException { if (!(resource.exists() && new File(appNGizerHome).exists())) { return; } Path warArchive = Files.createTempFile(null, null); try ( FileOutputStream out = new FileOutputStream(warArchive.toFile()); InputStream is = resource.getInputStream()) { IOUtils.copy(is, out); try (ZipFile zip = new ZipFile(warArchive.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); String folder = name.substring(0, name.lastIndexOf('/') + 1); if (!entry.isDirectory()) { if (folder.startsWith(WEB_INF_CLASSES)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } else { switch (folder) { case WEB_INF: if (!(WEB_INF + "web.xml").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case META_INF: if ((META_INF + "MANIFEST.MF").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case WEB_INF_LIB: writeFile(appNGizerHome, zip.getInputStream(entry), name); break; default: LOGGER.info("Skipping {}", name); break; } } } } } } finally { warArchive.toFile().delete(); } } @Autowired Updater(ServletContext context); } | Updater { protected void updateAppNGizer(Resource resource, String appNGizerHome) throws RestClientException, IOException { if (!(resource.exists() && new File(appNGizerHome).exists())) { return; } Path warArchive = Files.createTempFile(null, null); try ( FileOutputStream out = new FileOutputStream(warArchive.toFile()); InputStream is = resource.getInputStream()) { IOUtils.copy(is, out); try (ZipFile zip = new ZipFile(warArchive.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); String folder = name.substring(0, name.lastIndexOf('/') + 1); if (!entry.isDirectory()) { if (folder.startsWith(WEB_INF_CLASSES)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } else { switch (folder) { case WEB_INF: if (!(WEB_INF + "web.xml").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case META_INF: if ((META_INF + "MANIFEST.MF").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case WEB_INF_LIB: writeFile(appNGizerHome, zip.getInputStream(entry), name); break; default: LOGGER.info("Skipping {}", name); break; } } } } } } finally { warArchive.toFile().delete(); } } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } | Updater { protected void updateAppNGizer(Resource resource, String appNGizerHome) throws RestClientException, IOException { if (!(resource.exists() && new File(appNGizerHome).exists())) { return; } Path warArchive = Files.createTempFile(null, null); try ( FileOutputStream out = new FileOutputStream(warArchive.toFile()); InputStream is = resource.getInputStream()) { IOUtils.copy(is, out); try (ZipFile zip = new ZipFile(warArchive.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); String folder = name.substring(0, name.lastIndexOf('/') + 1); if (!entry.isDirectory()) { if (folder.startsWith(WEB_INF_CLASSES)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } else { switch (folder) { case WEB_INF: if (!(WEB_INF + "web.xml").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case META_INF: if ((META_INF + "MANIFEST.MF").equals(name)) { writeFile(appNGizerHome, zip.getInputStream(entry), name); } break; case WEB_INF_LIB: writeFile(appNGizerHome, zip.getInputStream(entry), name); break; default: LOGGER.info("Skipping {}", name); break; } } } } } } finally { warArchive.toFile().delete(); } } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } |
@Test public void testBlockedIP() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("foobar.org"); ResponseEntity<String> updated = new Updater(request.getServletContext()).updateAppng("1.17.0", null, request); Assert.assertEquals(HttpStatus.FORBIDDEN, updated.getStatusCode()); } | @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @Autowired Updater(ServletContext context); } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } | Updater { @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) public ResponseEntity<String> updateAppng(@PathVariable("version") String version, @RequestParam(required = false) String onSuccess, HttpServletRequest request) { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } isUpdateRunning.set(true); try { Resource appNGArchive = getArtifact(version, APPNG_APPLICATION); if (!appNGArchive.exists()) { return notFound(appNGArchive); } status.set("Stopping appNG"); completed.set(5.0d); getHost().setAutoDeploy(false); Container appNGizerContext = stopContext(getAppNGizerContext()); Container appNGContext = stopContext(getAppNGContext()); completed.set(30.0d); updateAppNG(appNGArchive, UpNGizr.appNGHome); status.set("Starting appNG"); completed.set(81.0d); LOGGER.info(status.get()); ExecutorService contextStarter = Executors.newFixedThreadPool(1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("upNGizr updater"); t.setPriority(Thread.MAX_PRIORITY); return t; } }); Future<Void> startAppNG = contextStarter.submit(() -> { startContext(appNGContext); return null; }); Long duration = waitFor(startAppNG, 95.0d, 3); LOGGER.info("Started appNG in {} seconds.", duration / 1000); if (null != appNGizerContext) { Future<Void> startAppNGizer = contextStarter.submit(() -> { updateAppNGizer(getArtifact(version, APPNGIZER_APPLICATION), UpNGizr.appNGizerHome); status.set("Starting appNGizer"); LOGGER.info(status.get()); startContext(appNGizerContext); completed.set(98.0d); return null; }); duration = waitFor(startAppNGizer, 98.0d, 2); LOGGER.info("Started appNGizer in {} seconds.", duration / 1000); } contextStarter.shutdown(); completed.set(100.0d); String statusLink = StringUtils.isEmpty(onSuccess) ? "" : (String.format("<br/>Forwarding to<br/><a href=\"%s\">%s</a>", onSuccess, onSuccess)); status.set("Update complete." + statusLink); return new ResponseEntity<>("OK", HttpStatus.OK); } catch (Exception e) { LOGGER.error("error", e); } finally { isUpdateRunning.set(false); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } |
@Test public void testCheckVersionAvailable() throws IOException { ResponseEntity<Void> checkVersionAvailable = new Updater(new MockServletContext()) .checkVersionAvailable("1.17.0", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.OK, checkVersionAvailable.getStatusCode()); } | @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } @Autowired Updater(ServletContext context); } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } |
@Test public void testCheckVersionNotAvailable() throws IOException { ResponseEntity<Void> checkVersionAvailable = new Updater(new MockServletContext()) .checkVersionAvailable("0.8.15", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.NOT_FOUND, checkVersionAvailable.getStatusCode()); } | @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } @Autowired Updater(ServletContext context); } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } | Updater { @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) public ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version, HttpServletRequest request) throws IOException { if (isBlocked(request)) { return forbidden(); } Resource resource = getArtifact(version, APPNG_APPLICATION); if (!resource.exists()) { return notFound(resource); } return new ResponseEntity<>(HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } |
@Test public void testNumberFractionDigits() { assertFalse("numberFractionDigits(foobar,1,1)"); assertFalse("numberFractionDigits(foobar,1,2)"); assertFalse("numberFractionDigits(foobar,2,1)"); assertFalse("numberFractionDigits(foobar,2,2)"); assertFalse("numberFractionDigits(foobar,3,1)"); assertTrue("numberFractionDigits(foobar,3,2)"); assertTrue("numberFractionDigits(foobar,3,3)"); assertTrue("numberFractionDigits(foobar,3,4)"); assertTrue("numberFractionDigits(foobar,4,3)"); assertTrue("numberFractionDigits(foobar,4,4)"); } | public static boolean numberFractionDigits(String string, int digits, int fraction) { return number(string, DOT, digits, fraction); } | RuleValidation { public static boolean numberFractionDigits(String string, int digits, int fraction) { return number(string, DOT, digits, fraction); } } | RuleValidation { public static boolean numberFractionDigits(String string, int digits, int fraction) { return number(string, DOT, digits, fraction); } RuleValidation(Request container); } | RuleValidation { public static boolean numberFractionDigits(String string, int digits, int fraction) { return number(string, DOT, digits, fraction); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); } | RuleValidation { public static boolean numberFractionDigits(String string, int digits, int fraction) { return number(string, DOT, digits, fraction); } RuleValidation(Request container); Map<String, List<FormUpload>> getFileParams(Map<String, List<FormUpload>> formUploads); boolean validate(String rule); static boolean string(String string); static boolean captcha(String value, String result); static boolean email(String string); static boolean equals(String string1, String string2); static boolean number(String string); static boolean number(String string, char separator); static boolean numberFractionDigits(String string, int digits, int fraction); static boolean number(String string, char separator, int digits, int fraction); static boolean regExp(String string, String regex); static boolean size(Object item, int size); static boolean sizeMax(Object item, int max); static boolean sizeMin(Object item, int min); static boolean sizeMinMax(Object item, int min, int max); static boolean fileType(List<FormUpload> fUpload, String types); static boolean fileSize(List<FormUpload> fUpload, String minSize, String maxSize); static boolean fileSizeMin(List<FormUpload> fUpload, String minSize); static boolean fileSizeMax(List<FormUpload> fUpload, String maxSize); static boolean fileCountMin(List<FormUpload> fUpload, int count); static boolean fileCountMax(List<FormUpload> fUpload, int count); static boolean fileCount(List<FormUpload> fUpload, int minCount, int maxCount); static final List<String> SHORT_RULES; } |
@Test public void testGetStartPage() throws IOException, URISyntaxException { ResponseEntity<String> startPage = new Updater(new MockServletContext()).getStartPage("1.17.0", "myTarget", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.OK, startPage.getStatusCode()); List<String> lines = Files.readAllLines(new File("src/test/resources/startpage.html").toPath()); List<String> actualLines = Arrays.asList(startPage.getBody().split(System.lineSeparator())); int size = lines.size(); Assert.assertEquals(size, actualLines.size()); for (int i = 0; i < size; i++) { Assert.assertEquals("error in line " + (i + 1), lines.get(i), actualLines.get(i)); } } | @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } @Autowired Updater(ServletContext context); } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } |
@Test public void testGetStartPageWithLocalHostName() throws IOException, URISyntaxException { MockServletContext context = new MockServletContext(); context.setInitParameter("useFQDN", "true"); ResponseEntity<String> startPage = new Updater(context).getStartPage("1.17.0", "myTarget", new MockHttpServletRequest()); Assert.assertEquals(HttpStatus.OK, startPage.getStatusCode()); Assert.assertTrue(startPage.getBody().contains(InetAddress.getLocalHost().getCanonicalHostName())); } | @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } @Autowired Updater(ServletContext context); } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } | Updater { @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) public ResponseEntity<String> getStartPage(@PathVariable("version") String version, @RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request) throws IOException, URISyntaxException { if (isBlocked(request) || isUpdateRunning.get()) { return forbidden(); } Resource artifactResource = getArtifact(version, APPNG_APPLICATION); if (!artifactResource.exists()) { return notFound(artifactResource); } ClassPathResource resource = new ClassPathResource("updater.html"); String content = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); int serverPort = request.getServerPort(); if (null == serverName) { serverName = request.getServerName(); } String uppNGizrBase = String.format(serverPort == 80 ? " serverPort); content = content.replace("<target>", onSuccess).replace("<path>", uppNGizrBase); content = content.replace("<version>", version).replace("<button>", "Update to " + version); return new ResponseEntity<>(content, HttpStatus.OK); } @Autowired Updater(ServletContext context); @RequestMapping(method = RequestMethod.GET, path = "/update/start/{version:.+}", produces = MediaType.TEXT_HTML_VALUE) ResponseEntity<String> getStartPage(@PathVariable("version") String version,
@RequestParam(required = false, defaultValue = "") String onSuccess, HttpServletRequest request); @RequestMapping(method = RequestMethod.GET, path = "/update/status", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) ResponseEntity<Status> getStatus(); @RequestMapping(path = "/checkVersionAvailable/{version:.+}", method = RequestMethod.GET) ResponseEntity<Void> checkVersionAvailable(@PathVariable("version") String version,
HttpServletRequest request); @RequestMapping(path = "/update/{version:.+}", produces = MediaType.TEXT_PLAIN_VALUE, method = RequestMethod.POST) ResponseEntity<String> updateAppng(@PathVariable("version") String version,
@RequestParam(required = false) String onSuccess, HttpServletRequest request); } |
@Test public void testParameter() throws IOException, JspException { StringWriter targetWriter = new StringWriter(); Parameter p1 = new Parameter(); p1.setName("param1"); p1.setBodyContent(new MockBodyContent("value1", targetWriter)); p1.setParent(this); p1.doEndTag(); Parameter p2 = new Parameter(); p2.setUnescape(true); p2.setBodyContent(new MockBodyContent(""Ä"", targetWriter)); p2.setName("param2"); p2.setParent(this); p2.doEndTag(); Parameter p3 = new Parameter(); p3.setName("param3"); p3.setParent(this); p3.doEndTag(); Assert.assertEquals("value1", parameters.get("param1")); Assert.assertEquals("\"Ä\"", parameters.get("param2")); Assert.assertNull(parameters.get("param3")); Assert.assertEquals("", targetWriter.toString()); } | public Parameter() { } | Parameter extends BodyTagSupport { public Parameter() { } } | Parameter extends BodyTagSupport { public Parameter() { } Parameter(); } | Parameter extends BodyTagSupport { public Parameter() { } Parameter(); @Override int doEndTag(); String getName(); void setName(String name); boolean isUnescape(); void setUnescape(boolean unescape); @Override String toString(); } | Parameter extends BodyTagSupport { public Parameter() { } Parameter(); @Override int doEndTag(); String getName(); void setName(String name); boolean isUnescape(); void setUnescape(boolean unescape); @Override String toString(); } |
@Test(expected = UnsupportedOperationException.class) public void testWriteToUrl() { Attribute attribute = init(Mode.WRITE, Scope.URL); attribute.doStartTag(); } | @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); @Override int doEndTag(); @Override int doStartTag(); @Override void release(); String getName(); void setName(String name); String getValue(); void setValue(String value); String getMode(); void setMode(String mode); String getScope(); void setScope(String scope); } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); @Override int doEndTag(); @Override int doStartTag(); @Override void release(); String getName(); void setName(String name); String getValue(); void setValue(String value); String getMode(); void setMode(String mode); String getScope(); void setScope(String scope); } |
@Test(expected = UnsupportedOperationException.class) public void testWriteToSite() { Attribute attribute = init(Mode.WRITE, Scope.SITE); attribute.doStartTag(); } | @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); @Override int doEndTag(); @Override int doStartTag(); @Override void release(); String getName(); void setName(String name); String getValue(); void setValue(String value); String getMode(); void setMode(String mode); String getScope(); void setScope(String scope); } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); @Override int doEndTag(); @Override int doStartTag(); @Override void release(); String getName(); void setName(String name); String getValue(); void setValue(String value); String getMode(); void setMode(String mode); String getScope(); void setScope(String scope); } |
@Test(expected = UnsupportedOperationException.class) public void testWriteToPlatform() { Attribute attribute = init(Mode.WRITE, Scope.PLATFORM); attribute.doStartTag(); } | @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); @Override int doEndTag(); @Override int doStartTag(); @Override void release(); String getName(); void setName(String name); String getValue(); void setValue(String value); String getMode(); void setMode(String mode); String getScope(); void setScope(String scope); } | Attribute extends TagSupport implements Tag { @Override public int doStartTag() { switch (modeInternal) { case READ: readValue(); try { JspWriter out = pageContext.getOut(); out.print(value); } catch (IOException ioe) { LOGGER.error("error while writing to JspWriter", ioe); } break; case WRITE: writeValue(); break; } return SKIP_BODY; } Attribute(String scope, String name); Attribute(); @Override int doEndTag(); @Override int doStartTag(); @Override void release(); String getName(); void setName(String name); String getValue(); void setValue(String value); String getMode(); void setMode(String mode); String getScope(); void setScope(String scope); } |
@Test public void test() { MultiSiteSupport multiSiteSupport = new MultiSiteSupport(); String siteName = "localhost"; String applicationName = "application"; MockServletContext servletContext = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setSession(new MockHttpSession(servletContext)); MockPageContext pageContext = new MockPageContext(servletContext, request); Properties properties = Mockito.mock(Properties.class); Mockito.when(properties.getString(Platform.Property.VHOST_MODE)).thenReturn(VHostMode.NAME_BASED.name()); Map<String, Object> platformScope = new ConcurrentHashMap<>(); platformScope.put(Platform.Environment.PLATFORM_CONFIG, properties); Site site = Mockito.mock(SiteImpl.class); Mockito.when(site.getName()).thenReturn(siteName); Mockito.when(site.getHost()).thenReturn(siteName); Mockito.when(site.getDomain()).thenReturn(siteName); Mockito.when(site.getProperties()).thenReturn(Mockito.mock(Properties.class)); Map<String, Site> siteMap = new HashMap<>(); siteMap.put(siteName, site); platformScope.put(Platform.Environment.SITES, siteMap); servletContext.setAttribute(Scope.PLATFORM.name(), platformScope); DefaultEnvironment environment = DefaultEnvironment.get(pageContext); ApplicationContext ctx = Mockito.mock(ApplicationContext.class); environment.setAttribute(PLATFORM, Platform.Environment.CORE_PLATFORM_CONTEXT, ctx); CoreService coreService = Mockito.mock(CoreService.class); Mockito.when(ctx.getBean(CoreService.class)).thenReturn(coreService); Mockito.when(coreService.getGrantingSite(siteName, applicationName)).thenReturn(null); try { multiSiteSupport.process(environment, applicationName, "method", request); Assert.fail("must throw exception"); } catch (Exception e) { Assert.assertEquals("no application '" + applicationName + "' for site '" + siteName + "'", e.getMessage()); } } | public void process(Environment env, String application, HttpServletRequest servletRequest) throws JspException { process(env, application, null, servletRequest); } | MultiSiteSupport { public void process(Environment env, String application, HttpServletRequest servletRequest) throws JspException { process(env, application, null, servletRequest); } } | MultiSiteSupport { public void process(Environment env, String application, HttpServletRequest servletRequest) throws JspException { process(env, application, null, servletRequest); } } | MultiSiteSupport { public void process(Environment env, String application, HttpServletRequest servletRequest) throws JspException { process(env, application, null, servletRequest); } void process(Environment env, String application, HttpServletRequest servletRequest); void process(Environment env, String application, String method, HttpServletRequest servletRequest); SiteImpl getCallingSite(); SiteImpl getExecutingSite(); ApplicationProvider getApplicationProvider(); } | MultiSiteSupport { public void process(Environment env, String application, HttpServletRequest servletRequest) throws JspException { process(env, application, null, servletRequest); } void process(Environment env, String application, HttpServletRequest servletRequest); void process(Environment env, String application, String method, HttpServletRequest servletRequest); SiteImpl getCallingSite(); SiteImpl getExecutingSite(); ApplicationProvider getApplicationProvider(); } |
@Test public void test() throws JspException { PageContext pageContext = AttributeTest.setupTagletTest(); DefaultEnvironment environment = DefaultEnvironment.get(pageContext); environment.setSubject(new SubjectImpl()); final MultiSiteSupport mock = Mockito.mock(MultiSiteSupport.class); ApplicationProvider app = Mockito.mock(ApplicationProvider.class); Mockito.when(app.getProperties()).thenReturn(Mockito.mock(Properties.class)); Mockito.when(app.getProperties().getBoolean("permissionsEnabled", true)).thenReturn(false); Mockito.when(mock.getApplicationProvider()).thenReturn(app); Mockito.when(mock.getExecutingSite()).thenReturn(Mockito.mock(SiteImpl.class)); Permission permission = new Permission() { @Override protected MultiSiteSupport processMultiSiteSupport(Environment env, HttpServletRequest servletRequest) throws JspException { return mock; } }; permission.setPageContext(pageContext); Assert.assertEquals(Tag.EVAL_BODY_INCLUDE, permission.doStartTag()); } | @Override public int doStartTag() throws JspException { try { Environment env = DefaultEnvironment.get(pageContext); HttpServletRequest servletRequest = (HttpServletRequest) pageContext.getRequest(); MultiSiteSupport multiSiteSupport = processMultiSiteSupport(env, servletRequest); SiteImpl executingSite = multiSiteSupport.getExecutingSite(); ApplicationProvider applicationProvider = multiSiteSupport.getApplicationProvider(); Subject subject = env.getSubject(); PermissionProcessor permissionProcessor = null; Boolean permissionsEnabled = applicationProvider.getProperties().getBoolean("permissionsEnabled", Boolean.TRUE); if (permissionsEnabled) { permissionProcessor = new DefaultPermissionProcessor(subject, executingSite, applicationProvider); } else { permissionProcessor = new DummyPermissionProcessor(subject, executingSite, applicationProvider); } boolean hasPermission = permissionProcessor.hasPermission(permission); if (hasPermission) { LOGGER.debug("subject has the permission: {}", permission); return EVAL_BODY_INCLUDE; } } catch (IllegalStateException e) { LOGGER.debug("session {} is invalid,", pageContext.getSession().getId()); } LOGGER.debug("subject does not have the permission: {}", permission); return SKIP_BODY; } | Permission extends TagSupport { @Override public int doStartTag() throws JspException { try { Environment env = DefaultEnvironment.get(pageContext); HttpServletRequest servletRequest = (HttpServletRequest) pageContext.getRequest(); MultiSiteSupport multiSiteSupport = processMultiSiteSupport(env, servletRequest); SiteImpl executingSite = multiSiteSupport.getExecutingSite(); ApplicationProvider applicationProvider = multiSiteSupport.getApplicationProvider(); Subject subject = env.getSubject(); PermissionProcessor permissionProcessor = null; Boolean permissionsEnabled = applicationProvider.getProperties().getBoolean("permissionsEnabled", Boolean.TRUE); if (permissionsEnabled) { permissionProcessor = new DefaultPermissionProcessor(subject, executingSite, applicationProvider); } else { permissionProcessor = new DummyPermissionProcessor(subject, executingSite, applicationProvider); } boolean hasPermission = permissionProcessor.hasPermission(permission); if (hasPermission) { LOGGER.debug("subject has the permission: {}", permission); return EVAL_BODY_INCLUDE; } } catch (IllegalStateException e) { LOGGER.debug("session {} is invalid,", pageContext.getSession().getId()); } LOGGER.debug("subject does not have the permission: {}", permission); return SKIP_BODY; } } | Permission extends TagSupport { @Override public int doStartTag() throws JspException { try { Environment env = DefaultEnvironment.get(pageContext); HttpServletRequest servletRequest = (HttpServletRequest) pageContext.getRequest(); MultiSiteSupport multiSiteSupport = processMultiSiteSupport(env, servletRequest); SiteImpl executingSite = multiSiteSupport.getExecutingSite(); ApplicationProvider applicationProvider = multiSiteSupport.getApplicationProvider(); Subject subject = env.getSubject(); PermissionProcessor permissionProcessor = null; Boolean permissionsEnabled = applicationProvider.getProperties().getBoolean("permissionsEnabled", Boolean.TRUE); if (permissionsEnabled) { permissionProcessor = new DefaultPermissionProcessor(subject, executingSite, applicationProvider); } else { permissionProcessor = new DummyPermissionProcessor(subject, executingSite, applicationProvider); } boolean hasPermission = permissionProcessor.hasPermission(permission); if (hasPermission) { LOGGER.debug("subject has the permission: {}", permission); return EVAL_BODY_INCLUDE; } } catch (IllegalStateException e) { LOGGER.debug("session {} is invalid,", pageContext.getSession().getId()); } LOGGER.debug("subject does not have the permission: {}", permission); return SKIP_BODY; } } | Permission extends TagSupport { @Override public int doStartTag() throws JspException { try { Environment env = DefaultEnvironment.get(pageContext); HttpServletRequest servletRequest = (HttpServletRequest) pageContext.getRequest(); MultiSiteSupport multiSiteSupport = processMultiSiteSupport(env, servletRequest); SiteImpl executingSite = multiSiteSupport.getExecutingSite(); ApplicationProvider applicationProvider = multiSiteSupport.getApplicationProvider(); Subject subject = env.getSubject(); PermissionProcessor permissionProcessor = null; Boolean permissionsEnabled = applicationProvider.getProperties().getBoolean("permissionsEnabled", Boolean.TRUE); if (permissionsEnabled) { permissionProcessor = new DefaultPermissionProcessor(subject, executingSite, applicationProvider); } else { permissionProcessor = new DummyPermissionProcessor(subject, executingSite, applicationProvider); } boolean hasPermission = permissionProcessor.hasPermission(permission); if (hasPermission) { LOGGER.debug("subject has the permission: {}", permission); return EVAL_BODY_INCLUDE; } } catch (IllegalStateException e) { LOGGER.debug("session {} is invalid,", pageContext.getSession().getId()); } LOGGER.debug("subject does not have the permission: {}", permission); return SKIP_BODY; } @Override int doStartTag(); String getPermission(); void setPermission(String permission); String getApplication(); void setApplication(String application); } | Permission extends TagSupport { @Override public int doStartTag() throws JspException { try { Environment env = DefaultEnvironment.get(pageContext); HttpServletRequest servletRequest = (HttpServletRequest) pageContext.getRequest(); MultiSiteSupport multiSiteSupport = processMultiSiteSupport(env, servletRequest); SiteImpl executingSite = multiSiteSupport.getExecutingSite(); ApplicationProvider applicationProvider = multiSiteSupport.getApplicationProvider(); Subject subject = env.getSubject(); PermissionProcessor permissionProcessor = null; Boolean permissionsEnabled = applicationProvider.getProperties().getBoolean("permissionsEnabled", Boolean.TRUE); if (permissionsEnabled) { permissionProcessor = new DefaultPermissionProcessor(subject, executingSite, applicationProvider); } else { permissionProcessor = new DummyPermissionProcessor(subject, executingSite, applicationProvider); } boolean hasPermission = permissionProcessor.hasPermission(permission); if (hasPermission) { LOGGER.debug("subject has the permission: {}", permission); return EVAL_BODY_INCLUDE; } } catch (IllegalStateException e) { LOGGER.debug("session {} is invalid,", pageContext.getSession().getId()); } LOGGER.debug("subject does not have the permission: {}", permission); return SKIP_BODY; } @Override int doStartTag(); String getPermission(); void setPermission(String permission); String getApplication(); void setApplication(String application); } |
@Test public void testTaglet() throws Exception { Mockito.when(taglet.processTaglet(site, application, request, tagletAttributes)).thenReturn("a taglet"); Mockito.when(application.getBean("taglet", Taglet.class)).thenReturn(taglet); boolean processPage = tagletProcessor.perform(site, site, application, tagletAttributes, request, "taglet", "", writer); Assert.assertTrue(processPage); Mockito.verify(application).getBean("taglet", Taglet.class); Mockito.verify(taglet).processTaglet(site, application, request, tagletAttributes); Assert.assertEquals("a taglet", writer.toString()); } | public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } boolean perform(Site callingSite, Site executingSite, Application application,
Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName,
String type, Writer out); MarshallService getMarshallService(); void setMarshallService(MarshallService marshallService); StyleSheetProvider getStyleSheetProvider(); void setStyleSheetProvider(StyleSheetProvider styleSheetProvider); } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } boolean perform(Site callingSite, Site executingSite, Application application,
Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName,
String type, Writer out); MarshallService getMarshallService(); void setMarshallService(MarshallService marshallService); StyleSheetProvider getStyleSheetProvider(); void setStyleSheetProvider(StyleSheetProvider styleSheetProvider); } |
@Test public void testGlobalTaglet() throws Exception { Mockito.when(globalTaglet.processTaglet(site, site, application, request, tagletAttributes)) .thenReturn("a global taglet"); Mockito.when(application.getBean("taglet", Taglet.class)).thenReturn(globalTaglet); boolean processPage = tagletProcessor.perform(site, site, application, tagletAttributes, request, "taglet", "", writer); Assert.assertTrue(processPage); Mockito.verify(application).getBean("taglet", Taglet.class); Mockito.verify(globalTaglet).processTaglet(site, site, application, request, tagletAttributes); Assert.assertEquals("a global taglet", writer.toString()); } | public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } boolean perform(Site callingSite, Site executingSite, Application application,
Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName,
String type, Writer out); MarshallService getMarshallService(); void setMarshallService(MarshallService marshallService); StyleSheetProvider getStyleSheetProvider(); void setStyleSheetProvider(StyleSheetProvider styleSheetProvider); } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } boolean perform(Site callingSite, Site executingSite, Application application,
Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName,
String type, Writer out); MarshallService getMarshallService(); void setMarshallService(MarshallService marshallService); StyleSheetProvider getStyleSheetProvider(); void setStyleSheetProvider(StyleSheetProvider styleSheetProvider); } |
@Test public void testReplaceInFile() throws Exception { ClassLoader classLoader = ApplicationStartupTest.class.getClassLoader(); File original = new File(classLoader.getResource("xml/sourceConfig.xml").toURI()); File copy = new File("src/test/resources/xml/copyConfig.xml"); File replacementSource = new File(classLoader.getResource("txt/replacement.txt").toURI()); FileUtils.deleteQuietly(copy); FileUtils.copyFile(original, copy); Charset utf8 = StandardCharsets.UTF_8; String replacement = IOUtils.toString(new FileInputStream(replacementSource), utf8); System.out.println("Replacement String: " + replacement); ApplicationStartup.replaceInFile(copy, "${replaceMe}", replacement); String newContent = IOUtils.toString(new FileInputStream(copy), utf8); Assert.assertEquals("C:\\Foo\\Bar\\Bla\\Blubb", newContent); } | protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search), Matcher.quoteReplacement(replacement)); System.out.println("Replaced " + search + " with " + replacement + " in " + path); Files.write(path, content.getBytes(charset)); } | ApplicationStartup { protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search), Matcher.quoteReplacement(replacement)); System.out.println("Replaced " + search + " with " + replacement + " in " + path); Files.write(path, content.getBytes(charset)); } } | ApplicationStartup { protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search), Matcher.quoteReplacement(replacement)); System.out.println("Replaced " + search + " with " + replacement + " in " + path); Files.write(path, content.getBytes(charset)); } } | ApplicationStartup { protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search), Matcher.quoteReplacement(replacement)); System.out.println("Replaced " + search + " with " + replacement + " in " + path); Files.write(path, content.getBytes(charset)); } static void main(String[] args); } | ApplicationStartup { protected static void replaceInFile(File file, String search, String replacement) throws IOException { Path path = file.toPath(); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll(Pattern.quote(search), Matcher.quoteReplacement(replacement)); System.out.println("Replaced " + search + " with " + replacement + " in " + path); Files.write(path, content.getBytes(charset)); } static void main(String[] args); } |
@Test public void testPageProcessor() throws Exception { Taglet myTaglet = Mockito.spy(new MyTaglet()); Mockito.when(application.getBean("taglet", Taglet.class)).thenReturn(myTaglet); boolean processPage = tagletProcessor.perform(site, site, application, tagletAttributes, request, "taglet", "", writer); Assert.assertFalse(processPage); Mockito.verify(application).getBean("taglet", Taglet.class); Mockito.verify(myTaglet).processTaglet(site, application, request, tagletAttributes); Assert.assertEquals("MyTaglet", writer.toString()); } | public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } boolean perform(Site callingSite, Site executingSite, Application application,
Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName,
String type, Writer out); MarshallService getMarshallService(); void setMarshallService(MarshallService marshallService); StyleSheetProvider getStyleSheetProvider(); void setStyleSheetProvider(StyleSheetProvider styleSheetProvider); } | TagletProcessor { public boolean perform(Site callingSite, Site executingSite, Application application, Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName, String type, Writer out) throws JAXBException, TransformerConfigurationException, FileNotFoundException, BusinessException { boolean processPage; if (XML.equalsIgnoreCase(type)) { processPage = processXmlTaglet(callingSite, executingSite, application, tagletAttributes, applicationRequest, methodName, out); } else { String result; Taglet taglet = application.getBean(methodName, Taglet.class); LOGGER.debug("calling taglet '{}' of type '{}' with attributes: {}", methodName, taglet.getClass().getName(), tagletAttributes); if (taglet instanceof GlobalTaglet) { result = ((GlobalTaglet) taglet).processTaglet(callingSite, executingSite, application, applicationRequest, tagletAttributes); } else { if (!callingSite.equals(executingSite)) { logNotGlobalWarning(callingSite, executingSite, taglet.getClass().getName(), GlobalTaglet.class.getName()); } result = taglet.processTaglet(callingSite, application, applicationRequest, tagletAttributes); } doWrite(out, result, application, methodName); processPage = doProcessPage(taglet); } return processPage; } boolean perform(Site callingSite, Site executingSite, Application application,
Map<String, String> tagletAttributes, org.appng.api.Request applicationRequest, String methodName,
String type, Writer out); MarshallService getMarshallService(); void setMarshallService(MarshallService marshallService); StyleSheetProvider getStyleSheetProvider(); void setStyleSheetProvider(StyleSheetProvider styleSheetProvider); } |
@Test public void test() throws Exception { differenceListener.ignoreDifference("/properties/property/description/text()"); Site created = new Site(); created.setName("localhost"); created.setHost("localhost"); created.setDomain("http: created.setDescription("none"); created.setActive(false); created.setCreateRepositoryPath(true); postAndVerify("/site", "xml/site-create.xml", created, HttpStatus.CREATED); getAndVerify("/site/localhost/property", "xml/site-property-list.xml", HttpStatus.OK); Property prop = new Property(); prop.setName(SiteProperties.ASSETS_DIR); prop.setValue("42"); prop.setDefaultValue("this has no effect"); prop.setDescription("foo"); putAndVerify("/site/localhost/property/" + prop.getName(), "xml/site-property-update.xml", prop, HttpStatus.OK); Property xss = new Property(); xss.setName(SiteProperties.XSS_EXCEPTIONS); xss.setValue("#comment\nfoo\nbar"); xss.setClob(true); xss.setDescription("exceptions for XSS protection"); putAndVerify("/site/localhost/property/" + xss.getName(), "xml/site-property-update2.xml", xss, HttpStatus.OK); prop.setName("theAnswer"); prop.setDefaultValue("42"); prop.setDescription("to life, the universe and everything"); postAndVerify("/site/localhost/property", "xml/site-property-create.xml", prop, HttpStatus.CREATED); getAndVerify("/site/localhost/property/theAnswer", "xml/site-property-create.xml", HttpStatus.OK); deleteAndVerify("/site/localhost/property/theAnswer", null, HttpStatus.NO_CONTENT); Properties properties = new Properties(); prop.setName("myNewProp"); properties.getProperty().add(prop); Property existing = new Property(); existing.setName(prop.getName()); properties.getProperty().add(existing); postAndVerify("/site/localhost/properties", "xml/site-properties-create.xml", properties, HttpStatus.OK); properties.getProperty().remove(existing); Property notExisting = new Property(); notExisting.setName("notExisting"); properties.getProperty().add(notExisting); putAndVerify("/site/localhost/properties", "xml/site-properties-update.xml", properties, HttpStatus.OK); deleteAndVerify("/site/localhost/properties", "xml/site-properties-delete.xml", properties, HttpStatus.OK); } | @GetMapping(value = "/site/{site}/property/{prop}") public ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop) { SiteImpl siteByName = getSiteByName(site); if (null == siteByName) { return notFound(); } return getPropertyResponse(prop, siteByName, null); } | SitePropertyController extends PropertyBase { @GetMapping(value = "/site/{site}/property/{prop}") public ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop) { SiteImpl siteByName = getSiteByName(site); if (null == siteByName) { return notFound(); } return getPropertyResponse(prop, siteByName, null); } } | SitePropertyController extends PropertyBase { @GetMapping(value = "/site/{site}/property/{prop}") public ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop) { SiteImpl siteByName = getSiteByName(site); if (null == siteByName) { return notFound(); } return getPropertyResponse(prop, siteByName, null); } } | SitePropertyController extends PropertyBase { @GetMapping(value = "/site/{site}/property/{prop}") public ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop) { SiteImpl siteByName = getSiteByName(site); if (null == siteByName) { return notFound(); } return getPropertyResponse(prop, siteByName, null); } @GetMapping(value = { "/site/{site}/property", "/site/{site}/properties" }) ResponseEntity<Properties> listProperties(@PathVariable("site") String site); @PutMapping(value = "/site/{site}/properties") ResponseEntity<Properties> updateProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @PostMapping(value = "/site/{site}/properties") ResponseEntity<Properties> createProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @DeleteMapping(value = "/site/{site}/properties") ResponseEntity<Properties> deleteProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @GetMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop); @PostMapping(value = "/site/{site}/property") ResponseEntity<Property> createProperty(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Property property); @PutMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> updateProperty(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Property property); @DeleteMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> deleteProperty(@PathVariable("site") String site,
@PathVariable("prop") String property); } | SitePropertyController extends PropertyBase { @GetMapping(value = "/site/{site}/property/{prop}") public ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop) { SiteImpl siteByName = getSiteByName(site); if (null == siteByName) { return notFound(); } return getPropertyResponse(prop, siteByName, null); } @GetMapping(value = { "/site/{site}/property", "/site/{site}/properties" }) ResponseEntity<Properties> listProperties(@PathVariable("site") String site); @PutMapping(value = "/site/{site}/properties") ResponseEntity<Properties> updateProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @PostMapping(value = "/site/{site}/properties") ResponseEntity<Properties> createProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @DeleteMapping(value = "/site/{site}/properties") ResponseEntity<Properties> deleteProperties(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Properties properties); @GetMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> getProperty(@PathVariable("site") String site, @PathVariable("prop") String prop); @PostMapping(value = "/site/{site}/property") ResponseEntity<Property> createProperty(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Property property); @PutMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> updateProperty(@PathVariable("site") String site,
@RequestBody org.appng.appngizer.model.xml.Property property); @DeleteMapping(value = "/site/{site}/property/{prop}") ResponseEntity<Property> deleteProperty(@PathVariable("site") String site,
@PathVariable("prop") String property); } |
@Test public void testInitialize() throws Exception { ignorePasswordAndInstalledDate(); postAndVerify("/platform/database/initialize", "xml/database-init.xml", null, HttpStatus.OK); } | @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseService.initDatabase(configurer.getProps(), isManaged, true); return info(platformConnection); } | DatabaseController extends ControllerBase { @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseService.initDatabase(configurer.getProps(), isManaged, true); return info(platformConnection); } } | DatabaseController extends ControllerBase { @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseService.initDatabase(configurer.getProps(), isManaged, true); return info(platformConnection); } } | DatabaseController extends ControllerBase { @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseService.initDatabase(configurer.getProps(), isManaged, true); return info(platformConnection); } @GetMapping(value = "/platform/database") ResponseEntity<Database> info(); @PutMapping(value = "/platform/database") ResponseEntity<Database> updateRootConnection(@RequestBody org.appng.appngizer.model.xml.Database database); @PostMapping(value = "/platform/database/initialize") ResponseEntity<Database> initialize(
@RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged); @GetMapping(value = "/site/{name}/database") ResponseEntity<Databases> getDatabaseConnections(@PathVariable("name") String name); @GetMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> getDatabaseConnectionForApplication(@PathVariable("site") String site,
@PathVariable("app") String app); @PutMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> updateDatabaseConnectionforApplication(@PathVariable("site") String site,
@PathVariable("app") String app, @RequestBody org.appng.appngizer.model.xml.Database database); @GetMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> getDatabaseConnection(@PathVariable("name") String name,
@PathVariable("id") Integer id); @PutMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> updateDatabaseConnection(@PathVariable("name") String name,
@PathVariable("id") Integer id, @RequestBody org.appng.appngizer.model.xml.Database database); } | DatabaseController extends ControllerBase { @PostMapping(value = "/platform/database/initialize") public ResponseEntity<Database> initialize( @RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged) throws Exception { DatabaseConnection platformConnection = databaseService.initDatabase(configurer.getProps(), isManaged, true); return info(platformConnection); } @GetMapping(value = "/platform/database") ResponseEntity<Database> info(); @PutMapping(value = "/platform/database") ResponseEntity<Database> updateRootConnection(@RequestBody org.appng.appngizer.model.xml.Database database); @PostMapping(value = "/platform/database/initialize") ResponseEntity<Database> initialize(
@RequestParam(name = "managed", required = false, defaultValue = "false") boolean isManaged); @GetMapping(value = "/site/{name}/database") ResponseEntity<Databases> getDatabaseConnections(@PathVariable("name") String name); @GetMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> getDatabaseConnectionForApplication(@PathVariable("site") String site,
@PathVariable("app") String app); @PutMapping(value = "/site/{site}/application/{app}/database") ResponseEntity<Database> updateDatabaseConnectionforApplication(@PathVariable("site") String site,
@PathVariable("app") String app, @RequestBody org.appng.appngizer.model.xml.Database database); @GetMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> getDatabaseConnection(@PathVariable("name") String name,
@PathVariable("id") Integer id); @PutMapping(value = "/site/{name}/database/{id}") ResponseEntity<Database> updateDatabaseConnection(@PathVariable("name") String name,
@PathVariable("id") Integer id, @RequestBody org.appng.appngizer.model.xml.Database database); } |
@Test public void testEncode() { Assert.assertEquals("name%20with%20spaces", AppNGizer.encode("name with spaces")); } | static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } | AppNGizer implements AppNGizerClient { static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } } | AppNGizer implements AppNGizerClient { static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } AppNGizer(String endpoint, String sharedSecret); } | AppNGizer implements AppNGizerClient { static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); } | AppNGizer implements AppNGizerClient { static String encode(String segment) { try { return UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { return segment; } } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); } |
@Ignore("Run locally") @Test(expected = HttpClientErrorException.class) public void testUploadPackage() throws Exception { getAppNGizer().uploadPackage("local", new File("pom.xml")); } | public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return exchange("/repository/" + encode(name) + "/upload", multipartRequest, HttpMethod.POST, headers, Package.class); } | AppNGizer implements AppNGizerClient { public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return exchange("/repository/" + encode(name) + "/upload", multipartRequest, HttpMethod.POST, headers, Package.class); } } | AppNGizer implements AppNGizerClient { public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return exchange("/repository/" + encode(name) + "/upload", multipartRequest, HttpMethod.POST, headers, Package.class); } AppNGizer(String endpoint, String sharedSecret); } | AppNGizer implements AppNGizerClient { public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return exchange("/repository/" + encode(name) + "/upload", multipartRequest, HttpMethod.POST, headers, Package.class); } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); } | AppNGizer implements AppNGizerClient { public Package uploadPackage(String name, File archive) throws IOException { MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>(); multipartRequest.add("file", new FileSystemResource(archive)); HttpHeaders headers = getHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return exchange("/repository/" + encode(name) + "/upload", multipartRequest, HttpMethod.POST, headers, Package.class); } AppNGizer(String endpoint, String sharedSecret); Home welcome(); Home login(); Subjects subjects(); Subject subject(String name); Subject createSubject(Subject subject); Subject updateSubject(String name, Subject subject); void deleteSubject(String name); Groups groups(); Group group(String name); Group createGroup(Group group); Group updateGroup(String name, Group group); void deleteGroup(String name); Applications applications(); Application application(String app); Application updateApplication(String app, Application application); void deleteApplication(String app); Properties applicationProperties(String app); Property createApplicationProperty(String app, Property property); Property updateApplicationProperty(String app, Property property); void deleteApplicationProperty(String app, String name); Roles roles(String app); Role role(String app, String name); Role createRole(String app, Role role); Role updateRole(String app, String name, Role role); void deleteRole(String app, String name); Permissions permissions(String app); Permission permission(String app, String name); Permission createPermission(String app, Permission permission); Permission updatePermission(String app, String name, Permission permission); void deletePermission(String app, String name); Sites sites(); Site site(String name); Site createSite(Site site); Site updateSite(String name, Site site); void deleteSite(String name); void reloadSite(String name); Properties siteProperties(String site); Property siteProperty(String site, String name); Property createSiteProperty(String site, Property property); Property updateSiteProperty(String site, String name, Property property); void deleteSiteProperty(String site, String name); Applications applications(String site); Application application(String site, String app); void activateApplication(String site, String app); void deactivateApplication(String site, String app); Grants siteGrants(String site, String app); Grants updateSiteGrants(String site, String app, Grants grants); Properties applicationProperties(String site, String app); Property createApplicationProperty(String site, String app, Property property); Property updateApplicationProperty(String site, String app, String name, Property property); void deleteApplicationProperty(String site, String app, String name); Repositories repositories(); Repository repository(String name); Repository createRepository(Repository repository); Repository updateRepository(String name, Repository repository); void deleteRepository(String name); Package installPackage(String name, Package packageToInstall); Package uploadPackage(String name, File archive); Properties platformProperties(); Property platformProperty(String name); Property createPlatformProperty(Property property); Property updatePlatformProperty(String name, Property property); void deletePlatformProperty(String name); Properties environment(); Properties system(); Database database(); Database initializeDatabase(); } |
@Test public void testStyleSheetProvider() throws Exception { ClassLoader classLoader = getClass().getClassLoader(); ssProvider.setName("container"); ssProvider.setInsertBefore("include-4.xsl"); addStyleSheet("include-1.xsl"); addStyleSheet("include-2.xsl"); addStyleSheet("include-3.xsl"); File expected = new File(classLoader.getResource("xsl/result.xsl").toURI()).getAbsoluteFile(); File result = new File("target/xsl/result-2.xsl"); FileUtils.writeByteArrayToFile(result, ssProvider.getStyleSheet(true)); List<String> lines1 = FileUtils.readLines(expected, "UTF-8"); List<String> lines2 = FileUtils.readLines(result, "UTF-8"); Assert.assertEquals(lines1.size(), lines2.size()); for (int i = 0; i < lines1.size(); i++) { Assert.assertEquals(lines1.get(i).trim(), lines2.get(i).trim()); } } | public StyleSheetProvider() { } | StyleSheetProvider { public StyleSheetProvider() { } } | StyleSheetProvider { public StyleSheetProvider() { } StyleSheetProvider(); } | StyleSheetProvider { public StyleSheetProvider() { } StyleSheetProvider(); void init(); void setMasterSource(InputStream masterXsl, String templateRoot); void addStyleSheet(InputStream styleSheet, String reference); byte[] getStyleSheet(boolean deleteIncludes); byte[] getStyleSheet(boolean deleteIncludes, OutputStream additionalOut); DocumentBuilderFactory getDocumentBuilderFactory(); void setDocumentBuilderFactory(DocumentBuilderFactory documentBuilderFactory); TransformerFactory getTransformerFactory(); void setTransformerFactory(TransformerFactory transformerFactory); DocumentBuilder getDocumentBuilder(); void setDocumentBuilder(DocumentBuilder documentBuilder); Transformer getTransformer(); void setTransformer(Transformer transformer); String getInsertBefore(); void setInsertBefore(String insertBefore); String getName(); void setName(String name); String getId(); void cleanup(); boolean isValid(); } | StyleSheetProvider { public StyleSheetProvider() { } StyleSheetProvider(); void init(); void setMasterSource(InputStream masterXsl, String templateRoot); void addStyleSheet(InputStream styleSheet, String reference); byte[] getStyleSheet(boolean deleteIncludes); byte[] getStyleSheet(boolean deleteIncludes, OutputStream additionalOut); DocumentBuilderFactory getDocumentBuilderFactory(); void setDocumentBuilderFactory(DocumentBuilderFactory documentBuilderFactory); TransformerFactory getTransformerFactory(); void setTransformerFactory(TransformerFactory transformerFactory); DocumentBuilder getDocumentBuilder(); void setDocumentBuilder(DocumentBuilder documentBuilder); Transformer getTransformer(); void setTransformer(Transformer transformer); String getInsertBefore(); void setInsertBefore(String insertBefore); String getName(); void setName(String name); String getId(); void cleanup(); boolean isValid(); } |
@Test public void test() throws Exception { String outFile = "src/test/resources/xml/application.xml"; ApplicationPropertyConstantCreator .main(new String[] { outFile, "org.appng.xml.ApplicationProperty", "target/tmp", "PROP_" }); String actual = FileUtils.readFileToString(new File("target/tmp/org/appng/xml/ApplicationProperty.java"), StandardCharsets.UTF_8); String expected = FileUtils.readFileToString(new File("src/test/resources/ApplicationProperty.java"), StandardCharsets.UTF_8); Assert.assertEquals(expected, actual); } | public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String prefix = args.length == 4 ? args[3] : ""; if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } File appXml = new File(filePath); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); ApplicationInfo application = applicationMarshallService.unmarshall(appXml, ApplicationInfo.class); readNameAndVersionFromPom(application, appXml); List<Property> properties = application.getProperties().getProperty(); Collections.sort(properties, new Comparator<Property>() { public int compare(Property o1, Property o2) { return o1.getId().compareToIgnoreCase(o2.getId()); } }); String separator = System.getProperty("line.separator"); int pckg = targetClass.lastIndexOf("."); StringBuilder sb = new StringBuilder(); sb.append("package " + targetClass.substring(0, pckg) + ";" + separator); sb.append(separator); sb.append(""); sb.append(separator); sb.append("public class " + targetClass.substring(pckg + 1) + " {" + separator); sb.append(separator); for (Property property : properties) { if (StringUtils.isNotBlank(property.getDescription())) { sb.append("\t" + separator); } sb.append("\tpublic static final String "); sb.append(prefix); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(property.getId()); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (StringUtils.containsNone(s, '_', '-', '.')) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + property.getId() + "\";" + separator); } sb.append(separator); sb.append("}"); String fileName = targetClass.replaceAll("\\.", "/") + ".java"; File outFile = new File(new File(outfolder).getAbsoluteFile(), fileName); outFile.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(sb.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); LOGGER.debug("Wrote {}", outFile.getAbsolutePath()); } } | ApplicationPropertyConstantCreator { public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String prefix = args.length == 4 ? args[3] : ""; if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } File appXml = new File(filePath); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); ApplicationInfo application = applicationMarshallService.unmarshall(appXml, ApplicationInfo.class); readNameAndVersionFromPom(application, appXml); List<Property> properties = application.getProperties().getProperty(); Collections.sort(properties, new Comparator<Property>() { public int compare(Property o1, Property o2) { return o1.getId().compareToIgnoreCase(o2.getId()); } }); String separator = System.getProperty("line.separator"); int pckg = targetClass.lastIndexOf("."); StringBuilder sb = new StringBuilder(); sb.append("package " + targetClass.substring(0, pckg) + ";" + separator); sb.append(separator); sb.append(""); sb.append(separator); sb.append("public class " + targetClass.substring(pckg + 1) + " {" + separator); sb.append(separator); for (Property property : properties) { if (StringUtils.isNotBlank(property.getDescription())) { sb.append("\t" + separator); } sb.append("\tpublic static final String "); sb.append(prefix); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(property.getId()); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (StringUtils.containsNone(s, '_', '-', '.')) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + property.getId() + "\";" + separator); } sb.append(separator); sb.append("}"); String fileName = targetClass.replaceAll("\\.", "/") + ".java"; File outFile = new File(new File(outfolder).getAbsoluteFile(), fileName); outFile.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(sb.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); LOGGER.debug("Wrote {}", outFile.getAbsolutePath()); } } } | ApplicationPropertyConstantCreator { public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String prefix = args.length == 4 ? args[3] : ""; if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } File appXml = new File(filePath); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); ApplicationInfo application = applicationMarshallService.unmarshall(appXml, ApplicationInfo.class); readNameAndVersionFromPom(application, appXml); List<Property> properties = application.getProperties().getProperty(); Collections.sort(properties, new Comparator<Property>() { public int compare(Property o1, Property o2) { return o1.getId().compareToIgnoreCase(o2.getId()); } }); String separator = System.getProperty("line.separator"); int pckg = targetClass.lastIndexOf("."); StringBuilder sb = new StringBuilder(); sb.append("package " + targetClass.substring(0, pckg) + ";" + separator); sb.append(separator); sb.append(""); sb.append(separator); sb.append("public class " + targetClass.substring(pckg + 1) + " {" + separator); sb.append(separator); for (Property property : properties) { if (StringUtils.isNotBlank(property.getDescription())) { sb.append("\t" + separator); } sb.append("\tpublic static final String "); sb.append(prefix); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(property.getId()); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (StringUtils.containsNone(s, '_', '-', '.')) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + property.getId() + "\";" + separator); } sb.append(separator); sb.append("}"); String fileName = targetClass.replaceAll("\\.", "/") + ".java"; File outFile = new File(new File(outfolder).getAbsoluteFile(), fileName); outFile.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(sb.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); LOGGER.debug("Wrote {}", outFile.getAbsolutePath()); } } } | ApplicationPropertyConstantCreator { public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String prefix = args.length == 4 ? args[3] : ""; if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } File appXml = new File(filePath); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); ApplicationInfo application = applicationMarshallService.unmarshall(appXml, ApplicationInfo.class); readNameAndVersionFromPom(application, appXml); List<Property> properties = application.getProperties().getProperty(); Collections.sort(properties, new Comparator<Property>() { public int compare(Property o1, Property o2) { return o1.getId().compareToIgnoreCase(o2.getId()); } }); String separator = System.getProperty("line.separator"); int pckg = targetClass.lastIndexOf("."); StringBuilder sb = new StringBuilder(); sb.append("package " + targetClass.substring(0, pckg) + ";" + separator); sb.append(separator); sb.append(""); sb.append(separator); sb.append("public class " + targetClass.substring(pckg + 1) + " {" + separator); sb.append(separator); for (Property property : properties) { if (StringUtils.isNotBlank(property.getDescription())) { sb.append("\t" + separator); } sb.append("\tpublic static final String "); sb.append(prefix); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(property.getId()); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (StringUtils.containsNone(s, '_', '-', '.')) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + property.getId() + "\";" + separator); } sb.append(separator); sb.append("}"); String fileName = targetClass.replaceAll("\\.", "/") + ".java"; File outFile = new File(new File(outfolder).getAbsoluteFile(), fileName); outFile.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(sb.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); LOGGER.debug("Wrote {}", outFile.getAbsolutePath()); } } static void main(String[] args); } | ApplicationPropertyConstantCreator { public static void main(String[] args) throws IOException, JAXBException { if (args.length < 3) { throw new IllegalArgumentException("need 3 params (filePath, targetClass, outFolder)"); } String filePath = args[0]; String targetClass = args[1]; String outfolder = args[2]; String prefix = args.length == 4 ? args[3] : ""; if (!targetClass.matches("([a-zA-Z]+[0-9]*)+(\\.[a-zA-Z]+[0-9]*)*")) { throw new IllegalArgumentException("not a valid classname: " + targetClass); } File appXml = new File(filePath); MarshallService applicationMarshallService = MarshallService.getApplicationMarshallService(); ApplicationInfo application = applicationMarshallService.unmarshall(appXml, ApplicationInfo.class); readNameAndVersionFromPom(application, appXml); List<Property> properties = application.getProperties().getProperty(); Collections.sort(properties, new Comparator<Property>() { public int compare(Property o1, Property o2) { return o1.getId().compareToIgnoreCase(o2.getId()); } }); String separator = System.getProperty("line.separator"); int pckg = targetClass.lastIndexOf("."); StringBuilder sb = new StringBuilder(); sb.append("package " + targetClass.substring(0, pckg) + ";" + separator); sb.append(separator); sb.append(""); sb.append(separator); sb.append("public class " + targetClass.substring(pckg + 1) + " {" + separator); sb.append(separator); for (Property property : properties) { if (StringUtils.isNotBlank(property.getDescription())) { sb.append("\t" + separator); } sb.append("\tpublic static final String "); sb.append(prefix); String[] tokens = StringUtils.splitByCharacterTypeCamelCase(property.getId()); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (StringUtils.containsNone(s, '_', '-', '.')) { if (i > 0) { sb.append("_"); } sb.append(s.toUpperCase()); } } sb.append(" = \"" + property.getId() + "\";" + separator); } sb.append(separator); sb.append("}"); String fileName = targetClass.replaceAll("\\.", "/") + ".java"; File outFile = new File(new File(outfolder).getAbsoluteFile(), fileName); outFile.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(sb.toString().getBytes(StandardCharsets.UTF_8)); fos.close(); LOGGER.debug("Wrote {}", outFile.getAbsolutePath()); } } static void main(String[] args); } |
@Test public void testFile() throws Exception { Map<String, StringBuilder> parsed = parseTags.parse(new File("pages/en/42.jsp")); Assert.assertEquals("The Hitchhiker's Guide to the Galaxy", parsed.get("title").toString()); String contents = parsed.get("contents").toString(); String expected = "The Hitchhiker's Guide to the Galaxy is a comic science fiction series"; Assert.assertTrue(contents.startsWith(expected)); } | public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); } |
@Test public void testNestedTags() throws Exception { String in = "<a:searchable index=\"true\" field=\"contents\">" + "<a:searchable index=\"true\" field=\"field1\"> A </a:searchable>" + "<a:searchable index=\"true\" field=\"field2\"> B </a:searchable>" + "<a:searchable index=\"false\"> C </a:searchable>" + " D </a:searchable>"; Map<String, StringBuilder> parsed = new ParseTags("a").parse(new ByteArrayInputStream(in.getBytes())); System.out.println(parsed); Assert.assertEquals("A", parsed.get("field1").toString()); Assert.assertEquals("B", parsed.get("field2").toString()); Assert.assertNull(parsed.get("field3")); Assert.assertEquals("A B D", parsed.get("contents").toString()); } | public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); } |
@Test public void testNotIndexed() throws Exception { String in = "<html><head></head><appNG:searchable index=\"false\">" + "<appNG:searchable index=\"true\" field=\"field1\"> A </appNG:searchable>" + "<appNG:searchable index=\"true\" field=\"field2\"> B </appNG:searchable>" + "<appNG:searchable index=\"false\"> C </appNG:searchable>" + " D </appNG:searchable></html>"; Map<String, StringBuilder> parsed = parseTags.parse(new ByteArrayInputStream(in.getBytes())); System.out.println(parsed); Assert.assertNull(parsed.get("field1")); Assert.assertNull(parsed.get("field2")); Assert.assertNull(parsed.get("field3")); Assert.assertNull(parsed.get("contents")); } | public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); } | ParseTags { public Map<String, StringBuilder> parse(InputStream is) throws IOException { try (InputStream inner = is) { Map<String, StringBuilder> fieldMap = new HashMap<>(); Document doc = Jsoup.parse(inner, null, ""); Elements searchables = doc.getElementsByTag(tagPrefix + ":" + SEARCHABLE); List<Node> skipped = new ArrayList<>(); for (Element node : searchables) { StringBuilder content = new StringBuilder(); if (append(skipped, node, content)) { String field = node.attr(ATTR_FIELD); if (!fieldMap.containsKey(field)) { fieldMap.put(field, content); } else { StringBuilder existingBuffer = fieldMap.get(field); existingBuffer.append(content.toString().trim()); } } } return fieldMap; } catch (IOException e) { throw e; } } ParseTags(String tagPrefix); Map<String, StringBuilder> parse(InputStream is); } |
@Test public void testGetString() throws IOException { Assert.assertEquals("abcd", processor.getString("/root/a/string")); Assert.assertEquals("abcd", processor.getString(processor.getNode("/root/a"), "string")); } | public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } | XPathProcessor { public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } } | XPathProcessor { public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public String getString(String xpathExpression) { return (String) evaluate(document, xpathExpression, XPathConstants.STRING); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void testGetBoolean() throws IOException { Assert.assertEquals(Boolean.TRUE, processor.getBoolean("/root/a/boolean")); Assert.assertEquals(Boolean.TRUE, processor.getBoolean(processor.getNode("/root/a"), "boolean")); } | public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } | XPathProcessor { public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } } | XPathProcessor { public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public Boolean getBoolean(String xpathExpression) { return (Boolean) evaluate(document, xpathExpression, XPathConstants.BOOLEAN); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void testGetNumber() throws IOException { Assert.assertEquals(3.45d, processor.getNumber("/root/a/double")); Assert.assertEquals(3.45d, processor.getNumber(processor.getNode("/root/a"), "double")); } | public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } | XPathProcessor { public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } } | XPathProcessor { public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public Number getNumber(String xpathExpression) { return (Number) evaluate(document, xpathExpression, XPathConstants.NUMBER); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void testGetXml() { Node node = processor.getNode("/root/b"); String xml = processor.getXml(node); ByteArrayOutputStream out = new ByteArrayOutputStream(); processor.getXml(node, out); Assert.assertEquals(xml, out.toString()); } | public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } | XPathProcessor { public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } } | XPathProcessor { public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public String getXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); getXml(node, outputStream); return new String(outputStream.toByteArray()); } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void testNewText() { Text text = processor.newText("data"); Assert.assertEquals("data", text.getData()); } | public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } | XPathProcessor { public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } } | XPathProcessor { public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public Text newText(String tagName) { Text text = document.createTextNode(tagName); return text; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void testFitToHeight() throws IOException { File targetFile = new File(targetFolder, "desert-height-100.jpg"); ImageProcessor ip = getSource(targetFile); ip.fitToHeight(100); ImageMetaData metaData = new ImageProcessor(ip.getImage(), null, true).getMetaData(); assertDimensions(133, 100, metaData); } | public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } return resize(width, height); } | ImageProcessor { public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } return resize(width, height); } } | ImageProcessor { public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } return resize(width, height); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); } | ImageProcessor { public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } return resize(width, height); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } | ImageProcessor { public ImageProcessor fitToHeight(Integer maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); if (height > maxHeight) { height = maxHeight; width = Math.round(((float) maxHeight / height) * width); } return resize(width, height); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } |
@Test public void testNewCDATA() { Text text = processor.newCDATA("data"); Assert.assertEquals("data", text.getData()); } | public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } | XPathProcessor { public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } } | XPathProcessor { public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public CDATASection newCDATA(String tagName) { CDATASection cdata = document.createCDATASection(tagName); return cdata; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void testNewElement() { Element el = processor.newElement("data"); Assert.assertEquals("data", el.getTagName()); } | public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } | XPathProcessor { public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } } | XPathProcessor { public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public Element newElement(String tagName) { Element element = document.createElement(tagName); return element; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void testNewAttribute() { Attr attr = processor.newAttribute("name", "value"); Assert.assertEquals("name", attr.getName()); Assert.assertEquals("value", attr.getValue()); } | public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } | XPathProcessor { public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } } | XPathProcessor { public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); } | XPathProcessor { public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } | XPathProcessor { public Attr newAttribute(String name, String value) { Attr attribute = document.createAttribute(name); attribute.setNodeValue(value); return attribute; } XPathProcessor(String url); XPathProcessor(URL url); XPathProcessor(InputStream is); XPathProcessor(Document document); void setNamespace(String prefix, String namespace); String getXml(Node node); void getXml(Node node, OutputStream outputStream); String getXml(); void getXml(OutputStream outputStream); String getXml(NodeList nodes); String getString(String xpathExpression); String getString(Node node, String xpathExpression); Boolean getBoolean(String xpathExpression); Boolean getBoolean(Node node, String xpathExpression); Number getNumber(String xpathExpression); Number getNumber(Node node, String xpathExpression); Node getNode(String xpathExpression); Node getNode(Node node, String xpathExpression); Element getElement(String xpathExpression); Element getElement(Node node, String xpathExpression); NodeList getNodes(String xpathExpression); NodeList getNodes(Node node, String xpathExpression); Attr newAttribute(String name, String value); Element newElement(String tagName); CDATASection newCDATA(String tagName); Text newText(String tagName); Node addAttribute(Node node, String name, String value); Document getDocument(); } |
@Test public void doTest() { MockitoAnnotations.initMocks(this); Map<String, List<String>> paramters = new HashMap<>(); paramters.put(NAME, Arrays.asList("Doe")); paramters.put(INTEGER_LIST, Arrays.asList("1", "2", "3")); paramters.put(BIRTH_DATE, Arrays.asList("14.05.1944")); Mockito.when(request.getParameterNames()).thenReturn(paramters.keySet()); Mockito.when(request.getParameterList(Mockito.anyString())).then(new Answer<List<String>>() { public List<String> answer(InvocationOnMock invocation) throws Throwable { return paramters.get(invocation.getArgumentAt(0, String.class)); } }); Map<String, List<FormUpload>> formUploads = getFormUploads(); List<FormUpload> pictures = formUploads.get(PICTURE); Mockito.when(request.getFormUploads()).thenReturn(formUploads); Mockito.when(request.getFormUploads(PICTURE)).thenReturn(pictures); Mockito.when(request.getFormUploads(MORE_PICTURES)).thenReturn(pictures); ConfigurableConversionService conversionService = getConversionService(); RequestDataBinder<Person> requestDataBinder = new RequestDataBinder<Person>(new Person(), request, conversionService); Person person = requestDataBinder.bind(); validate(pictures, person); } | @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) { addValue(mpvs, name, request.getFormUploads(name)); } doBind(mpvs); return (T) getTarget(); } | RequestDataBinder extends DataBinder { @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) { addValue(mpvs, name, request.getFormUploads(name)); } doBind(mpvs); return (T) getTarget(); } } | RequestDataBinder extends DataBinder { @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) { addValue(mpvs, name, request.getFormUploads(name)); } doBind(mpvs); return (T) getTarget(); } RequestDataBinder(T target, Request request); RequestDataBinder(T target, Request request, ConversionService conversionService); protected RequestDataBinder(T target); } | RequestDataBinder extends DataBinder { @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) { addValue(mpvs, name, request.getFormUploads(name)); } doBind(mpvs); return (T) getTarget(); } RequestDataBinder(T target, Request request); RequestDataBinder(T target, Request request, ConversionService conversionService); protected RequestDataBinder(T target); @SuppressWarnings("unchecked") T bind(); } | RequestDataBinder extends DataBinder { @SuppressWarnings("unchecked") public T bind() { MutablePropertyValues mpvs = new MutablePropertyValues(); for (String name : request.getParameterNames()) { addValue(mpvs, name, request.getParameterList(name)); } for (String name : request.getFormUploads().keySet()) { addValue(mpvs, name, request.getFormUploads(name)); } doBind(mpvs); return (T) getTarget(); } RequestDataBinder(T target, Request request); RequestDataBinder(T target, Request request, ConversionService conversionService); protected RequestDataBinder(T target); @SuppressWarnings("unchecked") T bind(); } |
@Test public void testSetItem() { dataContainer.setItem(persons.get(0)); Assert.assertEquals(fieldProcessor, dataContainer.getFieldProcessor()); Assert.assertEquals(persons.get(0), dataContainer.getItem()); Assert.assertNull(dataContainer.getPageable()); Assert.assertNull(dataContainer.getPage()); Assert.assertTrue(dataContainer.isSingleResult()); Assert.assertNull(dataContainer.getItems()); Assert.assertNull(dataContainer.getWrappedData().isPaginate()); } | public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } | DataContainer { public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } } | DataContainer { public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } DataContainer(final FieldProcessor fieldProcessor); } | DataContainer { public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } | DataContainer { public void setItem(Object item) { this.item = item; setSingleResult(true); initItem(); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } |
@Test public void testSetPage() { dataContainer.setPage(page); Assert.assertNull(dataContainer.getPageable()); Assert.assertEquals(page, dataContainer.getPage()); Assert.assertFalse(dataContainer.isSingleResult()); Assert.assertNull(dataContainer.getItems()); Assert.assertNull(dataContainer.getWrappedData().isPaginate()); } | public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } | DataContainer { public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } } | DataContainer { public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } DataContainer(final FieldProcessor fieldProcessor); } | DataContainer { public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } | DataContainer { public void setPage(Collection<?> items, Pageable pageable) { setPage(items, pageable, false); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } |
@Test public void testSetItems() { dataContainer.setItems(persons); Assert.assertNull(dataContainer.getPageable()); Assert.assertNull(dataContainer.getPage()); Assert.assertFalse(dataContainer.isSingleResult()); Assert.assertEquals(persons, dataContainer.getItems()); Assert.assertFalse(dataContainer.getWrappedData().isPaginate()); } | public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } | DataContainer { public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } } | DataContainer { public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } DataContainer(final FieldProcessor fieldProcessor); } | DataContainer { public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } | DataContainer { public void setItems(Collection<?> items) { this.items = items; setSingleResult(false); initItems(items); setPageable(null); } DataContainer(final FieldProcessor fieldProcessor); Object getItem(); void setItem(Object item); boolean isSingleResult(); Collection<?> getItems(); void setItems(Collection<?> items); void setPage(Collection<?> items, Pageable pageable); @SuppressWarnings({ "rawtypes", "unchecked" }) void setPage(Collection<?> items, Pageable pageable, boolean skipSort); Pageable getPageable(); Page<?> getPage(); void setPage(Page<?> page); List<Selection> getSelections(); List<SelectionGroup> getSelectionGroups(); Data getWrappedData(); FieldProcessor getFieldProcessor(); } |
@Test public void testMd5Digest() { String md5Digest = AuthTools.getMd5Digest(testPattern); Assert.assertEquals("7C2AD50DBEA658E2F87DDE1609114237", md5Digest); } | public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } | AuthTools { public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } } | AuthTools { public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } private AuthTools(); } | AuthTools { public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); } | AuthTools { public static String getMd5Digest(String input) { return getDigest(input, MessageDigestAlgorithms.MD5); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); } |
@Test public void testSha1Digest() { String sha1Digest = AuthTools.getSha1Digest(testPattern); Assert.assertEquals("746BDF044C80DD81336A522BF27D8C661947D3EF", sha1Digest); } | public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } | AuthTools { public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } } | AuthTools { public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } private AuthTools(); } | AuthTools { public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); } | AuthTools { public static String getSha1Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_1); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); } |
@Test public void testSha512Digest() { String sha512Digest = AuthTools.getSha512Digest(testPattern); Assert.assertEquals( "AB9D85DC074D06B675DAEE7FA4A70C7D0BD8F9A284713DAA0E5689DAA9367DD10258E331D3494053B4F5A1084D7881455DB5AADB84BDFAF5638677ED1D1C4881", sha512Digest); } | public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } | AuthTools { public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } } | AuthTools { public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } private AuthTools(); } | AuthTools { public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); } | AuthTools { public static String getSha512Digest(String input) { return getDigest(input, MessageDigestAlgorithms.SHA_512); } private AuthTools(); static byte[] base64ToByte(String data); static String byteToBase64(byte[] data); static String getRandomSalt(int length); static String getMd5Digest(String input); static String getSha1Digest(String input); static String getSha512Digest(String input); } |
@Test public void testFitToWidthAndHeight() throws IOException { ImageProcessor ip = getSource(new File(targetFolder, "desert-512x384.jpg")); ip.fitToWidthAndHeight(512, 512); ImageMetaData metaData = new ImageProcessor(ip.getImage(), null, true).getMetaData(); assertDimensions(512, 384, metaData); } | public ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); float ratioWidth = (float) maxwidth / width; float ratioHeight = (float) maxHeight / height; float ratio = Math.min(ratioWidth, ratioHeight); int scaledWidth = Math.round(width * ratio); int scaledHeight = Math.round(height * ratio); return resize(scaledWidth, scaledHeight); } | ImageProcessor { public ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); float ratioWidth = (float) maxwidth / width; float ratioHeight = (float) maxHeight / height; float ratio = Math.min(ratioWidth, ratioHeight); int scaledWidth = Math.round(width * ratio); int scaledHeight = Math.round(height * ratio); return resize(scaledWidth, scaledHeight); } } | ImageProcessor { public ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); float ratioWidth = (float) maxwidth / width; float ratioHeight = (float) maxHeight / height; float ratio = Math.min(ratioWidth, ratioHeight); int scaledWidth = Math.round(width * ratio); int scaledHeight = Math.round(height * ratio); return resize(scaledWidth, scaledHeight); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); } | ImageProcessor { public ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); float ratioWidth = (float) maxwidth / width; float ratioHeight = (float) maxHeight / height; float ratio = Math.min(ratioWidth, ratioHeight); int scaledWidth = Math.round(width * ratio); int scaledHeight = Math.round(height * ratio); return resize(scaledWidth, scaledHeight); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } | ImageProcessor { public ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight) throws IOException { ImageMetaData metaData = getMetaData(); int width = metaData.getWidth(); int height = metaData.getHeight(); float ratioWidth = (float) maxwidth / width; float ratioHeight = (float) maxHeight / height; float ratio = Math.min(ratioWidth, ratioHeight); int scaledWidth = Math.round(width * ratio); int scaledHeight = Math.round(height * ratio); return resize(scaledWidth, scaledHeight); } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } |
@Test public void testPerformException() { ApplicationRequest applicationRequest = initApplication(false); Mockito.when(config.getLinkpanel()).thenReturn(null); try { CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); fail("ProcessingException must occur!"); } catch (ProcessingException e) { String message = e.getMessage(); assertTrue(message.matches("error performing action 'myAction' of event 'myEvent', ID: \\d{6,12}")); } } | public FieldProcessor perform() throws ProcessingException { return perform(false); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } |
@Test public void testPerformWithErrorFromDataProvider() throws ProcessingException { ApplicationRequest applicationRequest = initApplication(true); AtomicReference<Messages> envMessages = new AtomicReference<Messages>(new Messages()); AtomicReference<Messages> actionMessages = new AtomicReference<Messages>(new Messages()); mockMessages(envMessages, actionMessages, false); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(5, FieldProcessor.class); DataContainer dataContainer = new DataContainer(fp); dataContainer.setItem(new Object()); fp.addErrorMessage("Error!"); return dataContainer; }).when(dataProvider).getData(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any()); CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); Assert.assertNull(envMessages.get()); Assert.assertNotNull(actionMessages.get()); Message message = actionMessages.get().getMessageList().get(0); Assert.assertEquals("Error!", message.getContent()); Assert.assertEquals(MessageType.ERROR, message.getClazz()); } | public FieldProcessor perform() throws ProcessingException { return perform(false); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } |
@Test public void testPerformWithErrorFromAction() throws ProcessingException { ApplicationRequest applicationRequest = initApplication(true); AtomicReference<Messages> envMessages = new AtomicReference<Messages>(new Messages()); AtomicReference<Messages> actionMessages = new AtomicReference<Messages>(new Messages()); mockMessages(envMessages, actionMessages, true); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(5, FieldProcessor.class); DataContainer dataContainer = new DataContainer(fp); dataContainer.setItem(new Object()); return dataContainer; }).when(dataProvider).getData(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any()); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(6, FieldProcessor.class); fp.addErrorMessage("BOOOOM!"); return null; }).when(actionProvider).perform(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any(), Mockito.any()); CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); Assert.assertNull(envMessages.get()); Assert.assertNotNull(actionMessages.get()); List<Message> messageList = actionMessages.get().getMessageList(); Assert.assertEquals("BOOOOM!", messageList.get(0).getContent()); Assert.assertEquals(MessageType.ERROR, messageList.get(0).getClazz()); } | public FieldProcessor perform() throws ProcessingException { return perform(false); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } |
@Test public void testPerform() throws ProcessingException { ApplicationRequest applicationRequest = initApplication(true); AtomicReference<Messages> envMessages = new AtomicReference<Messages>(new Messages()); AtomicReference<Messages> actionMessages = new AtomicReference<Messages>(new Messages()); mockMessages(envMessages, actionMessages, false); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(5, FieldProcessor.class); DataContainer dataContainer = new DataContainer(fp); dataContainer.setItem(new Object()); fp.addOkMessage("Done!"); return dataContainer; }).when(dataProvider).getData(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any()); Mockito.doAnswer(i -> { FieldProcessor fp = i.getArgumentAt(6, FieldProcessor.class); fp.addOkMessage("ACTION!"); return null; }).when(actionProvider).perform(Mockito.eq(site), Mockito.eq(application), Mockito.eq(environment), Mockito.any(), Mockito.eq(applicationRequest), Mockito.any(), Mockito.any()); CallableAction action = new CallableAction(site, application, applicationRequest, actionRef); action.perform(); Assert.assertNotNull(envMessages.get()); Assert.assertNull(actionMessages.get()); List<Message> messageList = envMessages.get().getMessageList(); Assert.assertEquals("Done!", messageList.get(0).getContent()); Assert.assertEquals(MessageType.OK, messageList.get(0).getClazz()); Assert.assertEquals("ACTION!", messageList.get(1).getContent()); Assert.assertEquals(MessageType.OK, messageList.get(1).getClazz()); } | public FieldProcessor perform() throws ProcessingException { return perform(false); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } | CallableAction { public FieldProcessor perform() throws ProcessingException { return perform(false); } CallableAction(Site site, Application application, ApplicationRequest applicationRequest,
ActionRef actionRef); protected CallableAction(Site site, ApplicationRequest applicationRequest, ElementHelper elementHelper); Action getAction(); FieldProcessor perform(); FieldProcessor perform(boolean isSectionHidden); boolean doInclude(); boolean doExecute(); boolean hasErrors(); String getOnSuccess(); boolean doForward(); @Override String toString(); } |
@Test public void testCustomString() { Assert.assertEquals("custom", propertyHolder.getString("customString")); Assert.assertEquals("string", propertyHolder.getString("emptyCustomString")); } | public String getString(String name, String defaultValue) { Property property = getProperty(name); if (null != property) { return property.getString(); } return defaultValue; } | PropertyHolder implements Properties { public String getString(String name, String defaultValue) { Property property = getProperty(name); if (null != property) { return property.getString(); } return defaultValue; } } | PropertyHolder implements Properties { public String getString(String name, String defaultValue) { Property property = getProperty(name); if (null != property) { return property.getString(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); } | PropertyHolder implements Properties { public String getString(String name, String defaultValue) { Property property = getProperty(name); if (null != property) { return property.getString(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } | PropertyHolder implements Properties { public String getString(String name, String defaultValue) { Property property = getProperty(name); if (null != property) { return property.getString(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } |
@Test public void testBoolean() { Assert.assertEquals(true, propertyHolder.getBoolean("boolean")); Assert.assertEquals(false, propertyHolder.getBoolean("bla", false)); } | public Boolean getBoolean(String name) { return getBoolean(name, null); } | PropertyHolder implements Properties { public Boolean getBoolean(String name) { return getBoolean(name, null); } } | PropertyHolder implements Properties { public Boolean getBoolean(String name) { return getBoolean(name, null); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); } | PropertyHolder implements Properties { public Boolean getBoolean(String name) { return getBoolean(name, null); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } | PropertyHolder implements Properties { public Boolean getBoolean(String name) { return getBoolean(name, null); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } |
@Test public void testFloat() { Assert.assertEquals(Float.valueOf(4.5f), propertyHolder.getFloat("float")); Assert.assertEquals(Float.valueOf(1.2f), propertyHolder.getFloat("bla", 1.2f)); } | public Float getFloat(String name, Float defaultValue) { Property property = getProperty(name); if (null != property) { return property.getFloat(); } return defaultValue; } | PropertyHolder implements Properties { public Float getFloat(String name, Float defaultValue) { Property property = getProperty(name); if (null != property) { return property.getFloat(); } return defaultValue; } } | PropertyHolder implements Properties { public Float getFloat(String name, Float defaultValue) { Property property = getProperty(name); if (null != property) { return property.getFloat(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); } | PropertyHolder implements Properties { public Float getFloat(String name, Float defaultValue) { Property property = getProperty(name); if (null != property) { return property.getFloat(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } | PropertyHolder implements Properties { public Float getFloat(String name, Float defaultValue) { Property property = getProperty(name); if (null != property) { return property.getFloat(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } |
@Test public void testDouble() { Assert.assertEquals(Double.valueOf(7.9d), propertyHolder.getDouble("double")); Assert.assertEquals(Double.valueOf(1.2d), propertyHolder.getDouble("bla", 1.2d)); } | public Double getDouble(String name, Double defaultValue) { Property property = getProperty(name); if (null != property) { return property.getDouble(); } return defaultValue; } | PropertyHolder implements Properties { public Double getDouble(String name, Double defaultValue) { Property property = getProperty(name); if (null != property) { return property.getDouble(); } return defaultValue; } } | PropertyHolder implements Properties { public Double getDouble(String name, Double defaultValue) { Property property = getProperty(name); if (null != property) { return property.getDouble(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); } | PropertyHolder implements Properties { public Double getDouble(String name, Double defaultValue) { Property property = getProperty(name); if (null != property) { return property.getDouble(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } | PropertyHolder implements Properties { public Double getDouble(String name, Double defaultValue) { Property property = getProperty(name); if (null != property) { return property.getDouble(); } return defaultValue; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } |
@Test public void testList() { Assert.assertEquals(Arrays.asList("1", "2"), propertyHolder.getList("list", ",")); Assert.assertEquals(Arrays.asList("3", "4"), propertyHolder.getList("bla", "3,4", ",")); } | public List<String> getList(String name, String defaultValue, String delimiter) { List<String> result = new ArrayList<>(); String string = getString(name, defaultValue); if (null != string && string.length() > 0) { String[] splitted = string.split(delimiter); for (String value : splitted) { result.add(value.trim()); } } return Collections.unmodifiableList(result); } | PropertyHolder implements Properties { public List<String> getList(String name, String defaultValue, String delimiter) { List<String> result = new ArrayList<>(); String string = getString(name, defaultValue); if (null != string && string.length() > 0) { String[] splitted = string.split(delimiter); for (String value : splitted) { result.add(value.trim()); } } return Collections.unmodifiableList(result); } } | PropertyHolder implements Properties { public List<String> getList(String name, String defaultValue, String delimiter) { List<String> result = new ArrayList<>(); String string = getString(name, defaultValue); if (null != string && string.length() > 0) { String[] splitted = string.split(delimiter); for (String value : splitted) { result.add(value.trim()); } } return Collections.unmodifiableList(result); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); } | PropertyHolder implements Properties { public List<String> getList(String name, String defaultValue, String delimiter) { List<String> result = new ArrayList<>(); String string = getString(name, defaultValue); if (null != string && string.length() > 0) { String[] splitted = string.split(delimiter); for (String value : splitted) { result.add(value.trim()); } } return Collections.unmodifiableList(result); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } | PropertyHolder implements Properties { public List<String> getList(String name, String defaultValue, String delimiter) { List<String> result = new ArrayList<>(); String string = getString(name, defaultValue); if (null != string && string.length() > 0) { String[] splitted = string.split(delimiter); for (String value : splitted) { result.add(value.trim()); } } return Collections.unmodifiableList(result); } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } |
@Test public void testProperties() { Properties props = new Properties(); props.put("a", "1"); props.put("b", "2"); Assert.assertEquals(props, propertyHolder.getProperties("properties")); Assert.assertEquals(null, propertyHolder.getProperties("bla")); } | public java.util.Properties getProperties(String name) { String clob = getClob(name); if (null != clob) { java.util.Properties properties = new java.util.Properties(); try { properties.load(new ByteArrayInputStream(clob.getBytes())); } catch (IOException e) { throw new IllegalArgumentException("failed converting property '" + name + "' to java.util.Properties", e); } return properties; } return null; } | PropertyHolder implements Properties { public java.util.Properties getProperties(String name) { String clob = getClob(name); if (null != clob) { java.util.Properties properties = new java.util.Properties(); try { properties.load(new ByteArrayInputStream(clob.getBytes())); } catch (IOException e) { throw new IllegalArgumentException("failed converting property '" + name + "' to java.util.Properties", e); } return properties; } return null; } } | PropertyHolder implements Properties { public java.util.Properties getProperties(String name) { String clob = getClob(name); if (null != clob) { java.util.Properties properties = new java.util.Properties(); try { properties.load(new ByteArrayInputStream(clob.getBytes())); } catch (IOException e) { throw new IllegalArgumentException("failed converting property '" + name + "' to java.util.Properties", e); } return properties; } return null; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); } | PropertyHolder implements Properties { public java.util.Properties getProperties(String name) { String clob = getClob(name); if (null != clob) { java.util.Properties properties = new java.util.Properties(); try { properties.load(new ByteArrayInputStream(clob.getBytes())); } catch (IOException e) { throw new IllegalArgumentException("failed converting property '" + name + "' to java.util.Properties", e); } return properties; } return null; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } | PropertyHolder implements Properties { public java.util.Properties getProperties(String name) { String clob = getClob(name); if (null != clob) { java.util.Properties properties = new java.util.Properties(); try { properties.load(new ByteArrayInputStream(clob.getBytes())); } catch (IOException e) { throw new IllegalArgumentException("failed converting property '" + name + "' to java.util.Properties", e); } return properties; } return null; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } |
@Test public void testMetaData() throws IOException { ImageProcessor ip = new ImageProcessor(sourceFile, null, true); ImageMetaData metaData = ip.getMetaData(); Assert.assertEquals(1024, metaData.getWidth()); Assert.assertEquals(768, metaData.getHeight()); Assert.assertEquals(845941L, metaData.getFileSize(), 0.0d); } | public ImageMetaData getMetaData() throws IOException { ImageInputStream input = new FileImageInputStream(sourceFile); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(input); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(input); ImageMetaData imageMetaData = new ImageMetaData(sourceFile, reader.getWidth(0), reader.getHeight(0)); input.close(); return imageMetaData; } else { input.close(); throw new IOException("no ImageReader found for " + sourceFile.getAbsolutePath()); } } | ImageProcessor { public ImageMetaData getMetaData() throws IOException { ImageInputStream input = new FileImageInputStream(sourceFile); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(input); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(input); ImageMetaData imageMetaData = new ImageMetaData(sourceFile, reader.getWidth(0), reader.getHeight(0)); input.close(); return imageMetaData; } else { input.close(); throw new IOException("no ImageReader found for " + sourceFile.getAbsolutePath()); } } } | ImageProcessor { public ImageMetaData getMetaData() throws IOException { ImageInputStream input = new FileImageInputStream(sourceFile); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(input); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(input); ImageMetaData imageMetaData = new ImageMetaData(sourceFile, reader.getWidth(0), reader.getHeight(0)); input.close(); return imageMetaData; } else { input.close(); throw new IOException("no ImageReader found for " + sourceFile.getAbsolutePath()); } } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); } | ImageProcessor { public ImageMetaData getMetaData() throws IOException { ImageInputStream input = new FileImageInputStream(sourceFile); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(input); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(input); ImageMetaData imageMetaData = new ImageMetaData(sourceFile, reader.getWidth(0), reader.getHeight(0)); input.close(); return imageMetaData; } else { input.close(); throw new IOException("no ImageReader found for " + sourceFile.getAbsolutePath()); } } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } | ImageProcessor { public ImageMetaData getMetaData() throws IOException { ImageInputStream input = new FileImageInputStream(sourceFile); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(input); if (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); reader.setInput(input); ImageMetaData imageMetaData = new ImageMetaData(sourceFile, reader.getWidth(0), reader.getHeight(0)); input.close(); return imageMetaData; } else { input.close(); throw new IOException("no ImageReader found for " + sourceFile.getAbsolutePath()); } } ImageProcessor(File imageMagickPath, File sourceFile, File targetFile); ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean checkMagicBytes); ImageProcessor(File sourceFile, File targetFile); ImageProcessor(File sourceFile, File targetFile, boolean checkMagicBytes); private ImageProcessor(File imageMagickPath, File sourceFile, File targetFile, boolean setGlobalSearchPath,
boolean checkMagicBytes); static boolean isImageMagickPresent(File imageMagickPath); static void setGlobalSearchPath(File imageMagickPath); ImageMetaData getMetaData(); ImageProcessor rotate(int degrees); ImageProcessor resize(int targetWidth, int targetHeight, boolean scaleUp); ImageProcessor resize(int targetWidth, int targetHeight); ImageProcessor quality(double quality); ImageProcessor strip(); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight); ImageProcessor autoCrop(int croppingWidth, int croppingHeight, int originalWidth, int originalHeight,
int croppingOffsetX, int croppingOffsetY); ImageProcessor crop(int targetWidth, int targetHeight, int offsetWidth, int offsetHeight); File getImage(); ImageProcessor fitToWidthAndHeight(int maxwidth, int maxHeight); ImageProcessor fitToWidth(Integer maxWidth); ImageProcessor fitToHeight(Integer maxHeight); IMOperation getOp(); } |
@Test public void testPlainProperties() { Properties plainProperties = propertyHolder.getPlainProperties(); Assert.assertEquals(plainProperties, propertyHolder.getPlainProperties()); } | public java.util.Properties getPlainProperties() { java.util.Properties props = new java.util.Properties(); Set<String> propertyNames = getPropertyNames(); for (String name : propertyNames) { Property property = getProperty(name); if (null != property) { String value = property.getString(); if (null == value) { value = property.getClob(); } if (null != value) { String shortName = name.substring(name.lastIndexOf(".") + 1); props.put(shortName, value); } } } return props; } | PropertyHolder implements Properties { public java.util.Properties getPlainProperties() { java.util.Properties props = new java.util.Properties(); Set<String> propertyNames = getPropertyNames(); for (String name : propertyNames) { Property property = getProperty(name); if (null != property) { String value = property.getString(); if (null == value) { value = property.getClob(); } if (null != value) { String shortName = name.substring(name.lastIndexOf(".") + 1); props.put(shortName, value); } } } return props; } } | PropertyHolder implements Properties { public java.util.Properties getPlainProperties() { java.util.Properties props = new java.util.Properties(); Set<String> propertyNames = getPropertyNames(); for (String name : propertyNames) { Property property = getProperty(name); if (null != property) { String value = property.getString(); if (null == value) { value = property.getClob(); } if (null != value) { String shortName = name.substring(name.lastIndexOf(".") + 1); props.put(shortName, value); } } } return props; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); } | PropertyHolder implements Properties { public java.util.Properties getPlainProperties() { java.util.Properties props = new java.util.Properties(); Set<String> propertyNames = getPropertyNames(); for (String name : propertyNames) { Property property = getProperty(name); if (null != property) { String value = property.getString(); if (null == value) { value = property.getClob(); } if (null != value) { String shortName = name.substring(name.lastIndexOf(".") + 1); props.put(shortName, value); } } } return props; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } | PropertyHolder implements Properties { public java.util.Properties getPlainProperties() { java.util.Properties props = new java.util.Properties(); Set<String> propertyNames = getPropertyNames(); for (String name : propertyNames) { Property property = getProperty(name); if (null != property) { String value = property.getString(); if (null == value) { value = property.getClob(); } if (null != value) { String shortName = name.substring(name.lastIndexOf(".") + 1); props.put(shortName, value); } } } return props; } PropertyHolder(String prefix, Iterable<? extends Property> properties); PropertyHolder(); PropertyHolder setFinal(); Set<String> getPropertyNames(); boolean propertyExists(String name); Property getProperty(String name); String getString(String name, String defaultValue); @Deprecated final Property addProperty(String name, Object defaultValue, String description); @Deprecated final Property addProperty(String name, Object defaultValue, String description, boolean isMultiline); final Property addProperty(String name, Object defaultValue, String description, Property.Type type); Boolean getBoolean(String name); Boolean getBoolean(String name, Boolean defaultValue); Integer getInteger(String name, Integer defaultValue); Float getFloat(String name, Float defaultValue); Double getDouble(String name, Double defaultValue); byte[] getBlob(String name); String getClob(String name, String defaultValue); String getString(String name); Integer getInteger(String name); Float getFloat(String name); Double getDouble(String name); String getClob(String name); Object getObject(String name); @SuppressWarnings("unchecked") T getObject(String name, T defaultValue); @Override String toString(); List<String> getList(String name, String defaultValue, String delimiter); List<String> getList(String name, String delimiter); java.util.Properties getPlainProperties(); java.util.Properties getProperties(String name); @Override String getDescriptionFor(String name); } |
@Test public void testNoData() { MetaData metaData2 = elementHelper.getFilteredMetaData(applicationRequest, metaData, false); Assert.assertTrue(metaData2.getFields().isEmpty()); metaData2 = elementHelper.getFilteredMetaData(applicationRequest, metaData, true); Assert.assertTrue(metaData2.getFields().isEmpty()); } | MetaData getFilteredMetaData(ApplicationRequest request, MetaData metaData, boolean write) { MetaData result = new MetaData(); if (null != metaData) { result.setBinding(metaData.getBinding()); result.setResultSelector(metaData.getResultSelector()); result.setBindClass(metaData.getBindClass()); result.setValidation(metaData.getValidation()); List<FieldDef> fieldDefinitions = metaData.getFields(); List<FieldDef> fields = filterFieldDefinitions(request, fieldDefinitions, write); result.getFields().addAll(fields); } return result; } | ElementHelper { MetaData getFilteredMetaData(ApplicationRequest request, MetaData metaData, boolean write) { MetaData result = new MetaData(); if (null != metaData) { result.setBinding(metaData.getBinding()); result.setResultSelector(metaData.getResultSelector()); result.setBindClass(metaData.getBindClass()); result.setValidation(metaData.getValidation()); List<FieldDef> fieldDefinitions = metaData.getFields(); List<FieldDef> fields = filterFieldDefinitions(request, fieldDefinitions, write); result.getFields().addAll(fields); } return result; } } | ElementHelper { MetaData getFilteredMetaData(ApplicationRequest request, MetaData metaData, boolean write) { MetaData result = new MetaData(); if (null != metaData) { result.setBinding(metaData.getBinding()); result.setResultSelector(metaData.getResultSelector()); result.setBindClass(metaData.getBindClass()); result.setValidation(metaData.getValidation()); List<FieldDef> fieldDefinitions = metaData.getFields(); List<FieldDef> fields = filterFieldDefinitions(request, fieldDefinitions, write); result.getFields().addAll(fields); } return result; } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); } | ElementHelper { MetaData getFilteredMetaData(ApplicationRequest request, MetaData metaData, boolean write) { MetaData result = new MetaData(); if (null != metaData) { result.setBinding(metaData.getBinding()); result.setResultSelector(metaData.getResultSelector()); result.setBindClass(metaData.getBindClass()); result.setValidation(metaData.getValidation()); List<FieldDef> fieldDefinitions = metaData.getFields(); List<FieldDef> fields = filterFieldDefinitions(request, fieldDefinitions, write); result.getFields().addAll(fields); } return result; } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container,
String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); } | ElementHelper { MetaData getFilteredMetaData(ApplicationRequest request, MetaData metaData, boolean write) { MetaData result = new MetaData(); if (null != metaData) { result.setBinding(metaData.getBinding()); result.setResultSelector(metaData.getResultSelector()); result.setBindClass(metaData.getBindClass()); result.setValidation(metaData.getValidation()); List<FieldDef> fieldDefinitions = metaData.getFields(); List<FieldDef> fields = filterFieldDefinitions(request, fieldDefinitions, write); result.getFields().addAll(fields); } return result; } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container,
String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; } |
@Test public void testInitNavigation() { Linkpanel linkpanel = new Linkpanel(); linkpanel.setId("panel"); linkpanel.setLocation(PanelLocation.TOP); addLink(linkpanel, "link1", "target", "${1 eq 1}"); addLink(linkpanel, "link2", "target", "${1 eq 2}"); rootCfg.setNavigation(linkpanel); PageConfig pageConfig = new PageConfig(); pageConfig.setLinkpanel(new Linkpanel()); Mockito.when(permissionProcessor.hasPermissions(Mockito.any(PermissionOwner.class))).thenReturn(true); elementHelper.initNavigation(applicationRequest, path, pageConfig); XmlValidator.validate(pageConfig.getLinkpanel()); } | public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container,
String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container,
String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; } |
@Test public void testInitNavigationNoPermission() { Linkpanel linkpanel = new Linkpanel(); Permissions permissions = new Permissions(); Permission p1 = new Permission(); p1.setRef("foo"); permissions.getPermissionList().add(p1); linkpanel.setPermissions(permissions); linkpanel.setId("panel"); linkpanel.setLocation(PanelLocation.TOP); addLink(linkpanel, "link1", "target", "${1 eq 1}"); addLink(linkpanel, "link2", "target", "${1 eq 2}"); rootCfg.setNavigation(linkpanel); PageConfig pageConfig = new PageConfig(); Linkpanel pageLinks = new Linkpanel(); pageLinks.setPermissions(new Permissions()); Link page = new Link(); page.setMode(Linkmode.INTERN); page.setLabel(new Label()); pageLinks.getLinks().add(page); pageConfig.setLinkpanel(pageLinks); Mockito.when(permissionProcessor.hasPermissions(Mockito.any(PermissionOwner.class))).thenReturn(true, false); elementHelper.initNavigation(applicationRequest, path, pageConfig); Assert.assertNull(pageConfig.getLinkpanel()); } | public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container,
String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); } | ElementHelper { public void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig) { ParameterSupport parameterSupport = applicationRequest.getParameterSupportDollar(); Linkpanel pageLinks = initLinkpanel(applicationRequest, pathInfo, pageConfig.getLinkpanel(), parameterSupport); Linkpanel navigation = applicationRequest.getApplicationConfig().getApplicationRootConfig().getNavigation(); if (null != navigation) { navigation = initLinkpanel(applicationRequest, pathInfo, navigation, parameterSupport); if (!(null == pageLinks || null == navigation)) { List<Link> links = navigation.getLinks(); for (Link link : links) { pageLinks.getLinks().add(link); } pageConfig.setLinkpanel(pageLinks); } else { pageConfig.setLinkpanel(navigation); } } } ElementHelper(Site site, Application application); ElementHelper(Site site, Application application, ExpressionEvaluator expressionEvaluator); void initNavigation(ApplicationRequest applicationRequest, Path pathInfo, PageConfig pageConfig); static Messages addMessages(Environment environment, Messages messages); Messages removeMessages(Environment environment); Messages getMessages(Environment environment); boolean hasMessages(Environment environment); void processDataContainer(org.appng.api.Request applicationRequest, DataContainer container,
String callerName); boolean isMessageParam(Object o); Class<?>[] getValidationGroups(MetaData metaData, Object bindObject); String getOutputPrefix(Environment env); static final String INTERNAL_ERROR; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.