List of usage examples for java.util.logging Level FINER
Level FINER
To view the source code for java.util.logging Level FINER.
Click Source Link
From source file:org.b3log.latke.repository.jdbc.JdbcRepository.java
/** * Caches the specified query results with the specified query. * /*from ww w.j a v a 2 s . c o m*/ * @param results * the specified query results * @param query * the specified query * @throws JSONException * json exception */ private void cacheQueryResults(final JSONArray results, final org.b3log.latke.repository.Query query) throws JSONException { String cacheKey; for (int i = 0; i < results.length(); i++) { final JSONObject jsonObject = results.optJSONObject(i); // 1. Caching for get by id. cacheKey = CACHE_KEY_PREFIX + jsonObject.optString(Keys.OBJECT_ID); CACHE.putAsync(cacheKey, jsonObject); LOGGER.log(Level.FINER, "Added an object[cacheKey={0}] in repository cache[{1}] for default index[oId]", new Object[] { cacheKey, getName() }); // 2. Caching for get by query with filters (EQUAL operator) only final Set<String[]> indexes = query.getIndexes(); final StringBuilder logMsgBuilder = new StringBuilder(); for (final String[] index : indexes) { final org.b3log.latke.repository.Query futureQuery = new org.b3log.latke.repository.Query() .setPageCount(1); for (int j = 0; j < index.length; j++) { final String propertyName = index[j]; futureQuery.setFilter( new PropertyFilter(propertyName, FilterOperator.EQUAL, jsonObject.opt(propertyName))); logMsgBuilder.append(propertyName).append(","); } if (logMsgBuilder.length() > 0) { logMsgBuilder.deleteCharAt(logMsgBuilder.length() - 1); } cacheKey = CACHE_KEY_PREFIX + futureQuery.getCacheKey() + "_" + getName(); final JSONObject futureQueryRet = new JSONObject(); final JSONObject pagination = new JSONObject(); futureQueryRet.put(Pagination.PAGINATION, pagination); pagination.put(Pagination.PAGINATION_PAGE_COUNT, 1); final JSONArray futureQueryResults = new JSONArray(); futureQueryRet.put(Keys.RESULTS, futureQueryResults); futureQueryResults.put(jsonObject); CACHE.putAsync(cacheKey, futureQueryRet); LOGGER.log(Level.FINER, "Added an object[cacheKey={0}] in repository cache[{1}] for index[{2}] for future query[{3}]", new Object[] { cacheKey, getName(), logMsgBuilder, futureQuery.toString() }); } } }
From source file:org.cloudifysource.dsl.internal.BaseDslScript.java
private boolean handleSpecialProperty(final String name, final Object arg) throws DSLException { Object localArg = arg;// w w w . j a v a 2 s. co m if (name.equals(EXTEND_PROPERTY_NAME)) { if (propertyCounter > 1) { throw new DSLException(EXTEND_PROPERTY_NAME + " must be first inside the service block"); } if (arg != null && arg.getClass().isArray()) { final Object[] arr = (Object[]) arg; if (arr.length != 1) { throw new DSLException(EXTEND_PROPERTY_NAME + " property must be a single string"); } localArg = ((Object[]) arg)[0]; } if (!(localArg instanceof String)) { throw new DSLException(EXTEND_PROPERTY_NAME + " property must be a string"); } if (!(this.activeObject instanceof Service)) { throw new DSLException(EXTEND_PROPERTY_NAME + " property can only be used on a service"); } final String extendServicePath = (String) localArg; try { File extendedServiceAbsPath = new File(extendServicePath); final RecipePathResolver resolver = new RecipePathResolver(); // Extract the current service directory final String dslFilePath = (String) getProperty(ServiceReader.DSL_FILE_PATH_PROPERTY_NAME); if (dslFilePath == null) { throw new IllegalStateException("No dsl file path present in binding context"); } final File activeServiceDirectory = new File(dslFilePath).getParentFile(); resolver.setCurrentDirectory(activeServiceDirectory); if (resolver.resolveService(extendedServiceAbsPath)) { extendedServiceAbsPath = resolver.getResolved(); } else { throw new DSLException("could not find extended service in paths " + StringUtils.join(resolver.getPathsLooked().toArray(), ", ")); } if (logger.isLoggable(Level.FINER)) { logger.finer("reading extended service file [" + extendedServiceAbsPath + "]"); } // Read the extended service final Service baseService = readServiceToExtend(extendedServiceAbsPath); // ServiceReader.readService(extendedServiceAbsPath); // Populate the current service with the extended service BeanUtils.copyProperties(this.activeObject, baseService); final Service activeService = (Service) activeObject; // Add extended service to the extension list activeService.getExtendedServicesPaths().addFirst(extendedServiceAbsPath.getAbsolutePath()); return true; } catch (final IllegalAccessException e) { throw new DSLException("Failed to parse extended service: " + extendServicePath, e); } catch (final InvocationTargetException e) { throw new DSLException("Failed to parse extended service: " + extendServicePath, e); } } return false; }
From source file:hudson.model.AbstractItem.java
public final String getUrl() { // try to stick to the current view if possible StaplerRequest req = Stapler.getCurrentRequest(); String shortUrl = getShortUrl(); String uri = req == null ? null : req.getRequestURI(); if (req != null) { String seed = Functions.getNearestAncestorUrl(req, this); LOGGER.log(Level.FINER, "seed={0} for {1} from {2}", new Object[] { seed, this, uri }); if (seed != null) { // trim off the context path portion and leading '/', but add trailing '/' return seed.substring(req.getContextPath().length() + 1) + '/'; }/*from w w w .ja va 2 s . c om*/ List<Ancestor> ancestors = req.getAncestors(); if (!ancestors.isEmpty()) { Ancestor last = ancestors.get(ancestors.size() - 1); if (last.getObject() instanceof View) { View view = (View) last.getObject(); if (view.getOwner().getItemGroup() == getParent() && !view.isDefault()) { // Showing something inside a view, so should use that as the base URL. String base = last.getUrl().substring(req.getContextPath().length() + 1) + '/'; LOGGER.log(Level.FINER, "using {0}{1} for {2} from {3}", new Object[] { base, shortUrl, this, uri }); return base + shortUrl; } else { LOGGER.log(Level.FINER, "irrelevant {0} for {1} from {2}", new Object[] { view.getViewName(), this, uri }); } } else { LOGGER.log(Level.FINER, "inapplicable {0} for {1} from {2}", new Object[] { last.getObject(), this, uri }); } } else { LOGGER.log(Level.FINER, "no ancestors for {0} from {1}", new Object[] { this, uri }); } } else { LOGGER.log(Level.FINER, "no current request for {0}", this); } // otherwise compute the path normally String base = getParent().getUrl(); LOGGER.log(Level.FINER, "falling back to {0}{1} for {2} from {3}", new Object[] { base, shortUrl, this, uri }); return base + shortUrl; }
From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java
/** * Returns the requested optimization level from the request. * * @param request the request object// w ww . ja v a2 s . c om * @return the optimization level specified in the request */ protected OptimizationLevel getOptimizationLevelFromRequest(HttpServletRequest request) { final String sourceMethod = "getOptimizationLevelFromRequest"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractHttpTransport.class.getName(), sourceMethod, new Object[] { request.getQueryString() }); } // Get the optimization level specified in the request and set the ComilationLevel String optimize = getParameter(request, OPTIMIZATIONLEVEL_REQPARAMS); OptimizationLevel level = OptimizationLevel.SIMPLE; if (optimize != null && !optimize.equals("")) { //$NON-NLS-1$ if (optimize.equalsIgnoreCase("whitespace")) //$NON-NLS-1$ level = OptimizationLevel.WHITESPACE; else if (optimize.equalsIgnoreCase("advanced")) //$NON-NLS-1$ level = OptimizationLevel.ADVANCED; else if (optimize.equalsIgnoreCase("none")) //$NON-NLS-1$ level = OptimizationLevel.NONE; } if (isTraceLogging) { log.exiting(AbstractHttpTransport.class.getName(), sourceMethod, level); } return level; }
From source file:org.b3log.latke.repository.gae.GAERepository.java
/** * Gets a json object with the specified parent key and id. * /*from w w w.ja v a 2 s.com*/ * @param parentKey the specified parent key * @param id the specified id * @return a json object, returns {@code null} if not found * @throws RepositoryException repository exception */ private JSONObject get(final Key parentKey, final String id) throws RepositoryException { JSONObject ret; if (cacheEnabled) { final String cacheKey = CACHE_KEY_PREFIX + id; ret = (JSONObject) CACHE.get(cacheKey); if (null != ret) { LOGGER.log(Level.FINER, "Got an object[cacheKey={0}] from repository cache[name={1}]", new Object[] { cacheKey, getName() }); return ret; } } final Key key = KeyFactory.createKey(parentKey, getName(), id); try { final Entity entity = datastoreService.get(key); ret = entity2JSONObject(entity); LOGGER.log(Level.FINER, "Got an object[oId={0}] from repository[name={1}]", new Object[] { id, getName() }); if (cacheEnabled) { final String cacheKey = CACHE_KEY_PREFIX + id; CACHE.putAsync(cacheKey, ret); LOGGER.log(Level.FINER, "Added an object[cacheKey={0}] in repository cache[{1}]", new Object[] { cacheKey, getName() }); } } catch (final EntityNotFoundException e) { LOGGER.log(Level.WARNING, "Not found an object[oId={0}] in repository[name={1}]", new Object[] { id, getName() }); return null; } return ret; }
From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java
public GranuleDescriptor(final String granuleLocation, final BoundingBox granuleBBox, final ImageReaderSpi suggestedSPI, final MultiLevelROI roiProvider, final int maxDecimationFactor, final boolean heterogeneousGranules, final boolean handleArtifactsFiltering) { this.maxDecimationFactor = maxDecimationFactor; final URL rasterFile = DataUtilities.fileToURL(new File(granuleLocation)); if (rasterFile == null) { return;//from w w w. ja va 2s . com } if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("File found " + granuleLocation); } this.originator = null; init(granuleBBox, rasterFile, suggestedSPI, roiProvider, heterogeneousGranules, handleArtifactsFiltering, null); }
From source file:org.b3log.solo.service.ArticleMgmtService.java
/** * Removes the article specified by the given id. * * @param articleId the given id// w w w. j a v a 2 s . c om * @throws ServiceException service exception */ public void removeArticle(final String articleId) throws ServiceException { LOGGER.log(Level.FINER, "Removing an article[id={0}]", articleId); final Transaction transaction = articleRepository.beginTransaction(); try { decTagRefCount(articleId); unArchiveDate(articleId); removeTagArticleRelations(articleId); removeArticleComments(articleId); final JSONObject article = articleRepository.get(articleId); articleRepository.remove(articleId); statistics.decBlogArticleCount(); if (article.getBoolean(Article.ARTICLE_IS_PUBLISHED)) { statistics.decPublishedBlogArticleCount(); } final JSONObject author = userRepository.getByEmail(article.optString(Article.ARTICLE_AUTHOR_EMAIL)); author.put(UserExt.USER_PUBLISHED_ARTICLE_COUNT, author.optInt(UserExt.USER_PUBLISHED_ARTICLE_COUNT) - 1); author.put(UserExt.USER_ARTICLE_COUNT, author.optInt(UserExt.USER_ARTICLE_COUNT) - 1); userRepository.update(author.optString(Keys.OBJECT_ID), author); transaction.commit(); } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.SEVERE, "Removes an article[id=" + articleId + "] failed", e); throw new ServiceException(e); } LOGGER.log(Level.FINER, "Removed an article[id={0}]", articleId); }
From source file:org.aselect.server.request.handler.xsaml20.sp.Xsaml20_AssertionConsumer.java
/** * Assertion consumer. <br>//from w ww. j a v a 2 s .c o m * * @param servletRequest * HttpServletRequest. * @param servletResponse * HttpServletResponse. * @return the request state * @throws ASelectException * on failure */ @SuppressWarnings("unchecked") public RequestState process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ASelectException { String sMethod = "process"; boolean checkAssertionSigning = false; Object samlResponseObject = null; String auth_proof = null; PrintWriter pwOut = null; try { pwOut = Utils.prepareForHtmlOutput(servletRequest, servletResponse); String sReceivedArtifact = servletRequest.getParameter("SAMLart"); String sReceivedResponse = servletRequest.getParameter("SAMLResponse"); String sRelayState = servletRequest.getParameter("RelayState"); _systemLogger.log(Level.INFO, MODULE, sMethod, "Received artifact: " + sReceivedArtifact + " RelayState=" + sRelayState); if (!(sReceivedArtifact == null || "".equals(sReceivedArtifact))) { String sFederationUrl = _sFederationUrl; // default, remove later on, can be null if (sRelayState.startsWith("idp=")) { sFederationUrl = sRelayState.substring(4); } else { // Could be Base64 encoded sRelayState = new String(Base64Codec.decode(sRelayState)); _systemLogger.log(Level.INFO, MODULE, sMethod, "RelayState=" + sRelayState); sFederationUrl = Utils.getParameterValueFromUrl(sRelayState, "idp"); } if (!Utils.hasValue(sFederationUrl)) { _systemLogger.log(Level.WARNING, MODULE, sMethod, "No idp value found in RelayState (or in <federation_url> config)"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } _systemLogger.log(Level.INFO, MODULE, sMethod, "FederationUrl=" + sFederationUrl); // use metadata MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle(); String sASelectServerUrl = metadataManager.getLocation(sFederationUrl, ArtifactResolutionService.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML2_SOAP11_BINDING_URI); _systemLogger.log(Level.INFO, MODULE, sMethod, "Artifact Resolution at " + sASelectServerUrl); if (sASelectServerUrl == null) { _systemLogger.log(Level.INFO, MODULE, sMethod, "Artifact NOT found"); throw new ASelectException(Errors.ERROR_ASELECT_NOT_FOUND); } SAMLObjectBuilder<Artifact> artifactBuilder = (SAMLObjectBuilder<Artifact>) _oBuilderFactory .getBuilder(Artifact.DEFAULT_ELEMENT_NAME); Artifact artifact = artifactBuilder.buildObject(); artifact.setArtifact(sReceivedArtifact); SAMLObjectBuilder<ArtifactResolve> artifactResolveBuilder = (SAMLObjectBuilder<ArtifactResolve>) _oBuilderFactory .getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME); ArtifactResolve artifactResolve = artifactResolveBuilder.buildObject(); artifactResolve.setID(SamlTools.generateIdentifier(_systemLogger, MODULE)); artifactResolve.setVersion(SAMLVersion.VERSION_20); artifactResolve.setIssueInstant(new DateTime()); // We decided that the other side could retrieve public key from metadata // by looking up the issuer as an entityID in the metadata // So we MUST supply an Issuer (which otherwise would be optional (by SAML standards)) SAMLObjectBuilder<Issuer> assertionIssuerBuilder = (SAMLObjectBuilder<Issuer>) _oBuilderFactory .getBuilder(Issuer.DEFAULT_ELEMENT_NAME); Issuer assertionIssuer = assertionIssuerBuilder.buildObject(); // 20100312, Bauke: eHerkenning, no assertion issuer format: // assertionIssuer.setFormat(NameIDType.ENTITY); // 20100311, Bauke: added for eHerkenning: Specific issuer id, independent of the Url PartnerData partnerData = MetaDataManagerSp.getHandle().getPartnerDataEntry(sFederationUrl); String specialSettings = (partnerData == null) ? null : partnerData.getSpecialSettings(); if (partnerData != null && partnerData.getLocalIssuer() != null) assertionIssuer.setValue(partnerData.getLocalIssuer()); else assertionIssuer.setValue(_sRedirectUrl); artifactResolve.setIssuer(assertionIssuer); artifactResolve.setArtifact(artifact); // Do some logging for testing _systemLogger.log(Level.INFO, MODULE, sMethod, "Sign the artifactResolve >======"); boolean useSha256 = (specialSettings != null && specialSettings.contains("sha256")); artifactResolve = (ArtifactResolve) SamlTools.signSamlObject(artifactResolve, useSha256 ? "sha256" : "sha1"); _systemLogger.log(Level.INFO, MODULE, sMethod, "Signed the artifactResolve ======<"); // Build the SOAP message SoapManager soapManager = null; if (isUseBackchannelClientcertificate()) { soapManager = new SoapManager(getSslSocketFactory()); } else { soapManager = new SoapManager(); } Envelope envelope = soapManager.buildSOAPMessage(artifactResolve); _systemLogger.log(Level.INFO, MODULE, sMethod, "Marshall"); Element envelopeElem = SamlTools.marshallMessage(envelope); _systemLogger.log(Level.INFO, MODULE, sMethod, "Writing SOAP message:\n" + XMLHelper.nodeToString(envelopeElem)); // XMLHelper.prettyPrintXML(envelopeElem)); // ------------ Send/Receive the SOAP message String sSamlResponse = soapManager.sendSOAP(XMLHelper.nodeToString(envelopeElem), sASelectServerUrl); // x_AssertionConsumer_x //byte[] sSamlResponseAsBytes = sSamlResponse.getBytes(); _systemLogger.log(Level.INFO, MODULE, sMethod, "Received response: " + sSamlResponse + " length=" + sSamlResponse.length()); // save original, but, for (internal) transport, encode base64 auth_proof = new String( org.apache.commons.codec.binary.Base64.encodeBase64(sSamlResponse.getBytes("UTF-8"))); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); // dbFactory.setExpandEntityReferences(false); // dbFactory.setIgnoringComments(true); DocumentBuilder builder = dbFactory.newDocumentBuilder(); StringReader stringReader = new StringReader(sSamlResponse); InputSource inputSource = new InputSource(stringReader); Document docReceivedSoap = builder.parse(inputSource); _systemLogger.log(Level.INFO, MODULE, sMethod, "parsed=" + docReceivedSoap.toString()); Element elementReceivedSoap = docReceivedSoap.getDocumentElement(); _systemLogger.log(Level.INFO, MODULE, sMethod, "getdoc=" + elementReceivedSoap.toString()); // Remove all SOAP elements Node eltArtifactResponse = SamlTools.getNode(elementReceivedSoap, "ArtifactResponse"); // Unmarshall to the SAMLmessage UnmarshallerFactory factory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = factory.getUnmarshaller((Element) eltArtifactResponse); ArtifactResponse artifactResponse = (ArtifactResponse) unmarshaller .unmarshall((Element) eltArtifactResponse); Issuer issuer = artifactResponse.getIssuer(); String sIssuer = (issuer == null) ? null : issuer.getValue(); // If issuer is not present in the response, use sASelectServerUrl value retrieved from metadata // else use value from the response String artifactResponseIssuer = (sIssuer == null || "".equals(sIssuer)) ? sASelectServerUrl : sIssuer; _systemLogger.log(Level.INFO, MODULE, sMethod, "Do artifactResponse signature verification=" + is_bVerifySignature()); // if (is_bVerifySignature()) { // RH, 20121205, o if (is_bVerifySignature() || isVerifyArtifactResponseSignature()) { // RH, 20121205, n // Check signature of artifactResolve here // We get the public key from the metadata // Therefore we need a valid Issuer to lookup the entityID in the metadata // We get the metadataURL from aselect.xml so we consider this safe and authentic if (artifactResponseIssuer == null || "".equals(artifactResponseIssuer)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "For signature verification the received message must have an Issuer"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } PublicKey pkey = metadataManager.getSigningKeyFromMetadata(artifactResponseIssuer); if (pkey == null || "".equals(pkey)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } if (SamlTools.checkSignature(artifactResponse, pkey)) { _systemLogger.log(Level.INFO, MODULE, sMethod, "artifactResponse was signed OK"); } else { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "artifactResponse was NOT signed OK"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } } samlResponseObject = artifactResponse.getMessage(); } else if (!(sReceivedResponse == null || "".equals(sReceivedResponse))) { // Handle http-post, can be unsolicited POST as well // Could be Base64 encoded // RelayState should contain intended application resource URL sRelayState = new String(Base64Codec.decode(sRelayState)); _systemLogger.log(Level.FINER, MODULE, sMethod, "Received Response: " + sReceivedResponse); // RH, 20130924, n // sReceivedResponse = new String(Base64Codec.decode(sReceivedResponse)); // RH, 20130924, o auth_proof = sReceivedResponse; // save original sReceivedResponse = new String( org.apache.commons.codec.binary.Base64.decodeBase64(sReceivedResponse.getBytes("UTF-8"))); // RH, 20130924, n _systemLogger.log(Level.INFO, MODULE, sMethod, "Received Response after base64 decoding: " + sReceivedResponse + " RelayState=" + sRelayState); // RH, 20130924, n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); // dbFactory.setExpandEntityReferences(false); // dbFactory.setIgnoringComments(true); DocumentBuilder builder = dbFactory.newDocumentBuilder(); StringReader stringReader = new StringReader(sReceivedResponse); InputSource inputSource = new InputSource(stringReader); Document docReceived = builder.parse(inputSource); Node eltSAMLResponse = SamlTools.getNode(docReceived, "Response"); _systemLogger.log(Level.INFO, MODULE, sMethod, "Found node Response: " + eltSAMLResponse + ((eltSAMLResponse == null) ? " NULL" : " ok")); // Unmarshall to the SAMLmessage UnmarshallerFactory factory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = factory.getUnmarshaller((Element) eltSAMLResponse); _systemLogger.log(Level.INFO, MODULE, sMethod, "Unmarshaller" + ((unmarshaller == null) ? " NULL" : " ok")); samlResponseObject = (Response) unmarshaller.unmarshall((Element) eltSAMLResponse); _systemLogger.log(Level.INFO, MODULE, sMethod, "Unmarshalling done, VerifySignature=" + is_bVerifySignature()); // 20120308: Bauke added signature checking // saml-profiles-2.0-os: The <Assertion> element(s) in the <Response> MUST be signed, // if the HTTP POST binding is used, and MAY be signed if the HTTPArtifact binding is used. if (is_bVerifySignature()) checkAssertionSigning = true; } else { _systemLogger.log(Level.WARNING, MODULE, sMethod, "No Artifact and no Response found in the message."); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } /////// // The object can either a Response (SSO case) or a StatusResponseType (SLO case) /////////////////////////////////////////////////////////////////////////// if (samlResponseObject instanceof Response) { // SSO Response samlResponse = (Response) samlResponseObject; _systemLogger.log(Level.INFO, MODULE, sMethod, "Processing 'Response'"); // +XMLHelper.prettyPrintXML(samlResponse.getDOM())); // RH, 20121205, sn MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle(); _systemLogger.log(Level.INFO, MODULE, sMethod, "Do Response signature verification=" + isVerifyResponseSignature()); if (isVerifyResponseSignature()) { Issuer issuer = samlResponse.getIssuer(); String sIssuer = (issuer == null) ? null : issuer.getValue(); // If issuer is not present in the response, use sASelectServerUrl value retrieved from metadata // else use value from the response // String responseIssuer = (sIssuer == null || "".equals(sIssuer))? sASelectServerUrl: sIssuer; String responseIssuer = (sIssuer == null || "".equals(sIssuer)) ? null : sIssuer; // There must be an issuer for now // Check signature of artifactResolve here // We get the public key from the metadata // Therefore we need a valid Issuer to lookup the entityID in the metadata // We get the metadataURL from aselect.xml so we consider this safe and authentic if (responseIssuer == null || "".equals(responseIssuer)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "For signature verification the received response must have an Issuer"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } PublicKey pkey = metadataManager.getSigningKeyFromMetadata(responseIssuer); if (pkey == null || "".equals(pkey)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } if (SamlTools.checkSignature(samlResponse, pkey)) { _systemLogger.log(Level.INFO, MODULE, sMethod, "Response was signed OK"); } else { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Response was NOT signed OK"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } } // RH, 20121205, en // Detect if this is a successful or an error Response String sStatusCode = samlResponse.getStatus().getStatusCode().getValue(); String sRemoteRid = samlResponse.getID(); // 20100531, Bauke: Remove added timestamp to get our local RID String sLocalRid = samlResponse.getInResponseTo(); int len = sLocalRid.length(); if (len > 9) sLocalRid = sLocalRid.substring(0, len - 9); _systemLogger.log(Level.INFO, MODULE, sMethod, "RemoteRid=" + sRemoteRid + " LocalRid=" + sLocalRid + " StatusCode=" + sStatusCode); _htSessionContext = _oSessionManager.getSessionContext(sLocalRid); if (_htSessionContext == null) { _systemLogger.log(Level.WARNING, MODULE, sMethod, "Unknown session in response from cross aselect server"); throw new ASelectCommunicationException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } if (sStatusCode.equals(StatusCode.SUCCESS_URI)) { _systemLogger.log(Level.INFO, MODULE, sMethod, "Response was successful " + samlResponse.toString()); _systemLogger.log(Level.INFO, MODULE, sMethod, "Number of Assertions found: " + samlResponse.getAssertions().size()); Assertion samlAssertion = samlResponse.getAssertions().get(0); _systemLogger.log(Level.INFO, MODULE, sMethod, "Assertion ID:" + samlAssertion.getID()); String sAssertIssuer = samlAssertion.getIssuer().getValue(); _systemLogger.log(Level.INFO, MODULE, sMethod, "Issuer:" + sAssertIssuer + " checkAssertionSigning=" + checkAssertionSigning); // 20120308: Bauke added signature checking // if (checkAssertionSigning) { // RH, 20121205, o if (checkAssertionSigning || isVerifyAssertionSignature()) { // RH, 20121205, n // Check signature of artifactResolve here. We get the public key from the metadata // Therefore we need a valid Issuer to lookup the entityID in the metadata // We get the metadataURL from aselect.xml so we consider this safe and authentic _systemLogger.log(Level.INFO, MODULE, sMethod, "Verify assertion signature, issuer=" + sAssertIssuer); if (!Utils.hasValue(sAssertIssuer)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No Issuer present in Assertion"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } // MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle(); // RH, 20121205, n PublicKey pkey = metadataManager.getSigningKeyFromMetadata(sAssertIssuer); if (pkey == null || "".equals(pkey)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } if (!SamlTools.checkSignature(samlAssertion, pkey)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Assertion was NOT signed OK"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } _systemLogger.log(Level.INFO, MODULE, sMethod, "Assertion was signed OK"); } // 20120308 String sNameID = samlAssertion.getSubject().getNameID().getValue(); _systemLogger.log(Level.INFO, MODULE, sMethod, "NameID:" + sNameID); String sNameIDQualifier = samlAssertion.getSubject().getNameID().getNameQualifier(); _systemLogger.log(Level.INFO, MODULE, sMethod, "NameIDQualifier:" + sNameIDQualifier); // Now check for time interval validation // We only check first object from the list // First the assertion itself if (is_bVerifyInterval() && !SamlTools.checkValidityInterval(samlAssertion)) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Assertion time interval was NOT valid"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } // then the AuthnStatement if (is_bVerifyInterval() && !SamlTools.checkValidityInterval(samlAssertion.getAuthnStatements().get(0))) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "AuthnStatement time interval was NOT valid"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } // check subjectlocalityaddress if (isLocalityAddressRequired() && !SamlTools.checkLocalityAddress(samlAssertion.getAuthnStatements().get(0), servletRequest.getRemoteAddr())) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "AuthnStatement subjectlocalityaddress was NOT valid"); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } // Get the (option) sessionindex from remote String sSessionindex = samlAssertion.getAuthnStatements().get(0).getSessionIndex(); _systemLogger.log(Level.INFO, MODULE, sMethod, "Sessionindex:" + sSessionindex); AuthnContext oAuthnContext = samlAssertion.getAuthnStatements().get(0).getAuthnContext(); List<AuthenticatingAuthority> authAuthorities = oAuthnContext.getAuthenticatingAuthorities(); String sAuthnAuthority = null; if (authAuthorities != null && authAuthorities.size() > 0) sAuthnAuthority = (String) authAuthorities.get(0).getURI(); String sAuthnContextClassRefURI = oAuthnContext.getAuthnContextClassRef() .getAuthnContextClassRef(); _systemLogger.log(Level.INFO, MODULE, sMethod, "AuthnContextClassRefURI:" + sAuthnContextClassRefURI); ; ///////////////////////// digid4 /////////////////////////////////////////// /// Digid4 still has to decide how to provide a "face2face" declaration // String sAuthnContextDeclRefIssueMethod = samlAssertion.getAuthnStatements().get(0).getAuthnContext(). ///////////////////////// digid4 /////////////////////////////////////////// String sSelectedLevel = SecurityLevel .convertAuthnContextClassRefURIToLevel(sAuthnContextClassRefURI, _systemLogger); // Check returned security level Integer intAppLevel = (Integer) _htSessionContext.get("level"); if (Integer.parseInt(sSelectedLevel) < intAppLevel) { _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Security level returned (" + sSelectedLevel + ") must be at least: " + intAppLevel); throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST); } // Retrieve the embedded attributes HashMap hmSamlAttributes = new HashMap(); String sEncodedAttributes = null; List<AttributeStatement> lAttrStatList = samlAssertion.getAttributeStatements(); Iterator<AttributeStatement> iASList = lAttrStatList.iterator(); while (iASList.hasNext()) { AttributeStatement sAttr = iASList.next(); List<Attribute> lAttr = sAttr.getAttributes(); Iterator<Attribute> iAttr = lAttr.iterator(); while (iAttr.hasNext()) { Attribute attr = iAttr.next(); String sAttrName = attr.getName(); String sAttrValue = null;// RH, 20120124, sn List<XMLObject> aValues = attr.getAttributeValues(); if (aValues != null && aValues.size() == 1) { // For now we only allow single valued simple type xs:string attributes XMLObject xmlObj = aValues.get(0); // XSStringImpl xsString = (XSStringImpl) attr.getOrderedChildren().get(0);// RH, 20120124, so // String sAttrValue = xsString.getValue();// RH, 20120124, o // sAttrValue = xsString.getValue();// RH, 20120124, eo sAttrValue = xmlObj.getDOM().getFirstChild().getTextContent(); _systemLogger.log(Level.INFO, MODULE, sMethod, "Name=" + sAttrName + " Value=" + sAttrValue); } else { _systemLogger.log(Level.INFO, MODULE, sMethod, "Only single valued attributes allowed, skipped attribute Name=" + sAttrName); } // RH, 20120124, en if ("attributes".equals(sAttrName)) sEncodedAttributes = sAttrValue; else hmSamlAttributes.put(sAttrName, sAttrValue); } } // Since the "attributes" Attribute is used for gathering, add the Saml Attributes to it HashMap<String, String> hmAttributes; if (sEncodedAttributes != null) { hmAttributes = org.aselect.server.utils.Utils.deserializeAttributes(sEncodedAttributes); } else { hmAttributes = new HashMap<String, String>(); } // Add the serialized attributes and a few specials hmSamlAttributes.putAll(hmAttributes); hmSamlAttributes.put("name_id", sNameID); // "sel_level" was already set by the IdP if (sAuthnAuthority != null) hmSamlAttributes.put("authority", sAuthnAuthority); // eHerkenning addition: OrgID = KvKnummer+Vestigingsnummer // If EntityConcernedID = 00000003123456780000 and EntityConcernedSubID = ...0001, // then orgid = 1234567800000001 // String sEntityId = (String)hmSamlAttributes.get("urn:nl:eherkenning:0.8def:EntityConcernedID"); // RH, 20110523, add support for other versions of eHerk String sEntityId = null; Pattern p = Pattern.compile("urn:nl:eherkenning:(.*):EntityConcernedID"); Set<String> keys = hmSamlAttributes.keySet(); Iterator keyIter = keys.iterator(); String eHerkversion = null; while (keyIter.hasNext()) { Matcher m = p.matcher((String) keyIter.next()); if (m.find()) { sEntityId = (String) hmSamlAttributes.get(m.group()); eHerkversion = m.group(1); _systemLogger.log(Level.INFO, MODULE, sMethod, "Found sEntityId=" + sEntityId + " eHerkversion=" + eHerkversion); break; // just take the first we find } } if (sEntityId != null) { int idx = sEntityId.length() - 12; // last 12 characters if (idx > 0) sEntityId = sEntityId.substring(idx); // String sEntitySubId = (String)hmSamlAttributes.get("urn:nl:eherkenning:0.8def:EntityConcernedSubID"); String sEntitySubId = (String) hmSamlAttributes .get("urn:nl:eherkenning:" + eHerkversion + ":EntityConcernedSubID"); if (sEntitySubId != null) { _systemLogger.log(Level.INFO, MODULE, sMethod, "Found sEntitySubId=" + sEntitySubId); idx = sEntitySubId.length() - 12; // last 12 characters to be on the safe side if (idx > 0) sEntitySubId = sEntitySubId.substring(idx); sEntityId = sEntitySubId; } else { // ditch the last 4 zeroes idx = sEntityId.length() - 4; if (idx > 0) sEntityId = sEntityId.substring(0, idx); } hmSamlAttributes.put("orgid", sEntityId); } // eHerkenning: AuthID = Unique Persistent Identifier if (isUseNameIDAsAuthID()) { // RH, 20130923, sn hmSamlAttributes.put("authid", sNameID); } else { // RH, 20130923, en // Use the fifth word from sAuthnAuthority (split using :) and add sNameID if (sNameIDQualifier != null) { String sAuthID = "", sAuthSubID = ""; String[] tokens = sNameIDQualifier.split(":"); if (tokens.length > 4) sAuthID = tokens[4]; // if (tokens.length > 5) // sAuthSubID = tokens[5]; // Test new layout of eherkenning // Maybe do something with pattern search here if (tokens.length > 6) sAuthSubID = tokens[6]; sAuthID += "_" + sAuthSubID + "_" + sNameID; // add separator hmSamlAttributes.put("authid", sAuthID); } } // RH, 20130923, n if (isCarryAuthProof()) { // Put the original authentication proof in hmSamlAttributes before serialization in attributes // so they will be available for gatherer hmSamlAttributes.put("auth_proof", auth_proof); // original response, still base64 encoded // _systemLogger.log(Level.FINEST, MODULE, sMethod, "auth_proof=" + auth_proof); } // And serialize them back to where they came from sEncodedAttributes = org.aselect.server.utils.Utils.serializeAttributes(hmSamlAttributes); hmSamlAttributes.put("attributes", sEncodedAttributes); if (!isCarryAuthProof() && isLogAuthProof()) { // Put the original authentication proof in hmSamlAttributes only temporarily to be removed later // if isCarryAuthProof() true they were already there hmSamlAttributes.put("auth_proof", auth_proof); // original response, still base64 encoded // _systemLogger.log(Level.FINEST, MODULE, sMethod, "auth_proof=" + auth_proof); } // This is the quickest way to get "name_id" into the Context hmSamlAttributes.put("name_id", sNameID); // also as plain attribute ///////////// Digid4 ////////////////////////////// // must be made configurable and parameterized, still looking for some reference to identify the service (maybe issuer) String[] splittedNameId = sNameID.split(":"); if (splittedNameId.length == 2 && splittedNameId[0].toUpperCase().startsWith("S") && splittedNameId[0].length() == 9) { // for now this identifies as digid4 hmSamlAttributes.put("uid", splittedNameId[1]); // add special attributes for digid4 if ("S00000000".equalsIgnoreCase(splittedNameId[0])) { hmSamlAttributes.put("bsn", splittedNameId[1]); } else if ("S00000001".equalsIgnoreCase(splittedNameId[0])) { hmSamlAttributes.put("sofi", splittedNameId[1]); } else if ("S00000002".equalsIgnoreCase(splittedNameId[0])) { hmSamlAttributes.put("anummer", splittedNameId[1]); } else if ("S00000100".equalsIgnoreCase(splittedNameId[0])) { hmSamlAttributes.put("oeb", splittedNameId[1]); } } ///////////////////////////////////////////////////// // 20100422, Bauke: no uid, then use NameID String sUid = (String) hmSamlAttributes.get("uid"); if (sUid == null || sUid.equals("")) hmSamlAttributes.put("uid", sNameID); _systemLogger.log(Level.INFO, MODULE, sMethod, "NameID=" + sNameID + " remote_rid=" + sRemoteRid + " local_rid=" + sLocalRid + " sel_level=" + sSelectedLevel + " organization/authsp=" + sAssertIssuer); // htRemoteAttributes.put("attributes", HandlerTools.serializeAttributes(htAttributes)); hmSamlAttributes.put("remote_rid", sRemoteRid); hmSamlAttributes.put("local_rid", sLocalRid); hmSamlAttributes.put("sel_level", sSelectedLevel); hmSamlAttributes.put("authsp_level", sSelectedLevel); // default value, issueTGT will correct this hmSamlAttributes.put("organization", sAssertIssuer); hmSamlAttributes.put("authsp", sAssertIssuer); // RH, 20120201, sn // also save the provided session if present, saml2 specs say there might be more than one session to track if (isIncludeSessionindexes() && sSessionindex != null && sSessionindex.length() > 0) { Vector sessionindexes = new Vector<String>(); sessionindexes.add(sSessionindex); hmSamlAttributes.put("remote_sessionlist", sessionindexes); } // RH, 20120201, en // Bauke, 20081204: If we want to send the IdP token as an attribute // to the application, we will need the following code: /* * String sAssertion = XMLHelper.nodeToString(samlAssertion.getDOM()); * _systemLogger.log(Level.INFO, MODULE, sMethod, "sAssertion="+sAssertion); * BASE64Encoder b64Enc = new BASE64Encoder(); * sAssertion = b64Enc.encode(sAssertion.getBytes("UTF-8")); * htRemoteAttributes.put("saml_remote_token", sAssertion); */ // End of IdP token _systemLogger.log(Level.INFO, MODULE, sMethod, "htRemoteAttributes=" + hmSamlAttributes); handleSSOResponse(_htSessionContext, hmSamlAttributes, servletRequest, servletResponse); } else { _systemLogger.log(Level.WARNING, MODULE, sMethod, "Response was not successful: " + sStatusCode); // Handle various error conditions here String sErrorCode = Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER; // default String sErrorSubCode = null; if (samlResponse.getStatus().getStatusCode().getStatusCode() != null) { // Get the subcode sErrorSubCode = SamlTools .mapStatus(samlResponse.getStatus().getStatusCode().getStatusCode().getValue()); _systemLogger.log(Level.FINER, MODULE, sMethod, "ErrorSubcode: " + sErrorSubCode); } StatusMessage statMsg = samlResponse.getStatus().getStatusMessage(); if (statMsg != null) { sErrorCode = statMsg.getMessage(); _systemLogger.log(Level.FINER, MODULE, sMethod, "StatusMessage found: " + sErrorCode); } else { if (sErrorSubCode != null && !"".equals(sErrorSubCode)) { sErrorCode = sErrorSubCode; } } _systemLogger.log(Level.INFO, MODULE, sMethod, "ErrorCode=" + sErrorCode); //else if (samlResponse.getStatus().getStatusCode().getStatusCode().getValue().equals(StatusCode.AUTHN_FAILED_URI)) // sErrorCode = Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER; // Expect these codes: Errors.ERROR_ASELECT_SERVER_CANCEL, // Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER; //HashMap htRemoteAttributes = new HashMap(); //htRemoteAttributes.put("remote_rid", sRemoteRid); //htRemoteAttributes.put("local_rid", sLocalRid); //htRemoteAttributes.put("result_code", sErrorCode); // Choose your response (3rd is implemented below) // 1. handleSSOResponse(htRemoteAttributes, request, response); // Lets application display error // 2. throw new ASelectException(Errors.ERROR_ASELECT_AUTHSP_ACCESS_DENIED); // Standard server error // 3. Show error page: showErrorPage(sErrorCode, _htSessionContext, pwOut, servletRequest); } } else { // SLO _systemLogger.log(Level.WARNING, "Unexpected SAMLObject type: " + samlResponseObject.getClass()); throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR); } } catch (ASelectException e) { throw e; } catch (Exception e) { _systemLogger.log(Level.WARNING, MODULE, sMethod, "Internal error", e); throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e); } finally { if (pwOut != null) pwOut.close(); // 20130821, Bauke: save friendly name after session is gone if (_htSessionContext != null) { String sStatus = (String) _htSessionContext.get("status"); String sAppId = (String) _htSessionContext.get("app_id"); if ("del".equals(sStatus) && Utils.hasValue(sAppId)) { String sUF = ApplicationManager.getHandle().getFriendlyName(sAppId); HandlerTools.setEncryptedCookie(servletResponse, "requestor_friendly_name", sUF, _configManager.getCookieDomain(), -1/*age*/, _systemLogger); } } _oSessionManager.finalSessionProcessing(_htSessionContext, true/*really do it*/); } return null; }
From source file:com.granule.json.utils.internal.JSONObject.java
/** * Method to write a text ony XML tagset, like <F>FOO</F> * @param writer The writer object to render the XML to. * @param indentDepth How far to indent. * @param contentOnly Whether or not to write the object name as part of the output * @param compact Whether or not to write the ohject in compact form, or nice indent form. * @throws IOException Trhown if an error occurs on write. *//*from www . j a v a2 s . c o m*/ private void writeTextOnlyObject(Writer writer, int indentDepth, boolean contentOnly, boolean compact) throws IOException { if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeTextOnlyObject(Writer, int, boolean, boolean)"); if (!contentOnly) { writeAttribute(writer, this.objectName, this.tagText.trim(), indentDepth, compact); } else { if (!compact) { writeIndention(writer, indentDepth); writer.write("\"" + escapeStringSpecialCharacters(this.tagText.trim()) + "\""); } else { writer.write("\"" + escapeStringSpecialCharacters(this.tagText.trim()) + "\""); } } if (logger.isLoggable(Level.FINER)) logger.exiting(className, "writeTextOnlyObject(Writer, int, boolean, boolean)"); }
From source file:org.jenkinsci.plugins.pipeline.maven.dao.PipelineMavenPluginH2Dao.java
/** * List the artifacts generated by the given build * * @param jobFullName see {@link Item#getFullName()} * @param buildNumber see {@link Run#getNumber()} * @return list of artifact details stored as maps ("gav", "type", "skip_downstream_triggers") *//*from w w w. j a va 2s . c o m*/ @Nonnull public List<Map<String, String>> getGeneratedArtifacts(@Nonnull String jobFullName, @Nonnull int buildNumber) { LOGGER.log(Level.FINER, "getGeneratedArtifacts({0}, {1})", new Object[] { jobFullName, buildNumber }); String generatedArtifactsSql = "SELECT DISTINCT MAVEN_ARTIFACT.*, GENERATED_MAVEN_ARTIFACT.* " + " FROM MAVEN_ARTIFACT " + " INNER JOIN GENERATED_MAVEN_ARTIFACT ON MAVEN_ARTIFACT.ID = GENERATED_MAVEN_ARTIFACT.ARTIFACT_ID" + " INNER JOIN JENKINS_BUILD AS UPSTREAM_BUILD ON GENERATED_MAVEN_ARTIFACT.BUILD_ID = UPSTREAM_BUILD.ID " + " INNER JOIN JENKINS_JOB AS UPSTREAM_JOB ON UPSTREAM_BUILD.JOB_ID = UPSTREAM_JOB.ID " + " WHERE " + " UPSTREAM_JOB.FULL_NAME = ? AND" + " UPSTREAM_BUILD.NUMBER = ? "; List<Map<String, String>> results = new ArrayList<>(); try (Connection cnn = this.jdbcConnectionPool.getConnection()) { try (PreparedStatement stmt = cnn.prepareStatement(generatedArtifactsSql)) { stmt.setString(1, jobFullName); stmt.setInt(2, buildNumber); try (ResultSet rst = stmt.executeQuery()) { while (rst.next()) { Map<String, String> artifact = new HashMap<>(); String gav = rst.getString("maven_artifact.group_id") + ":" + rst.getString("maven_artifact.artifact_id") + ":" + rst.getString("maven_artifact.version"); artifact.put("gav", gav); artifact.put("type", rst.getString("maven_artifact.type")); artifact.put("skip_downstream_triggers", rst.getString("generated_maven_artifact.skip_downstream_triggers")); results.add(artifact); } } } } catch (SQLException e) { throw new RuntimeSqlException(e); } return results; }