_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q163400
FileHelper.updateMetadata
train
public static void updateMetadata(final File file, final PropertyMap map) throws FrameworkException { updateMetadata(file, map, false); }
java
{ "resource": "" }
q163401
FileHelper.writeToFile
train
public static void writeToFile(final File fileNode, final InputStream data) throws FrameworkException, IOException { setFileProperties(fileNode); try (final FileOutputStream out = new FileOutputStream(fileNode.getFileOnDisk())) { IOUtils.copy(data, out); } }
java
{ "resource": "" }
q163402
FileHelper.getFileByAbsolutePath
train
public static AbstractFile getFileByAbsolutePath(final SecurityContext securityContext, final String absolutePath) { try { return StructrApp.getInstance(securityContext).nodeQuery(AbstractFile.class).and(StructrApp.key(AbstractFile.class, "path"), absolutePath).getFirst(); } catch (FrameworkException ex) { ex.printStackTrace(); logger.warn("File not found: {}", absolutePath); } return null; }
java
{ "resource": "" }
q163403
FileHelper.createFolderPath
train
public static Folder createFolderPath(final SecurityContext securityContext, final String path) throws FrameworkException { final App app = StructrApp.getInstance(securityContext); if (path == null) { return null; } Folder folder = (Folder) FileHelper.getFileByAbsolutePath(securityContext, path); if (folder != null) { return folder; } String[] parts = PathHelper.getParts(path); String partialPath = ""; for (String part : parts) { // ignore ".." and "." in paths if ("..".equals(part) || ".".equals(part)) { continue; } Folder parent = folder; partialPath += PathHelper.PATH_SEP + part; folder = (Folder) FileHelper.getFileByAbsolutePath(securityContext, partialPath); if (folder == null) { folder = app.create(Folder.class, part); } if (parent != null) { folder.setParent(parent); } } return folder; }
java
{ "resource": "" }
q163404
PlingStemmer.noLatin
train
public static boolean noLatin(String s) { return(s.indexOf('h')>0 || s.indexOf('j')>0 || s.indexOf('k')>0 || s.indexOf('w')>0 || s.indexOf('y')>0 || s.indexOf('z')>0 || s.indexOf("ou")>0 || s.indexOf("sh")>0 || s.indexOf("ch")>0 || s.endsWith("aus")); }
java
{ "resource": "" }
q163405
GraphObjectModificationState.updateChangeLog
train
public void updateChangeLog(final Principal user, final Verb verb, final PropertyKey key, final Object previousValue, final Object newValue) { if ((Settings.ChangelogEnabled.getValue() || Settings.UserChangelogEnabled.getValue()) && key != null) { final String name = key.jsonName(); if (!hiddenPropertiesInAuditLog.contains(name) && !(key.isUnvalidated() || key.isReadOnly())) { final JsonObject obj = new JsonObject(); obj.add("time", toElement(System.currentTimeMillis())); obj.add("userId", toElement(user.getUuid())); obj.add("userName", toElement(user.getName())); obj.add("verb", toElement(verb)); obj.add("key", toElement(key.jsonName())); obj.add("prev", toElement(previousValue)); obj.add("val", toElement(newValue)); if (Settings.ChangelogEnabled.getValue()) { changeLog.append(obj.toString()); changeLog.append("\n"); } if (Settings.UserChangelogEnabled.getValue()) { // remove user for user-centric logging to reduce redundancy obj.remove("userId"); obj.remove("userName"); // add target to identify change event obj.add("target", toElement(getUuid())); appendUserChangelog(user.getUuid(), obj.toString()); } } } }
java
{ "resource": "" }
q163406
GraphObjectModificationState.updateChangeLog
train
public void updateChangeLog(final Principal user, final Verb verb, final String object) { if ((Settings.ChangelogEnabled.getValue() || Settings.UserChangelogEnabled.getValue())) { final JsonObject obj = new JsonObject(); obj.add("time", toElement(System.currentTimeMillis())); if (user != null) { obj.add("userId", toElement(user.getUuid())); obj.add("userName", toElement(user.getName())); } else { obj.add("userId", JsonNull.INSTANCE); obj.add("userName", JsonNull.INSTANCE); } obj.add("verb", toElement(verb)); obj.add("target", toElement(object)); if (Settings.ChangelogEnabled.getValue()) { if (changeLog.length() > 0 && verb.equals(Verb.create)) { // ensure that node creation appears first in the log changeLog.insert(0, "\n"); changeLog.insert(0, obj.toString()); } else { changeLog.append(obj.toString()); changeLog.append("\n"); } } if (Settings.UserChangelogEnabled.getValue() && user != null) { // remove user for user-centric logging to reduce redundancy obj.remove("userId"); obj.remove("userName"); appendUserChangelog(user.getUuid(), obj.toString()); } } }
java
{ "resource": "" }
q163407
PropertyConverter.convertForSorting
train
public Comparable convertForSorting(S source) throws FrameworkException { if(source != null) { if (source instanceof Comparable) { return (Comparable)source; } // fallback return source.toString(); } return null; }
java
{ "resource": "" }
q163408
ClassFileManager.getClassLoader
train
@Override public ClassLoader getClassLoader(final Location location) { return new SecureClassLoader() { @Override protected Class<?> findClass(String name) throws ClassNotFoundException { final JavaClassObject obj = objects.get(name); if (obj != null) { byte[] b = obj.getBytes(); return super.defineClass(name, obj.getBytes(), 0, b.length); } throw new ClassNotFoundException(name); } }; }
java
{ "resource": "" }
q163409
ClassFileManager.getJavaFileForOutput
train
@Override public JavaFileObject getJavaFileForOutput(final Location location, final String className, final Kind kind, final FileObject sibling) throws IOException { JavaClassObject obj = new JavaClassObject(className, kind); objects.put(className, obj); return obj; }
java
{ "resource": "" }
q163410
JobQueueManager.startJob
train
public boolean startJob(final Long jobId) { final ScheduledJob job = removeFromQueueInternal(jobId); if (job != null) { activeJobs.put(jobId, job); job.startJob(); return true; } else { return false; } }
java
{ "resource": "" }
q163411
JarConfigurationProvider.getRelationClassCandidatesForRelType
train
private List<Class<? extends RelationshipInterface>> getRelationClassCandidatesForRelType(final String relType) { List<Class<? extends RelationshipInterface>> candidates = new ArrayList(); for (final Class<? extends RelationshipInterface> candidate : getRelationshipEntities().values()) { Relation rel = instantiate(candidate); if (rel == null) { continue; } if (rel.name().equals(relType)) { candidates.add(candidate); } } return candidates; }
java
{ "resource": "" }
q163412
JarConfigurationProvider.findNearestMatchingRelationClass
train
private Class findNearestMatchingRelationClass(final String sourceTypeName, final String relType, final String targetTypeName) { final Class sourceType = getNodeEntityClass(sourceTypeName); final Class targetType = getNodeEntityClass(targetTypeName); final Map<Integer, Class> candidates = new TreeMap<>(); for (final Class candidate : getRelationClassCandidatesForRelType(relType)) { final Relation rel = instantiate(candidate); final int distance = getDistance(rel.getSourceType(), sourceType, -1) + getDistance(rel.getTargetType(), targetType, -1); if (distance >= 2000) { candidates.put(distance - 2000, candidate); } } if (candidates.isEmpty()) { return null; } else { final Entry<Integer, Class> candidateEntry = candidates.entrySet().iterator().next(); final Class c = candidateEntry.getValue(); combinedTypeRelationClassCache.put(getCombinedType(sourceTypeName, relType, targetTypeName), c); return c; } }
java
{ "resource": "" }
q163413
JarConfigurationProvider.registerEntityCreationTransformation
train
@Override public void registerEntityCreationTransformation(Class type, Transformation<GraphObject> transformation) { final Set<Transformation<GraphObject>> transformations = getEntityCreationTransformationsForType(type); if (!transformations.contains(transformation)) { transformations.add(transformation); } }
java
{ "resource": "" }
q163414
JarConfigurationProvider.registerPropertyGroup
train
@Override public void registerPropertyGroup(Class type, PropertyKey key, PropertyGroup propertyGroup) { getPropertyGroupMapForType(type).put(key.dbName(), propertyGroup); }
java
{ "resource": "" }
q163415
JarConfigurationProvider.getResourcesToScan
train
private Set<String> getResourcesToScan() { final String classPath = System.getProperty("java.class.path"); final Set<String> modules = new TreeSet<>(); final Pattern pattern = Pattern.compile(".*(structr).*(war|jar)"); final Matcher matcher = pattern.matcher(""); for (final String jarPath : classPath.split("[".concat(pathSep).concat("]+"))) { final String lowerPath = jarPath.toLowerCase(); if (lowerPath.endsWith(classesDir) || lowerPath.endsWith(testClassesDir)) { modules.add(jarPath); } else { final String moduleName = lowerPath.substring(lowerPath.lastIndexOf(pathSep) + 1); matcher.reset(moduleName); if (matcher.matches()) { modules.add(jarPath); } } } for (final String resource : Services.getInstance().getResources()) { final String lowerResource = resource.toLowerCase(); if (lowerResource.endsWith(".jar") || lowerResource.endsWith(".war")) { modules.add(resource); } } return modules; }
java
{ "resource": "" }
q163416
DeploymentServlet.unzip
train
private void unzip(final File file, final String outputDir) throws IOException { try (final ZipFile zipFile = new ZipFile(file)) { final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final File targetFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { targetFile.mkdirs(); } else { targetFile.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); try (OutputStream out = new FileOutputStream(targetFile)) { IOUtils.copy(in, out); IOUtils.closeQuietly(in); } } } } }
java
{ "resource": "" }
q163417
ResourceHelper.parsePath
train
public static List<Resource> parsePath(final SecurityContext securityContext, final HttpServletRequest request, final Map<Pattern, Class<? extends Resource>> resourceMap, final Value<String> propertyView) throws FrameworkException { final String path = request.getPathInfo(); // intercept empty path and send 204 No Content if (StringUtils.isBlank(path)) { throw new NoResultsException("No content"); } // 1.: split request path into URI parts final String[] pathParts = path.split("[/]+"); // 2.: create container for resource constraints final Set<String> propertyViews = Services.getInstance().getConfigurationProvider().getPropertyViews(); final List<Resource> resourceChain = new ArrayList<>(pathParts.length); // 3.: try to assign resource constraints for each URI part for (int i = 0; i < pathParts.length; i++) { // eliminate empty strings final String part = pathParts[i].trim(); if (part.length() > 0) { boolean found = false; // check views first if (propertyViews.contains(part)) { Resource resource = new ViewFilterResource(); resource.checkAndConfigure(part, securityContext, request); resource.configurePropertyView(propertyView); resourceChain.add(resource); // mark this part as successfully parsed found = true; } else { // look for matching pattern for (Map.Entry<Pattern, Class<? extends Resource>> entry : resourceMap.entrySet()) { Pattern pattern = entry.getKey(); Matcher matcher = pattern.matcher(pathParts[i]); if (matcher.matches()) { Class<? extends Resource> type = entry.getValue(); Resource resource = null; try { // instantiate resource constraint resource = type.newInstance(); } catch (Throwable t) { logger.warn("Error instantiating resource class", t); } if (resource != null) { // set security context resource.setSecurityContext(securityContext); if (resource.checkAndConfigure(part, securityContext, request)) { logger.debug("{} matched, adding resource of type {} for part {}", new Object[] { matcher.pattern(), type.getName(), part }); // allow constraint to modify context resource.configurePropertyView(propertyView); // add constraint and go on resourceChain.add(resource); found = true; // first match wins, so choose priority wisely ;) break; } } } } } if (!found) { throw new NotFoundException("Cannot resolve URL path"); } } } return resourceChain; }
java
{ "resource": "" }
q163418
ResourceHelper.optimizeNestedResourceChain
train
public static Resource optimizeNestedResourceChain(final SecurityContext securityContext, final HttpServletRequest request, final Map<Pattern, Class<? extends Resource>> resourceMap, final Value<String> propertyView) throws FrameworkException { final List<Resource> resourceChain = ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView); ViewFilterResource view = null; int num = resourceChain.size(); boolean found = false; do { for (Iterator<Resource> it = resourceChain.iterator(); it.hasNext(); ) { Resource constr = it.next(); if (constr instanceof ViewFilterResource) { view = (ViewFilterResource) constr; it.remove(); } } found = false; try { for (int i = 0; i < num; i++) { Resource firstElement = resourceChain.get(i); Resource secondElement = resourceChain.get(i + 1); Resource combinedConstraint = firstElement.tryCombineWith(secondElement); if (combinedConstraint != null) { // remove source constraints resourceChain.remove(firstElement); resourceChain.remove(secondElement); // add combined constraint resourceChain.add(i, combinedConstraint); // signal success found = true; } } } catch (Throwable t) { // ignore exceptions thrown here but make it possible to set a breakpoint final boolean test = false; } } while (found); if (resourceChain.size() == 1) { Resource finalResource = resourceChain.get(0); if (view != null) { finalResource = finalResource.tryCombineWith(view); } if (finalResource == null) { // fall back to original resource finalResource = resourceChain.get(0); } return finalResource; } else { logger.warn("Resource chain evaluation for path {} resulted in {} entries, returning status code 400.", new Object[] { request.getPathInfo(), resourceChain.size() }); } throw new IllegalPathException("Cannot resolve URL path"); }
java
{ "resource": "" }
q163419
Function.logException
train
protected void logException (final Object caller, final Throwable t, final Object[] parameters) { logException(t, "{}: Exception in '{}' for parameters: {}", new Object[] { getReplacement(), caller, getParametersAsString(parameters) }); }
java
{ "resource": "" }
q163420
Function.logException
train
protected void logException (final Throwable t, final String msg, final Object[] messageParams) { logger.error(msg, messageParams, t); }
java
{ "resource": "" }
q163421
Function.assertArrayHasLengthAndAllElementsNotNull
train
protected void assertArrayHasLengthAndAllElementsNotNull(final Object[] array, final Integer length) throws ArgumentCountException, ArgumentNullException { if (array.length != length) { throw ArgumentCountException.notEqual(array.length, length); } for (final Object element : array) { if (element == null) { throw new ArgumentNullException(); } } }
java
{ "resource": "" }
q163422
GeoHelper.createLocation
train
public static Location createLocation(final GeoCodingResult coords) throws FrameworkException { final PropertyMap props = new PropertyMap(); double latitude = coords.getLatitude(); double longitude = coords.getLongitude(); String type = Location.class.getSimpleName(); props.put(AbstractNode.type, type); props.put(StructrApp.key(Location.class, "latitude"), latitude); props.put(StructrApp.key(Location.class, "longitude"), longitude); return StructrApp.getInstance().create(Location.class, props); }
java
{ "resource": "" }
q163423
GeoHelper.geocode
train
public static GeoCodingResult geocode(final String street, final String house, String postalCode, final String city, final String state, final String country) throws FrameworkException { final String language = Settings.GeocodingLanguage.getValue(); final String cacheKey = cacheKey(street, house, postalCode, city, state, country, language); GeoCodingResult result = geoCache.get(cacheKey); if (result == null) { GeoCodingProvider provider = getGeoCodingProvider(); if (provider != null) { try { result = provider.geocode(street, house, postalCode, city, state, country, language); if (result != null) { // store in cache geoCache.put(cacheKey, result); } } catch (IOException ioex) { // IOException, try again next time logger.warn("Unable to obtain geocoding result using provider {}: {}", new Object[] { provider.getClass().getName(), ioex.getMessage() }); } } } return result; }
java
{ "resource": "" }
q163424
AuthHelper.isConfirmationKeyValid
train
public static boolean isConfirmationKeyValid(final String confirmationKey, final Integer validityPeriod) { final String[] parts = confirmationKey.split("!"); if (parts.length == 2) { final long confirmationKeyCreated = Long.parseLong(parts[1]); final long maxValidity = confirmationKeyCreated + validityPeriod * 60 * 1000; return (maxValidity >= new Date().getTime()); } return Settings.ConfirmationKeyValidWithoutTimestamp.getValue(); }
java
{ "resource": "" }
q163425
CsvServlet.writeCsv
train
public static void writeCsv(final ResultStream<GraphObject> result, final Writer out, final String propertyView) throws IOException { final StringBuilder row = new StringBuilder(); boolean headerWritten = false; for (final GraphObject obj : result) { // Write column headers if (!headerWritten) { row.setLength(0); for (PropertyKey key : obj.getPropertyKeys(propertyView)) { row.append("\"").append(key.dbName()).append("\"").append(DEFAULT_FIELD_SEPARATOR); } // remove last ; int pos = row.lastIndexOf("" + DEFAULT_FIELD_SEPARATOR); if (pos >= 0) { row.deleteCharAt(pos); } // append DOS-style line feed as defined in RFC 4180 out.append(row).append("\r\n"); // flush each line out.flush(); headerWritten = true; } row.setLength(0); for (PropertyKey key : obj.getPropertyKeys(propertyView)) { Object value = obj.getProperty(key); row.append("\"").append((value != null ? escapeForCsv(value) : "")).append("\"").append(DEFAULT_FIELD_SEPARATOR); } // remove last ; row.deleteCharAt(row.lastIndexOf("" + DEFAULT_FIELD_SEPARATOR)); out.append(row).append("\r\n"); // flush each line out.flush(); } }
java
{ "resource": "" }
q163426
EntityAndPropertiesContainer.init
train
@Override public void init(SecurityContext securityContext, Node dbNode, Class type, final long transactionId) { throw new UnsupportedOperationException("Not supported by this container."); }
java
{ "resource": "" }
q163427
MailService.extractFileAttachment
train
private File extractFileAttachment(final Mailbox mb, final Part p) { File file = null; try { final Class fileClass = p.getContentType().toLowerCase().startsWith("image/") ? Image.class : File.class; final App app = StructrApp.getInstance(); try (final Tx tx = app.tx()) { org.structr.web.entity.Folder fileFolder = FileHelper.createFolderPath(SecurityContext.getSuperUserInstance(), getStoragePath(mb.getUuid())); try { String fileName = decodeText(p.getFileName()); if (fileName == null) { fileName = NodeServiceCommand.getNextUuid(); } file = FileHelper.createFile(SecurityContext.getSuperUserInstance(), p.getInputStream(), p.getContentType(), fileClass, fileName, fileFolder); } catch (FrameworkException ex) { logger.warn("EMail in mailbox[" + mb.getUuid() + "] attachment has invalid name. Using random UUID as fallback."); file = FileHelper.createFile(SecurityContext.getSuperUserInstance(), p.getInputStream(), p.getContentType(), fileClass, NodeServiceCommand.getNextUuid(), fileFolder); } tx.success(); } catch (IOException | FrameworkException ex) { logger.error("Exception while extracting file attachment: ", ex); } } catch (MessagingException ex) { logger.error("Exception while extracting file attachment: ", ex); } return file; }
java
{ "resource": "" }
q163428
Tx.setSecurityContext
train
public void setSecurityContext(final SecurityContext sc) { if (securityContext == null) { if (sc.isSuperUserSecurityContext() == Boolean.FALSE) { securityContext = sc; } } }
java
{ "resource": "" }
q163429
LogResource.findInterval
train
private long findInterval(final String dateFormat) { final long max = TimeUnit.DAYS.toMillis(365); final long step = TimeUnit.SECONDS.toMillis(60); try { final SimpleDateFormat format = new SimpleDateFormat(dateFormat); final long initial = format.parse(format.format(3600)).getTime(); for (long i = initial; i < max; i += step) { final long current = format.parse(format.format(i)).getTime(); if (initial != current) { return i - initial; } } return max; } catch (ParseException pex) { logger.warn("", pex); } return max; }
java
{ "resource": "" }
q163430
SecurityContext.getEffectiveLocale
train
public Locale getEffectiveLocale() { // Priority 5: Default locale Locale locale = Locale.getDefault(); boolean userHasLocaleString = false; if (cachedUser != null) { // Priority 2: User locale final String userLocaleString = cachedUser.getLocale(); if (userLocaleString != null) { userHasLocaleString = true; try { locale = LocaleUtils.toLocale(userLocaleString); } catch (IllegalArgumentException e) { locale = Locale.forLanguageTag(userLocaleString); } } } if (request != null) { if (!userHasLocaleString) { // Priority 4: Browser locale locale = request.getLocale(); final Cookie[] cookies = request.getCookies(); if (cookies != null) { // Priority 3: Cookie locale for (Cookie c : cookies) { if (c.getName().equals(LOCALE_KEY)) { final String cookieLocaleString = c.getValue(); try { locale = LocaleUtils.toLocale(cookieLocaleString); } catch (IllegalArgumentException e) { locale = Locale.forLanguageTag(cookieLocaleString); } } } } } // Priority 1: URL parameter locale String requestedLocaleString = request.getParameter(LOCALE_KEY); if (StringUtils.isNotBlank(requestedLocaleString)) { try { locale = LocaleUtils.toLocale(requestedLocaleString); } catch (IllegalArgumentException e) { locale = Locale.forLanguageTag(requestedLocaleString); } } } return locale; }
java
{ "resource": "" }
q163431
Command.setArgument
train
public final void setArgument(final String key, final Object value) { if (key != null && value != null) { this.arguments.put(key, value); } }
java
{ "resource": "" }
q163432
HashHelper.getHash
train
public static String getHash(final String password, final String salt) { if (StringUtils.isEmpty(salt)) { return getSimpleHash(password); } return DigestUtils.sha512Hex(DigestUtils.sha512Hex(password).concat(salt)); }
java
{ "resource": "" }
q163433
HtmlServlet.notFound
train
private Page notFound(final HttpServletResponse response, final SecurityContext securityContext) throws IOException, FrameworkException { final List<Page> errorPages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).and(StructrApp.key(Page.class, "showOnErrorCodes"), "404", false).getAsList(); for (final Page errorPage : errorPages) { if (isVisibleForSite(securityContext.getRequest(), errorPage)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return errorPage; } } response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; }
java
{ "resource": "" }
q163434
HtmlServlet.findFirstNodeByName
train
private AbstractNode findFirstNodeByName(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException { final String name = PathHelper.getName(path); if (!name.isEmpty()) { logger.debug("Requested name: {}", name); final Query query = StructrApp.getInstance(securityContext).nodeQuery(); final ConfigurationProvider config = StructrApp.getConfiguration(); if (!possiblePropertyNamesForEntityResolving.isEmpty()) { query.and(); resolvePossiblePropertyNamesForObjectResolution(config, query, name); query.parent(); } final List<AbstractNode> results = Iterables.toList(query.getResultStream()); logger.debug("{} results", results.size()); request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, results); return (results.size() > 0 ? (AbstractNode) results.get(0) : null); } return null; }
java
{ "resource": "" }
q163435
HtmlServlet.findNodeByUuid
train
private AbstractNode findNodeByUuid(final SecurityContext securityContext, final String uuid) throws FrameworkException { if (!uuid.isEmpty()) { logger.debug("Requested id: {}", uuid); return (AbstractNode) StructrApp.getInstance(securityContext).getNodeById(uuid); } return null; }
java
{ "resource": "" }
q163436
HtmlServlet.findFile
train
private File findFile(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException { List<Linkable> entryPoints = findPossibleEntryPoints(securityContext, request, path); // If no results were found, try to replace whitespace by '+' or '%20' if (entryPoints.isEmpty()) { entryPoints = findPossibleEntryPoints(securityContext, request, PathHelper.replaceWhitespaceByPlus(path)); } if (entryPoints.isEmpty()) { entryPoints = findPossibleEntryPoints(securityContext, request, PathHelper.replaceWhitespaceByPercentTwenty(path)); } for (Linkable node : entryPoints) { if (node instanceof File && (path.equals(node.getPath()) || node.getUuid().equals(PathHelper.getName(path)))) { return (File) node; } } return null; }
java
{ "resource": "" }
q163437
HtmlServlet.findPage
train
private Page findPage(final SecurityContext securityContext, List<Page> pages, final String path, final EditMode edit) throws FrameworkException { if (pages == null) { pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList(); Collections.sort(pages, new GraphObjectComparator(StructrApp.key(Page.class, "position"), GraphObjectComparator.ASCENDING)); } for (final Page page : pages) { final String pagePath = page.getPath(); if (pagePath != null && pagePath.equals(path) && (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page))) { return page; } } final String name = PathHelper.getName(path); for (final Page page : pages) { final String pageName = page.getName(); if (pageName != null && pageName.equals(name) && (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page))) { return page; } } for (final Page page : pages) { final String pageUuid = page.getUuid(); if (pageUuid != null && pageUuid.equals(name) && (EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page))) { return page; } } return null; }
java
{ "resource": "" }
q163438
HtmlServlet.findIndexPage
train
private Page findIndexPage(final SecurityContext securityContext, List<Page> pages, final EditMode edit) throws FrameworkException { final PropertyKey<Integer> positionKey = StructrApp.key(Page.class, "position"); if (pages == null) { pages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).getAsList(); Collections.sort(pages, new GraphObjectComparator(positionKey, GraphObjectComparator.ASCENDING)); } for (Page page : pages) { if (securityContext.isVisible(page) && page.getProperty(positionKey) != null && ((EditMode.CONTENT.equals(edit) || isVisibleForSite(securityContext.getRequest(), page)) || (page.getEnableBasicAuth() && page.isVisibleToAuthenticatedUsers()))) { return page; } } return null; }
java
{ "resource": "" }
q163439
HtmlServlet.checkRegistration
train
private boolean checkRegistration(final Authenticator auth, final HttpServletRequest request, final HttpServletResponse response, final String path) throws FrameworkException, IOException { logger.debug("Checking registration ..."); final String key = request.getParameter(CONFIRM_KEY_KEY); if (StringUtils.isEmpty(key)) { return false; } final PropertyKey<String> confirmationKeyKey = StructrApp.key(User.class, "confirmationKey"); final String targetPage = filterMaliciousRedirects(request.getParameter(TARGET_PAGE_KEY)); final String errorPage = filterMaliciousRedirects(request.getParameter(ERROR_PAGE_KEY)); if (CONFIRM_REGISTRATION_PAGE.equals(path)) { final App app = StructrApp.getInstance(); List<Principal> results; try (final Tx tx = app.tx()) { results = app.nodeQuery(Principal.class).and(confirmationKeyKey, key).getAsList(); tx.success(); } if (!results.isEmpty()) { final Principal user = results.get(0); try (final Tx tx = app.tx()) { // Clear confirmation key and set session id user.setProperty(confirmationKeyKey, null); if (AuthHelper.isConfirmationKeyValid(key, Settings.ConfirmationKeyRegistrationValidityPeriod.getValue())) { if (Settings.RestUserAutologin.getValue()) { AuthHelper.doLogin(request, user); } else { logger.warn("Refusing login because {} is disabled", Settings.RestUserAutologin.getKey()); } } else { logger.warn("Confirmation key for user {} is not valid anymore - refusing login.", user.getName()); } tx.success(); } // Redirect to target page if (StringUtils.isNotBlank(targetPage)) { response.sendRedirect("/" + targetPage); } return true; } else { // Redirect to error page if (StringUtils.isNotBlank(errorPage)) { response.sendRedirect("/" + errorPage); } return true; } } return false; }
java
{ "resource": "" }
q163440
HtmlServlet.isVisibleForSite
train
private boolean isVisibleForSite(final HttpServletRequest request, final Page page) { final Site site = page.getSite(); if (site == null) { return true; } final String serverName = request.getServerName(); final int serverPort = request.getServerPort(); if (StringUtils.isNotBlank(serverName) && !serverName.equals(site.getHostname())) { return false; } final Integer sitePort = site.getPort(); if (sitePort != null && serverPort != sitePort) { return false; } return true; }
java
{ "resource": "" }
q163441
SessionHelper.clearSession
train
public static void clearSession(final String sessionId) { if (StringUtils.isBlank(sessionId)) { return; } final App app = StructrApp.getInstance(); final PropertyKey<String[]> sessionIdKey = StructrApp.key(Principal.class, "sessionIds"); final Query<Principal> query = app.nodeQuery(Principal.class).and(sessionIdKey, new String[]{sessionId}).disableSorting(); try { for (final Principal p : query.getAsList()) { p.removeSessionId(sessionId); } } catch (Exception fex) { logger.warn("Error while removing sessionId " + sessionId + " from all principals", fex); } }
java
{ "resource": "" }
q163442
SessionHelper.clearInvalidSessions
train
public static void clearInvalidSessions(final Principal user) { logger.info("Clearing invalid sessions for user {} ({})", user.getName(), user.getUuid()); final PropertyKey<String[]> sessionIdKey = StructrApp.key(Principal.class, "sessionIds"); final String[] sessionIds = user.getProperty(sessionIdKey); if (sessionIds != null && sessionIds.length > 0) { final SessionCache sessionCache = Services.getInstance().getService(HttpService.class).getSessionCache(); for (final String sessionId : sessionIds) { HttpSession session = null; try { session = sessionCache.get(sessionId); } catch (Exception ex) { logger.warn("Unable to retrieve session " + sessionId + " from session cache:", ex); } if (session == null || SessionHelper.isSessionTimedOut(session)) { SessionHelper.clearSession(sessionId); } } } }
java
{ "resource": "" }
q163443
NodeWrapper.evaluateCustomQuery
train
public boolean evaluateCustomQuery(final String customQuery, final Map<String, Object> parameters) { final SessionTransaction tx = db.getCurrentTransaction(); boolean result = false; try { result = tx.getBoolean(customQuery, parameters); } catch (Exception ignore) {} return result; }
java
{ "resource": "" }
q163444
LinkedTreeNodeImpl.ensureCorrectChildPositions
train
private void ensureCorrectChildPositions() throws FrameworkException { final List<Relation<T, T, OneStartpoint<T>, ManyEndpoint<T>>> childRels = treeGetChildRelationships(); int position = 0; for (Relation<T, T, OneStartpoint<T>, ManyEndpoint<T>> childRel : childRels) { childRel.setProperty(getPositionProperty(), position++); } }
java
{ "resource": "" }
q163445
LinkedTreeNodeImpl.getAllChildNodes
train
@Override public Set<T> getAllChildNodes() { Set<T> allChildNodes = new HashSet(); List<T> childNodes = treeGetChildren(); for (final T child : childNodes) { allChildNodes.add(child); if (child instanceof LinkedTreeNode) { final LinkedTreeNode treeNode = (LinkedTreeNode)child; allChildNodes.addAll(treeNode.getAllChildNodes()); } } return allChildNodes; }
java
{ "resource": "" }
q163446
AbstractEndpoint.getNotionProperties
train
protected PropertyMap getNotionProperties(final SecurityContext securityContext, final Class type, final String storageKey) { final Map<String, PropertyMap> notionPropertyMap = (Map<String, PropertyMap>)securityContext.getAttribute("notionProperties"); if (notionPropertyMap != null) { final Set<PropertyKey> keySet = Services.getInstance().getConfigurationProvider().getPropertySet(type, PropertyView.Public); final PropertyMap notionProperties = notionPropertyMap.get(storageKey); if (notionProperties != null) { for (final Iterator<PropertyKey> it = notionProperties.keySet().iterator(); it.hasNext();) { final PropertyKey key = it.next(); if (!keySet.contains(key)) { it.remove(); } } return notionProperties; } } return null; }
java
{ "resource": "" }
q163447
NodeFactory.getNodesAt
train
protected List<NodeInterface> getNodesAt(final NodeInterface locationNode) { final List<NodeInterface> nodes = new LinkedList<>(); for(RelationshipInterface rel : locationNode.getIncomingRelationships(NodeHasLocation.class)) { NodeInterface startNode = rel.getSourceNode(); nodes.add(startNode); // add more nodes which are "at" this one nodes.addAll(getNodesAt(startNode)); } return nodes; }
java
{ "resource": "" }
q163448
Importer.fileExists
train
private File fileExists(final String path, final long checksum) throws FrameworkException { final PropertyKey<Long> checksumKey = StructrApp.key(File.class, "checksum"); final PropertyKey<String> pathKey = StructrApp.key(File.class, "path"); return app.nodeQuery(File.class).and(pathKey, path).and(checksumKey, checksum).getFirst(); }
java
{ "resource": "" }
q163449
PagingHelper.subList
train
public static <T> List<T> subList(final List<T> list, int pageSize, int page) { if (pageSize <= 0 || page == 0) { return Collections.EMPTY_LIST; } int size = list.size(); int fromIndex = page > 0 ? (page - 1) * pageSize : size + (page * pageSize); int toIndex = fromIndex + pageSize; int finalFromIndex = Math.max(0, fromIndex); int finalToIndex = Math.min(size, Math.max(0, toIndex)); // prevent fromIndex to be greater than toIndex if (finalFromIndex > finalToIndex) { finalFromIndex = finalToIndex; } try { return list.subList(finalFromIndex, finalToIndex); } catch (Throwable t) { logger.warn("Invalid range for sublist in paging, pageSize {}, page {}: {}", new Object[] { pageSize, page, t.getMessage() }); } return Collections.EMPTY_LIST; }
java
{ "resource": "" }
q163450
PathHelper.getRelativeNodePath
train
public static String getRelativeNodePath(String basePath, String targetPath) { // Both paths are equal if (basePath.equals(targetPath)) { return "."; } if (basePath.equals(PATH_SEP) && (targetPath.length() > 1)) { // Base path is root path return targetPath.substring(1); } String[] baseAncestors = FilenameUtils.normalizeNoEndSeparator(basePath).split(PATH_SEP); String[] targetAncestors = FilenameUtils.normalizeNoEndSeparator(targetPath).split(PATH_SEP); int length = (baseAncestors.length < targetAncestors.length) ? baseAncestors.length : targetAncestors.length; int lastCommonRoot = -1; int i; // Iterate over the shorter path for (i = 0; i < length; i++) { if (baseAncestors[i].equals(targetAncestors[i])) { lastCommonRoot = i; } else { break; } } // Last common root is the common base path if (lastCommonRoot != -1) { StringBuilder newRelativePath = new StringBuilder(); // How often must we go back from base path to common root? for (i = lastCommonRoot + 1; i < baseAncestors.length; i++) { if (baseAncestors[i].length() > 0) { newRelativePath.append(".." + PATH_SEP); } } // How often must we go forth from common root to get to tagret path? for (i = lastCommonRoot + 1; i < targetAncestors.length; i++) { newRelativePath.append(targetAncestors[i]).append(PATH_SEP); } // newRelativePath.append(targetAncestors[targetAncestors.length - 1]); String result = newRelativePath.toString(); if (result.endsWith(PATH_SEP)) { result = result.substring(0, result.length() - 1); } return result; } return targetPath; }
java
{ "resource": "" }
q163451
PathHelper.getName
train
public static String getName(final String path) { String cleanedPath = clean(path); if (cleanedPath != null && cleanedPath.contains(PATH_SEP)) { return StringUtils.substringAfterLast(cleanedPath, PATH_SEP); } else { return cleanedPath; } }
java
{ "resource": "" }
q163452
PathHelper.getParts
train
public static String[] getParts(final String path) { String cleanedPath = clean(path); return StringUtils.splitByWholeSeparator(cleanedPath, PATH_SEP); }
java
{ "resource": "" }
q163453
FileUploadHandler.finish
train
public void finish() { try { FileChannel channel = getChannel(false); if (channel != null && channel.isOpen()) { channel.force(true); channel.close(); this.privateFileChannel = null; //file.increaseVersion(); file.notifyUploadCompletion(); } } catch (IOException e) { logger.warn("Unable to finish file upload", e); } }
java
{ "resource": "" }
q163454
FinalSet.indexOf
train
public int indexOf(T x) { int r=Arrays.binarySearch(data,x); return(r>=0?r:-1); }
java
{ "resource": "" }
q163455
DeployCommand.endsWithUuid
train
public static boolean endsWithUuid(final String name) { if (name.length() > 32) { return pattern.matcher(name.substring(name.length() - 32)).matches(); } else { return false; } }
java
{ "resource": "" }
q163456
PropertyMap.contentHashCode
train
public int contentHashCode(Set<PropertyKey> comparableKeys, boolean includeSystemProperties) { Map<PropertyKey, Object> sortedMap = new TreeMap<>(new PropertyKeyComparator()); int hashCode = 42; sortedMap.putAll(properties); if (comparableKeys == null) { // calculate hash code for all properties in this map for (Entry<PropertyKey, Object> entry : sortedMap.entrySet()) { if (includeSystemProperties || !entry.getKey().isUnvalidated()) { hashCode ^= entry.hashCode(); } } } else { for (Entry<PropertyKey, Object> entry : sortedMap.entrySet()) { PropertyKey key = entry.getKey(); if (comparableKeys.contains(key)) { if (includeSystemProperties || !key.isUnvalidated()) { hashCode ^= entry.hashCode(); } } } } return hashCode; }
java
{ "resource": "" }
q163457
NodeRelationshipsCommand.execute
train
public List<RelationshipInterface> execute(NodeInterface sourceNode, RelationshipType relType, Direction dir) throws FrameworkException { RelationshipFactory factory = new RelationshipFactory(securityContext); List<RelationshipInterface> result = new LinkedList<>(); Node node = sourceNode.getNode(); Iterable<Relationship> rels; if (node == null) { return Collections.EMPTY_LIST; } if (relType != null) { rels = node.getRelationships(dir, relType); } else { rels = node.getRelationships(dir); } try { for (Relationship r : rels) { result.add(factory.instantiate(r)); } } catch (RuntimeException e) { logger.warn("Exception occured: ", e.getMessage()); /** * ********* FIXME * * Here an exception occurs: * * org.neo4j.kernel.impl.nioneo.store.InvalidRecordException: Node[5] is neither firstNode[37781] nor secondNode[37782] for Relationship[188125] * at org.neo4j.kernel.impl.nioneo.xa.ReadTransaction.getMoreRelationships(ReadTransaction.java:131) * at org.neo4j.kernel.impl.nioneo.xa.NioNeoDbPersistenceSource$ReadOnlyResourceConnection.getMoreRelationships(NioNeoDbPersistenceSource.java:280) * at org.neo4j.kernel.impl.persistence.PersistenceManager.getMoreRelationships(PersistenceManager.java:100) * at org.neo4j.kernel.impl.core.NodeManager.getMoreRelationships(NodeManager.java:585) * at org.neo4j.kernel.impl.core.NodeImpl.getMoreRelationships(NodeImpl.java:358) * at org.neo4j.kernel.impl.core.IntArrayIterator.hasNext(IntArrayIterator.java:115) * * */ } return result; }
java
{ "resource": "" }
q163458
DatePropertyParser.parse
train
public static Date parse(String source, final String pattern) { if (StringUtils.isBlank(pattern)) { return parseISO8601DateString(source); } else { try { // SimpleDateFormat is not fully ISO8601 compatible, so we replace 'Z' by +0000 if (StringUtils.contains(source, "Z")) { source = StringUtils.replace(source, "Z", "+0000"); } return new SimpleDateFormat(pattern).parse(source); } catch (ParseException ignore) { } // try to parse as ISO8601 date (supports multiple formats) return parseISO8601DateString(source); } }
java
{ "resource": "" }
q163459
DatePropertyParser.parseISO8601DateString
train
public static Date parseISO8601DateString(String source) { final String[] supportedFormats = new String[] { "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ssXXX", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZ" }; // SimpleDateFormat is not fully ISO8601 compatible, so we replace 'Z' by +0000 if (StringUtils.contains(source, "Z")) { source = StringUtils.replace(source, "Z", "+0000"); } Date parsedDate = null; for (final String format : supportedFormats) { try { parsedDate = new SimpleDateFormat(format).parse(source); } catch (ParseException pe) { } if (parsedDate != null) { return parsedDate; } } return null; }
java
{ "resource": "" }
q163460
DatePropertyParser.format
train
public static String format(final Date date, String format) { if (date != null) { if (StringUtils.isBlank(format)) { format = DateProperty.getDefaultFormat(); } return new SimpleDateFormat(format).format(date); } return null; }
java
{ "resource": "" }
q163461
AbstractCommand.getGraphObject
train
public GraphObject getGraphObject(final String id, final String nodeId) { if (isValidUuid(id)) { final AbstractNode node = getNode(id); if (node != null) { return node; } else { if (nodeId == null) { logger.warn("Relationship access by UUID is deprecated and not supported by Neo4j, this can take a very long time."); } final AbstractRelationship rel = getRelationship(id, nodeId); if (rel != null) { return rel; } } } else { logger.warn("Invalid UUID used for getGraphObject: {} is not a valid UUID.", id); } return null; }
java
{ "resource": "" }
q163462
AbstractCommand.getNode
train
public AbstractNode getNode(final String id) { final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { final AbstractNode node = (AbstractNode) app.getNodeById(id); tx.success(); return node; } catch (FrameworkException fex) { logger.warn("Unable to get node", fex); } return null; }
java
{ "resource": "" }
q163463
AbstractCommand.getRelationship
train
public AbstractRelationship getRelationship(final String id, final String nodeId) { if (id == null) { return null; } if (nodeId == null) { return getRelationship(id); } final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { final AbstractNode node = (AbstractNode) app.getNodeById(nodeId); for (final AbstractRelationship rel : node.getRelationships()) { if (rel.getUuid().equals(id)) { return rel; } } tx.success(); } catch (FrameworkException fex) { logger.warn("Unable to get relationship", fex); } return null; }
java
{ "resource": "" }
q163464
AbstractCommand.getRelationship
train
public AbstractRelationship getRelationship(final String id) { if (id == null) { return null; } final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { final AbstractRelationship rel = (AbstractRelationship) app.getRelationshipById(id); tx.success(); return rel; } catch (FrameworkException fex) { logger.warn("Unable to get relationship", fex); } return null; }
java
{ "resource": "" }
q163465
AbstractCommand.moveChildNodes
train
protected void moveChildNodes(final DOMNode sourceNode, final DOMNode targetNode) { DOMNode child = (DOMNode) sourceNode.getFirstChild(); while (child != null) { DOMNode next = (DOMNode) child.getNextSibling(); targetNode.appendChild(child); child = next; } }
java
{ "resource": "" }
q163466
PageImportVisitor.fixDocumentElements
train
private void fixDocumentElements(final Page page) { final NodeList heads = page.getElementsByTagName("head"); if (heads.getLength() > 1) { final Node head1 = heads.item(0); final Node head2 = heads.item(1); final Node parent = head1.getParentNode(); final boolean h1 = head1.hasChildNodes(); final boolean h2 = head2.hasChildNodes(); if (h1 && h2) { // merge for (Node child = head2.getFirstChild(); child != null; child = child.getNextSibling()) { head2.removeChild(child); head1.appendChild(child); } parent.removeChild(head2); } else if (h1 && !h2) { // remove head2 parent.removeChild(head2); } else if (!h1 && h2) { // remove head1 parent.removeChild(head1); } else { // remove first, doesn't matter parent.removeChild(head1); } } }
java
{ "resource": "" }
q163467
AbstractStructrCmisService.getCMISInfo
train
public CMISInfo getCMISInfo(final Class<? extends GraphObject> type) { try { return type.newInstance().getCMISInfo(); } catch (Throwable t) {} return null; }
java
{ "resource": "" }
q163468
AbstractStructrCmisService.getBaseTypeId
train
public BaseTypeId getBaseTypeId(final Class<? extends GraphObject> type) { final CMISInfo info = getCMISInfo(type); if (info != null) { return info.getBaseTypeId(); } return null; }
java
{ "resource": "" }
q163469
AbstractStructrCmisService.getBaseTypeId
train
public BaseTypeId getBaseTypeId(final String typeId) { try { return BaseTypeId.fromValue(typeId); } catch (IllegalArgumentException iex) {} return null; }
java
{ "resource": "" }
q163470
AbstractStructrCmisService.typeFromObjectTypeId
train
public Class typeFromObjectTypeId(final String objectTypeId, final BaseTypeId defaultType, final Class defaultClass) { // default for cmuis:folder if (defaultType.value().equals(objectTypeId)) { return defaultClass; } return StructrApp.getConfiguration().getNodeEntityClass(objectTypeId); }
java
{ "resource": "" }
q163471
Services.registerServiceClass
train
public void registerServiceClass(Class serviceClass) { registeredServiceClasses.put(serviceClass.getSimpleName(), serviceClass); // make it possible to select options in configuration editor Settings.Services.addAvailableOption(serviceClass.getSimpleName()); }
java
{ "resource": "" }
q163472
Services.isReady
train
public boolean isReady(final Class serviceClass) { Service service = serviceCache.get(serviceClass); return (service != null && service.isRunning()); }
java
{ "resource": "" }
q163473
MailHelper.replacePlaceHoldersInTemplate
train
public static String replacePlaceHoldersInTemplate(final String template, final Map<String, String> replacementMap) { List<String> toReplace = new ArrayList<>(); List<String> replaceBy = new ArrayList<>(); for (Entry<String, String> property : replacementMap.entrySet()) { toReplace.add(property.getKey()); replaceBy.add(property.getValue()); } return StringUtils.replaceEachRepeatedly(template, toReplace.toArray(new String[toReplace.size()]), replaceBy.toArray(new String[replaceBy.size()])); }
java
{ "resource": "" }
q163474
JavaParserModule.indexSourceTree
train
public void indexSourceTree(final Folder rootFolder) { logger.info("Starting indexing of source tree " + rootFolder.getPath()); final SecurityContext securityContext = rootFolder.getSecurityContext(); app = StructrApp.getInstance(securityContext); structrTypeSolver.parseRoot(rootFolder); final CombinedTypeSolver typeSolver = new CombinedTypeSolver(); typeSolver.add(new ReflectionTypeSolver()); typeSolver.add(structrTypeSolver); facade = JavaParserFacade.get(typeSolver); logger.info("Done with indexing of source tree " + rootFolder.getPath()); }
java
{ "resource": "" }
q163475
Factory.bulkInstantiate
train
public Iterable<T> bulkInstantiate(final Iterable<S> input) throws FrameworkException { return Iterables.map(this, input); }
java
{ "resource": "" }
q163476
SyncCommand.exportToFile
train
public static void exportToFile(final DatabaseService graphDb, final String fileName, final String query, final boolean includeFiles) throws FrameworkException { final App app = StructrApp.getInstance(); try (final Tx tx = app.tx()) { final NodeFactory nodeFactory = new NodeFactory(SecurityContext.getSuperUserInstance()); final RelationshipFactory relFactory = new RelationshipFactory(SecurityContext.getSuperUserInstance()); final Set<AbstractNode> nodes = new HashSet<>(); final Set<AbstractRelationship> rels = new HashSet<>(); boolean conditionalIncludeFiles = includeFiles; if (query != null) { logger.info("Using Cypher query {} to determine export set, disabling export of files", query); conditionalIncludeFiles = false; for (final GraphObject obj : StructrApp.getInstance().query(query, null)) { if (obj.isNode()) { nodes.add((AbstractNode)obj.getSyncNode()); } else { rels.add((AbstractRelationship)obj.getSyncRelationship()); } } logger.info("Query returned {} nodes and {} relationships.", new Object[] { nodes.size(), rels.size() } ); } else { Iterables.addAll(nodes, nodeFactory.bulkInstantiate(graphDb.getAllNodes())); Iterables.addAll(rels, relFactory.bulkInstantiate(graphDb.getAllRelationships())); } try (final FileOutputStream fos = new FileOutputStream(fileName)) { exportToStream(fos, nodes, rels, null, conditionalIncludeFiles); } tx.success(); } catch (Throwable t) { logger.warn("", t); throw new FrameworkException(500, t.getMessage()); } }
java
{ "resource": "" }
q163477
SyncCommand.exportToFile
train
public static void exportToFile(final String fileName, final Iterable<? extends NodeInterface> nodes, final Iterable<? extends RelationshipInterface> relationships, final Iterable<String> filePaths, final boolean includeFiles) throws FrameworkException { try (final Tx tx = StructrApp.getInstance().tx()) { try (final FileOutputStream fos = new FileOutputStream(fileName)) { exportToStream(fos, nodes, relationships, filePaths, includeFiles); } tx.success(); } catch (Throwable t) { throw new FrameworkException(500, t.getMessage()); } }
java
{ "resource": "" }
q163478
SyncCommand.exportToStream
train
public static void exportToStream(final OutputStream outputStream, final Iterable<? extends NodeInterface> nodes, final Iterable<? extends RelationshipInterface> relationships, final Iterable<String> filePaths, final boolean includeFiles) throws FrameworkException { try (final ZipOutputStream zos = new ZipOutputStream(outputStream)) { final Set<String> filesToInclude = new LinkedHashSet<>(); if (filePaths != null) { for (String file : filePaths) { filesToInclude.add(file); } } // set compression zos.setLevel(6); if (includeFiles) { logger.info("Exporting files.."); // export files first exportDirectory(zos, new File("files"), "", filesToInclude.isEmpty() ? null : filesToInclude); } // export database exportDatabase(zos, new BufferedOutputStream(zos), nodes, relationships); // finish ZIP file zos.finish(); // close stream zos.flush(); zos.close(); } catch (Throwable t) { logger.warn("", t); throw new FrameworkException(500, t.getMessage()); } }
java
{ "resource": "" }
q163479
SyncCommand.serializeData
train
public static void serializeData(DataOutputStream outputStream, byte[] data) throws IOException { outputStream.writeInt(data.length); outputStream.write(data); outputStream.flush(); }
java
{ "resource": "" }
q163480
Resource.getFirstPartOfString
train
private String getFirstPartOfString(final String source) { final int pos = source.indexOf("."); if (pos > -1) { return source.substring(0, pos); } return source; }
java
{ "resource": "" }
q163481
RestAuthenticator.initializeAndExamineRequest
train
@Override public SecurityContext initializeAndExamineRequest(final HttpServletRequest request, final HttpServletResponse response) throws FrameworkException { logger.warn("KAI: RestAuthenticator.initializeAndExamineRequest"); SecurityContext securityContext; Principal user = SessionHelper.checkSessionAuthentication(request); if (user == null) { user = getUser(request, true); } if (user == null) { // If no user could be determined, assume frontend access securityContext = SecurityContext.getInstance(user, request, AccessMode.Frontend); } else { if (user instanceof SuperUser) { securityContext = SecurityContext.getSuperUserInstance(request); } else { securityContext = SecurityContext.getInstance(user, request, AccessMode.Backend); SessionHelper.clearInvalidSessions(user); } } securityContext.setAuthenticator(this); // Check CORS settings (Cross-origin resource sharing, see http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) final String origin = request.getHeader("Origin"); if (!StringUtils.isBlank(origin)) { final Services services = Services.getInstance(); response.setHeader("Access-Control-Allow-Origin", origin); // allow cross site resource sharing (read only) final String maxAge = Settings.AccessControlMaxAge.getValue(); if (StringUtils.isNotBlank(maxAge)) { response.setHeader("Access-Control-Max-Age", maxAge); } final String allowMethods = Settings.AccessControlAllowMethods.getValue(); if (StringUtils.isNotBlank(allowMethods)) { response.setHeader("Access-Control-Allow-Methods", allowMethods); } final String allowHeaders = Settings.AccessControlAllowHeaders.getValue(); if (StringUtils.isNotBlank(allowHeaders)) { response.setHeader("Access-Control-Allow-Headers", allowHeaders); } final String allowCredentials = Settings.AccessControlAllowCredentials.getValue(); if (StringUtils.isNotBlank(allowCredentials)) { response.setHeader("Access-Control-Allow-Credentials", allowCredentials); } final String exposeHeaders = Settings.AccessControlExposeHeaders.getValue(); if (StringUtils.isNotBlank(exposeHeaders)) { response.setHeader("Access-Control-Expose-Headers", exposeHeaders); } } examined = true; return securityContext; }
java
{ "resource": "" }
q163482
PlNationalIdentificationNumberProvider.calculateSexCode
train
private int calculateSexCode(Person.Sex sex) { return SEX_FIELDS[baseProducer.randomInt(SEX_FIELDS.length - 1)] + (sex == Person.Sex.MALE ? 1 : 0); }
java
{ "resource": "" }
q163483
ZhFairyUtil.getRandomNumStr
train
public static String getRandomNumStr(BaseProducer baseProducer, int max, int paddingSize) { int rndNum = baseProducer.randomBetween(1, max); String numStr = "" + rndNum; while (numStr.length() < paddingSize) { numStr = "0" + numStr; } return numStr; }
java
{ "resource": "" }
q163484
Bootstrap.create
train
public static Fairy create(Locale locale, String dataFilePrefix) { return builder().withLocale(locale) .withFilePrefix(dataFilePrefix) .build(); }
java
{ "resource": "" }
q163485
Bootstrap.getFairyModuleForLocale
train
private static FairyModule getFairyModuleForLocale(DataMaster dataMaster, Locale locale, RandomGenerator randomGenerator) { LanguageCode code; try { code = LanguageCode.valueOf(locale.getLanguage().toUpperCase()); } catch (IllegalArgumentException e) { LOG.warn("Uknown locale " + locale); code = LanguageCode.EN; } switch (code) { case PL: return new PlFairyModule(dataMaster, randomGenerator); case EN: return new EnFairyModule(dataMaster, randomGenerator); case ES: return new EsFairyModule(dataMaster, randomGenerator); case FR: return new EsFairyModule(dataMaster, randomGenerator); case SV: return new SvFairyModule(dataMaster, randomGenerator); case ZH: return new ZhFairyModule(dataMaster, randomGenerator); case DE: return new DeFairyModule(dataMaster, randomGenerator); case KA: return new KaFairyModule(dataMaster, randomGenerator); default: LOG.info("No data for your language - using EN"); return new EnFairyModule(dataMaster, randomGenerator); } }
java
{ "resource": "" }
q163486
MapBasedDataMaster.readResources
train
public void readResources(String path) throws IOException { Enumeration<URL> resources = getClass().getClassLoader().getResources(path); if (!resources.hasMoreElements()) { throw new IllegalArgumentException(String.format("File %s was not found on classpath", path)); } Yaml yaml = new Yaml(); while (resources.hasMoreElements()) { appendData(yaml.loadAs(resources.nextElement().openStream(), Data.class)); } }
java
{ "resource": "" }
q163487
BaseProducer.randomElement
train
public <T> T randomElement(List<T> elements) { return elements.get(randomBetween(0, elements.size() - 1)); }
java
{ "resource": "" }
q163488
BaseProducer.randomElement
train
public <T extends Enum<?>> T randomElement(Class<T> enumType) { return enumType.getEnumConstants()[randomBetween(0, enumType.getEnumConstants().length - 1)]; }
java
{ "resource": "" }
q163489
BaseProducer.randomElements
train
public <T> List<T> randomElements(List<T> elements, int count) { if (elements.size() >= count) { return extractRandomList(elements, count); } else { List<T> randomElements = new ArrayList<T>(); randomElements.addAll(extractRandomList(elements, count % elements.size())); do { randomElements.addAll(extractRandomList(elements, elements.size())); } while (randomElements.size() < count); return randomElements; } }
java
{ "resource": "" }
q163490
MacroSubstitutionNamingStrategy.split
train
private static String[] split(String input) { char macroStart = MACRO_START.charAt(0); char macroEnd = MACRO_END.charAt(0); int startIndex = 0; boolean inMacro = false; List<String> list = new ArrayList<String>(); for (int endIndex = 0; endIndex < input.length(); endIndex++) { char chr = input.charAt(endIndex); if (!inMacro) { if (chr == macroStart) { String result = input.substring(startIndex, endIndex); if (result.length() > 0) { list.add(result); } inMacro = true; startIndex = endIndex; } } else { if (chr == macroEnd) { String result = input.substring(startIndex, endIndex + 1); if (result.length() > 0) { list.add(result); } inMacro = false; startIndex = endIndex + 1; } } } String result = input.substring(startIndex); if (result.length() > 0) { list.add(result); } return list.toArray(new String[list.size()]); }
java
{ "resource": "" }
q163491
AbstractSyncAsyncMessageBus.initDispatcherThreads
train
private void initDispatcherThreads(Feature.AsynchronousMessageDispatch configuration) { for (int i = 0; i < configuration.getNumberOfMessageDispatchers(); i++) { // each thread will run forever and process incoming // message publication requests Thread dispatcher = configuration.getDispatcherThreadFactory().newThread(new Runnable() { public void run() { while (true) { IMessagePublication publication = null; try { publication = pendingMessages.take(); publication.execute(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } catch(Throwable t){ handlePublicationError(new InternalPublicationError(t, "Error in asynchronous dispatch",publication)); } } } }); dispatcher.setName("MsgDispatcher-"+i); dispatchers.add(dispatcher); dispatcher.start(); } }
java
{ "resource": "" }
q163492
MetadataReader.getFilter
train
private IMessageFilter[] getFilter(Method method, Handler subscription) { Filter[] filterDefinitions = collectFilters(method, subscription); if (filterDefinitions.length == 0) { return null; } IMessageFilter[] filters = new IMessageFilter[filterDefinitions.length]; int i = 0; for (Filter filterDef : filterDefinitions) { IMessageFilter filter = filterCache.get(filterDef.value()); if (filter == null) { try { filter = filterDef.value().newInstance(); filterCache.put(filterDef.value(), filter); } catch (Exception e) { throw new RuntimeException(e);// propagate as runtime exception } } filters[i] = filter; i++; } return filters; }
java
{ "resource": "" }
q163493
MetadataReader.getMessageListener
train
public MessageListener getMessageListener(Class target) { MessageListener listenerMetadata = new MessageListener(target); // get all handlers (this will include all (inherited) methods directly annotated using @Handler) Method[] allHandlers = ReflectionUtils.getMethods(AllMessageHandlers, target); final int length = allHandlers.length; Method handler; for (int i = 0; i < length; i++) { handler = allHandlers[i]; // retain only those that are at the bottom of their respective class hierarchy (deepest overriding method) if (!ReflectionUtils.containsOverridingMethod(allHandlers, handler)) { // for each handler there will be no overriding method that specifies @Handler annotation // but an overriding method does inherit the listener configuration of the overridden method Handler handlerConfig = ReflectionUtils.getAnnotation(handler, Handler.class); Enveloped enveloped = ReflectionUtils.getAnnotation( handler, Enveloped.class ); if (!handlerConfig.enabled() || !isValidMessageHandler(handler)) { continue; // disabled or invalid listeners are ignored } Method overriddenHandler = ReflectionUtils.getOverridingMethod(handler, target); // if a handler is overridden it inherits the configuration of its parent method Map<String, Object> handlerProperties = MessageHandler.Properties.Create(overriddenHandler == null ? handler : overriddenHandler, handlerConfig, enveloped, getFilter(handler, handlerConfig), listenerMetadata); MessageHandler handlerMetadata = new MessageHandler(handlerProperties); listenerMetadata.addHandler(handlerMetadata); } } return listenerMetadata; }
java
{ "resource": "" }
q163494
ReflectionUtils.getOverridingMethod
train
public static Method getOverridingMethod( final Method overridingMethod, final Class subclass ) { Class current = subclass; while ( !current.equals( overridingMethod.getDeclaringClass() ) ) { try { return current.getDeclaredMethod( overridingMethod.getName(), overridingMethod.getParameterTypes() ); } catch ( NoSuchMethodException e ) { current = current.getSuperclass(); } } return null; }
java
{ "resource": "" }
q163495
ReflectionUtils.getAnnotation
train
private static <A extends Annotation> A getAnnotation( AnnotatedElement from, Class<A> annotationType, Set<AnnotatedElement> visited) { if( visited.contains(from) ) return null; visited.add(from); A ann = from.getAnnotation( annotationType ); if( ann != null) return ann; for ( Annotation metaAnn : from.getAnnotations() ) { ann = getAnnotation(metaAnn.annotationType(), annotationType, visited); if ( ann != null ) { return ann; } } return null; }
java
{ "resource": "" }
q163496
MessageListener.getHandlers
train
public List<MessageHandler> getHandlers(IPredicate<MessageHandler> filter) { List<MessageHandler> matching = new ArrayList<MessageHandler>(); for (MessageHandler handler : handlers) { if (filter.apply(handler)) { matching.add(handler); } } return matching; }
java
{ "resource": "" }
q163497
Pool.borrowObject
train
public T borrowObject() { T object; if ((object = pool.poll()) == null) { object = createObject(); } return object; }
java
{ "resource": "" }
q163498
AuthRequestHelper.validateAuthorizationRequest
train
public static boolean validateAuthorizationRequest(AuthRequestDto authRequestDto, OAuthApplicationDto oAuthApplicationDto) throws OAuthException { if (StringUtils.isNotBlank(oAuthApplicationDto.getClientId()) && oAuthApplicationDto.getClientId().equals(authRequestDto.getClientId())) { try { String decodedRedirectUri = java.net.URLDecoder.decode(authRequestDto.getRedirectUri(), "UTF-8"); if (StringUtils.isNotBlank(oAuthApplicationDto.getRedirectUri()) && oAuthApplicationDto.getRedirectUri().equals(decodedRedirectUri)) { return true; } else { _logger.info("Request Redirect URI '" + authRequestDto.getRedirectUri() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST); } } catch (UnsupportedEncodingException e) { _logger.info("Request Redirect URI '" + authRequestDto.getRedirectUri() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST); } } else { _logger.info("Request Client ID '" + authRequestDto.getClientId() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_CLIENT_ID, HttpResponseStatus.BAD_REQUEST); } }
java
{ "resource": "" }
q163499
AuthRequestHelper.generateAuthorizationCode
train
public static String generateAuthorizationCode() { StringBuilder buf = new StringBuilder(AUTHORIZATION_CODE_LENGTH); SecureRandom rand = new SecureRandom(); for (int i = 0; i < AUTHORIZATION_CODE_LENGTH; i++) { buf.append(allowedCharacters[rand.nextInt(allowedCharacters.length)]); } return buf.toString(); }
java
{ "resource": "" }