/** * Extracts the username from the specified DN. If the username cannot be extracted because the CN * is in an unrecognized format, the entire CN is returned. If the CN cannot be extracted because * the DN is in an unrecognized format, the entire DN is returned. * * @param dn the dn to extract the username from * @return the exatracted username */ public static String extractUsername(String dn) { String username = dn; String cn = ""; // ensure the dn is specified if (StringUtils.isNotBlank(dn)) { // attempt to locate the cn if (dn.startsWith("CN=")) { cn = StringUtils.substringBetween(dn, "CN=", ","); } else if (dn.startsWith("/CN=")) { cn = StringUtils.substringBetween(dn, "CN=", "/"); } else if (dn.startsWith("C=") || dn.startsWith("/C=")) { cn = StringUtils.substringAfter(dn, "CN="); } else if (dn.startsWith("/") && StringUtils.contains(dn, "CN=")) { cn = StringUtils.substringAfter(dn, "CN="); } // attempt to get the username from the cn if (StringUtils.isNotBlank(cn)) { if (cn.endsWith(")")) { username = StringUtils.substringBetween(cn, "(", ")"); } else if (cn.contains(" ")) { username = StringUtils.substringAfterLast(cn, " "); } else { username = cn; } } } return username; }
public void load() throws IOException, SQLException { conn = Mysql.getConn("semsearch"); List<String> lines = FileUtils.readLines(new File(this.filePath)); AANPaper paper = new AANPaper(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i).trim(); if (line.equals("")) { process(paper); } if (line.startsWith("id")) { paper = new AANPaper(); String temp = StringUtils.substringAfter(line, "{").trim(); temp = StringUtils.substringBeforeLast(temp, "}"); paper.setId(temp); } else if (line.startsWith("author")) { String temp = StringUtils.substringAfter(line, "{").trim(); temp = StringUtils.substringBeforeLast(temp, "}"); paper.setAuthor(temp); } else if (line.startsWith("title")) { String temp = StringUtils.substringAfter(line, "{").trim(); temp = StringUtils.substringBeforeLast(temp, "}"); paper.setTitle(temp); } else if (line.startsWith("venue")) { String temp = StringUtils.substringAfter(line, "{").trim(); temp = StringUtils.substringBeforeLast(temp, "}"); paper.setVenue(temp); } else if (line.startsWith("year")) { String temp = StringUtils.substringAfter(line, "{").trim(); temp = StringUtils.substringBeforeLast(temp, "}"); paper.setYear(temp); } System.out.println(line); } }
static RabbitConnectionFactoryConfig uriToConnectionConfig(String uri) { RabbitConnectionFactoryConfig properties = new RabbitConnectionFactoryConfig(); if (isNotEmpty(uri)) { String username = StringUtils.substringBetween(uri, "amqp://", ":"); String password = StringUtils.substringBetween(uri, username + ":", "@"); String hostWithPort = StringUtils.substringBetween(uri, "@", "/"); // If no virtual host is specified if (isEmpty(hostWithPort)) { hostWithPort = StringUtils.substringAfter(uri, "@"); } int port = properties.getPort(); String host = hostWithPort; boolean hasPort = StringUtils.contains(hostWithPort, ":"); if (hasPort) { host = StringUtils.substringBefore(hostWithPort, ":"); port = NumberUtils.toInt(StringUtils.substringAfter(hostWithPort, ":")); } String virtualHost = StringUtils.substringAfter(uri, hostWithPort + "/"); properties.setUsername(username); properties.setPassword(password); properties.setHost(host); properties.setPort(port); if (isNotEmpty(virtualHost)) { properties.setVirtualHost(virtualHost); } } return properties; }
/** * Build a new image. * * @param deck Deck name * @param repo Repo * @return Image name * @throws IOException If fails */ private String build(final String deck, final XML repo) throws IOException { final String name = String.format("%s-%08x", deck, BuildImage.RND.nextInt()); final String hash = "#"; String uri = repo.xpath("uri/text()").get(0); final String branch; final String path; if (uri.contains(hash)) { final String[] tail = StringUtils.substringAfter(uri, hash).split(":", 2); branch = tail[0]; path = tail[1]; uri = StringUtils.substringBefore(uri, hash); } else { branch = "master"; path = "."; } final long start = System.currentTimeMillis(); this.script.exec( "t1.thindeck.com", new ArrayMap<String, String>() .with("image", name) .with("uri", uri) .with("branch", branch) .with("path", path)); Logger.info(this, "Docker image %s built in %[ms]s", name, System.currentTimeMillis() - start); return name; }
@Test public void verifyOK() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL); mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID); mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI); mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET); mockRequest.setParameter(OAuthConstants.CODE, CODE); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ((OAuth20WrapperController) oauth20WrapperController) .getServicesManager() .save(getRegisteredService(REDIRECT_URI, CLIENT_SECRET)); final Map<String, Object> map = new HashMap<>(); map.put(NAME, VALUE); final List<String> list = Arrays.asList(VALUE, VALUE); map.put(NAME2, list); final Principal p = org.jasig.cas.authentication.TestUtils.getPrincipal(ID, map); final TicketGrantingTicketImpl impl = new TicketGrantingTicketImpl( TGT_ID, org.jasig.cas.authentication.TestUtils.getAuthentication(p), new NeverExpiresExpirationPolicy()); ((OAuth20WrapperController) oauth20WrapperController) .getTicketRegistry() .addTicket( new ServiceTicketImpl( CODE, impl, org.jasig.cas.authentication.TestUtils.getService(), false, new ExpirationPolicy() { private static final long serialVersionUID = -7321055962209199811L; @Override public boolean isExpired(final TicketState ticketState) { return false; } })); oauth20WrapperController.handleRequest(mockRequest, mockResponse); ((OAuth20WrapperController) oauth20WrapperController).getTicketRegistry().deleteTicket(CODE); assertEquals("text/plain", mockResponse.getContentType()); assertEquals(200, mockResponse.getStatus()); final String body = mockResponse.getContentAsString(); assertTrue( body.startsWith( OAuthConstants.ACCESS_TOKEN + '=' + TGT_ID + '&' + OAuthConstants.EXPIRES + '=')); // delta = 2 seconds final int delta = 2; final int timeLeft = Integer.parseInt(StringUtils.substringAfter(body, '&' + OAuthConstants.EXPIRES + '=')); assertTrue(timeLeft >= TIMEOUT - 10 - delta); }
XMLNode(Object nodeObject) { super(nodeObject); String tagName = ((Element) userObject).getTagName(); if ("book:book".equals(tagName)) { name = "root"; iconName = "/"; isFile = false; } else if ("coll:pages".equals(tagName)) { Element x = (Element) userObject; id = x.getAttribute("id"); name = x.getAttribute("name"); iconName = "collection"; isFile = false; } else if ("book:pages".equals(tagName)) { Element x = (Element) userObject; id = x.getAttribute("id"); name = x.getAttribute("name"); iconName = "book"; isFile = false; } else if ("book:structure".equals(tagName)) { Element x = (Element) userObject; name = x.getAttribute("name"); id = x.getAttribute("id"); iconName = "page"; isFile = false; } else if ("book:page".equals(tagName)) { name = ((Element) userObject).getAttribute("pid"); href = ((Element) userObject).getAttribute("href"); iconName = StringUtils.substringAfter(name, ".").toLowerCase(); isFile = true; if (((Element) userObject).getAttribute("firstpage").equals("true")) iconName = "firstpage"; } }
@MetaData(value = "保存") protected HttpHeaders doSave() { getEntityService().save(bindingEntity); // 附件关联处理,自动处理以attachment为前缀的参数 if (bindingEntity instanceof AttachmentableEntity) { Enumeration<?> names = getRequest().getParameterNames(); Set<String> attachmentNames = Sets.newHashSet(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); if (name.startsWith("_attachment_")) { attachmentNames.add(name); } } if (attachmentNames.size() > 0) { AttachmentFileService attachmentFileService = SpringContextHolder.getBean(AttachmentFileService.class); for (String attachmentName : attachmentNames) { String[] attachments = getParameterIds(attachmentName); attachmentFileService.attachmentBind( attachments, bindingEntity, StringUtils.substringAfter(attachmentName, "_attachment_")); } } } setModel(OperationResult.buildSuccessResult("数据保存成功", bindingEntity)); return buildDefaultHttpHeaders(); }
private String cleanErrorMessageForDisplay(String errorMessage) { String clean = StringUtils.substringAfter( errorMessage, "org.mozilla.javascript.JavaScriptException: Error:"); clean = clean.replaceAll("\\(handlebars\\.js#\\d+\\)", ""); return clean; }
private RoleGrantedAuthority renameProject( RoleGrantedAuthority authority, String projectName, String newProjectName) { GrantedAuthorityTarget target = authority.getTarget(); String targetId = target.getTargetId(); GrantedAuthorityTarget newTarget = null; switch (target.getType()) { case PROJECT: { String projName = targetId; if (projName.equals(projectName)) { newTarget = new GrantedAuthorityTarget(newProjectName, GrantedAuthorityTarget.Type.PROJECT); } } break; case BRANCH: { String projName = StringUtils.substringBefore(targetId, "/"); // $NON-NLS-1$ if (projName.equals(projectName)) { String branchName = StringUtils.substringAfter(targetId, "/"); // $NON-NLS-1$ String newTargetId = newProjectName + "/" + branchName; // $NON-NLS-1$ newTarget = new GrantedAuthorityTarget(newTargetId, GrantedAuthorityTarget.Type.BRANCH); } } break; } return (newTarget != null) ? new RoleGrantedAuthority(newTarget, authority.getRoleName()) : null; }
/** 分析并设置contentType与headers. */ private static HttpServletResponse initResponseHeader( final String contentType, final String... headers) { // 分析headers参数 String encoding = DEFAULT_ENCODING; boolean noCache = DEFAULT_NOCACHE; for (String header : headers) { String headerName = StringUtils.substringBefore(header, ":"); String headerValue = StringUtils.substringAfter(header, ":"); if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) { encoding = headerValue; } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) { noCache = Boolean.parseBoolean(headerValue); } else { throw new IllegalArgumentException(headerName + "不是一个合法的header类型"); } } HttpServletResponse response = ServletActionContext.getResponse(); // 设置headers参数 String fullContentType = contentType + ";charset=" + encoding; response.setContentType(fullContentType); if (noCache) { ServletUtils.setDisableCacheHeader(response); } return response; }
/** * Creating a map which its key is a gene name and its value is the mappability. It also * calculates the number of tiles which are within the gene. * * @param btOutputFileLines BowTie output file name * @param readFileLines Reads file content in a list * @param chr1FileLines chromosome file name in a list * @return * @throws IOException */ private Map<String, Mappability> createMappability( List<String> btOutputFileLines, List<String> readFileLines, List<String> chr1FileLines) throws IOException { Map<String, Mappability> result = new HashMap<>(); for (String btOutputLine : btOutputFileLines) { String[] splittedLine = StringUtils.split(btOutputLine, FileUtils.SEPARATOR_TAB); Integer tileStart = getTileStartIndex(splittedLine); Integer tileEnd = getTileEndIndex(splittedLine); Gene gene = getGeneId(splittedLine); String geneName = gene.getName(); if (!result.containsKey(geneName)) { result.put(geneName, new Mappability(0, getTotalNumberOfTiles(geneName, readFileLines))); } Mappability output = result.get(geneName); if (isTileWithinGene(tileStart, tileEnd, gene)) { output.addNumberOfMatches(); } result.put(geneName, output); } // Add the missing tiles from output for (int lineIndex = 0; lineIndex < chr1FileLines.size(); lineIndex++) { if (lineIndex % 2 == 0) { // Reading the first line String geneName = StringUtils.substringAfter(chr1FileLines.get(lineIndex), FileUtils.CHR_INDICATOR); if (!result.containsKey(geneName)) { result.put(geneName, null); } } chr1FileLines.get(lineIndex); } return result; }
private void parseWebFragmentXml() throws XMLStreamException, IOException, TransformerException { final XMLInputFactory xif = XMLInputFactory.newInstance(); final XMLStreamReader xsr = xif.createXMLStreamReader(getInputStream()); xsr.nextTag(); // web-fragment tag skipped while (xsr.hasNext() && xsr.nextTag() == XMLStreamConstants.START_ELEMENT) { final String tagName = xsr.getLocalName(); // webFragmentName if ("name".equalsIgnoreCase(tagName)) { final String element = xsr.getElementText(); allWebFragmentNames.add(element); webFragmentXmlComponents.add("<name>" + element + "</name>"); } else { final TransformerFactory tf = TransformerFactory.newInstance(); final Transformer t = tf.newTransformer(); final StringWriter res = new StringWriter(); t.transform(new StAXSource(xsr), new StreamResult(res)); final String element = org.apache.commons.lang3.StringUtils.substringAfter(res.toString(), "?>"); if ("ordering".equalsIgnoreCase(tagName)) { // ordering parseOrdering(element); } else { // webFragmentXmlComponents webFragmentXmlComponents.add(element); } } } if (allWebFragmentNames.isEmpty()) { throw new IllegalStateException( "Name tag is missing. Please specify a name in the web-fragment.xml!"); } }
public static <T extends Comparable<T>> Range<T> parse(String value, Function<String, T> parser) { Validate.notNull(parser, "Parser is required"); if (StringUtils.isBlank(value) || StringUtils.equals(SEPARATOR, value)) { return Ranges.all(); } else if (!StringUtils.contains(value, SEPARATOR)) { T element = parser.apply(value); return Ranges.atMost(element); } else { String lower = StringUtils.substringBefore(value, SEPARATOR); String upper = StringUtils.substringAfter(value, SEPARATOR); if (StringUtils.isBlank(lower)) { // ..n Pair<T, BoundType> boundary = parseUpperBoundary(upper, parser); return Ranges.upTo(boundary.getLeft(), boundary.getRight()); } else if (StringUtils.isBlank(upper)) { // n.. Pair<T, BoundType> boundary = parseLowerBoundary(lower, parser); return Ranges.downTo(boundary.getLeft(), boundary.getRight()); } else { // n..m Pair<T, BoundType> down = parseLowerBoundary(lower, parser); Pair<T, BoundType> up = parseUpperBoundary(upper, parser); return Ranges.range(down.getLeft(), down.getRight(), up.getLeft(), up.getRight()); } } }
private static Geopoint parseCoords(final String location) { final String latitude = StringUtils.substringBefore(location, SEPARATOR_STRING); final String longitude = StringUtils.substringAfter(location, SEPARATOR_STRING); if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) { return new Geopoint(latitude, longitude); } return null; }
private String prepareCountHql(String orgHql) { String fromHql = orgHql; fromHql = "from " + StringUtils.substringAfter(fromHql, "from"); fromHql = StringUtils.substringBefore(fromHql, "order by"); String countHql = "select count(*) " + fromHql; return countHql; }
private int count(String hql, Map<String, Object> paramMap) { StringBuffer sb = new StringBuffer("") .append("select count(*) from ") .append( StringUtils.substringBeforeLast(StringUtils.substringAfter(hql, "from"), "order ")); Query query = getSession().createQuery(sb.toString()); setQuery(query, paramMap); return ((Long) query.uniqueResult()).intValue(); }
/** Converts a ConstraintViolation to a FieldError */ private static FieldError of(ConstraintViolation<?> constraintViolation) { // Get the field name by removing the first part of the propertyPath. // (The first part would be the service method name) String field = StringUtils.substringAfter(constraintViolation.getPropertyPath().toString(), "."); return new FieldError( field, constraintViolation.getMessageTemplate(), constraintViolation.getMessage()); }
/** * * * <li><b>Substring/Left/Right/Mid</b> - null-safe substring extractions * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b> - substring extraction relative to * other strings */ @Test public void testSubstringLeftStringUtils() { System.out.println(strOne + ":" + strOne.length()); System.out.println(StringUtils.substring(strOne, 3)); System.out.println(StringUtils.substring(strOne, 3, 7)); System.out.println(StringUtils.substringAfter(strOne, " ")); System.out.println(StringUtils.substringAfterLast(strOne, " ")); System.out.println(StringUtils.substringBefore(strOne, " ")); System.out.println(StringUtils.substringBeforeLast(strOne, " ")); System.out.println(StringUtils.substringBetween(strOne, "the", "not")); }
private String getSimpleCountHQL(String hql) { String fromHql = hql; // select子句与order by子句会影响count查询,进行简单的排除. fromHql = "from " + StringUtils.substringAfter(fromHql, "from"); fromHql = StringUtils.substringBefore(fromHql, "order by"); String countHql = "select count(*) " + fromHql; return countHql; }
/** * Get the guessed file extension of an URL. A file extension can contain up-to 4 characters in * addition to the dot. * * @param url the relative or absolute URL * @return the file extension, including the leading dot, or the empty string if none could be * determined */ static String getExtension(final String url) { final String urlExt; if (url.startsWith("data:")) { // "data:image/png;base64,i53…" -> ".png" urlExt = StringUtils.substringAfter(StringUtils.substringBefore(url, ";"), "/"); } else { // "http://example.com/foo/bar.png" -> ".png" urlExt = StringUtils.substringAfterLast(url, "."); } return urlExt.length() >= 1 && urlExt.length() <= 4 ? "." + urlExt : ""; }
private static void saveBase64ToFile(final String url, final File file) { // TODO: when we use SDK level 8 or above, we can use the streaming version of the base64 // Android utilities. OutputStream out = null; try { out = new FileOutputStream(file); out.write(Base64.decode(StringUtils.substringAfter(url, ";base64,"), Base64.DEFAULT)); } catch (final IOException e) { Log.e("HtmlImage.saveBase64ToFile: cannot write file for decoded inline image", e); } finally { IOUtils.closeQuietly(out); } }
public static String getQuartzParametersByFormula(String quartzExpr) { Map<String, String> resMap = new HashMap<String, String>(); String arrayStrings[] = quartzExpr.split("\\s+"); if (arrayStrings.length == 6) { String hours = arrayStrings[2]; String interval = arrayStrings[1]; String startHour = StringUtils.substringBefore(hours, "-"); String endHour = StringUtils.substringAfter(hours, "-"); String startMinute = StringUtils.substringBefore(interval, "/"); String endMinute = "00"; StringBuilder sb = new StringBuilder(); sb.append(startHour) .append(":") .append(startMinute) .append("-") .append(endHour) .append(":") .append(endMinute); resMap.put("sRegionTime", sb.toString()); String weekDays = arrayStrings[5].indexOf("\"") > 0 ? StringUtils.substringBefore(arrayStrings[5], "\"") : arrayStrings[5]; for (DAY_OF_WEEK b : DAY_OF_WEEK.values()) { weekDays = StringUtils.replace(weekDays, b.getQuartzStr(), b.getInternalStr()); } resMap.put("saRegionWeekDay", weekDays); resMap.put("nLen", StringUtils.substringAfter(interval, "/")); } JSONObject res = new JSONObject(resMap); return res.toString(); }
public static String getQuartzFormulaByParameters( String sRegionTime, String saRegionWeekDay, Integer nLen) { // sRegionTime is in format HH:MM-HH:MM // saRegionWeekDay is in format "mo,tu,we,th,fr,sa". Need to convert to MON, TUE, WED, THU, FRI, // SAT, SUN String startTime = StringUtils.substringBefore(sRegionTime, "-"); String endTime = StringUtils.substringAfter(sRegionTime, "-"); String startHour = StringUtils.substringBefore(startTime, ":"); String startMinute = StringUtils.substringAfter(startTime, ":"); String endHour = StringUtils.substringBefore(endTime, ":"); for (DAY_OF_WEEK b : DAY_OF_WEEK.values()) { saRegionWeekDay = saRegionWeekDay.replace(b.getInternalStr(), b.getQuartzStr()); } String res = StringUtils.replace(QUARTZ_FORMAT, "[INTERVAL]", nLen.toString()); res = StringUtils.replace(res, "[START_MINUTE]", startMinute); res = StringUtils.replace(res, "[HOURS_PERIOD]", startHour + "-" + endHour); res = StringUtils.replace(res, "[DAYS]", saRegionWeekDay); return res; }
/** * @param filterName * @param value */ public PropertyFilter(final String filterName, final String value) { String matchTypeStr; String matchPattenCode = LikeMatchPatten.ALL.toString(); String matchTypeCode; String propertyTypeCode; if (filterName.contains("LIKE") && filterName.charAt(0) != 'L') { matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX); matchPattenCode = StringUtils.substring(matchTypeStr, 0, 1); matchTypeCode = StringUtils.substring(matchTypeStr, 1, matchTypeStr.length() - 1); propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length()); } else { matchTypeStr = StringUtils.substringBefore(filterName, PARAM_PREFIX); matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1); propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length()); } try { matchType = Enum.valueOf(MatchType.class, matchTypeCode); likeMatchPatten = Enum.valueOf(LikeMatchPatten.class, matchPattenCode); } catch (RuntimeException e) { throw new IllegalArgumentException( "filter name: " + filterName + "Not prepared in accordance with rules, not get more types of property.", e); } try { propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue(); } catch (RuntimeException e) { throw new IllegalArgumentException( "filter name: " + filterName + "Not prepared in accordance with the rules, attribute value types can not be.", e); } String propertyNameStr = StringUtils.substringAfter(filterName, PARAM_PREFIX); propertyNames = StringUtils.split(propertyNameStr, PropertyFilter.OR_SEPARATOR); Validate.isTrue( propertyNames.length > 0, "filter name: " + filterName + "Not prepared in accordance with the rules, property names can not be."); this.propertyValue = ConvertUtils.convert(value, propertyType); }
/** * 将sql中问号替换成实际值 * * @param sql select * from a where name=? * @param paramValues * @return */ public static String formatSql(final String sql, final Object[] paramValues) { String fsql = sql; for (Object value : paramValues) { String tmp = fsql; fsql = StringUtils.substringBefore(tmp, "?"); if (value instanceof String) { fsql += "'" + value + "'"; } else { fsql += ClassUtil.convertValueToString(value); } fsql += StringUtils.substringAfter(tmp, "?"); } return fsql; }
/** * See class comment * * @param file file * @param environment environment name for the file * @return map with properties TO, never null */ @SneakyThrows public List<Property> parseFile(@NonNull File file, String environment) { System.out.println(" - Parsing file: " + file); List<String> lines = FileUtils.readLines(file, "UTF-8"); List<Property> properties = new ArrayList<>(); StringBuilder comment = new StringBuilder(); for (String line : lines) { line = line.trim(); if (line.isEmpty()) { // reset current comment buffer comment = new StringBuilder(); } else if (line.startsWith("#")) { // add next line of comment to the comment buffer comment.append(line).append("\n"); } else { // reached the property definition - run parsing and reset the // buffer Property property = new Property(); property.setName(StringUtils.substringBefore(line, "=").trim()); property.setDefaultValue(StringUtils.substringAfter(line, "=").trim()); String commentLines = comment.toString(); System.out.println( " - - found property: '" + property.getName() + "' with comments: " + StringUtils.replace(commentLines, "\n", "\\n")); property.setMetadatas(commentParser.parseComment(commentLines)); System.out.println(property); comment = new StringBuilder(); property.setSourceFileName(file.getAbsolutePath()); property.setEnvironment(environment); properties.add(property); } } return properties; }
private int getShowId(String name) { try { Response response = client.get( "http://www.tvrage.com/feeds/search.php?show=" + URLEncoder.encode(name, "utf-8")); String responseString = response.getBodyAsString(); String sid = StringUtils.substringBefore( StringUtils.substringAfter(responseString, "<showid>"), "</showid>"); if (sid == null) { return -1; } log.debug("found id: {} for show: {}", sid, name); return Integer.parseInt(sid); } catch (Exception e) { throw new RuntimeException(e); } }
@Transactional(readOnly = true) @Override public A authFind(final String key) { if (key == null) { throw new NotFoundException("Null key"); } A any = find(key); if (any == null) { throw new NotFoundException( StringUtils.substringBefore( StringUtils.substringAfter(getClass().getSimpleName(), "JPA"), "DAO") + " " + key); } securityChecks(any); return any; }
/** * Extracts an UriBuilder for the current request, taking into account the possibility of * header-based URI override. * * @param uriInfo * @param httpHeaders * @return * @throws URISyntaxException */ public static UriBuilder getUriBuilder(final UriInfo uriInfo, final HttpHeaders httpHeaders) throws URISyntaxException { final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder(); final List<String> hosts = httpHeaders.getRequestHeader(HttpHeaders.HOST); if ((hosts != null) && (!hosts.isEmpty())) { final String host = hosts.get(0); uriBuilder.host(StringUtils.substringBefore(host, ":")); final String port = StringUtils.substringAfter(host, ":"); if (StringUtils.isNotBlank(port)) { uriBuilder.port(Integer.valueOf(port)); } } final String protocol = getSingleHeader(httpHeaders, Constants.FORWARDED_PROTOCOL_HTTP_HEADER); if (StringUtils.isNotBlank(protocol)) { uriBuilder.scheme(protocol); } return uriBuilder; }
private List<RoleGrantedAuthority> getUserAuthorities(String loginName, ILockedRepository repo) { String json = BlobUtils.getHeadContent(repo.r(), loginName + AUTHORITIES_SUFFIX); if (json == null) { throw new UserNotFoundException(loginName); } Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); Map<String, Set<String>> authoritiesMap = gson.fromJson(json, new TypeToken<Map<String, Set<String>>>() {}.getType()); List<RoleGrantedAuthority> authorities = Lists.newArrayList(); for (Map.Entry<String, Set<String>> entry : authoritiesMap.entrySet()) { String targetStr = entry.getKey(); Type type = Type.valueOf(StringUtils.substringBefore(targetStr, ":")); // $NON-NLS-1$ String targetId = StringUtils.substringAfter(targetStr, ":"); // $NON-NLS-1$ for (String roleName : entry.getValue()) { authorities.add( new RoleGrantedAuthority(new GrantedAuthorityTarget(targetId, type), roleName)); } } Collections.sort(authorities, new RoleGrantedAuthorityComparator()); return authorities; }