_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q163300 | WaybackRequest.createCaptureQueryRequet | train | public static WaybackRequest createCaptureQueryRequet(String url, String replay, String start, String end) {
WaybackRequest r = new WaybackRequest();
r.setCaptureQueryRequest();
r.setRequestUrl(url);
r.setReplayTimestamp(replay);
r.setStartTimestamp(start);
r.setEndTimestamp(end);
return r;
} | java | {
"resource": ""
} |
q163301 | WaybackRequest.createReplayRequest | train | public static WaybackRequest createReplayRequest(String url, String replay, String start, String end) {
WaybackRequest r = new WaybackRequest();
r.setReplayRequest();
r.setRequestUrl(url);
r.setReplayTimestamp(replay);
r.setStartTimestamp(start);
r.setEndTimestamp(end);
return r;
} | java | {
"resource": ""
} |
q163302 | WaybackRequest.setRequestUrl | train | public void setRequestUrl(String urlStr) {
// This looks a little confusing: We're trying to fixup an incoming
// request URL that starts with:
// "http(s):/www.archive.org"
// so it becomes:
// "http(s)://www.archive.org"
// (note the missing second "/" in the first)
//
// if that is not the case, then see if the incoming scheme
// is known, adding an implied "http://" scheme if there doesn't appear
// to be a scheme..
// TODO: make the default "http://" configurable.
if (!urlStr.startsWith(UrlOperations.HTTP_SCHEME) &&
!urlStr.startsWith(UrlOperations.HTTPS_SCHEME) &&
!urlStr.startsWith(UrlOperations.FTP_SCHEME) &&
!urlStr.startsWith(UrlOperations.FTPS_SCHEME)) {
if(urlStr.startsWith("http:/")) {
urlStr = UrlOperations.HTTP_SCHEME + urlStr.substring(6);
} else if(urlStr.startsWith("https:/")) {
urlStr = UrlOperations.HTTPS_SCHEME + urlStr.substring(7);
} else if(urlStr.startsWith("ftp:/")) {
urlStr = UrlOperations.FTP_SCHEME + urlStr.substring(5);
} else if(urlStr.startsWith("ftps:/")) {
urlStr = UrlOperations.FTPS_SCHEME + urlStr.substring(6);
} else {
if(UrlOperations.urlToScheme(urlStr) == null) {
urlStr = UrlOperations.HTTP_SCHEME + urlStr;
}
}
}
try {
String decodedUrlStr = URLDecoder.decode(urlStr, "UTF-8");
String idnEncodedHost = UsableURIFactory.getInstance(decodedUrlStr, "UTF-8").getHost();
if (idnEncodedHost != null) {
// If url is absolute, replace host with IDN-encoded host.
String unicodeEncodedHost = URLEncoder.encode(IDNA.toUnicode(idnEncodedHost), "UTF-8");
urlStr = urlStr.replace(unicodeEncodedHost, idnEncodedHost);
}
} catch (UnsupportedEncodingException ex) {
// Should never happen as UTF-8 is required to be present
throw new RuntimeException(ex);
} catch (URIException ex) {
throw new RuntimeException(ex);
}
put(REQUEST_URL, urlStr);
} | java | {
"resource": ""
} |
q163303 | WaybackRequest.extractHttpRequestInfo | train | public void extractHttpRequestInfo(HttpServletRequest httpRequest) {
putUnlessNull(REQUEST_REFERER_URL, httpRequest.getHeader("REFERER"));
String remoteAddr = httpRequest.getHeader("X-Forwarded-For");
remoteAddr = (remoteAddr == null) ?
httpRequest.getRemoteAddr() :
remoteAddr + ", " + httpRequest.getRemoteAddr();
putUnlessNull(REQUEST_REMOTE_ADDRESS, remoteAddr);
// Check for AJAX
String x_req_with = httpRequest.getHeader("X-Requested-With");
if (x_req_with != null) {
if (x_req_with.equals("XMLHttpRequest")) {
this.setAjaxRequest(true);
}
} else if (this.getRefererUrl() != null && httpRequest.getParameter("ajaxpipe") != null) {
this.setAjaxRequest(true);
}
if (isMementoEnabled()) {
// Check for Memento Accept-Datetime
String acceptDateTime = httpRequest.getHeader(MementoUtils.ACCEPT_DATETIME);
if (acceptDateTime != null) {
this.setMementoAcceptDatetime(true);
}
}
putUnlessNull(REQUEST_WAYBACK_HOSTNAME, httpRequest.getLocalName());
putUnlessNull(REQUEST_AUTH_TYPE, httpRequest.getAuthType());
putUnlessNull(REQUEST_REMOTE_USER, httpRequest.getRemoteUser());
putUnlessNull(REQUEST_AUTHORIZATION,
httpRequest.getHeader(REQUEST_AUTHORIZATION));
putUnlessNull(REQUEST_WAYBACK_PORT,
String.valueOf(httpRequest.getLocalPort()));
putUnlessNull(REQUEST_WAYBACK_CONTEXT, httpRequest.getContextPath());
Locale l = null;
if (accessPoint != null) {
l = accessPoint.getLocale();
}
if (l == null) {
l = httpRequest.getLocale();
}
//setLocale(l);
this.locale = l;
putUnlessNull(REQUEST_LOCALE_LANG,l.getDisplayLanguage());
Cookie[] cookies = httpRequest.getCookies();
if(cookies != null) {
for(Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
String oldVal = get(name);
if(oldVal == null || oldVal.length() == 0) {
put(name,value);
}
}
}
} | java | {
"resource": ""
} |
q163304 | PortMapper.addRequestHandler | train | public void addRequestHandler(String host, String firstPath,
RequestHandler requestHandler) {
String key = hostPathToKey(host, firstPath);
if (pathMap.containsKey(key)) {
LOGGER.warning("Duplicate port:path map for " + port +
":" + key);
} else {
pathMap.put(key, requestHandler);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Registered requestHandler(port/host/path) (" +
port + "/" + host + "/" + firstPath + "): " + key);
}
}
} | java | {
"resource": ""
} |
q163305 | IndexQueueUpdater.updateQueue | train | public int updateQueue() throws IOException {
int added = 0;
long lastMarkPoint = lastMark.getLastMark();
long currentMarkPoint = db.getCurrentMark();
if(currentMarkPoint > lastMarkPoint) {
// TODO: touchy touchy... need transactions here to not have
// state sync problems if something goes badly in this block..
// for example, it would be possible to constantly enqueue the
// same files forever..
CloseableIterator<String> newNames =
db.getNamesBetweenMarks(lastMarkPoint, currentMarkPoint);
while(newNames.hasNext()) {
String newName = newNames.next();
LOGGER.info("Queued " + newName + " for indexing.");
queue.enqueue(newName);
added++;
}
newNames.close();
lastMark.setLastMark(currentMarkPoint);
}
return added;
} | java | {
"resource": ""
} |
q163306 | BDBMap.getTimestampForId | train | public static String getTimestampForId(String context, String ip) {
BDBMap bdbMap = getContextMap(context);
String dateStr = bdbMap.get(ip);
return (dateStr != null) ? dateStr : Timestamp.currentTimestamp().getDateStr();
} | java | {
"resource": ""
} |
q163307 | BDBMap.addTimestampForId | train | public static void addTimestampForId(String context, String ip, String time) {
BDBMap bdbMap = getContextMap(context);
bdbMap.put(ip, time);
} | java | {
"resource": ""
} |
q163308 | SelectorReplayDispatcher.shouldDetectMimeType | train | protected boolean shouldDetectMimeType(String mimeType) {
for (String prefix : untrustfulMimeTypes) {
if (mimeType.startsWith(prefix)) return true;
}
return false;
} | java | {
"resource": ""
} |
q163309 | NutchResourceIndex.getNodeContent | train | protected String getNodeContent(Element e, String key) {
NodeList nodes = e.getElementsByTagName(key);
String result = null;
if (nodes != null && nodes.getLength() > 0) {
result = getNodeTextValue(nodes.item(0));
}
return (result == null || result.length() == 0)? null: result;
} | java | {
"resource": ""
} |
q163310 | BDBResourceFileLocationDB.nameToUrls | train | public String[] nameToUrls(final String name) throws IOException {
String[] urls = null;
String valueString = get(name);
if(valueString != null && valueString.length() > 0) {
urls = valueString.split(urlDelimiterRE);
}
return urls;
} | java | {
"resource": ""
} |
q163311 | BDBResourceFileLocationDB.addNameUrl | train | public void addNameUrl(final String name, final String url)
throws IOException {
// need to first see if there is already an entry for this name.
// if not, add url as the value.
// if so, check the current url locations for name
// if url exists, do nothing
// if url does not exist, add, and set that as the value.
String newValue = null;
String oldValue = get(name);
if(oldValue != null && oldValue.length() > 0) {
String curUrls[] = oldValue.split(urlDelimiterRE);
boolean found = false;
for(int i=0; i < curUrls.length; i++) {
if(url.equals(curUrls[i])) {
found = true;
break;
}
}
if(found == false) {
newValue = oldValue + " " + url;
}
} else {
// null or empty value
newValue = url;
if(oldValue == null) log.addName(name);
}
// did we find a value?
if(newValue != null) {
put(name,newValue);
}
} | java | {
"resource": ""
} |
q163312 | BDBResourceFileLocationDB.removeNameUrl | train | public void removeNameUrl(final String name, final String url)
throws IOException {
// need to first see if there is already an entry for this name.
// if not, do nothing
// if so, loop thru all current url locations for name
// keep any that are not url
// if any locations are left, update to the new value, sans url
// if none are left, remove the entry from the db
StringBuilder newValue = new StringBuilder();
String oldValue = get(name);
if(oldValue != null && oldValue.length() > 0) {
String curUrls[] = oldValue.split(urlDelimiterRE);
for(int i=0; i < curUrls.length; i++) {
if(!url.equals(curUrls[i])) {
if(newValue.length() > 0) {
newValue.append(urlDelimiter);
}
newValue.append(curUrls[i]);
}
}
if(newValue.length() > 0) {
// update
put(name, newValue.toString());
} else {
// remove the entry:
delete(name);
}
}
} | java | {
"resource": ""
} |
q163313 | ArchivalUrl.getDateSpec | train | public static String getDateSpec(WaybackRequest wbRequest, String datespec) {
int dateLen = 0;
if(datespec != null) {
dateLen = datespec.length();
}
StringBuilder sb =
new StringBuilder(dateLen +10);
if(dateLen > 0) {
sb.append(datespec);
}
if(wbRequest.isCSSContext()) {
sb.append(ArchivalUrlRequestParser.CSS_CONTEXT);
sb.append(ArchivalUrlRequestParser.FLAG_DELIM);
dateLen++;
}
if(wbRequest.isJSContext()) {
sb.append(ArchivalUrlRequestParser.JS_CONTEXT);
sb.append(ArchivalUrlRequestParser.FLAG_DELIM);
dateLen++;
}
if(wbRequest.isIMGContext()) {
sb.append(ArchivalUrlRequestParser.IMG_CONTEXT);
sb.append(ArchivalUrlRequestParser.FLAG_DELIM);
dateLen++;
}
if(wbRequest.isObjectEmbedContext()) {
sb.append(ArchivalUrlRequestParser.OBJECT_EMBED_WRAPPED_CONTEXT);
sb.append(ArchivalUrlRequestParser.FLAG_DELIM);
dateLen++;
}
if(wbRequest.isIdentityContext()) {
sb.append(ArchivalUrlRequestParser.IDENTITY_CONTEXT);
sb.append(ArchivalUrlRequestParser.FLAG_DELIM);
dateLen++;
}
if(wbRequest.isIFrameWrapperContext()) {
sb.append(ArchivalUrlRequestParser.IFRAME_WRAPPED_CONTEXT);
sb.append(ArchivalUrlRequestParser.FLAG_DELIM);
dateLen++;
}
if(wbRequest.isFrameWrapperContext()) {
sb.append(ArchivalUrlRequestParser.FRAME_WRAPPED_CONTEXT);
sb.append(ArchivalUrlRequestParser.FLAG_DELIM);
dateLen++;
}
return sb.toString();
} | java | {
"resource": ""
} |
q163314 | StaticMapExclusionFilter.setFilterGroup | train | @Override
public void setFilterGroup(ExclusionCaptureFilterGroup filterGroup) {
super.setFilterGroup(filterGroup);
if ((filterGroup != null) && (filterGroup.getCaptureFilterGroupCanonicalizer() != null)) {
this.canonicalizer = filterGroup.getCaptureFilterGroupCanonicalizer();
}
} | java | {
"resource": ""
} |
q163315 | DefaultLiveWebRedirector.handleRedirect | train | @Override
public LiveWebState handleRedirect(WaybackException e, WaybackRequest wbRequest, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException
{
if (statusLiveWebPolicy == null) {
return LiveWebState.NOT_FOUND;
}
// Don't do any redirect for identity context or if no handler is set
if ((wbRequest == null) || wbRequest.isIdentityContext() || (liveWebHandler == null)) {
return LiveWebState.NOT_FOUND;
}
int status = e.getStatus();
String stateName = statusLiveWebPolicy.getProperty(String.valueOf(status));
if (stateName == null) {
stateName = statusLiveWebPolicy.getProperty(DEFAULT);
}
RedirectType state = RedirectType.ALL;
if (stateName != null) {
state = RedirectType.valueOf(stateName);
}
String redirUrl = null;
if (state == RedirectType.NONE) {
return LiveWebState.NOT_FOUND;
}
// If embeds_only and not embed return if it was found
if (state == RedirectType.EMBEDS_ONLY) {
// boolean allowRedirect = wbRequest.isAnyEmbeddedContext();
// if (!allowRedirect) {
// String referrer = wbRequest.getRefererUrl();
// String replayPrefix = wbRequest.getAccessPoint().getReplayPrefix();
//
// if ((referrer != null) && (replayPrefix != null) && referrer.startsWith(replayPrefix)) {
// allowRedirect = true;
// }
// }
if (!wbRequest.isAnyEmbeddedContext()) {
return LiveWebState.FOUND;
}
// if (!wbRequest.isAnyEmbeddedContext()) {
// redirUrl = wbRequest.getRequestUrl();
// }
}
// Now try to do a redirect
redirUrl = liveWebHandler.getLiveWebRedirect(httpRequest, wbRequest, e);
// Don't redirect if redirUrl null
if (redirUrl == null) {
return LiveWebState.NOT_FOUND;
}
// If set to DEFAULT then compute the standard redir url
if (redirUrl.equals(DEFAULT)) {
redirUrl = getLiveWebPrefix() + wbRequest.getRequestUrl();
}
httpResponse.sendRedirect(redirUrl);
return LiveWebState.REDIRECTED;
} | java | {
"resource": ""
} |
q163316 | ResultsPartition.filter | train | public void filter(CaptureSearchResults results) {
Iterator<CaptureSearchResult> itr = results.iterator();
while(itr.hasNext()) {
CaptureSearchResult result = itr.next();
String captureDate = result.getCaptureTimestamp();
if((captureDate.compareTo(startDateStr) >= 0)
&& (captureDate.compareTo(endDateStr) < 0)) {
matches.add(result);
}
}
} | java | {
"resource": ""
} |
q163317 | ByteOp.copy | train | public static byte[] copy(byte[] src, int offset, int length) {
byte[] copy = new byte[length];
System.arraycopy(src, offset, copy, 0, length);
return copy;
} | java | {
"resource": ""
} |
q163318 | ByteOp.cmp | train | public static boolean cmp(byte[] a, byte[] b) {
if(a.length != b.length) {
return false;
}
for(int i = 0; i < a.length; i++) {
if(a[i] != b[i]) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q163319 | ByteOp.discardStream | train | public static void discardStream(InputStream is,int size) throws IOException {
byte[] buffer = new byte[size];
while(is.read(buffer, 0, size) != -1) {
}
} | java | {
"resource": ""
} |
q163320 | ByteOp.discardStreamCount | train | public static long discardStreamCount(InputStream is,int size) throws IOException {
long count = 0;
byte[] buffer = new byte[size];
int amt = 0;
while((amt = is.read(buffer, 0, size)) != -1) {
count += amt;
}
return count;
} | java | {
"resource": ""
} |
q163321 | BitArray.set | train | public void set(int i, boolean value) {
int idx = i / 8;
if(idx >= bb.limit()) {
throw new IndexOutOfBoundsException();
}
int bit = 7 - (i % 8);
if(value) {
bb.put(idx, (byte) (bb.get(idx) | MASKS[bit]));
} else {
bb.put(idx,(byte) (bb.get(idx) & MASKSR[bit]));
}
} | java | {
"resource": ""
} |
q163322 | TagMagix.getTagAttr | train | public static String getTagAttr(StringBuilder page, final String tag,
final String attr) {
String found = null;
Pattern daPattern = TagMagix.getPattern(tag, attr);
Matcher matcher = daPattern.matcher(page);
int idx = 0;
if (matcher.find(idx)) {
found = matcher.group(1);
found = trimAttrValue(found);
}
return found;
} | java | {
"resource": ""
} |
q163323 | TagMagix.getTagAttrWhere | train | public static String getTagAttrWhere(StringBuilder page, final String tag,
final String findAttr, final String whereAttr, final String whereVal) {
Pattern tagPattern = getWholeTagPattern(tag);
Pattern findAttrPattern = getAttrPattern(findAttr);
Pattern whereAttrPattern = getAttrPattern(whereAttr);
Matcher tagMatcher = tagPattern.matcher(page);
while (tagMatcher.find()) {
String wholeTag = tagMatcher.group();
Matcher whereAttrMatcher = whereAttrPattern.matcher(wholeTag);
if (whereAttrMatcher.find()) {
String attrValue = whereAttrMatcher.group(1);
attrValue = trimAttrValue(attrValue);
if (attrValue.compareToIgnoreCase(whereVal) == 0) {
// this tag contains the right set, return the value for
// the attribute findAttr:
Matcher findAttrMatcher = findAttrPattern.matcher(wholeTag);
String value = null;
if (findAttrMatcher.find()) {
value = findAttrMatcher.group(1);
value = trimAttrValue(value);
}
return value;
}
// not the tag we want... maybe there is another: loop
}
}
return null;
} | java | {
"resource": ""
} |
q163324 | UrlOperations.isAuthority | train | public static boolean isAuthority(String authString) {
Matcher m = AUTHORITY_REGEX.matcher(authString);
return (m != null) && m.matches();
} | java | {
"resource": ""
} |
q163325 | UrlOperations.resolveUrl | train | public static String resolveUrl(String baseUrl, String url) {
String resolvedUrl = resolveUrl(baseUrl, url, null);
if (resolvedUrl == null) {
resolvedUrl = url.replace(" ", "%20");
resolvedUrl = resolvedUrl.replace("\r", "%0D");
}
return resolvedUrl;
} | java | {
"resource": ""
} |
q163326 | UrlOperations.resolveUrl | train | public static String resolveUrl(String baseUrl, String url, String defaultValue) {
for(final String scheme : ALL_SCHEMES) {
if(url.startsWith(scheme)) {
try {
return UsableURIFactory.getInstance(url).getEscapedURI();
} catch (URIException e) {
LOGGER.warning(e.getLocalizedMessage() + ": " + url);
// can't let a space exist... send back close to whatever came
// in...
return defaultValue;
}
}
}
UsableURI absBaseURI;
UsableURI resolvedURI = null;
try {
absBaseURI = UsableURIFactory.getInstance(baseUrl);
resolvedURI = UsableURIFactory.getInstance(absBaseURI, url);
} catch (URIException e) {
LOGGER.warning(e.getLocalizedMessage() + ": " + url);
return defaultValue;
}
return resolvedURI.getEscapedURI();
} | java | {
"resource": ""
} |
q163327 | UrlOperations.schemeToDefaultPort | train | public static int schemeToDefaultPort(final String scheme) {
if(scheme.equals(HTTP_SCHEME)) {
return 80;
}
if(scheme.equals(HTTPS_SCHEME)) {
return 443;
}
if(scheme.equals(FTP_SCHEME)) {
return 21;
}
if(scheme.equals(RTSP_SCHEME)) {
return 554;
}
if(scheme.equals(MMS_SCHEME)) {
return 1755;
}
return -1;
} | java | {
"resource": ""
} |
q163328 | UrlOperations.stripDefaultPortFromUrl | train | public static String stripDefaultPortFromUrl(String url) {
String scheme = urlToScheme(url);
if(scheme == null) {
return url;
}
int defaultPort = schemeToDefaultPort(scheme);
if(defaultPort == -1) {
return url;
}
String portStr = null;
// is there a slash after the scheme?
int slashIdx = url.indexOf('/', scheme.length());
if(slashIdx == -1) {
portStr = String.format(":%d", defaultPort);
if(url.endsWith(portStr)) {
return url.substring(0,url.length() - portStr.length());
}
}
portStr = String.format(":%d/", defaultPort);
int idx = url.indexOf(portStr);
if(idx == -1) {
return url;
}
// if that occurred before the first / (after the scheme) then strip it:
if(slashIdx < idx) {
return url;
}
// we want to strip out the portStr:
StringBuilder sb = new StringBuilder(url.length());
sb.append(url.substring(0,idx));
sb.append(url.substring(idx + (portStr.length()-1)));
return sb.toString();
} | java | {
"resource": ""
} |
q163329 | UrlOperations.urlToHost | train | public static String urlToHost(String url) {
String lcUrl = url.toLowerCase();
if(lcUrl.startsWith(DNS_SCHEME)) {
return lcUrl.substring(DNS_SCHEME.length());
}
for(String scheme : ALL_SCHEMES) {
if(lcUrl.startsWith(scheme)) {
int authorityIdx = scheme.length();
Matcher m =
HOST_REGEX_SIMPLE.matcher(lcUrl.substring(authorityIdx));
if(m.find()) {
return m.group(1);
}
}
}
return url;
} | java | {
"resource": ""
} |
q163330 | UrlOperations.urlToUserInfo | train | public static String urlToUserInfo(String url) {
String lcUrl = url.toLowerCase();
if(lcUrl.startsWith(DNS_SCHEME)) {
return null;
}
for(String scheme : ALL_SCHEMES) {
if(lcUrl.startsWith(scheme)) {
int authorityIdx = scheme.length();
Matcher m =
USERINFO_REGEX_SIMPLE.matcher(lcUrl.substring(authorityIdx));
if(m.find()) {
return m.group(1);
}
}
}
return null;
} | java | {
"resource": ""
} |
q163331 | UrlOperations.getUrlParentDir | train | public static String getUrlParentDir(String url) {
try {
UsableURI uri = UsableURIFactory.getInstance(url);
String path = uri.getPath();
if(path.length() > 1) {
int startIdx = path.length()-1;
if(path.charAt(path.length()-1) == '/') {
startIdx--;
}
int idx = path.lastIndexOf('/',startIdx);
if(idx >= 0) {
uri.setPath(path.substring(0,idx+1));
uri.setQuery(null);
return uri.toUnicodeHostString();
}
}
} catch (URIException e) {
LOGGER.warning(e.getLocalizedMessage() + ": " + url);
}
return null;
} | java | {
"resource": ""
} |
q163332 | AccessPoint.shutdown | train | @Override
public void shutdown() {
if (collection != null) {
try {
collection.shutdown();
} catch (IOException e) {
LOGGER.severe("FAILED collection shutdown" + e.getMessage());
}
}
if (exclusionFactory != null) {
exclusionFactory.shutdown();
}
} | java | {
"resource": ""
} |
q163333 | AccessPoint.setLiveWebPrefix | train | public void setLiveWebPrefix(String liveWebPrefix) {
if (liveWebPrefix == null || liveWebPrefix.isEmpty()) {
this.liveWebRedirector = null;
}
this.liveWebRedirector = new DefaultLiveWebRedirector(liveWebPrefix);
} | java | {
"resource": ""
} |
q163334 | AggressiveUrlCanonicalizer.doStripRegexMatch | train | protected boolean doStripRegexMatch(StringBuilder url, Matcher matcher) {
if(matcher != null && matcher.matches()) {
url.delete(matcher.start(1), matcher.end(1));
return true;
}
return false;
} | java | {
"resource": ""
} |
q163335 | AggressiveUrlCanonicalizer.canonicalize | train | public String canonicalize(String url) {
if (url == null || url.length() <= 0) {
return url;
}
// hang on, we're about to get aggressive:
url = url.toLowerCase();
StringBuilder sb = new StringBuilder(url);
boolean changed = false;
for(int i=0; i<choosers.length; i++) {
if(sb.indexOf(choosers[i]) != -1) {
changed |= doStripRegexMatch(sb,strippers[i].matcher(sb));
}
}
if(changed) {
url = sb.toString();
}
int index = url.lastIndexOf('?');
if (index > 0) {
if (index == (url.length() - 1)) {
// '?' is last char in url. Strip it.
url = url.substring(0, url.length() - 1);
} else if (url.charAt(index + 1) == '&') {
// Next char is '&'. Strip it.
if (url.length() == (index + 2)) {
// Then url ends with '?&'. Strip them.
url = url.substring(0, url.length() - 2);
} else {
// The '&' is redundant. Strip it.
url = url.substring(0, index + 1) +
url.substring(index + 2);
}
} else if (url.charAt(url.length() - 1) == '&') {
// If we have a lone '&' on end of query str,
// strip it.
url = url.substring(0, url.length() - 1);
}
}
return url;
} | java | {
"resource": ""
} |
q163336 | CaptureSearchResults.addSearchResult | train | public void addSearchResult(CaptureSearchResult result, boolean append) {
String resultDate = result.getCaptureTimestamp();
if ((firstResultTimestamp == null) ||
(firstResultTimestamp.compareTo(resultDate) > 0)) {
firstResultTimestamp = resultDate;
}
if ((lastResultTimestamp == null) ||
(lastResultTimestamp.compareTo(resultDate) < 0)) {
lastResultTimestamp = resultDate;
}
if (append) {
if (!results.isEmpty()) {
results.getLast().setNextResult(result);
result.setPrevResult(results.getLast());
}
results.add(result);
} else {
if (!results.isEmpty()) {
results.getFirst().setPrevResult(result);
result.setNextResult(results.getFirst());
}
results.add(0, result);
}
} | java | {
"resource": ""
} |
q163337 | Partitioner.getSize | train | public static PartitionSize getSize(String name) {
for(PartitionSize pa : sizes) {
if(pa.name().equals(name)) {
return pa;
}
}
return twoYearSize;
} | java | {
"resource": ""
} |
q163338 | Partitioner.getSize | train | public PartitionSize getSize(Date first, Date last, int maxP) {
long diffMS = last.getTime() - first.getTime();
for(PartitionSize pa : sizes) {
long maxMS = maxP * pa.intervalMS();
if(maxMS > diffMS) {
return pa;
}
}
return twoYearSize;
} | java | {
"resource": ""
} |
q163339 | Partitioner.getRange | train | public List<Partition<T>> getRange(PartitionSize size, Date start,
Date end) {
// logDates("Constructing partitions Size(" + size.name() + ")",start,end);
// Date origStart = new Date(start.getTime());
List<Partition<T>> partitions = new ArrayList<Partition<T>>();
Calendar cStart = Calendar.getInstance(TZ_UTC);
cStart.setTime(start);
size.alignStart(cStart);
// logDates("AlignedStart("+size.name()+")",origStart,cStart.getTime());
Calendar cEnd = size.increment(cStart, 1);
// logDates("AlignedEnd("+size.name()+")",cStart.getTime(),cEnd.getTime());
while(cStart.getTime().compareTo(end) < 0) {
partitions.add(new Partition<T>(cStart.getTime(), cEnd.getTime()));
cStart = cEnd;
cEnd = size.increment(cStart, 1);
// logDates("Incremented("+size.name()+")",
// cStart.getTime(),cEnd.getTime());
}
return partitions;
} | java | {
"resource": ""
} |
q163340 | Partitioner.populate | train | public void populate(List<Partition<T>> partitions,
Iterator<T> itr) {
int idx = 0;
int size = partitions.size();
T element = null;
while(idx < size) {
Partition<T> partition = partitions.get(idx);
if(element == null) {
if(itr.hasNext()) {
element = itr.next();
} else {
// all done
break;
}
}
// will current result fit in the current partition?
while(partition.containsDate(map.elementToDate(element))) {
map.addElementToPartition(element, partition);
element = null;
if(itr.hasNext()) {
element = itr.next();
} else {
break;
}
}
idx++;
}
if(itr.hasNext()) {
// eew... Likely bad usage. is this an error?
LOGGER.warning("Not all elements fit in partitions!");
}
} | java | {
"resource": ""
} |
q163341 | RequestMapper.addRequestHandler | train | public void addRequestHandler(int port, String host, String path,
RequestHandler requestHandler) {
Integer portInt = Integer.valueOf(port);
PortMapper portMapper = portMap.get(portInt);
if (portMapper == null) {
portMapper = new PortMapper(portInt);
portMap.put(portInt, portMapper);
}
portMapper.addRequestHandler(host, path, requestHandler);
LOGGER.info("Registered " + port + "/" +
(host == null ? "*" : host) + "/" +
(path == null ? "*" : path) + " --> " +
requestHandler);
} | java | {
"resource": ""
} |
q163342 | RequestMapper.handleRequest | train | public boolean handleRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
boolean handled = false;
// Internally UIResults.forward(), don't handle here
if (request.getAttribute(UIResults.FERRET_NAME) != null) {
return false;
}
if (globalPreRequestHandler != null) {
handled = globalPreRequestHandler.handleRequest(request, response);
}
if (handled == false) {
RequestHandlerContext handlerContext = mapRequest(request);
if (handlerContext != null) {
RequestHandler requestHandler =
handlerContext.getRequestHandler();
// need to add trailing "/" iff prefix is not "/":
String pathPrefix = handlerContext.getPathPrefix();
if (!pathPrefix.equals("/")) {
pathPrefix += "/";
}
request.setAttribute(REQUEST_CONTEXT_PREFIX,pathPrefix);
handled = requestHandler.handleRequest(request, response);
}
}
if (handled == false) {
if(globalPostRequestHandler != null) {
handled = globalPostRequestHandler.handleRequest(request,
response);
}
}
return handled;
} | java | {
"resource": ""
} |
q163343 | RequestMapper.shutdown | train | public void shutdown() {
for (ShutdownListener shutdownListener : shutdownListeners) {
try {
shutdownListener.shutdown();
} catch(Exception e) {
LOGGER.severe("failed shutdown"+e.getMessage());
}
}
} | java | {
"resource": ""
} |
q163344 | AnsiPrintStream.processCharsetSelect | train | private boolean processCharsetSelect(ArrayList<Object> options) {
int set = optionInt(options, 0);
char seq = ((Character) options.get(1)).charValue();
processCharsetSelect(set, seq);
return true;
} | java | {
"resource": ""
} |
q163345 | AnsiRenderer.render | train | public static Appendable render(final String input, Appendable target) throws IOException {
int i = 0;
int j, k;
while (true) {
j = input.indexOf(BEGIN_TOKEN, i);
if (j == -1) {
if (i == 0) {
target.append(input);
return target;
}
target.append(input.substring(i, input.length()));
return target;
}
target.append(input.substring(i, j));
k = input.indexOf(END_TOKEN, j);
if (k == -1) {
target.append(input);
return target;
}
j += BEGIN_TOKEN_LEN;
String spec = input.substring(j, k);
String[] items = spec.split(CODE_TEXT_SEPARATOR, 2);
if (items.length == 1) {
target.append(input);
return target;
}
String replacement = render(items[1], items[0].split(CODE_LIST_SEPARATOR));
target.append(replacement);
i = k + END_TOKEN_LEN;
}
} | java | {
"resource": ""
} |
q163346 | TimeBasedOneTimePasswordHelper.zeroPrepend | train | static String zeroPrepend(long num, int digits) {
String numStr = Long.toString(num);
if (numStr.length() >= digits) {
return numStr;
} else {
return String.format("%0" + digits + "d", num);
}
} | java | {
"resource": ""
} |
q163347 | TimeBasedOneTimePasswordHelper.decodeBase32 | train | static byte[] decodeBase32(String str) {
// each base-32 character encodes 5 bits
int numBytes = ((str.length() * 5) + 7) / 8;
byte[] result = new byte[numBytes];
int resultIndex = 0;
int which = 0;
int working = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
int val;
if (ch >= 'a' && ch <= 'z') {
val = ch - 'a';
} else if (ch >= 'A' && ch <= 'Z') {
val = ch - 'A';
} else if (ch >= '2' && ch <= '7') {
val = 26 + (ch - '2');
} else if (ch == '=') {
// special case
which = 0;
break;
} else {
throw new IllegalArgumentException("Invalid base-32 character: " + ch);
}
/*
* There are probably better ways to do this but this seemed the most straightforward.
*/
switch (which) {
case 0:
// all 5 bits is top 5 bits
working = (val & 0x1F) << 3;
which = 1;
break;
case 1:
// top 3 bits is lower 3 bits
working |= (val & 0x1C) >> 2;
result[resultIndex++] = (byte) working;
// lower 2 bits is upper 2 bits
working = (val & 0x03) << 6;
which = 2;
break;
case 2:
// all 5 bits is mid 5 bits
working |= (val & 0x1F) << 1;
which = 3;
break;
case 3:
// top 1 bit is lowest 1 bit
working |= (val & 0x10) >> 4;
result[resultIndex++] = (byte) working;
// lower 4 bits is top 4 bits
working = (val & 0x0F) << 4;
which = 4;
break;
case 4:
// top 4 bits is lowest 4 bits
working |= (val & 0x1E) >> 1;
result[resultIndex++] = (byte) working;
// lower 1 bit is top 1 bit
working = (val & 0x01) << 7;
which = 5;
break;
case 5:
// all 5 bits is mid 5 bits
working |= (val & 0x1F) << 2;
which = 6;
break;
case 6:
// top 2 bits is lowest 2 bits
working |= (val & 0x18) >> 3;
result[resultIndex++] = (byte) working;
// lower 3 bits of byte 6 is top 3 bits
working = (val & 0x07) << 5;
which = 7;
break;
case 7:
// all 5 bits is lower 5 bits
working |= (val & 0x1F);
result[resultIndex++] = (byte) working;
which = 0;
break;
}
}
if (which != 0) {
result[resultIndex++] = (byte) working;
}
if (resultIndex != result.length) {
result = Arrays.copyOf(result, resultIndex);
}
return result;
} | java | {
"resource": ""
} |
q163348 | AbstractNode.getName | train | @Override
public final String getName() {
String name = getProperty(AbstractNode.name);
if (name == null) {
name = getUuid();
}
return name;
} | java | {
"resource": ""
} |
q163349 | AbstractNode.getPropertyKeys | train | @Override
public Set<PropertyKey> getPropertyKeys(final String propertyView) {
// check for custom view in content-type field
if (securityContext != null && securityContext.hasCustomView()) {
final Set<PropertyKey> keys = new LinkedHashSet<>(StructrApp.getConfiguration().getPropertySet(entityType, PropertyView.All));
final Set<String> customView = securityContext.getCustomView();
for (Iterator<PropertyKey> it = keys.iterator(); it.hasNext();) {
if (!customView.contains(it.next().jsonName())) {
it.remove();
}
}
return keys;
}
// this is the default if no application/json; properties=[...] content-type header is present on the request
return StructrApp.getConfiguration().getPropertySet(entityType, propertyView);
} | java | {
"resource": ""
} |
q163350 | AbstractNode.getComparableProperty | train | @Override
public final <T> Comparable getComparableProperty(final PropertyKey<T> key) {
if (key != null) {
final T propertyValue = getProperty(key);
// check property converter
PropertyConverter<T, ?> converter = key.databaseConverter(securityContext, this);
if (converter != null) {
try {
return converter.convertForSorting(propertyValue);
} catch (Throwable t) {
logger.warn("Unable to convert property {} of type {}: {}", new Object[]{
key.dbName(),
getClass().getSimpleName(),
t.getMessage()
});
logger.warn("", t);
}
}
// conversion failed, may the property value itself is comparable
if (propertyValue instanceof Comparable) {
return (Comparable) propertyValue;
}
// last try: convertFromInput to String to make comparable
if (propertyValue != null) {
return propertyValue.toString();
}
}
return null;
} | java | {
"resource": ""
} |
q163351 | AbstractNode.getRelationshipInfo | train | public final Map<String, Long> getRelationshipInfo(final Direction dir) throws FrameworkException {
return StructrApp.getInstance(securityContext).command(NodeRelationshipStatisticsCommand.class).execute(this, dir);
} | java | {
"resource": ""
} |
q163352 | AbstractNode.getOwnerNode | train | @Override
public final Principal getOwnerNode() {
if (cachedOwnerNode == null) {
final Ownership ownership = getIncomingRelationshipAsSuperUser(PrincipalOwnsNode.class);
if (ownership != null) {
Principal principal = ownership.getSourceNode();
cachedOwnerNode = (Principal) principal;
}
}
return cachedOwnerNode;
} | java | {
"resource": ""
} |
q163353 | AbstractNode.hasRelationship | train | public final <A extends NodeInterface, B extends NodeInterface, S extends Source, T extends Target> boolean hasRelationship(final Class<? extends Relation<A, B, S, T>> type) {
return this.getRelationships(type).iterator().hasNext();
} | java | {
"resource": ""
} |
q163354 | AbstractNode.propagationAllowed | train | private boolean propagationAllowed(final AbstractNode thisNode, final RelationshipInterface rel, final SchemaRelationshipNode.Direction propagationDirection, final boolean doLog) {
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.Both)) {
return true;
}
// early exit
if (propagationDirection.equals(SchemaRelationshipNode.Direction.None)) {
return false;
}
final String sourceNodeId = rel.getSourceNode().getUuid();
final String thisNodeId = thisNode.getUuid();
if (sourceNodeId.equals(thisNodeId)) {
// evaluation WITH the relationship direction
switch (propagationDirection) {
case Out:
return false;
case In:
return true;
}
} else {
// evaluation AGAINST the relationship direction
switch (propagationDirection) {
case Out:
return true;
case In:
return false;
}
}
return false;
} | java | {
"resource": ""
} |
q163355 | AgentService.createAgent | train | private Agent createAgent(Task forTask) {
logger.debug("Creating new agent for task {}", forTask.getClass().getSimpleName());
Agent agent = null;
try {
agent = lookupAgent(forTask);
if (agent != null) {
// register us in agent..
agent.setAgentService(this);
}
} catch (Throwable t) {
t.printStackTrace();
}
return (agent);
} | java | {
"resource": ""
} |
q163356 | ReferenceGroup.getDirectAccessReferenceGroup | train | public <T> PropertyKey<T> getDirectAccessReferenceGroup(String name, Class<T> type) {
if (!propertyKeys.containsKey(name)) {
throw new IllegalArgumentException("ReferenceGroup " + dbName + " does not contain grouped property " + name + "!");
}
return new GenericProperty(propertyKeys.get(name).dbName());
} | java | {
"resource": ""
} |
q163357 | UiAuthenticator.checkExternalAuthentication | train | protected Principal checkExternalAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws FrameworkException {
final String path = PathHelper.clean(request.getPathInfo());
final String[] uriParts = PathHelper.getParts(path);
logger.debug("Checking external authentication ...");
if (uriParts == null || uriParts.length != 3 || !("oauth".equals(uriParts[0]))) {
logger.debug("Incorrect URI parts for OAuth process, need /oauth/<name>/<action>");
return null;
}
final String name = uriParts[1];
final String action = uriParts[2];
// Try to getValue an OAuth2 server for the given name
final StructrOAuthClient oauthServer = StructrOAuthClient.getServer(name);
if (oauthServer == null) {
logger.debug("No OAuth2 authentication server configured for {}", path);
return null;
}
if ("login".equals(action)) {
try {
response.sendRedirect(oauthServer.getEndUserAuthorizationRequestUri(request));
return null;
} catch (Exception ex) {
logger.error("Could not send redirect to authorization server", ex);
}
} else if ("auth".equals(action)) {
final String accessToken = oauthServer.getAccessToken(request);
final SecurityContext superUserContext = SecurityContext.getSuperUserInstance();
if (accessToken != null) {
logger.debug("Got access token {}", accessToken);
String value = oauthServer.getCredential(request);
logger.debug("Got credential value: {}", new Object[] { value });
if (value != null) {
final PropertyKey credentialKey = oauthServer.getCredentialKey();
Principal user = AuthHelper.getPrincipalForCredential(credentialKey, value);
if (user == null && Settings.RestUserAutocreate.getValue()) {
user = RegistrationResource.createUser(superUserContext, credentialKey, value, true, getUserClass(), null);
// let oauth implementation augment user info
oauthServer.initializeUser(user);
}
if (user != null) {
AuthHelper.doLogin(request, user);
HtmlServlet.setNoCacheHeaders(response);
try {
logger.debug("Response status: {}", response.getStatus());
response.sendRedirect(oauthServer.getReturnUri());
} catch (IOException ex) {
logger.error("Could not redirect to {}: {}", new Object[]{oauthServer.getReturnUri(), ex});
}
return user;
}
}
}
}
try {
response.sendRedirect(oauthServer.getErrorUri());
} catch (IOException ex) {
logger.error("Could not redirect to {}: {}", new Object[]{ oauthServer.getReturnUri(), ex });
}
return null;
} | java | {
"resource": ""
} |
q163358 | ValidationHelper.isValidStringMinLength | train | public static boolean isValidStringMinLength(final GraphObject node, final PropertyKey<String> key, final int minLength, final ErrorBuffer errorBuffer) {
String value = node.getProperty(key);
String type = node.getType();
if (StringUtils.isNotBlank(value)) {
if (value.length() >= minLength) {
return true;
}
errorBuffer.add(new TooShortToken(type, key, minLength));
return false;
}
errorBuffer.add(new EmptyPropertyToken(type, key));
return false;
} | java | {
"resource": ""
} |
q163359 | LinkedListNodeImpl.listGetPrevious | train | @Override
public T listGetPrevious(final T currentElement) {
Relation<T, T, OneStartpoint<T>, OneEndpoint<T>> prevRel = currentElement.getIncomingRelationship(getSiblingLinkType());
if (prevRel != null) {
return (T)prevRel.getSourceNode();
}
return null;
} | java | {
"resource": ""
} |
q163360 | LinkedListNodeImpl.listGetNext | train | @Override
public T listGetNext(final T currentElement) {
Relation<T, T, OneStartpoint<T>, OneEndpoint<T>> nextRel = currentElement.getOutgoingRelationship(getSiblingLinkType());
if (nextRel != null) {
return (T)nextRel.getTargetNode();
}
return null;
} | java | {
"resource": ""
} |
q163361 | LinkedListNodeImpl.listInsertBefore | train | @Override
public void listInsertBefore(final T currentElement, final T newElement) throws FrameworkException {
if (currentElement.getUuid().equals(newElement.getUuid())) {
throw new IllegalStateException("Cannot link a node to itself!");
}
final T previousElement = listGetPrevious(currentElement);
if (previousElement == null) {
linkNodes(getSiblingLinkType(), newElement, currentElement);
} else {
// delete old relationship
unlinkNodes(getSiblingLinkType(), previousElement, currentElement);
// dont create self link
if (!previousElement.getUuid().equals(newElement.getUuid())) {
linkNodes(getSiblingLinkType(), previousElement, newElement);
}
// dont create self link
if (!newElement.getUuid().equals(currentElement.getUuid())) {
linkNodes(getSiblingLinkType(), newElement, currentElement);
}
}
} | java | {
"resource": ""
} |
q163362 | LinkedListNodeImpl.listInsertAfter | train | @Override
public void listInsertAfter(final T currentElement, final T newElement) throws FrameworkException {
if (currentElement.getUuid().equals(newElement.getUuid())) {
throw new IllegalStateException("Cannot link a node to itself!");
}
final T next = listGetNext(currentElement);
if (next == null) {
linkNodes(getSiblingLinkType(), currentElement, newElement);
} else {
// unlink predecessor and successor
unlinkNodes(getSiblingLinkType(), currentElement, next);
// link predecessor to new element
linkNodes(getSiblingLinkType(), currentElement, newElement);
// dont create self link
if (!newElement.getUuid().equals(next.getUuid())) {
// link new element to successor
linkNodes(getSiblingLinkType(), newElement, next);
}
}
} | java | {
"resource": ""
} |
q163363 | LinkedListNodeImpl.listRemove | train | @Override
public void listRemove(final T currentElement) throws FrameworkException {
final T previousElement = listGetPrevious(currentElement);
final T nextElement = listGetNext(currentElement);
if (currentElement != null) {
if (previousElement != null) {
unlinkNodes(getSiblingLinkType(), previousElement, currentElement);
}
if (nextElement != null) {
unlinkNodes(getSiblingLinkType(), currentElement, nextElement);
}
}
if (previousElement != null && nextElement != null) {
Node previousNode = previousElement.getNode();
Node nextNode = nextElement.getNode();
if (previousNode != null && nextNode != null) {
linkNodes(getSiblingLinkType(), previousElement, nextElement);
}
}
} | java | {
"resource": ""
} |
q163364 | XMLHandler.handleSetProperty | train | private void handleSetProperty(final Element element, final Map<String, Object> entityData, final Map<String, Object> config) {
String propertyName = (String)config.get(PROPERTY_NAME);
if (propertyName == null) {
propertyName = element.tagName;
}
entityData.put(propertyName, element.text);
} | java | {
"resource": ""
} |
q163365 | StructrSchema.createFromDatabase | train | public static JsonSchema createFromDatabase(final App app, final List<String> types) throws FrameworkException, URISyntaxException {
try (final Tx tx = app.tx()) {
final JsonSchema schema = StructrSchemaDefinition.initializeFromDatabase(app, types);
tx.success();
return schema;
}
} | java | {
"resource": ""
} |
q163366 | StructrSchema.createFromSource | train | public static JsonSchema createFromSource(final String source) throws InvalidSchemaException, URISyntaxException {
return StructrSchema.createFromSource(new StringReader(source));
} | java | {
"resource": ""
} |
q163367 | StructrSchema.createFromSource | train | public static JsonSchema createFromSource(final Reader reader) throws InvalidSchemaException, URISyntaxException {
final Gson gson = new GsonBuilder().create();
final Map<String, Object> rawData = gson.fromJson(reader, Map.class);
return StructrSchemaDefinition.initializeFromSource(rawData);
} | java | {
"resource": ""
} |
q163368 | StructrSchema.replaceDatabaseSchema | train | public static void replaceDatabaseSchema(final App app, final JsonSchema newSchema) throws FrameworkException, URISyntaxException {
Services.getInstance().setOverridingSchemaTypesAllowed(true);
try (final Tx tx = app.tx()) {
for (final SchemaRelationshipNode schemaRelationship : app.nodeQuery(SchemaRelationshipNode.class).getAsList()) {
app.delete(schemaRelationship);
}
for (final SchemaNode schemaNode : app.nodeQuery(SchemaNode.class).getAsList()) {
app.delete(schemaNode);
}
for (final SchemaMethod schemaMethod : app.nodeQuery(SchemaMethod.class).getAsList()) {
app.delete(schemaMethod);
}
for (final SchemaMethodParameter schemaMethodParameter : app.nodeQuery(SchemaMethodParameter.class).getAsList()) {
app.delete(schemaMethodParameter);
}
for (final SchemaProperty schemaProperty : app.nodeQuery(SchemaProperty.class).getAsList()) {
app.delete(schemaProperty);
}
for (final SchemaView schemaView : app.nodeQuery(SchemaView.class).getAsList()) {
app.delete(schemaView);
}
newSchema.createDatabaseSchema(app, JsonSchema.ImportMode.replace);
tx.success();
}
} | java | {
"resource": ""
} |
q163369 | StructrSchema.extendDatabaseSchema | train | public static void extendDatabaseSchema(final App app, final JsonSchema newSchema) throws FrameworkException, URISyntaxException {
try (final Tx tx = app.tx()) {
newSchema.createDatabaseSchema(app, JsonSchema.ImportMode.extend);
tx.success();
}
} | java | {
"resource": ""
} |
q163370 | Char.eatPercentage | train | public static char eatPercentage(String a, int[] n) {
// Length 0
if (!a.startsWith("%") || a.length() < 3) {
n[0] = 0;
return ((char) 0);
}
char c;
// Try to parse first char
try {
c = (char) Integer.parseInt(a.substring(1, 3), 16);
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
}
// For non-UTF8, return the char
int len = Utf8Length(c);
n[0] = 3;
if (len <= 1) return (c);
// Else collect the UTF8
String dec = "" + c;
for (int i = 1; i < len; i++) {
try {
dec += (char) Integer.parseInt(a.substring(1 + i * 3, 3 + i * 3), 16);
} catch (Exception e) {
return (c);
}
}
// Try to decode the UTF8
int[] eatLength = new int[1];
char utf8 = eatUtf8(dec, eatLength);
if (eatLength[0] != len) return (c);
n[0] = len * 3;
return (utf8);
} | java | {
"resource": ""
} |
q163371 | Char.eatAmpersand | train | public static char eatAmpersand(String a, int[] n) {
n[0] = 0;
if (!a.startsWith("&")) return ((char) 0);
// Seek to ';'
// We also accept spaces and the end of the String as a delimiter
while (n[0] < a.length() && !Character.isSpaceChar(a.charAt(n[0])) && a.charAt(n[0]) != ';')
n[0]++;
if (n[0] <= 1) {
n[0] = -1;
return ((char) 0);
}
if (n[0] < a.length() && a.charAt(n[0]) == ';') {
a = a.substring(1, n[0]);
n[0]++;
} else {
a = a.substring(1, n[0]);
}
// Hexadecimal characters
if (a.startsWith("#x")) {
try {
return ((char) Integer.parseInt(a.substring(2), 16));
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
}
}
// Decimal characters
if (a.startsWith("#")) {
try {
return ((char) Integer.parseInt(a.substring(1)));
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
}
}
// Others
if (ampersandMap.get(a) != null) return (ampersandMap.get(a));
else if (ampersandMap.get(a.toLowerCase()) != null) return (ampersandMap.get(a.toLowerCase()));
n[0] = -1;
return ((char) 0);
} | java | {
"resource": ""
} |
q163372 | Char.eatUtf8 | train | public static char eatUtf8(String a, int[] n) {
if (a.length() == 0) {
n[0] = 0;
return ((char) 0);
}
n[0] = Utf8Length(a.charAt(0));
if (a.length() >= n[0]) {
switch (n[0]) {
case 1:
return (a.charAt(0));
case 2:
if ((a.charAt(1) & 0xC0) != 0x80) break;
return ((char) (((a.charAt(0) & 0x1F) << 6) + (a.charAt(1) & 0x3F)));
case 3:
if ((a.charAt(1) & 0xC0) != 0x80 || (a.charAt(2) & 0xC0) != 0x80) break;
return ((char) (((a.charAt(0) & 0x0F) << 12) + ((a.charAt(1) & 0x3F) << 6) + ((a.charAt(2) & 0x3F))));
case 4:
if ((a.charAt(1) & 0xC0) != 0x80 || (a.charAt(2) & 0xC0) != 0x80 || (a.charAt(3) & 0xC0) != 0x80) break;
return ((char) (((a.charAt(0) & 0x07) << 18) + ((a.charAt(1) & 0x3F) << 12) + ((a.charAt(2) & 0x3F) << 6) + ((a.charAt(3) & 0x3F))));
}
}
n[0] = -1;
return ((char) 0);
} | java | {
"resource": ""
} |
q163373 | Char.decodeUTF8 | train | public static String decodeUTF8(String s) {
StringBuilder result = new StringBuilder();
int[] eatLength = new int[1];
while (s.length() != 0) {
char c = eatUtf8(s, eatLength);
if (eatLength[0] != -1) {
result.append(c);
s = s.substring(eatLength[0]);
} else {
result.append(s.charAt(0));
s = s.substring(1);
}
}
return (result.toString());
} | java | {
"resource": ""
} |
q163374 | Char.decodePercentage | train | public static String decodePercentage(String s) {
StringBuilder result = new StringBuilder();
int[] eatLength = new int[1];
while (s.length() != 0) {
char c = eatPercentage(s, eatLength);
if (eatLength[0] > 1) {
result.append(c);
s = s.substring(eatLength[0]);
} else {
result.append(s.charAt(0));
s = s.substring(1);
}
}
return (result.toString());
} | java | {
"resource": ""
} |
q163375 | Char.decodeAmpersand | train | public static String decodeAmpersand(String s) {
if(s==null || s.indexOf('&')==-1) return(s);
StringBuilder result = new StringBuilder();
int[] eatLength = new int[1];// add this in order to multithread safe
while (s.length() != 0) {
char c = eatAmpersand(s, eatLength);
if (eatLength[0] > 1) {
result.append(c);
s = s.substring(eatLength[0]);
} else {
result.append(s.charAt(0));
s = s.substring(1);
}
}
return (result.toString());
} | java | {
"resource": ""
} |
q163376 | Char.decodeBackslash | train | public static String decodeBackslash(String s) {
if(s==null || s.indexOf('\\')==-1) return(s);
StringBuilder result = new StringBuilder();
int[] eatLength = new int[1];
while (s.length() != 0) {
char c = eatBackslash(s, eatLength);
if (eatLength[0] > 1) {
result.append(c);
s = s.substring(eatLength[0]);
} else {
result.append(s.charAt(0));
s = s.substring(1);
}
}
return (result.toString());
} | java | {
"resource": ""
} |
q163377 | Char.encodeBackslash | train | public static String encodeBackslash(CharSequence s, Legal legal) {
StringBuilder b=new StringBuilder((int)(s.length()*1.5));
for(int i=0;i<s.length();i++) {
if(legal.isLegal(s.charAt(i))) {
b.append(s.charAt(i));
} else {
if(charToBackslash.containsKey(s.charAt(i))) {
b.append(charToBackslash.get(s.charAt(i)));
continue;
}
b.append("\\u");
String hex = Integer.toHexString(s.charAt(i));
for(int j=0;j<4-hex.length();j++)
b.append('0');
b.append(hex);
}
}
return(b.toString());
} | java | {
"resource": ""
} |
q163378 | Char.eatBackslash | train | public static char eatBackslash(String a, int[] n) {
if (!a.startsWith("\\")) {
n[0] = 0;
return ((char) 0);
}
// Unicodes BS u XXXX
if (a.startsWith("\\u")) {
try {
n[0] = 6;
return ((char) Integer.parseInt(a.substring(2, 6), 16));
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
}
}
// Unicodes BS uu XXXX
if (a.startsWith("\\uu")) {
try {
n[0] = 7;
return ((char) Integer.parseInt(a.substring(3, 7), 16));
} catch (Exception e) {
n[0] = -1;
return ((char) 0);
}
}
// Classical escape sequences
if (a.startsWith("\\b")) {
n[0] = 2;
return ((char) 8);
}
if (a.startsWith("\\t")) {
n[0] = 2;
return ((char) 9);
}
if (a.startsWith("\\n")) {
n[0] = 2;
return ((char) 10);
}
if (a.startsWith("\\f")) {
n[0] = 2;
return ((char) 12);
}
if (a.startsWith("\\r")) {
n[0] = 2;
return ((char) 13);
}
if (a.startsWith("\\\\")) {
n[0] = 2;
return ('\\');
}
if (a.startsWith("\\\"")) {
n[0] = 2;
return ('"');
}
if (a.startsWith("\\'")) {
n[0] = 2;
return ('\'');
}
// Octal codes
n[0] = 1;
while (n[0] < a.length() && a.charAt(n[0]) >= '0' && a.charAt(n[0]) <= '8')
n[0]++;
if (n[0] == 1) {
n[0] = 0;
return ((char) 0);
}
try {
return ((char) Integer.parseInt(a.substring(1, n[0]), 8));
} catch (Exception e) {
}
n[0] = -1;
return ((char) 0);
} | java | {
"resource": ""
} |
q163379 | Char.decode | train | public static String decode(String s) {
StringBuilder b = new StringBuilder();
int[] eatLength = new int[1];
while (s.length() > 0) {
char c = eatPercentage(s, eatLength);
if (eatLength[0] <= 0) {
c = eatAmpersand(s, eatLength);
if (eatLength[0] <= 0) {
c = eatBackslash(s, eatLength);
if (eatLength[0] <= 0) {
c = eatUtf8(s, eatLength);
if (eatLength[0] <= 0) {
c = s.charAt(0);
eatLength[0] = 1;
}
}
}
}
b.append(c);
s = s.substring(eatLength[0]);
}
return (b.toString());
} | java | {
"resource": ""
} |
q163380 | Char.encodeXmlAttribute | train | public static String encodeXmlAttribute(String str) {
if (str == null) return null;
int len = str.length();
if (len == 0) return str;
StringBuffer encoded = new StringBuffer();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c == '<') encoded.append("<");
else if (c == '\"') encoded.append(""");
else if (c == '>') encoded.append(">");
else if (c == '\'') encoded.append("'");
else if (c == '&') encoded.append("&");
else encoded.append(c);
}
return encoded.toString();
} | java | {
"resource": ""
} |
q163381 | Char.encodeURIPathComponent | train | public static String encodeURIPathComponent(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
result.append(Char.encodeURIPathComponent(s.charAt(i)));
}
return (result.toString());
} | java | {
"resource": ""
} |
q163382 | Char.encodeURIPathComponentXML | train | public static String encodeURIPathComponentXML(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '&') result.append(Char.encodePercentage(s.charAt(i)));
else if (s.charAt(i) == '"') result.append(Char.encodePercentage(s.charAt(i)));
else result.append(Char.encodeURIPathComponent(s.charAt(i)));
}
return (result.toString());
} | java | {
"resource": ""
} |
q163383 | Char.encodeUTF8 | train | public static String encodeUTF8(String c) {
StringBuilder r = new StringBuilder();
for (int i = 0; i < c.length(); i++) {
r.append(encodeUTF8(c.charAt(i)));
}
return (r.toString());
} | java | {
"resource": ""
} |
q163384 | Char.normalize | train | public static String normalize(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++)
b.append(normalize(s.charAt(i)));
return (b.toString());
} | java | {
"resource": ""
} |
q163385 | Char.cutLast | train | public static String cutLast(String s) {
return (s.length() == 0 ? "" : s.substring(0, s.length() - 1));
} | java | {
"resource": ""
} |
q163386 | Char.hexAll | train | public static String hexAll(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
result.append(Integer.toHexString(s.charAt(i)).toUpperCase()).append(' ');
}
return (result.toString());
} | java | {
"resource": ""
} |
q163387 | Char.lowCaseFirst | train | public static String lowCaseFirst(String s) {
if (s == null || s.length() == 0) return (s);
return (Character.toLowerCase(s.charAt(0)) + s.substring(1));
} | java | {
"resource": ""
} |
q163388 | Char.truncate | train | public static CharSequence truncate(CharSequence s, int len) {
if (s.length() == len) return (s);
if (s.length() > len) return (s.subSequence(0, len));
StringBuilder result = new StringBuilder(s);
while (result.length() < len)
result.append(' ');
return (result);
} | java | {
"resource": ""
} |
q163389 | Char.capitalize | train | public static String capitalize(String s) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i == 0 || i > 0 && !Character.isLetterOrDigit(s.charAt(i - 1))) c = Character.toUpperCase(c);
else c = Character.toLowerCase(c);
result.append(c);
}
return (result.toString());
} | java | {
"resource": ""
} |
q163390 | Char.endsWith | train | public static boolean endsWith(CharSequence s, String end) {
return (s.length() >= end.length() && s.subSequence(s.length() - end.length(), s.length()).equals(end));
} | java | {
"resource": ""
} |
q163391 | StructrOAuthClient.getServer | train | public static StructrOAuthClient getServer(final String name) {
String configuredOauthServers = Settings.OAuthServers.getValue();
String[] authServers = configuredOauthServers.split(" ");
for (String authServer : authServers) {
if (authServer.equals(name)) {
String authLocation = Settings.getOrCreateStringSetting("oauth", authServer, "authorization_location").getValue("");
String tokenLocation = Settings.getOrCreateStringSetting("oauth", authServer, "token_location").getValue("");
String clientId = Settings.getOrCreateStringSetting("oauth", authServer, "client_id").getValue("");
String clientSecret = Settings.getOrCreateStringSetting("oauth", authServer, "client_secret").getValue("");
String redirectUri = Settings.getOrCreateStringSetting("oauth", authServer, "redirect_uri").getValue("");
// Minumum required fields
if (clientId != null && clientSecret != null && redirectUri != null) {
Class serverClass = getServerClassForName(name);
Class tokenResponseClass = getTokenResponseClassForName(name);
if (serverClass != null) {
StructrOAuthClient oauthServer;
try {
oauthServer = (StructrOAuthClient) serverClass.newInstance();
oauthServer.init(authLocation, tokenLocation, clientId, clientSecret, redirectUri, tokenResponseClass);
logger.info("Using OAuth server {}", oauthServer);
return oauthServer;
} catch (Throwable t) {
logger.error("Could not instantiate auth server", t);
}
} else {
logger.warn("No OAuth provider found for name {}, ignoring.", name);
}
}
}
}
return null;
} | java | {
"resource": ""
} |
q163392 | FileHelper.transformFile | train | public static <T extends File> T transformFile(final SecurityContext securityContext, final String uuid, final Class<T> fileType) throws FrameworkException, IOException {
AbstractFile existingFile = getFileByUuid(securityContext, uuid);
if (existingFile != null) {
existingFile.unlockSystemPropertiesOnce();
existingFile.setProperties(securityContext, new PropertyMap(AbstractNode.type, fileType == null ? File.class.getSimpleName() : fileType.getSimpleName()));
existingFile = getFileByUuid(securityContext, uuid);
return (T)(fileType != null ? fileType.cast(existingFile) : (File) existingFile);
}
return null;
} | java | {
"resource": ""
} |
q163393 | FileHelper.createFileBase64 | train | public static <T extends File> T createFileBase64(final SecurityContext securityContext, final String rawData, final Class<T> t) throws FrameworkException, IOException {
Base64URIData uriData = new Base64URIData(rawData);
return createFile(securityContext, uriData.getBinaryData(), uriData.getContentType(), t);
} | java | {
"resource": ""
} |
q163394 | FileHelper.createFile | train | public static <T extends File> T createFile(final SecurityContext securityContext, final InputStream fileStream, final String contentType, final Class<T> fileType, final String name)
throws FrameworkException, IOException {
return createFile(securityContext, fileStream, contentType, fileType, name, null);
} | java | {
"resource": ""
} |
q163395 | FileHelper.decodeAndSetFileData | train | public static void decodeAndSetFileData(final File file, final String rawData) throws FrameworkException, IOException {
Base64URIData uriData = new Base64URIData(rawData);
setFileData(file, uriData.getBinaryData(), uriData.getContentType(), true);
} | java | {
"resource": ""
} |
q163396 | FileHelper.setFileData | train | public static void setFileData(final File file, final InputStream fileStream, final String contentType) throws FrameworkException, IOException {
FileHelper.writeToFile(file, fileStream);
setFileProperties(file, contentType);
} | java | {
"resource": ""
} |
q163397 | FileHelper.setFileProperties | train | public static void setFileProperties (final File file, final String contentType) throws IOException, FrameworkException {
final java.io.File fileOnDisk = file.getFileOnDisk(false);
final PropertyMap map = new PropertyMap();
map.put(StructrApp.key(File.class, "contentType"), contentType != null ? contentType : FileHelper.getContentMimeType(fileOnDisk, file.getProperty(File.name)));
map.put(StructrApp.key(File.class, "size"), FileHelper.getSize(fileOnDisk));
map.put(StructrApp.key(File.class, "version"), 1);
map.putAll(getChecksums(file, fileOnDisk));
file.setProperties(file.getSecurityContext(), map);
} | java | {
"resource": ""
} |
q163398 | FileHelper.setFileProperties | train | public static void setFileProperties (File fileNode) throws FrameworkException {
final PropertyMap properties = new PropertyMap();
String id = fileNode.getProperty(GraphObject.id);
if (id == null) {
final String newUuid = UUID.randomUUID().toString().replaceAll("[\\-]+", "");
id = newUuid;
fileNode.unlockSystemPropertiesOnce();
properties.put(GraphObject.id, newUuid);
}
fileNode.unlockSystemPropertiesOnce();
fileNode.setProperties(fileNode.getSecurityContext(), properties);
} | java | {
"resource": ""
} |
q163399 | FileHelper.getChecksums | train | private static PropertyMap getChecksums(final File file, final java.io.File fileOnDisk) throws IOException {
final PropertyMap propertiesWithChecksums = new PropertyMap();
Folder parentFolder = file.getParent();
String checksums = null;
while (parentFolder != null && checksums == null) {
checksums = parentFolder.getEnabledChecksums();
parentFolder = parentFolder.getParent();
}
if (checksums == null) {
checksums = Settings.DefaultChecksums.getValue();
}
// New, very fast xxHash default checksum, will always be calculated
propertiesWithChecksums.put(StructrApp.key(File.class, "checksum"), FileHelper.getChecksum(fileOnDisk));
if (StringUtils.contains(checksums, "crc32")) {
propertiesWithChecksums.put(StructrApp.key(File.class, "crc32"), FileHelper.getCRC32Checksum(fileOnDisk));
}
if (StringUtils.contains(checksums, "md5")) {
propertiesWithChecksums.put(StructrApp.key(File.class, "md5"), FileHelper.getMD5Checksum(file));
}
if (StringUtils.contains(checksums, "sha1")) {
propertiesWithChecksums.put(StructrApp.key(File.class, "sha1"), FileHelper.getSHA1Checksum(file));
}
if (StringUtils.contains(checksums, "sha512")) {
propertiesWithChecksums.put(StructrApp.key(File.class, "sha512"), FileHelper.getSHA512Checksum(file));
}
return propertiesWithChecksums;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.