code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
protected String getImgSrcToRender() throws JspException { BinaryResourcesHandler binaryRsHandler = (BinaryResourcesHandler) pageContext.getServletContext() .getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE); if (null == binaryRsHandler) throw new JspException( "You are using a Jawr image tag while the Jawr Binary servlet has not been initialized. Initialization of Jawr Image servlet either failed or never occurred."); HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); return ImageTagUtils.getImageUrl(src, base64, binaryRsHandler, request, response); }
Returns the image source to render @return the image source to render @throws JspException if a JSP exception occurs.
public static String rewriteGeneratedBinaryResourceDebugUrl(String requestPath, String content, String binaryServletMapping) { // Write the content of the CSS in the Stringwriter if (binaryServletMapping == null) { binaryServletMapping = ""; } // Define the replacement pattern for the generated binary resource // (like jar:img/myImg.png) String relativeRootUrlPath = PathNormalizer.getRootRelativePath(requestPath); String replacementPattern = PathNormalizer .normalizePath("$1" + relativeRootUrlPath + binaryServletMapping + "/$5_cbDebug/$7$8"); Matcher matcher = GENERATED_BINARY_RESOURCE_PATTERN.matcher(content); // Rewrite the images define in the classpath, to point to the image // servlet StringBuffer result = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(result, replacementPattern); } matcher.appendTail(result); return result.toString(); }
Rewrites the generated binary resource URL for debug mode @param requestPath the request path @param content the content to rewrite @param binaryServletMapping the binary servlet mapping @return the rewritten content
@Override protected int msd(BigInteger a, BigInteger b) { if (a.equals(b)) { return -1; } /* * return floor(log_2(a xor b)). */ return a.xor(b).bitLength() - 1; }
{@inheritDoc}
@Override public void put(String key, Object obj) { cache.put(new Element(key, obj)); }
/* (non-Javadoc) @see net.jawr.web.cache.AbstractCacheManager#put(java.lang.String, java.lang.Object)
@Override public Object remove(String key) { Element element = cache.get(key); if (element != null) { cache.remove(key); } return element; }
/* (non-Javadoc) @see net.jawr.web.cache.AbstractCacheManager#remove(java.lang.String)
public List<T> execute(HyperionClient client) { EntityList<T> entityResponse = client.update(build()); return entityResponse.getEntries(); }
Execute the request using the supplied client @param client the client @return The request
@Override protected Node<K, V> unionWithComparator(Node<K, V> root1, Node<K, V> root2) { if (root1 == null) { return root2; } else if (root2 == null) { return root1; } Node<K, V> newRoot; Deque<LeftistNode<K, V>> path = new LinkedList<LeftistNode<K, V>>(); // find initial int c = comparator.compare(root1.key, root2.key); if (c <= 0) { newRoot = root1; root1 = unlinkRightChild(root1); } else { newRoot = root2; root2 = unlinkRightChild(root2); } Node<K, V> cur = newRoot; path.push((LeftistNode<K, V>) cur); // merge while (root1 != null && root2 != null) { c = comparator.compare(root1.key, root2.key); if (c <= 0) { // link as right child of cur if (cur.o_c == null) { cur.o_c = root1; } else { cur.o_c.y_s = root1; } root1.y_s = cur; cur = root1; path.push((LeftistNode<K, V>) cur); root1 = unlinkRightChild(root1); } else { // link as right child of cur if (cur.o_c == null) { cur.o_c = root2; } else { cur.o_c.y_s = root2; } root2.y_s = cur; cur = root2; path.push((LeftistNode<K, V>) cur); root2 = unlinkRightChild(root2); } } if (root1 != null) { // link as right child of cur if (cur.o_c == null) { cur.o_c = root1; } else { cur.o_c.y_s = root1; } root1.y_s = cur; } if (root2 != null) { // link as right child of cur if (cur.o_c == null) { cur.o_c = root2; } else { cur.o_c.y_s = root2; } root2.y_s = cur; } /* * Traverse path upwards, update null path length and swap if needed. */ while (!path.isEmpty()) { LeftistNode<K, V> n = path.pop(); if (n.o_c != null) { // at least on child LeftistNode<K, V> nLeft = (LeftistNode<K, V>) n.o_c; int nplLeft = nLeft.npl; int nplRight = -1; if (nLeft.y_s != n) { // two children LeftistNode<K, V> nRight = (LeftistNode<K, V>) nLeft.y_s; nplRight = nRight.npl; } n.npl = 1 + Math.min(nplLeft, nplRight); if (nplLeft < nplRight) { // swap swapChildren(n); } } else { // no children n.npl = 0; } } return newRoot; }
Top-down union of two leftist heaps with comparator. @param root1 the root of the first heap @param root2 the root of the right heap @return the new root of the merged heap
boolean rule1(final IFactory factory, final Inclusion[] gcis) { boolean result = false; // TODO: make this "binarisation" more efficient by doing it for all // elements rather than relying on multiple calls to this rule and // stripping off one Role for each call. if (lhs.length > 2) { result = true; final int k = lhs.length - 1; int[] newLhs1 = new int[k]; System.arraycopy(lhs, 0, newLhs1, 0, newLhs1.length); int u = factory.getRole(newLhs1); int[] newLhs2 = { u, lhs[k] }; gcis[0] = new RI(newLhs1, u); gcis[1] = new RI(newLhs2, rhs); } return result; }
r<sub>1</sub> &#8728; &#133; &#8728; r<sub>k</sub> &#8849; s &rarr; {r<sub>1</sub> &#8728; &#133; &#8728; r<sub>k-1</sub> &#8849; u, u &#8728; r<sub>k</sub> &#8849; s} @param gcis @return
private void initReader(Object obj) { if (obj instanceof WorkingDirectoryLocationAware) { ((WorkingDirectoryLocationAware) obj).setWorkingDirectory(workingDirectory); } if (obj instanceof ServletContextAware) { ((ServletContextAware) obj).setServletContext(servletContext); } if (obj instanceof ResourceBrowser) { resourceInfoProviders.add(0, (ResourceBrowser) obj); } }
Initialize the reader @param obj the reader to initialize
@Override public Set<String> getResourceNames(String dirName) { Set<String> resourceNames = new TreeSet<>(); List<ResourceBrowser> list = new ArrayList<>(); list.addAll(resourceInfoProviders); for (ResourceBrowser rsBrowser : list) { if (generatorRegistry.isPathGenerated(dirName)) { if (rsBrowser instanceof ResourceGenerator) { ResourceGenerator rsGeneratorBrowser = (ResourceGenerator) rsBrowser; if (rsGeneratorBrowser.getResolver().matchPath(dirName)) { resourceNames.addAll(rsBrowser.getResourceNames(dirName)); break; } } } else { if (!(rsBrowser instanceof ResourceGenerator)) { resourceNames.addAll(rsBrowser.getResourceNames(dirName)); break; } } } return resourceNames; }
/* (non-Javadoc) @see net.jawr.web.resource.handler.reader.ResourceBrowser#getResourceNames (java.lang.String)
@Override public boolean isDirectory(String resourceName) { boolean result = false; List<ResourceBrowser> list = new ArrayList<>(); list.addAll(resourceInfoProviders); for (Iterator<ResourceBrowser> iterator = list.iterator(); iterator.hasNext() && !result;) { ResourceBrowser rsBrowser = iterator.next(); if (generatorRegistry.isPathGenerated(resourceName)) { if (rsBrowser instanceof ResourceGenerator) { ResourceGenerator rsGeneratorBrowser = (ResourceGenerator) rsBrowser; if (rsGeneratorBrowser.getResolver().matchPath(resourceName)) { result = rsBrowser.isDirectory(resourceName); } } } else { if (!(rsBrowser instanceof ResourceGenerator)) { result = rsBrowser.isDirectory(resourceName); } } } return result; }
/* (non-Javadoc) @see net.jawr.web.resource.handler.reader.ResourceBrowser#isDirectory(java .lang.String)
@Override public String getFilePath(String resourcePath) { String filePath = null; List<ResourceBrowser> list = new ArrayList<>(); list.addAll(resourceInfoProviders); for (Iterator<ResourceBrowser> iterator = list.iterator(); iterator.hasNext() && filePath == null;) { ResourceBrowser rsBrowser = iterator.next(); if (generatorRegistry.isPathGenerated(resourcePath)) { if (rsBrowser instanceof ResourceGenerator) { ResourceGenerator rsGeneratorBrowser = (ResourceGenerator) rsBrowser; if (rsGeneratorBrowser.getResolver().matchPath(resourcePath)) { filePath = rsBrowser.getFilePath(resourcePath); } } } else { if (!(rsBrowser instanceof ResourceGenerator)) { filePath = rsBrowser.getFilePath(resourcePath); } } } return filePath; }
/* (non-Javadoc) @see net.jawr.web.resource.handler.reader.ResourceReaderHandler#getFilePath( java.lang.String)
@Override public void afterPropertiesSet() { this.urlRewriter = new CssImageUrlRewriter(config); cssSkinResolver = (AbstractCssSkinVariantResolver) config.getGeneratorRegistry() .getVariantResolver(JawrConstant.SKIN_VARIANT_TYPE); if (cssSkinResolver == null) { cssSkinResolver = new CssSkinVariantResolver(); config.getGeneratorRegistry().registerVariantResolver(cssSkinResolver); } // Init skin mapping String cfgSkinMappingType = config.getProperty(JawrConstant.SKIN_TYPE_MAPPING_CONFIG_PARAM); if (StringUtils.isNotEmpty(cfgSkinMappingType)) { if (cfgSkinMappingType.equals(JawrConstant.SKIN_TYPE_MAPPING_LOCALE_SKIN) || cfgSkinMappingType.equals(JawrConstant.SKIN_TYPE_MAPPING_SKIN_LOCALE)) { this.skinMappingType = cfgSkinMappingType; } else { throw new IllegalArgumentException( "The value for the '" + JawrConstant.SKIN_TYPE_MAPPING_LOCALE_SKIN + "' " + "property [" + cfgSkinMappingType + "] is invalid. " + "Please check the docs for valid values "); } } this.skinMapping = getSkinMapping(rsBrowser, config); resourceProviderStrategyClass = CssSkinVariantResourceProviderStrategy.class; }
/* (non-Javadoc) @see net.jawr.web.resource.bundle.generator. PostInitializationAwareResourceGenerator#afterPropertiesSet()
@Override protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData) throws IOException { if (minifier == null) { boolean keepLicence = status.getJawrConfig().getBooleanProperty(JAWR_CSS_POSTPROCESSOR_CSSMIN_KEEP_LICENCE, false); this.minifier = new CSSMinifier(keepLicence); } try { return minifier.minifyCSS(bundleData); } catch (StackOverflowError e) { throw new Error( "An error occured while processing the bundle '" + status.getCurrentBundle().getName() + "'", e); } }
/* (non-Javadoc) @see net.jawr.web.resource.bundle.postprocess.impl. AbstractChainedResourceBundlePostProcessor#doPostProcessBundle(net.jawr. web.resource.bundle.postprocess.BundleProcessingStatus, java.lang.StringBuffer)
@Override public <T extends ApiObject> EntityResponse<T> query(Request<T> request) { LegacyEntityResponse<T> legacyResponse = executeRequest(request, objectMapper.getTypeFactory() .constructParametrizedType(LegacyEntityResponse.class, LegacyEntityResponse.class, request.getEntityType())); EntityResponse<T> response = new EntityResponse<T>(); response.setEntries(legacyResponse.getEntries()); Page page = new Page(); response.setPage(page); page.setStart(legacyResponse.getStart()); page.setResponseCount(legacyResponse.getResponseCount()); page.setTotalCount(legacyResponse.getTotalCount()); return response; }
{@inheritDoc}
@Override public <T extends ApiObject> EntityList<T> create(Request<T> request) { EntityList<T> requestList = (EntityList<T>) request.getRequestBody(); if(requestList.getEntries().size() > 1) throw new InternalException("V1 calls can only have a single entry on create."); T item = requestList.getEntries().get(0); request.setRequestBody(item); T legacyResponse = executeRequest(request,objectMapper.getTypeFactory().constructType(request.getEntityType())); EntityList<T> response = new EntityList<>(); List<T> list = new ArrayList<>(); response.setEntries(list); list.add(legacyResponse); return response; }
{@inheritDoc}
private void performInitializations() { try { BMSClient.getInstance().initialize(getApplicationContext(), backendURL, backendGUID, BMSClient.REGION_US_SOUTH); } catch (MalformedURLException e) { e.printStackTrace(); } MCAAuthorizationManager mcaAuthorizationManager = MCAAuthorizationManager.createInstance(this.getApplicationContext()); mcaAuthorizationManager.registerAuthenticationListener(customRealm, new MyChallengeHandler()); // to make the authorization happen next time mcaAuthorizationManager.clearAuthorizationData(); BMSClient.getInstance().setAuthorizationManager(mcaAuthorizationManager); Logger.setLogLevel(Logger.LEVEL.DEBUG); Logger.setSDKDebugLoggingEnabled(true); }
Initialize BMSClient and set the authorization manager
private void getNetworkInfo() { // Create a listener to check for new network connections (e.g. switching from mobile to Wifi, or losing internet connection) NetworkConnectionListener listener = new NetworkConnectionListener() { @Override public void networkChanged(NetworkConnectionType newConnection) { Log.i("BMSCore", "New network connection: " + newConnection.toString()); } }; // Initilize the network monitor with the application context and network change listener this.networkMonitor = new NetworkMonitor(getApplicationContext(), listener); // Start listening for network changes networkMonitor.startMonitoringNetworkChanges(); // See if the device currently has internet access, and see what type of connection it is using Log.i("BMSCore", "Is connected to the internet: " + networkMonitor.isInternetAccessAvailable()); Log.i("BMSCore", "Connection type: " + networkMonitor.getCurrentConnectionType().toString()); // Check that the user has given permissions to read the phone's state. // If permission is granted, get the type of mobile data network being used. int networkPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE); if (networkPermission == PackageManager.PERMISSION_GRANTED) { Log.i("BMSCore", "Mobile network type: " + networkMonitor.getMobileNetworkType()); } else { Log.i("BMSCore", "Obtaining permission to read phone state"); if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { // Asynchronously explain to the user why you are attempting to request this permission. // Once this is done, try to request the permission again. } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, MY_PERMISSIONS_READ_PHONE_STATE); } } }
Exercise the NetworkMonitor API
private void sendSomeRequests() { ResponseListener responseListener = new MyResponseListener(); sendCustomUrlRequest(responseListener); sendAutoRetryRequest(responseListener); downloadImage(responseListener); uploadData(responseListener); uploadFile(responseListener); uploadText(responseListener); }
Exercise the Request and Response APIs
private void sendAutoRetryRequest(ResponseListener responseListener) { Log.i("BMSCore", String.format("\n\nSending request to 504 endpoint")); Request request504 = new Request("http://httpstat.us/504", Request.POST, 1000, 5); request504.send(getApplicationContext(), "Sample upload text", responseListener); }
Exercise auto-retries by trying to resend a request up to 5 times with a 504 (gateway timeout) response
public T execute(HyperionClient client) { EntityList<T> entityResponse = client.update(build()); List<T> entries = entityResponse.getEntries(); return entries.size() == 0 ? null : entries.get(0); }
Execute the request using the supplied client @param client the client @return The request
public void startAuthorizationProcess(final Context context, ResponseListener listener) { authorizationQueue.add(listener); //start the authorization process only if this is the first time we ask for authorization if (authorizationQueue.size() == 1) { try { if (preferences.clientId.get() == null) { logger.info("starting registration process"); invokeInstanceRegistrationRequest(context); } else { logger.info("starting authorization process"); invokeAuthorizationRequest(context); } } catch (Throwable t) { handleAuthorizationFailure(t); } } else{ logger.info("authorization process already running, adding response listener to the queue"); logger.debug(String.format("authorization process currently handling %d requests", authorizationQueue.size())); } }
Main method to start authorization process @param context android context @param listener response listener that will get the result of the process
public void logout(Context context, ResponseListener listener) { AuthorizationRequestManager.RequestOptions options = new AuthorizationRequestManager.RequestOptions(); options.parameters = new HashMap<String,String>(1); options.parameters.put("client_id", preferences.clientId.get()); options.headers = new HashMap<>(1); addSessionIdHeader(options.headers); options.requestMethod = Request.GET; try { authorizationRequestSend(context,"logout", options, listener); } catch (Exception e) { logger.debug("Could not log out"); } }
logs out user @param context Android Activity that will handle the authorization (like facebook or google) @param listener Response listener
private void invokeInstanceRegistrationRequest(final Context context) { AuthorizationRequestManager.RequestOptions options = new AuthorizationRequestManager.RequestOptions(); options.parameters = createRegistrationParams(); options.headers = createRegistrationHeaders(); options.requestMethod = Request.POST; InnerAuthorizationResponseListener listener = new InnerAuthorizationResponseListener() { @Override public void handleAuthorizationSuccessResponse(Response response) throws Exception { saveCertificateFromResponse(response); invokeAuthorizationRequest(context); } }; authorizationRequestSend(null, "clients/instance", options, listener); }
Invoke request for registration, the result of the request should contain ClientId. @param context android context
private HashMap<String, String> createRegistrationParams() { registrationKeyPair = KeyPairUtility.generateRandomKeyPair(); JSONObject csrJSON = new JSONObject(); HashMap<String, String> params; try { DeviceIdentity deviceData = new BaseDeviceIdentity(preferences.deviceIdentity.getAsMap()); AppIdentity applicationData = new BaseAppIdentity(preferences.appIdentity.getAsMap()); csrJSON.put("deviceId", deviceData.getId()); csrJSON.put("deviceOs", "" + deviceData.getOS()); csrJSON.put("deviceModel", deviceData.getModel()); csrJSON.put("applicationId", applicationData.getId()); csrJSON.put("applicationVersion", applicationData.getVersion()); csrJSON.put("environment", "android"); String csrValue = jsonSigner.sign(registrationKeyPair, csrJSON); params = new HashMap<>(1); params.put("CSR", csrValue); return params; } catch (Exception e) { throw new RuntimeException("Failed to create registration params", e); } }
Generate the params that will be used during the registration phase @return Map with all the parameters
private HashMap<String, String> createRegistrationHeaders() { HashMap<String, String> headers = new HashMap<>(); addSessionIdHeader(headers); return headers; }
Generate the headers that will be used during the registration phase @return Map with all the headers
private HashMap<String, String> createTokenRequestParams(String grantCode) { HashMap<String, String> params = new HashMap<>(); params.put("code", grantCode); params.put("client_id", preferences.clientId.get()); params.put("grant_type", "authorization_code"); params.put("redirect_uri", HTTP_LOCALHOST); return params; }
Generate the params that will be used during the token request phase @param grantCode from the authorization phase @return Map with all the headers
private void saveCertificateFromResponse(Response response) { try { String responseBody = response.getResponseText(); JSONObject jsonResponse = new JSONObject(responseBody); //handle certificate String certificateString = jsonResponse.getString("certificate"); X509Certificate certificate = CertificatesUtility.base64StringToCertificate(certificateString); CertificatesUtility.checkValidityWithPublicKey(certificate, registrationKeyPair.getPublic()); certificateStore.saveCertificate(registrationKeyPair, certificate); //save the clientId separately preferences.clientId.set(jsonResponse.getString("clientId")); } catch (Exception e) { throw new RuntimeException("Failed to save certificate from response", e); } logger.debug("certificate successfully saved"); }
Extract the certificate data from response and save it on local storage @param response contains the certificate data
private void invokeAuthorizationRequest(Context context) { AuthorizationRequestManager.RequestOptions options = new AuthorizationRequestManager.RequestOptions(); options.parameters = createAuthorizationParams(); options.headers = new HashMap<>(1); addSessionIdHeader(options.headers); options.requestMethod = Request.GET; InnerAuthorizationResponseListener listener = new InnerAuthorizationResponseListener() { @Override public void handleAuthorizationSuccessResponse(Response response) throws Exception { String location = extractLocationHeader(response); String grantCode = extractGrantCode(location); invokeTokenRequest(grantCode); } }; authorizationRequestSend(context, "authorization", options, listener); }
Invoke the authorization request, the result of the request should be a grant code @param context android activity that will handle authentication (facebook, google)
private HashMap<String, String> createAuthorizationParams() { HashMap<String, String> params = new HashMap<>(3); params.put("response_type", "code"); params.put("client_id", preferences.clientId.get()); params.put("redirect_uri", HTTP_LOCALHOST); return params; }
Generate the params that will be used during the authorization phase @return Map with all the params
private String extractGrantCode(String urlString) throws MalformedURLException { URL url = new URL(urlString); String code = Utils.getParameterValueFromQuery(url.getQuery(), "code"); if (code == null){ throw new RuntimeException("Failed to extract grant code from url"); } logger.debug("Grant code extracted successfully"); return code; }
Extract grant code from url string @param urlString url that contain the grant code @return grant code @throws MalformedURLException in case of illegal url format
private void invokeTokenRequest(String grantCode) { AuthorizationRequestManager.RequestOptions options = new AuthorizationRequestManager.RequestOptions(); options.parameters = createTokenRequestParams(grantCode); options.headers = createTokenRequestHeaders(grantCode); addSessionIdHeader(options.headers); options.requestMethod = Request.POST; InnerAuthorizationResponseListener listener = new InnerAuthorizationResponseListener() { @Override public void handleAuthorizationSuccessResponse(Response response) throws Exception { saveTokenFromResponse(response); handleAuthorizationSuccess(response); } }; authorizationRequestSend(null, "token", options, listener); }
Invoke request to get token, the result of the response should be a valid token @param grantCode grant code that will be used during the request
private HashMap<String, String> createTokenRequestHeaders(String grantCode) { JSONObject payload = new JSONObject(); HashMap<String, String> headers; try { payload.put("code", grantCode); KeyPair keyPair = certificateStore.getStoredKeyPair(); String jws = jsonSigner.sign(keyPair, payload); headers = new HashMap<>(1); headers.put("X-WL-Authenticate", jws); } catch (Exception e) { throw new RuntimeException("Failed to create token request headers", e); } return headers; }
Generate the headers that will be used during the token request phase @param grantCode from the authorization phase @return Map with all the headers
private void saveTokenFromResponse(Response response) { try { JSONObject responseJSON = ((ResponseImpl)response).getResponseJSON(); String accessToken = responseJSON.getString("access_token"); String idToken = responseJSON.getString("id_token"); //save the tokens preferences.accessToken.set(accessToken); preferences.idToken.set(idToken); //save the user identity separately String[] idTokenData = idToken.split("\\."); byte[] decodedIdTokenData = Base64.decode(idTokenData[1], Base64.DEFAULT); String decodedIdTokenString = new String(decodedIdTokenData); JSONObject idTokenJSON = new JSONObject(decodedIdTokenString); if (idTokenJSON.has("imf.user")) { preferences.userIdentity.set(idTokenJSON.getJSONObject("imf.user")); } logger.debug("token successfully saved"); } catch (Exception e) { throw new RuntimeException("Failed to save token from response", e); } }
Extract token from response and save it locally @param response response that contain the token
private void authorizationRequestSend(final Context context, String path, AuthorizationRequestManager.RequestOptions options, ResponseListener listener) { try { AuthorizationRequestManager authorizationRequestManager = new AuthorizationRequestManager(); authorizationRequestManager.initialize(context, listener); authorizationRequestManager.sendRequest(path, options); } catch (Exception e) { throw new RuntimeException("Failed to send authorization request", e); } }
Use authorization request agent for sending the request @param context android activity that will handle authentication (facebook, google) @param path path to the server @param options send options @param listener response listener
private void handleAuthorizationFailure(Response response, Throwable t, JSONObject extendedInfo) { logger.error("authorization process failed"); if (t != null) { t.printStackTrace(); } Iterator<ResponseListener> iterator = authorizationQueue.iterator(); while(iterator.hasNext()) { ResponseListener next = iterator.next(); next.onFailure(response, t, extendedInfo); iterator.remove(); } }
Handle failure in the authorization process. All the response listeners will be updated with failure @param response response that caused to failure @param t additional info about the failure
private void handleAuthorizationSuccess(Response response) { Iterator<ResponseListener> iterator = authorizationQueue.iterator(); while(iterator.hasNext()) { ResponseListener next = iterator.next(); next.onSuccess(response); iterator.remove(); } }
Handle success in the authorization process. All the response listeners will be updated with success @param response final success response from the server
public static String adaptReplacementToMatcher(String replacement) { // Double the backslashes, so they are left as they are after replacement. String result = replacement.replaceAll("\\\\", "\\\\\\\\"); // Add backslashes after dollar signs result = result.replaceAll("\\$", "\\\\\\$"); return result; }
Fixes a bad problem with regular expression replacement strings. Replaces \ and $ for escaped versions for regex replacement. This was somehow fixed in java 5 (a similar method was added). Since Jawr supports 1.4, this method is used instead. @param replacement @return
public void setProxy(Proxy proxy) { if(proxy != null) { java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getPort())); client.setProxy(p); } else client.setProxy(java.net.Proxy.NO_PROXY); }
Set the proxy configuration to use for this client. @param proxy The proxy configuration
public void setKeepAliveConfiguration(KeepAliveConfiguration keepAliveConfiguration) { if(keepAliveConfiguration != null) client.setConnectionPool(new ConnectionPool(keepAliveConfiguration.getMaxIdleConnections(), keepAliveConfiguration.getKeepAliveDurationMs())); }
Set the keep alive configuration to use for this client. @param keepAliveConfiguration The keep alive configuration
public void setLogger(String logger) { if(logger != null && logger.trim().length() > 0) this.logger = LoggerFactory.getLogger(logger); }
Set an alternate logger for this client to use for log statements. This can be used to direct client logs to different destinations. The default value is "com.dottydingo.hyperion.client.HyperionClient" @param logger The logger to use
public <T extends ApiObject> EntityList<T> get(Request<T> request) { return executeRequest(request,objectMapper.getTypeFactory() .constructParametrizedType(EntityList.class,EntityList.class, request.getEntityType())); }
Perform a get (GET) operation using the supplied request. @param request The request @return The results of the get operation
public <T extends ApiObject> EntityResponse<T> query(Request<T> request) { return executeRequest(request, objectMapper.getTypeFactory() .constructParametrizedType(EntityResponse.class, EntityResponse.class, request.getEntityType())); }
Perform a query (GET) operation using the supplied request @param request The request @return The results of the query operation
public int delete(Request request) { DeleteResponse response = executeRequest(request,objectMapper.getTypeFactory().constructType( DeleteResponse.class)); return response.getCount(); }
Perform a delete (DELETE) operation using the supplied request @param request The request @return The number of items deleted
protected <R> R executeRequest(Request request, JavaType javaType) { long start = System.currentTimeMillis(); boolean error = true; try { Response response = executeRequest(request); R r = readResponse(response, javaType); error = false; return r; } finally { if(clientEventListener != null) { ClientEvent event = new ClientEvent(baseUrl,request.getEntityName(),request.getRequestMethod(), System.currentTimeMillis() - start,error); clientEventListener.handleEvent(event); } } }
Execute the request @param request The request @param javaType The return type @return The response
protected com.squareup.okhttp.Request buildHttpRequest(Request request) { RequestBody requestBody = null; if(request.getRequestMethod().isBodyRequest()) requestBody = RequestBody.create(JSON, serializeBody(request)); return new com.squareup.okhttp.Request.Builder() .url(buildUrl(request)) .headers(getHeaders(request)) .method(request.getRequestMethod().name(),requestBody) .build(); }
Build the actual http request @param request The data service request @return The http request
protected Response executeRequest(Request request) { try { com.squareup.okhttp.Request httpRequest = buildHttpRequest(request); if(logger.isInfoEnabled()) logger.info("Sending request: {} {}",httpRequest.method(),httpRequest.urlString()); if(logger.isDebugEnabled() && request.getRequestMethod().isBodyRequest()) { Buffer buffer = new Buffer(); httpRequest.body().writeTo(buffer); if(maxLoggedBodySize == -1 || buffer.size() <= maxLoggedBodySize ) logger.debug("Request body: {}", buffer.readUtf8()); else logger.debug("Request body not captured: too large. "); } if(logger.isTraceEnabled()) logger.trace("Request headers: {}",httpRequest.headers().toString()); Response response = client.newCall(httpRequest).execute(); if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && authorizationFactory != null && authorizationFactory.retryOnAuthenticationError()) { if(authorizationFactory instanceof ResettableAuthorizationFactory) ((ResettableAuthorizationFactory) authorizationFactory).reset(); response = client.newCall(httpRequest).execute(); } logger.info("Response code: {}",response.code()); if(logger.isTraceEnabled()) logger.trace("Response headers: {}",response.headers().toString()); if(logger.isDebugEnabled()) { ByteArrayOutputStream copy = new ByteArrayOutputStream(); copy(response.body().byteStream(),copy); response = response.newBuilder().body(ResponseBody.create(response.body().contentType(),copy.toByteArray())).build(); if(maxLoggedBodySize == -1 || copy.size() <= maxLoggedBodySize) logger.debug("Response body: {}",copy.toString()); else logger.debug("Response body not captured: too large."); } if (response.code() >= HttpURLConnection.HTTP_BAD_REQUEST) { throw readException(response); } return response; } catch (IOException e) { throw new ClientConnectionException("Error calling service.",e); } }
Execute the request @param request The data service request @return The HTTP response
protected <T> T readResponse(Response response,JavaType javaType) { try { return objectMapper.readValue(response.body().byteStream(), javaType); } catch (IOException e) { throw new ClientMarshallingException("Error reading results.",e); } }
Read the response and unmarshall into the expected type @param response The http response @param javaType The type to return @return The response value
protected String serializeBody(Request request) { try { return objectMapper.writeValueAsString(request.getRequestBody()); } catch (JsonProcessingException e) { throw new ClientMarshallingException("Error writing request.",e); } }
Serialize the request body @param request The data service request @return The JSON representation of the request
protected HyperionException readException(Response response) throws IOException { ErrorResponse errorResponse = null; try { errorResponse = objectMapper.readValue(response.body().byteStream(), ErrorResponse.class); } catch (Exception ignore) { } HyperionException resolvedException = null; if (errorResponse != null) { try { Class exceptionClass = Class.forName(errorResponse.getType()); resolvedException = (HyperionException) exceptionClass.getConstructor(String.class) .newInstance(errorResponse.getMessage()); } catch (Throwable ignore) { } if (resolvedException == null) { resolvedException = new HyperionException(errorResponse.getStatusCode(), errorResponse.getMessage()); } resolvedException.setErrorDetails(errorResponse.getErrorDetails()); resolvedException.setErrorTime(errorResponse.getErrorTime()); resolvedException.setRequestId(errorResponse.getRequestId()); } if (resolvedException == null) { resolvedException = new HyperionException(response.code(), response.message()); } return resolvedException; }
Create the proper exception for the error response @param response The http response @return The exception for the error response @throws IOException
protected String buildUrl(Request request) { StringBuilder sb = new StringBuilder(512); sb.append(baseUrl).append(request.getEntityName()).append("/"); if(request.getPath() != null) sb.append(request.getPath()); String queryString = buildQueryString(request); if(queryString.length()>0) { sb.append("?").append(queryString); } return sb.toString(); }
Build the URL for the specified request @param request the data service request @return The URL string
protected String buildQueryString(Request request) { MultiMap resolvedParameters = null; if(parameterFactory != null) { resolvedParameters = parameterFactory.getParameters(); } if(hasEntries(resolvedParameters)) resolvedParameters = resolvedParameters.merge(request.getParameters()); else resolvedParameters = request.getParameters(); if(authorizationFactory != null) { MultiMap authEntries = authorizationFactory.getParameters(); if(hasEntries(authEntries)) resolvedParameters = resolvedParameters.merge(authEntries); } int ct = 0; StringBuilder sb = new StringBuilder(512); for (Map.Entry<String, List<String>> entry : resolvedParameters.entries()) { for (String value : entry.getValue()) { if(ct++ > 0) sb.append("&"); sb.append(encode(entry.getKey())).append("=").append(encode(value)); } } return sb.toString(); }
Build the query string for the specified request @param request the data service request @return The query string
protected Headers getHeaders(Request request) { Headers.Builder headers = new Headers.Builder(); MultiMap resolvedHeaders = null; if(headerFactory != null) resolvedHeaders = headerFactory.getHeaders(); if(hasEntries(resolvedHeaders)) resolvedHeaders = resolvedHeaders.merge(request.getHeaders()); else resolvedHeaders = request.getHeaders(); if(authorizationFactory != null) { MultiMap authEntries = authorizationFactory.getHeaders(); if(hasEntries(authEntries)) resolvedHeaders = resolvedHeaders.merge(authEntries); } if(resolvedHeaders.getFirst("user-agent") == null) headers.add("user-agent",userAgent); if(resolvedHeaders.getFirst(CLIENT_VERSION_HEADER_NAME) == null) headers.add(CLIENT_VERSION_HEADER_NAME,getClientVersion()); for (Map.Entry<String, List<String>> entry : resolvedHeaders.entries()) { for (String value : entry.getValue()) { headers.add(entry.getKey(), value); } } return headers.build(); }
Return the headers for the supplied request @param request The data service request @return The headers
protected String encode(String value) { try { return URLEncoder.encode(value,"UTF-8"); } catch (UnsupportedEncodingException e) { throw new ClientException(500,"Error encoding parameter.",e); } }
Encode the supplied string @param value The string @return The enclded value
protected void processLegacyRequest(HyperionContext hyperionContext) { EndpointRequest request = hyperionContext.getEndpointRequest(); EndpointResponse response = hyperionContext.getEndpointResponse(); ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin(); EntityPlugin plugin = hyperionContext.getEntityPlugin(); PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext); Set<String> fieldSet = persistenceContext.getRequestedFields(); if(fieldSet != null) fieldSet.add("id"); RequestContext<ApiObject<Serializable>> requestContext = null; try { requestContext = marshaller.unmarshallWithContext(request.getInputStream(), apiVersionPlugin.getApiClass()); } catch (MarshallingException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST, hyperionContext.getLocale(), e.getMessage()),e); } ApiObject clientObject = requestContext.getRequestObject(); List<Serializable> ids = convertIds(hyperionContext, plugin); if(ids.size() != 1) throw new BadRequestException(messageSource.getErrorMessage(ERROR_SINGLE_ID_REQUIRED,hyperionContext.getLocale())); persistenceContext.setProvidedFields(requestContext.getProvidedFields()); ApiObject saved = (ApiObject) plugin.getPersistenceOperations().updateItems( Collections.singletonList(clientObject), persistenceContext).get(0); processChangeEvents(hyperionContext,persistenceContext); response.setResponseCode(200); hyperionContext.setResult(saved); }
Process a legacy V1 request (single item) @param hyperionContext The context
IConceptSet get(int concept) { IConceptSet subsumes = set.get(concept); if (null == subsumes) { // A Concept always subsumes itself and TOP subsumes = new SparseConceptSet(); subsumes.add(concept); subsumes.add(IFactory.TOP_CONCEPT); set.put(concept, subsumes); size++; } return subsumes; }
/* (non-Javadoc) @see au.csiro.snorocket.Subsumptions#get(int)
IntIterator keyIterator() { return new IntIterator() { final IntIterator setitr = set.keyIterator(); public boolean hasNext() { return setitr.hasNext(); } public int next() { return setitr.next(); } }; }
Returns an iterator over the keys of this map. The keys are returned in no particular order. @return an iterator over the keys of this map.
@Override public void release() { super.release(); setBase64Expr(null); setAlignExpr(null); setAltExpr(null); setBorderExpr(null); setDirExpr(null); setDisabledExpr(null); setLangExpr(null); setOnblurExpr(null); setOnchangeExpr(null); setOnclickExpr(null); setOndblclickExpr(null); setOnfocusExpr(null); setOnkeydownExpr(null); setOnkeypressExpr(null); setOnkeyupExpr(null); setOnmousedownExpr(null); setOnmousemoveExpr(null); setOnmouseoutExpr(null); setOnmouseoverExpr(null); setOnmouseupExpr(null); setSrcExpr(null); setStyleExpr(null); setStyleClassExpr(null); setStyleIdExpr(null); setTabindexExpr(null); setTitleExpr(null); setValueExpr(null); }
Resets attribute values for tag reuse.
private void evaluateExpressions() throws JspException { String string = null; Boolean bool = null; if (getBase64Expr() != null && (bool = EvalHelper.evalBoolean("base64", getBase64Expr(), this, pageContext)) != null) { setBase64(bool.booleanValue()); } // The "align" attribute is deprecated. This needs to be removed when // the "align" attribute is finally removed. if (getAlignExpr() != null && (string = EvalHelper.evalString("align", getAlignExpr(), this, pageContext)) != null) { setAlign(string); } if (getAltExpr() != null && (string = EvalHelper.evalString("alt", getAltExpr(), this, pageContext)) != null) { setAlt(string); } if (getBorderExpr() != null && (string = EvalHelper.evalString("border", getBorderExpr(), this, pageContext)) != null) { setBorder(string); } if (getDirExpr() != null && (string = EvalHelper.evalString("dir", getDirExpr(), this, pageContext)) != null) { setDir(string); } if (getDisabledExpr() != null && (bool = EvalHelper.evalBoolean("disabled", getDisabledExpr(), this, pageContext)) != null) { setDisabled(bool.booleanValue()); } if (getLangExpr() != null && (string = EvalHelper.evalString("lang", getLangExpr(), this, pageContext)) != null) { setLang(string); } if (getOnblurExpr() != null && (string = EvalHelper.evalString("onblur", getOnblurExpr(), this, pageContext)) != null) { setOnblur(string); } if (getOnchangeExpr() != null && (string = EvalHelper.evalString("onchange", getOnchangeExpr(), this, pageContext)) != null) { setOnchange(string); } if (getOnclickExpr() != null && (string = EvalHelper.evalString("onclick", getOnclickExpr(), this, pageContext)) != null) { setOnclick(string); } if (getOndblclickExpr() != null && (string = EvalHelper.evalString("ondblclick", getOndblclickExpr(), this, pageContext)) != null) { setOndblclick(string); } if (getOnfocusExpr() != null && (string = EvalHelper.evalString("onfocus", getOnfocusExpr(), this, pageContext)) != null) { setOnfocus(string); } if (getOnkeydownExpr() != null && (string = EvalHelper.evalString("onkeydown", getOnkeydownExpr(), this, pageContext)) != null) { setOnkeydown(string); } if (getOnkeypressExpr() != null && (string = EvalHelper.evalString("onkeypress", getOnkeypressExpr(), this, pageContext)) != null) { setOnkeypress(string); } if (getOnkeyupExpr() != null && (string = EvalHelper.evalString("onkeyup", getOnkeyupExpr(), this, pageContext)) != null) { setOnkeyup(string); } if (getOnmousedownExpr() != null && (string = EvalHelper.evalString("onmousedown", getOnmousedownExpr(), this, pageContext)) != null) { setOnmousedown(string); } if (getOnmousemoveExpr() != null && (string = EvalHelper.evalString("onmousemove", getOnmousemoveExpr(), this, pageContext)) != null) { setOnmousemove(string); } if (getOnmouseoutExpr() != null && (string = EvalHelper.evalString("onmouseout", getOnmouseoutExpr(), this, pageContext)) != null) { setOnmouseout(string); } if (getOnmouseoverExpr() != null && (string = EvalHelper.evalString("onmouseover", getOnmouseoverExpr(), this, pageContext)) != null) { setOnmouseover(string); } if (getOnmouseupExpr() != null && (string = EvalHelper.evalString("onmouseup", getOnmouseupExpr(), this, pageContext)) != null) { setOnmouseup(string); } if (getSrcExpr() != null && (string = EvalHelper.evalString("src", getSrcExpr(), this, pageContext)) != null) { setSrc(string); } if (getStyleExpr() != null && (string = EvalHelper.evalString("style", getStyleExpr(), this, pageContext)) != null) { setStyle(string); } if (getStyleClassExpr() != null && (string = EvalHelper.evalString("styleClass", getStyleClassExpr(), this, pageContext)) != null) { setStyleClass(string); } if (getStyleIdExpr() != null && (string = EvalHelper.evalString("styleId", getStyleIdExpr(), this, pageContext)) != null) { setStyleId(string); } if (getTabindexExpr() != null && (string = EvalHelper.evalString("tabindex", getTabindexExpr(), this, pageContext)) != null) { setTabindex(string); } if (getTitleExpr() != null && (string = EvalHelper.evalString("title", getTitleExpr(), this, pageContext)) != null) { setTitle(string); } if (getValueExpr() != null && (string = EvalHelper.evalString("value", getValueExpr(), this, pageContext)) != null) { setValue(string); } }
Processes all attribute values which use the JSTL expression evaluation engine to determine their values. @throws JspException if a JSP exception has occurred
public static String getContextPath(ServletContext servletContext) { String contextPath = DEFAULT_CONTEXT_PATH; // Get the context path if (servletContext != null) { contextPath = servletContext.getContextPath(); if (StringUtils.isEmpty(contextPath)) { contextPath = DEFAULT_CONTEXT_PATH; } } return contextPath; }
Returns the context path associated to the servlet context @param servletContext the servlet context @return the context path associated to the servlet context
@Override @ConstantTime public Integer findMin() { if (Constants.NOT_BENCHMARK && size == 0) { throw new NoSuchElementException(); } return array[1].key; }
{@inheritDoc}
@Override @ConstantTime public V findMinValue() { if (Constants.NOT_BENCHMARK && size == 0) { throw new NoSuchElementException(); } return array[1].value; }
{@inheritDoc}
@Override @LogarithmicTime public void insert(Integer key, V value) { if (Constants.NOT_BENCHMARK) { if (key == null) { throw new NullPointerException("Null keys not permitted"); } // make space if needed if (size == array.length - 2) { if (array.length == 2) { ensureCapacity(1); } else { ensureCapacity(2 * (array.length - 2)); } } } ++size; int hole = size; int pred = hole >> 1; Elem<V> predElem = array[pred]; while (predElem.key > key) { array[hole].key = predElem.key; array[hole].value = predElem.value; hole = pred; pred >>= 1; predElem = array[pred]; } array[hole].key = key; array[hole].value = value; }
{@inheritDoc}
@Override @LogarithmicTime public Integer deleteMin() { if (Constants.NOT_BENCHMARK && size == 0) { throw new NoSuchElementException(); } Integer result = array[1].key; // first move up elements on a min-path int hole = 1; int succ = 2; int sz = size; while (succ < sz) { int key1 = array[succ].key; int key2 = array[succ + 1].key; if (key1 > key2) { succ++; array[hole].key = key2; array[hole].value = array[succ].value; } else { array[hole].key = key1; array[hole].value = array[succ].value; } hole = succ; succ <<= 1; } // bubble up rightmost element int bubble = array[sz].key; int pred = hole >> 1; while (array[pred].key > bubble) { array[hole].key = array[pred].key; array[hole].value = array[pred].value; hole = pred; pred >>= 1; } // finally move data to hole array[hole].key = bubble; array[hole].value = array[sz].value; array[size].key = SUP_KEY; array[size].value = null; size = sz - 1; if (Constants.NOT_BENCHMARK) { // free unused space int currentCapacity = array.length - 2; if (2 * minCapacity <= currentCapacity && 4 * size < currentCapacity) { ensureCapacity(currentCapacity / 2); } } return result; }
{@inheritDoc}
@SuppressWarnings("unchecked") private void ensureCapacity(int capacity) { checkCapacity(capacity); Elem<V>[] newArray = (Elem<V>[]) Array.newInstance(Elem.class, capacity + 2); if (newArray.length >= array.length) { System.arraycopy(array, 0, newArray, 0, array.length); for (int i = array.length; i < newArray.length; i++) { newArray[i] = new Elem<V>(SUP_KEY, null); } } else { System.arraycopy(array, 0, newArray, 0, newArray.length); } array = newArray; }
Ensure that the array representation has the necessary capacity. @param capacity the requested capacity
protected void processLegacyRequest(HyperionContext hyperionContext) { EndpointRequest request = hyperionContext.getEndpointRequest(); EndpointResponse response = hyperionContext.getEndpointResponse(); ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin(); EntityPlugin plugin = hyperionContext.getEntityPlugin(); ApiObject clientObject = null; try { clientObject = marshaller.unmarshall(request.getInputStream(),apiVersionPlugin.getApiClass()); } catch (MarshallingException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e); } clientObject.setId(null); PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext); Set<String> fieldSet = persistenceContext.getRequestedFields(); if(fieldSet != null) fieldSet.add("id"); ApiObject saved = (ApiObject) plugin.getPersistenceOperations().createOrUpdateItems( Collections.singletonList(clientObject), persistenceContext).get(0); processChangeEvents(hyperionContext, persistenceContext); response.setResponseCode(200); hyperionContext.setResult(saved); }
Process a legacy V1 request (single item) @param hyperionContext The context
protected void processCollectionRequest(HyperionContext hyperionContext) { EndpointRequest request = hyperionContext.getEndpointRequest(); EndpointResponse response = hyperionContext.getEndpointResponse(); ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin(); EntityPlugin plugin = hyperionContext.getEntityPlugin(); List<ApiObject<Serializable>> clientObjects = null; try { clientObjects = marshaller.unmarshallCollection(request.getInputStream(), apiVersionPlugin.getApiClass()); } catch (WriteLimitException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_WRITE_LIMIT,hyperionContext.getLocale(),e.getWriteLimit()),e); } catch (MarshallingException e) { throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e); } PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext); Set<String> fieldSet = persistenceContext.getRequestedFields(); if(fieldSet != null) fieldSet.add("id"); List<ApiObject> saved = plugin.getPersistenceOperations().createOrUpdateItems(clientObjects, persistenceContext); processChangeEvents(hyperionContext,persistenceContext); response.setResponseCode(200); EntityList<ApiObject> entityResponse = new EntityList<>(); entityResponse.setEntries(saved); hyperionContext.setResult(entityResponse); }
Process a multi-item request @param hyperionContext The context
void store(int A, int r, int B) { getB(A, r).add(B); getA(B, r).add(A); }
Record A [ r.B @param A @param r @param B
public void subtract(R1 relationships) { if (null == base) { throw new AssertionError(""); } for (int i = 0; i < base.length; i++) { if (null == base[i]) { continue; } final IConceptSet set = data[i] = new SparseConceptHashSet(); set.addAll(base[i]); if (null != relationships.data[i]) { set.removeAll(relationships.data[i]); } } }
This should only ever be called when the relationships wrap an initial state and no other methods have been called. @param relationships
protected IConceptSet getB(int A, int r) { if (A >= CONCEPTS) { resizeConcepts(A); } if (r >= ROLES) { resizeRoles(r); } final int index = indexOf(A, r); if (null == data[index]) { data[index] = new SparseConceptSet(); addRole(r); if (null != base && index < base.length && null != base[index]) { data[index].addAll(base[index]); } } return data[index]; }
Returns {B | A [ r.B} or {B | (A,B) in R(r)} @param A @param r @return
protected IConceptSet getA(int B, int r) { if (B >= CONCEPTS) { resizeConcepts(B); } if (r >= ROLES) { resizeRoles(r); } // Note the "+1" in the following line: final int index = indexOf(B, r) + 1; if (null == data[index]) { data[index] = new SparseConceptSet(); addRole(r); if (null != base && index < base.length && null != base[index]) { data[index].addAll(base[index]); } } return data[index]; }
Returns {A | A [ r.B} or {A | (A,B) in R(r)} Lazily initialise data from base as a side-effect of this call. @param B @param r @return
@Override protected void processRequest(String requestedPath, HttpServletRequest request, HttpServletResponse response, BundleHashcodeType bundleHashcodeType) throws IOException { boolean responseHeaderWritten = false; boolean validBundle = true; if (!jawrConfig.isDebugModeOn() && jawrConfig.isStrictMode() && bundleHashcodeType.equals(BundleHashcodeType.INVALID_HASHCODE)) { validBundle = false; } // If debug mode is off, check for If-Modified-Since and // If-none-match headers and set response caching headers. if (!this.jawrConfig.isDebugModeOn()) { // If a browser checks for changes, always respond 'no changes'. if (validBundle && (null != request.getHeader(IF_MODIFIED_SINCE_HEADER) || null != request.getHeader(IF_NONE_MATCH_HEADER))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if (LOGGER.isDebugEnabled()) LOGGER.debug("Returning 'not modified' header. "); return; } if (validBundle) { // Add caching headers setResponseHeaders(response); } else { responseHeaderWritten = illegalBundleRequestHandler.writeResponseHeader(requestedPath, request, response); if (!responseHeaderWritten) { // Add caching headers setResponseHeaders(response); } } } // Returns the real file path String filePath = getRealFilePath(requestedPath, bundleHashcodeType); try { if (isValidRequestedPath(filePath) && (validBundle || illegalBundleRequestHandler.canWriteContent(requestedPath, request))) { // Set the content type response.setContentType(getContentType(requestedPath, request)); writeContent(filePath, request, response); } else { if (!responseHeaderWritten) { LOGGER.error("Unable to load the image for the request URI : " + request.getRequestURI()); response.sendError(HttpServletResponse.SC_NOT_FOUND); } } } catch (EOFException eofex) { LOGGER.info("Browser cut off response", eofex); } catch (ResourceNotFoundException e) { LOGGER.info("Unable to write resource " + request.getRequestURI(), e); response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException ex) { LOGGER.error("Unable to write resource " + request.getRequestURI(), ex); response.sendError(HttpServletResponse.SC_NOT_FOUND); } if (LOGGER.isDebugEnabled()) LOGGER.debug("request succesfully attended"); }
Process the request @param requestedPath the requested path @param request the request @param response the response @param bundleHashcodeType the bundle hashcode type @throws IOException if an IOException occurs
protected Properties readConfigFile(String path) { Properties props = new Properties(); // Load properties file InputStream is = null; try { if (path.startsWith(FILE_PREFIX)) { if (LOGGER.isDebugEnabled() && !checking) LOGGER.debug("Using filesystem properties file location at: " + configLocation); is = new FileInputStream(new File(path.substring(FILE_PREFIX.length()))); } else { if (LOGGER.isDebugEnabled() && !checking) LOGGER.debug("Reading properties from file at classpath: " + configLocation); is = ClassLoaderResourceUtils.getResourceAsStream(path, this); } loadConfig(props, path, is); } catch (IOException e) { throw new IllegalArgumentException("jawr configuration could not be found at " + path + ". Make sure parameter is properly set " + "in web.xml. "); } finally { IOUtils.close(is); } return props; }
Reads a config file at the specified path. If the path starts with file:, it will be read from the filesystem. Otherwise it will be loaded from the classpath. @param path the configuration path @return the configuration properties
@LinearTime public static <K, V> DaryArrayAddressableHeap<K, V> heapify(int d, K[] keys, V[] values, Comparator<? super K> comparator) { if (d < 2) { throw new IllegalArgumentException("D-ary heaps must have at least 2 children per node"); } if (keys == null) { throw new IllegalArgumentException("Keys array cannot be null"); } if (values != null && keys.length != values.length) { throw new IllegalArgumentException("Values array must have the same length as the keys array"); } if (keys.length == 0) { return new DaryArrayAddressableHeap<K, V>(d, comparator); } DaryArrayAddressableHeap<K, V> h = new DaryArrayAddressableHeap<K, V>(d, comparator, keys.length); for (int i = 0; i < keys.length; i++) { K key = keys[i]; V value = (values == null) ? null : values[i]; AbstractArrayAddressableHeap<K, V>.ArrayHandle ah = h.new ArrayHandle(key, value); ah.index = i + 1; h.array[i + 1] = ah; } h.size = keys.length; for (int i = keys.length / d; i > 0; i--) { h.fixdownWithComparator(i); } return h; }
Create a heap from an array of elements. The elements of the array are not destroyed. The method has linear time complexity. @param <K> the type of keys maintained by the heap @param <V> the type of values maintained by the heap @param d the number of children of the d-ary heap @param keys an array of keys @param values an array of values, can be null @param comparator the comparator to use @return a d-ary heap @throws IllegalArgumentException in case the number of children per node are less than 2 @throws IllegalArgumentException in case the keys array is null @throws IllegalArgumentException in case the values array has different length than the keys array
public Iterator<AddressableHeap.Handle<K, V>> handlesIterator() { return new Iterator<AddressableHeap.Handle<K, V>>() { private int pos = 1; public boolean hasNext() { return pos <= size; } public AddressableHeap.Handle<K, V> next() { return array[pos++]; } public void remove() { throw new UnsupportedOperationException(); } }; }
Get an iterator for all handles currently in the heap. This method is especially useful when building a heap using the heapify method. Unspecified behavior will occur if the heap is modified while using this iterator. @return an iterator which will return all handles of the heap
@Override @SuppressWarnings("unchecked") protected void ensureCapacity(int capacity) { checkCapacity(capacity); ArrayHandle[] newArray = (ArrayHandle[]) Array.newInstance(ArrayHandle.class, capacity + 1); System.arraycopy(array, 1, newArray, 1, size); array = newArray; }
Ensure that the array representation has the necessary capacity. @param capacity the requested capacity
public String getFullPath(String path) { if (StringUtils.isEmpty(pathPrefix)) { return path; } return PathNormalizer.asPath(pathPrefix + path); }
Returns the full path for the specified resource @param path the resource path @return the full path for the specified resource
@Override @SuppressWarnings("unchecked") @ConstantTime(amortized = true) public AddressableHeap.Handle<K, V> insert(K key, V value) { if (other != this) { throw new IllegalStateException("A heap cannot be used after a meld"); } if (key == null) { throw new NullPointerException("Null keys not permitted"); } Node<K, V> n = new Node<K, V>(this, key, value); if (root == null) { root = n; } else { if (comparator == null) { if (((Comparable<? super K>) n.key).compareTo(root.key) < 0) { root = link(root, n); } else { link(n, root); } } else { if (comparator.compare(n.key, root.key) < 0) { root = link(root, n); } else { link(n, root); } } } size++; return n; }
{@inheritDoc} @throws IllegalStateException if the heap has already been used in the right hand side of a meld
@Override @LogarithmicTime(amortized = true) public AddressableHeap.Handle<K, V> deleteMin() { if (comparator == null) { return comparableDeleteMin(); } else { return comparatorDeleteMin(); } }
{@inheritDoc}
@Override @SuppressWarnings("unchecked") @ConstantTime(amortized = true) public void meld(MergeableAddressableHeap<K, V> other) { SimpleFibonacciHeap<K, V> h = (SimpleFibonacciHeap<K, V>) other; // check same comparator if (comparator != null) { if (h.comparator == null || !h.comparator.equals(comparator)) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } } else if (h.comparator != null) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } if (h.other != h) { throw new IllegalStateException("A heap cannot be used after a meld."); } // meld if (root == null) { root = h.root; } else if (h.root != null) { if (comparator == null) { if (((Comparable<? super K>) h.root.key).compareTo(root.key) < 0) { root = link(root, h.root); } else { link(h.root, root); } } else { if (comparator.compare(h.root.key, root.key) < 0) { root = link(root, h.root); } else { link(h.root, root); } } } size += h.size; // clear other h.size = 0; h.root = null; // take ownership h.other = this; }
{@inheritDoc}
@SuppressWarnings("unchecked") private void comparableDecreaseKey(Node<K, V> n, K newKey) { int c = ((Comparable<? super K>) newKey).compareTo(n.key); if (c > 0) { throw new IllegalArgumentException("Keys can only be decreased!"); } n.key = newKey; if (c == 0) { return; } if (n.next == null) { throw new IllegalArgumentException("Invalid handle!"); } // if not root and heap order violation Node<K, V> y = n.parent; if (y != null && ((Comparable<? super K>) n.key).compareTo(y.key) < 0) { cut(n, y); root.mark = false; cascadingRankChange(y); if (((Comparable<? super K>) n.key).compareTo(root.key) < 0) { root = link(root, n); } else { link(n, root); } } }
/* Decrease the key of a node.
private void comparatorDecreaseKey(Node<K, V> n, K newKey) { int c = comparator.compare(newKey, n.key); if (c > 0) { throw new IllegalArgumentException("Keys can only be decreased!"); } n.key = newKey; if (c == 0) { return; } if (n.next == null) { throw new IllegalArgumentException("Invalid handle!"); } // if not root and heap order violation Node<K, V> y = n.parent; if (y != null && comparator.compare(n.key, y.key) < 0) { cut(n, y); root.mark = false; cascadingRankChange(y); if (comparator.compare(n.key, root.key) < 0) { root = link(root, n); } else { link(n, root); } } }
/* Decrease the key of a node.
private void forceDecreaseKeyToMinimum(Node<K, V> n) { Node<K, V> y = n.parent; if (y != null) { cut(n, y); root.mark = false; cascadingRankChange(y); root = link(root, n); } }
/* Decrease the key of a node to the minimum. Helper function for performing a delete operation. Does not change the node's actual key, but behaves as the key is the minimum key in the heap.
private Node<K, V> link(Node<K, V> y, Node<K, V> x) { y.parent = x; Node<K, V> child = x.child; if (child == null) { x.child = y; y.next = y; y.prev = y; } else { y.prev = child; y.next = child.next; child.next = y; y.next.prev = y; } return x; }
/* (unfair) Link y as a child of x.
private void cascadingRankChange(Node<K, V> y) { while (y.mark == true) { y.mark = false; if (y.rank > 0) { --y.rank; } y = y.parent; } y.mark = true; if (y.rank > 0) { --y.rank; } }
/* Cascading rank change. Assumes that the root is unmarked.
public int compareTo(AbstractConcept other) { // Need to sort by concrete subclass first, and then by object hashCode final int meta = getClass().hashCode() - other.getClass().hashCode(); final int quickCompare = hashCode() - other.hashCode(); int result = 0 == meta ? (0 == quickCompare ? compareToWhenHashCodesEqual(other) : quickCompare) : meta; // If compare result is 0, then the objects must be equal() assert 0 != result || this.equals(other); return result; }
Default {@link Comparable#compareTo(Object)} implementation that calls {@link #compareToWhenHashCodesEqual(AbstractConcept)} if and only if the {@link #hashCode()} values of {@code this} and {@code other} are equal. @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
@Override @ConstantTime(amortized = false) public void clear() { rootList.head = null; rootList.tail = null; size = 0; }
{@inheritDoc}
@Override public void meld(MergeableAddressableHeap<K, V> other) { BinaryTreeSoftAddressableHeap<K, V> h = (BinaryTreeSoftAddressableHeap<K, V>) other; // check same comparator if (comparator != null) { if (h.comparator == null || !h.comparator.equals(comparator)) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } } else if (h.comparator != null) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } if (rankLimit != h.rankLimit) { throw new IllegalArgumentException("Cannot meld heaps with different error rates!"); } if (h.other != h) { throw new IllegalStateException("A heap cannot be used after a meld."); } // perform the meld mergeInto(h.rootList.head, h.rootList.tail); size += h.size; // clear other h.size = 0; h.rootList.head = null; h.rootList.tail = null; // take ownership h.other = this; }
{@inheritDoc} @throws IllegalArgumentException if {@code other} has a different error rate
@Override public Handle<K, V> insert(K key, V value) { if (other != this) { throw new IllegalStateException("A heap cannot be used after a meld"); } if (key == null) { throw new NullPointerException("Null keys not permitted"); } /* * Create a single element heap */ SoftHandle<K, V> n = new SoftHandle<K, V>(this, key, value); TreeNode<K, V> treeNode = new TreeNode<K, V>(n); RootListNode<K, V> rootListNode = new RootListNode<K, V>(treeNode); /* * Merge new list into old list */ mergeInto(rootListNode, rootListNode); size++; return n; }
{@inheritDoc}
@Override public SoftHandle<K, V> findMin() { if (size == 0) { throw new NoSuchElementException(); } return rootList.head.suffixMin.root.cHead; }
{@inheritDoc}
@Override public Handle<K, V> deleteMin() { if (size == 0) { throw new NoSuchElementException(); } // find tree with minimum RootListNode<K, V> minRootListNode = rootList.head.suffixMin; TreeNode<K, V> root = minRootListNode.root; // remove from list SoftHandle<K, V> result = root.cHead; if (result.next != null) { result.next.prev = null; result.next.tree = root; } root.cHead = result.next; root.cSize--; // replenish keys if needed if (root.cHead == null || root.cSize <= targetSize(root.rank) / 2) { if (root.left != null || root.right != null) { // get keys from children sift(root); updateSuffixMin(minRootListNode); } else if (root.cHead == null) { // no children and empty list, just remove the tree RootListNode<K, V> minRootPrevListNode = minRootListNode.prev; delete(minRootListNode); updateSuffixMin(minRootPrevListNode); } } result.next = null; result.prev = null; result.tree = null; size--; return result; }
{@inheritDoc}
@SuppressWarnings("unchecked") private void updateSuffixMin(RootListNode<K, V> t) { if (comparator == null) { while (t != null) { if (t.next == null) { t.suffixMin = t; } else { RootListNode<K, V> nextSuffixMin = t.next.suffixMin; if (((Comparable<? super K>) t.root.cKey).compareTo(nextSuffixMin.root.cKey) <= 0) { t.suffixMin = t; } else { t.suffixMin = nextSuffixMin; } } t = t.prev; } } else { while (t != null) { if (t.next == null) { t.suffixMin = t; } else { RootListNode<K, V> nextSuffixMin = t.next.suffixMin; if (comparator.compare(t.root.cKey, nextSuffixMin.root.cKey) <= 0) { t.suffixMin = t; } else { t.suffixMin = nextSuffixMin; } } t = t.prev; } } }
Update all suffix minimum pointers for a node and all its predecessors in the root list. @param t the node
private void mergeInto(RootListNode<K, V> head, RootListNode<K, V> tail) { // if root list empty, just copy if (rootList.head == null) { rootList.head = head; rootList.tail = tail; return; } // initialize RootListNode<K, V> resultHead; RootListNode<K, V> resultTail; RootListNode<K, V> resultTailPrev = null; RootListNode<K, V> cur1 = rootList.head; RootListNode<K, V> cur2 = head; // add first node if (cur1.root.rank <= cur2.root.rank) { resultHead = cur1; resultTail = cur1; RootListNode<K, V> cur1next = cur1.next; cur1.next = null; cur1 = cur1next; if (cur1next != null) { cur1next.prev = null; } } else { resultHead = cur2; resultTail = cur2; RootListNode<K, V> cur2next = cur2.next; cur2.next = null; cur2 = cur2next; if (cur2next != null) { cur2next.prev = null; } } // merge int rank1, rank2; while (true) { int resultRank = resultTail.root.rank; // read rank1 if (cur1 != null) { rank1 = cur1.root.rank; } else { if (cur2 != null && cur2.root.rank <= resultRank) { rank1 = Integer.MAX_VALUE; } else { break; } } // read rank2 if (cur2 != null) { rank2 = cur2.root.rank; } else { if (cur1 != null && cur1.root.rank <= resultRank) { rank2 = Integer.MAX_VALUE; } else { break; } } if (rank1 <= rank2) { switch (Integer.compare(rank1, resultRank)) { case 0: // combine into result resultTail.root = combine(cur1.root, resultTail.root); resultTail.root.parent = resultTail; // remove cur1 RootListNode<K, V> cur1next = cur1.next; cur1.next = null; if (cur1next != null) { cur1next.prev = null; } cur1 = cur1next; break; case -1: // can happen if three same ranks cur1next = cur1.next; // add before tail into result cur1.next = resultTail; resultTail.prev = cur1; cur1.prev = resultTailPrev; if (resultTailPrev != null) { resultTailPrev.next = cur1; } else { resultHead = cur1; } resultTailPrev = cur1; // advance cur1 if (cur1next != null) { cur1next.prev = null; } cur1 = cur1next; break; case 1: // append into result resultTail.next = cur1; cur1.prev = resultTail; resultTailPrev = resultTail; resultTail = cur1; // remove cur1 cur1 = cur1.next; resultTail.next = null; if (cur1 != null) { cur1.prev = null; } break; } } else { // symmetric case rank2 < rank1 switch (Integer.compare(rank2, resultRank)) { case 0: // combine into result resultTail.root = combine(cur2.root, resultTail.root); resultTail.root.parent = resultTail; // remove cur2 RootListNode<K, V> cur2next = cur2.next; cur2.next = null; if (cur2next != null) { cur2next.prev = null; } cur2 = cur2next; break; case -1: // can happen if three same ranks cur2next = cur2.next; // add before tail into result cur2.next = resultTail; resultTail.prev = cur2; cur2.prev = resultTailPrev; if (resultTailPrev != null) { resultTailPrev.next = cur2; } else { resultHead = cur2; } resultTailPrev = cur2; // advance cur2 if (cur2next != null) { cur2next.prev = null; } cur2 = cur2next; break; case 1: // append into result resultTail.next = cur2; cur2.prev = resultTail; resultTailPrev = resultTail; resultTail = cur2; // remove cur2 cur2 = cur2.next; resultTail.next = null; if (cur2 != null) { cur2.prev = null; } break; } } } // record up to which point a suffix minimum update is needed RootListNode<K, V> updateSuffixFix = resultTail; // here rank of cur1 is more than result rank if (cur1 != null) { cur1.prev = resultTail; resultTail.next = cur1; resultTail = rootList.tail; } // here rank of cur2 is more than result rank if (cur2 != null) { cur2.prev = resultTail; resultTail.next = cur2; resultTail = tail; } // update suffix minimum updateSuffixMin(updateSuffixFix); // store final list rootList.head = resultHead; rootList.tail = resultTail; }
Merge a list into the root list. Assumes that the two lists are sorted in non-decreasing order of rank. @param head the list head @param tail the list tail
private void delete(RootListNode<K, V> n) { RootListNode<K, V> nPrev = n.prev; if (nPrev != null) { nPrev.next = n.next; } else { rootList.head = n.next; } if (n.next != null) { n.next.prev = nPrev; } else { rootList.tail = nPrev; } n.prev = null; n.next = null; }
Delete a node from the root list. @param n the node
@SuppressWarnings("unchecked") private void delete(SoftHandle<K, V> n) { if (n.tree == null) { throw new IllegalArgumentException("Invalid handle!"); } /* * Delete from belonging list. Care must be taken as the tree reference * is valid only if the node is the first in the list. */ TreeNode<K, V> tree = n.tree; if (tree.cHead != n) { /* * Not first in list. Each case, remove and leave as ghost element. */ if (n.next != null) { n.next.prev = n.prev; } n.prev.next = n.next; } else { /* * First in list */ SoftHandle<K, V> nNext = n.next; tree.cHead = nNext; if (nNext != null) { /* * More elements exists, remove and leave as ghost element. * Update new first element to point to correct tree. */ nNext.prev = null; nNext.tree = tree; } else { /* * No more elements, sift. */ sift(tree); /* * If still no elements, remove tree. */ if (tree.cHead == null) { if (tree.parent instanceof TreeNode) { TreeNode<K, V> p = (TreeNode<K, V>) tree.parent; if (p.left == tree) { p.left = null; } else { p.right = null; } } else { delete((RootListNode<K, V>) tree.parent); } } } } n.tree = null; n.prev = null; n.next = null; size--; }
Delete an element. @param n the element to delete
public QueryExpression eq(String propertyName,String value) { return new SimpleQueryExpression(propertyName, ComparisonOperator.EQUAL,wrap(value)); }
Create an equals expression @param propertyName The propery name @param value The value @return The query expression
public QueryExpression ne(String propertyName,String value) { return new SimpleQueryExpression(propertyName, ComparisonOperator.NOT_EQUAL,wrap(value)); }
Create a not equals expression @param propertyName The propery name @param value The value @return The query expression
public QueryExpression gt(String propertyName,String value) { return new SimpleQueryExpression(propertyName, ComparisonOperator.GREATER_THAN,wrap(value)); }
Create a greater than expression @param propertyName The propery name @param value The value @return The query expression
public QueryExpression lt(String propertyName,String value) { return new SimpleQueryExpression(propertyName, ComparisonOperator.LESS_THAN,wrap(value)); }
Create a less than expression @param propertyName The propery name @param value The value @return The query expression
public QueryExpression ge(String propertyName,String value) { return new SimpleQueryExpression(propertyName, ComparisonOperator.GREATER_THAN_OR_EQUAL,wrap(value)); }
Create a greater than or equals expression @param propertyName The propery name @param value The value @return The query expression