Unnamed: 0
int64
0
637
label
int64
0
1
code
stringlengths
24
8.83k
500
1
private <T> void setValidatedValueHandlerToValueContextIfPresent(ValidationContext<?> validationContext, ValueContext<?, T> valueContext, ConstraintMetaData metaData) { if ( metaData.requiresUnwrapping() ) { @SuppressWarnings("unchecked") //we know the handler matches the value type ValidatedValueUnwrapper<? super T> handler = (ValidatedValueUnwrapper<T>) getValidatedValueHandler( metaData.getType() ); if ( handler == null ) { throw log.getNoUnwrapperFoundForTypeException( metaData.getType().toString() ); } valueContext.setValidatedValueHandler( handler ); } }
501
1
public boolean getValidateClientProvidedNewSessionId() { return false; }
502
1
protected Object findValue(String expr, Class toType) { if (altSyntax() && toType == String.class) { return TextParseUtil.translateVariables('%', expr, stack); } else { expr = stripExpressionIfAltSyntax(expr); return getStack().findValue(expr, toType, throwExceptionOnELFailure); } } /** * Renders an action URL by consulting the {@link org.apache.struts2.dispatcher.mapper.ActionMapper}. * @param action the action * @param namespace the namespace * @param method the method * @param req HTTP request * @param res HTTP response * @param parameters parameters * @param scheme http or https * @param includeContext should the context path be included or not * @param encodeResult should the url be encoded * @param forceAddSchemeHostAndPort should the scheme host and port be forced * @param escapeAmp should ampersand (&amp;) be escaped to &amp;amp; * @return the action url. */
503
1
public HttpBinding getBinding() { if (this.binding == null) { this.binding = new AttachmentHttpBinding(); this.binding.setTransferException(isTransferException()); this.binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); } return this.binding; } @Override
504
1
public HttpBinding getBinding() { if (binding == null) { // create a new binding and use the options from this endpoint binding = new DefaultHttpBinding(); binding.setHeaderFilterStrategy(getHeaderFilterStrategy()); binding.setTransferException(isTransferException()); binding.setEagerCheckContentAvailable(isEagerCheckContentAvailable()); } return binding; } /** * To use a custom HttpBinding to control the mapping between Camel message and HttpClient. */
505
1
public void setMaxTrailerSize(int maxTrailerSize) { this.maxTrailerSize = maxTrailerSize; } /** * This field indicates if the protocol is treated as if it is secure. This * normally means https is being used but can be used to fake https e.g * behind a reverse proxy. */
506
1
public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, final Set<InternetAddress> to, final Set<InternetAddress> cc, final Set<InternetAddress> bcc) { final class Debug implements RecipientProviderUtilities.IDebug { private final ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class); private final PrintStream logger = context.getListener().getLogger(); public void send(final String format, final Object... args) { descriptor.debug(logger, format, args); } } final Debug debug = new Debug(); Set<User> users = null; final Run<?, ?> currentRun = context.getRun(); if (currentRun == null) { debug.send("currentRun was null"); } else { if (!Objects.equals(currentRun.getResult(), Result.FAILURE)) { debug.send("currentBuild did not fail"); } else { users = new HashSet<>(); debug.send("Collecting builds with suspects..."); final HashSet<Run<?, ?>> buildsWithSuspects = new HashSet<>(); Run<?, ?> firstFailedBuild = currentRun; Run<?, ?> candidate = currentRun; while (candidate != null) { final Result candidateResult = candidate.getResult(); if ( candidateResult == null || !candidateResult.isWorseOrEqualTo(Result.FAILURE) ) { break; } firstFailedBuild = candidate; candidate = candidate.getPreviousCompletedBuild(); } if (firstFailedBuild instanceof AbstractBuild) { buildsWithSuspects.add(firstFailedBuild); } else { debug.send(" firstFailedBuild was not an instance of AbstractBuild"); } debug.send("Collecting suspects..."); users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); } } if (users != null) { RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); } } @Extension
507
1
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse) throws IOException, ServletException { assertEquals("Invalid method", "POST", ((HttpServletRequest) filterRequest).getMethod()); } };
508
1
public void restorePersistentSettingsTest() throws Exception { logger.info("--> start 2 nodes"); Settings nodeSettings = settingsBuilder() .put("discovery.type", "zen") .put("discovery.zen.ping_timeout", "200ms") .put("discovery.initial_state_timeout", "500ms") .build(); internalCluster().startNode(nodeSettings); Client client = client(); String secondNode = internalCluster().startNode(nodeSettings); logger.info("--> wait for the second node to join the cluster"); assertThat(client.admin().cluster().prepareHealth().setWaitForNodes("2").get().isTimedOut(), equalTo(false)); int random = randomIntBetween(10, 42); logger.info("--> set test persistent setting"); client.admin().cluster().prepareUpdateSettings().setPersistentSettings( ImmutableSettings.settingsBuilder() .put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 2) .put(IndicesTTLService.INDICES_TTL_INTERVAL, random, TimeUnit.MINUTES)) .execute().actionGet(); assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis())); assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() .getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), equalTo(2)); logger.info("--> create repository"); PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo") .setType("fs").setSettings(ImmutableSettings.settingsBuilder().put("location", newTempDir())).execute().actionGet(); assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true)); logger.info("--> start snapshot"); CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).execute().actionGet(); assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), equalTo(0)); assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(0)); assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); logger.info("--> clean the test persistent setting"); client.admin().cluster().prepareUpdateSettings().setPersistentSettings( ImmutableSettings.settingsBuilder() .put(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, 1) .put(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1))) .execute().actionGet(); assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(1).millis())); stopNode(secondNode); assertThat(client.admin().cluster().prepareHealth().setWaitForNodes("1").get().isTimedOut(), equalTo(false)); logger.info("--> restore snapshot"); client.admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap").setRestoreGlobalState(true).setWaitForCompletion(true).execute().actionGet(); assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() .getMetaData().persistentSettings().getAsTime(IndicesTTLService.INDICES_TTL_INTERVAL, TimeValue.timeValueMinutes(1)).millis(), equalTo(TimeValue.timeValueMinutes(random).millis())); logger.info("--> ensure that zen discovery minimum master nodes wasn't restored"); assertThat(client.admin().cluster().prepareState().setRoutingTable(false).setNodes(false).execute().actionGet().getState() .getMetaData().persistentSettings().getAsInt(ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES, -1), not(equalTo(2))); } @Test
509
1
public void init(FilterConfig conf) throws ServletException { if (conf != null && "zookeeper".equals(conf.getInitParameter("signer.secret.provider"))) { SolrZkClient zkClient = (SolrZkClient)conf.getServletContext().getAttribute(KerberosPlugin.DELEGATION_TOKEN_ZK_CLIENT); conf.getServletContext().setAttribute("signer.secret.provider.zookeeper.curator.client", getCuratorClient(zkClient)); } super.init(conf); } /** * Return the ProxyUser Configuration. FilterConfig properties beginning with * "solr.impersonator.user.name" will be added to the configuration. */ @Override
510
1
Attributes setPropertiesFromAttributes( StylesheetHandler handler, String rawName, Attributes attributes, ElemTemplateElement target, boolean throwError) throws org.xml.sax.SAXException { XSLTElementDef def = getElemDef(); AttributesImpl undefines = null; boolean isCompatibleMode = ((null != handler.getStylesheet() && handler.getStylesheet().getCompatibleMode()) || !throwError); if (isCompatibleMode) undefines = new AttributesImpl(); // Keep track of which XSLTAttributeDefs have been processed, so // I can see which default values need to be set. List processedDefs = new ArrayList(); // Keep track of XSLTAttributeDefs that were invalid List errorDefs = new ArrayList(); int nAttrs = attributes.getLength(); for (int i = 0; i < nAttrs; i++) { String attrUri = attributes.getURI(i); // Hack for Crimson. -sb if((null != attrUri) && (attrUri.length() == 0) && (attributes.getQName(i).startsWith("xmlns:") || attributes.getQName(i).equals("xmlns"))) { attrUri = org.apache.xalan.templates.Constants.S_XMLNAMESPACEURI; } String attrLocalName = attributes.getLocalName(i); XSLTAttributeDef attrDef = def.getAttributeDef(attrUri, attrLocalName); if (null == attrDef) { if (!isCompatibleMode) { // Then barf, because this element does not allow this attribute. handler.error(XSLTErrorResources.ER_ATTR_NOT_ALLOWED, new Object[]{attributes.getQName(i), rawName}, null);//"\""+attributes.getQName(i)+"\"" //+ " attribute is not allowed on the " + rawName // + " element!", null); } else { undefines.addAttribute(attrUri, attrLocalName, attributes.getQName(i), attributes.getType(i), attributes.getValue(i)); } } else { // Can we switch the order here: boolean success = attrDef.setAttrValue(handler, attrUri, attrLocalName, attributes.getQName(i), attributes.getValue(i), target); // Now we only add the element if it passed a validation check if (success) processedDefs.add(attrDef); else errorDefs.add(attrDef); } } XSLTAttributeDef[] attrDefs = def.getAttributes(); int nAttrDefs = attrDefs.length; for (int i = 0; i < nAttrDefs; i++) { XSLTAttributeDef attrDef = attrDefs[i]; String defVal = attrDef.getDefault(); if (null != defVal) { if (!processedDefs.contains(attrDef)) { attrDef.setDefAttrValue(handler, target); } } if (attrDef.getRequired()) { if ((!processedDefs.contains(attrDef)) && (!errorDefs.contains(attrDef))) handler.error( XSLMessages.createMessage( XSLTErrorResources.ER_REQUIRES_ATTRIB, new Object[]{ rawName, attrDef.getName() }), null); } } return undefines; }
511
1
public SecurityConstraint [] findSecurityConstraints(Request request, Context context) { ArrayList<SecurityConstraint> results = null; // Are there any defined security constraints? SecurityConstraint constraints[] = context.findConstraints(); if ((constraints == null) || (constraints.length == 0)) { if (log.isDebugEnabled()) log.debug(" No applicable constraints defined"); return null; } // Check each defined security constraint String uri = request.getRequestPathMB().toString(); // Bug47080 - in rare cases this may be null // Mapper treats as '/' do the same to prevent NPE if (uri == null) { uri = "/"; } String method = request.getMethod(); int i; boolean found = false; for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } for(int k=0; k < patterns.length; k++) { if(uri.equals(patterns[k])) { found = true; if(collection[j].findMethod(method)) { if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } } } if(found) { return resultsToArray(results); } int longest = -1; for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } boolean matched = false; int length = -1; for(int k=0; k < patterns.length; k++) { String pattern = patterns[k]; if(pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) { if(pattern.length() == 2) { matched = true; length = pattern.length(); } else if(pattern.regionMatches(0,uri,0, pattern.length()-1) || (pattern.length()-2 == uri.length() && pattern.regionMatches(0,uri,0, pattern.length()-2))) { matched = true; length = pattern.length(); } } } if(matched) { if(length > longest) { found = false; if(results != null) { results.clear(); } longest = length; } if(collection[j].findMethod(method)) { found = true; if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } } if(found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } boolean matched = false; int pos = -1; for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } for(int k=0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if(pattern.startsWith("*.")){ int slash = uri.lastIndexOf('/'); int dot = uri.lastIndexOf('.'); if(slash >= 0 && dot > slash && dot != uri.length()-1 && uri.length()-dot == pattern.length()-1) { if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) { matched = true; pos = j; } } } } } if(matched) { found = true; if(collection[pos].findMethod(method)) { if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } if(found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } boolean matched = false; for(int k=0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if(pattern.equals("/")){ matched = true; } } if(matched) { if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } if(results == null) { // No applicable security constraint was found if (log.isDebugEnabled()) log.debug(" No applicable constraint located"); } return resultsToArray(results); } /** * Convert an ArrayList to a SecurityConstraint []. */
512
1
private void writeSession(SessionInformations session, boolean displayUser) throws IOException { final String nextColumnAlignRight = "</td><td align='right'>"; final String nextColumnAlignCenter = "</td><td align='center'>"; write("<td><a href='?part=sessions&amp;sessionId="); write(htmlEncodeButNotSpace(session.getId())); write("'>"); write(htmlEncodeButNotSpace(session.getId())); write("</a>"); write(nextColumnAlignRight); write(durationFormat.format(session.getLastAccess())); write(nextColumnAlignRight); write(durationFormat.format(session.getAge())); write(nextColumnAlignRight); write(expiryFormat.format(session.getExpirationDate())); write(nextColumnAlignRight); write(integerFormat.format(session.getAttributeCount())); write(nextColumnAlignCenter); if (session.isSerializable()) { write("#oui#"); } else { write("<span class='severe'>#non#</span>"); } write(nextColumnAlignRight); write(integerFormat.format(session.getSerializedSize())); final String nextColumn = "</td><td>"; write(nextColumn); final String remoteAddr = session.getRemoteAddr(); if (remoteAddr == null) { write("&nbsp;"); } else { write(remoteAddr); } write(nextColumnAlignCenter); writeCountry(session); if (displayUser) { write(nextColumn); final String remoteUser = session.getRemoteUser(); if (remoteUser == null) { write("&nbsp;"); } else { writeDirectly(htmlEncodeButNotSpace(remoteUser)); } } write("</td><td align='center' class='noPrint'>"); write(A_HREF_PART_SESSIONS); write("&amp;action=invalidate_session&amp;sessionId="); write(urlEncode(session.getId())); write("' onclick=\"javascript:return confirm('" + getStringForJavascript("confirm_invalidate_session") + "');\">"); write("<img width='16' height='16' src='?resource=user-trash.png' alt='#invalidate_session#' title='#invalidate_session#' />"); write("</a>"); write("</td>"); }
513
1
public boolean isUseRouteBuilder() { return false; } @Test
514
1
private <T> T run(PrivilegedAction<T> action) { return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run(); } // JAXB closes the underlying input stream
515
1
public void execute(FunctionContext context) { RegionConfiguration configuration = (RegionConfiguration) context.getArguments(); if (this.cache.getLogger().fineEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("Function ").append(ID).append(" received request: ").append(configuration); this.cache.getLogger().fine(builder.toString()); } // Create or retrieve region RegionStatus status = createOrRetrieveRegion(configuration); // Dump XML if (DUMP_SESSION_CACHE_XML) { writeCacheXml(); } // Return status context.getResultSender().lastResult(status); }
516
1
public static int methodUrl(String path, ByteChunk out, int readTimeout, Map<String, List<String>> reqHead, Map<String, List<String>> resHead, String method) throws IOException { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(false); connection.setReadTimeout(readTimeout); connection.setRequestMethod(method); if (reqHead != null) { for (Map.Entry<String, List<String>> entry : reqHead.entrySet()) { StringBuilder valueList = new StringBuilder(); for (String value : entry.getValue()) { if (valueList.length() > 0) { valueList.append(','); } valueList.append(value); } connection.setRequestProperty(entry.getKey(), valueList.toString()); } } connection.connect(); int rc = connection.getResponseCode(); if (resHead != null) { Map<String, List<String>> head = connection.getHeaderFields(); resHead.putAll(head); } InputStream is; if (rc < 400) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } if (is != null) { try (BufferedInputStream bis = new BufferedInputStream(is)) { byte[] buf = new byte[2048]; int rd = 0; while((rd = bis.read(buf)) > 0) { out.append(buf, 0, rd); } } } return rc; }
517
1
public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env, final Set<InternetAddress> to, final Set<InternetAddress> cc, final Set<InternetAddress> bcc) { final class Debug implements RecipientProviderUtilities.IDebug { private final ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class); private final PrintStream logger = context.getListener().getLogger(); public void send(final String format, final Object... args) { descriptor.debug(logger, format, args); } } final Debug debug = new Debug(); Set<User> users = null; final Run<?, ?> currentRun = context.getRun(); if (currentRun == null) { debug.send("currentRun was null"); } else { final AbstractTestResultAction<?> testResultAction = currentRun.getAction(AbstractTestResultAction.class); if (testResultAction == null) { debug.send("testResultAction was null"); } else { if (testResultAction.getFailCount() <= 0) { debug.send("getFailCount() returned <= 0"); } else { users = new HashSet<>(); debug.send("Collecting builds where a test started failing..."); final HashSet<Run<?, ?>> buildsWhereATestStartedFailing = new HashSet<>(); for (final TestResult caseResult : testResultAction.getFailedTests()) { final Run<?, ?> runWhereTestStartedFailing = caseResult.getFailedSinceRun(); if (runWhereTestStartedFailing != null) { debug.send(" runWhereTestStartedFailing: %d", runWhereTestStartedFailing.getNumber()); buildsWhereATestStartedFailing.add(runWhereTestStartedFailing); } else { context.getListener().error("getFailedSinceRun returned null for %s", caseResult.getFullDisplayName()); } } // For each build where a test started failing, walk backward looking for build results worse than // UNSTABLE. All of those builds will be used to find suspects. debug.send("Collecting builds with suspects..."); final HashSet<Run<?, ?>> buildsWithSuspects = new HashSet<>(); for (final Run<?, ?> buildWhereATestStartedFailing : buildsWhereATestStartedFailing) { debug.send(" buildWhereATestStartedFailing: %d", buildWhereATestStartedFailing.getNumber()); buildsWithSuspects.add(buildWhereATestStartedFailing); Run<?, ?> previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild(); if (previousBuildToCheck != null) { debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber()); } while (previousBuildToCheck != null) { if (buildsWithSuspects.contains(previousBuildToCheck)) { // Short-circuit if the build to check has already been checked. debug.send(" already contained in buildsWithSuspects; stopping search"); break; } final Result previousResult = previousBuildToCheck.getResult(); if (previousResult == null) { debug.send(" previousResult was null"); } else { debug.send(" previousResult: %s", previousResult.toString()); if (previousResult.isBetterThan(Result.FAILURE)) { debug.send(" previousResult was better than FAILURE; stopping search"); break; } else { debug.send(" previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search"); buildsWithSuspects.add(previousBuildToCheck); previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild(); if (previousBuildToCheck != null) { debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber()); } } } } } debug.send("Collecting suspects..."); users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); } } } if (users != null) { RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); } } @Extension
518
1
public static DateTimeZone randomDateTimeZone() { DateTimeZone timeZone; // It sounds like some Java Time Zones are unknown by JODA. For example: Asia/Riyadh88 // We need to fallback in that case to a known time zone try { timeZone = DateTimeZone.forTimeZone(randomTimeZone()); } catch (IllegalArgumentException e) { timeZone = DateTimeZone.forOffsetHours(randomIntBetween(-12, 12)); } return timeZone; }
519
1
public void testTriggerWithLockedDownInstance() throws Exception { FreeStyleProject project = DuplicatesUtil.createGerritTriggeredJob(j, projectName); Setup.lockDown(j); GerritTrigger trigger = project.getTrigger(GerritTrigger.class); trigger.setSilentStartMode(false); GerritServer gerritServer = new GerritServer(PluginImpl.DEFAULT_SERVER_NAME); SshdServerMock.configureFor(sshd, gerritServer); PluginImpl.getInstance().addServer(gerritServer); gerritServer.getConfig().setNumberOfSendingWorkerThreads(NUMBEROFSENDERTHREADS); ((Config)gerritServer.getConfig()).setGerritAuthKeyFile(sshKey.getPrivateKey()); gerritServer.start(); gerritServer.triggerEvent(Setup.createPatchsetCreated()); TestUtils.waitForBuilds(project, 1); //wait until command is registered // CS IGNORE MagicNumber FOR NEXT 2 LINES. REASON: ConstantsNotNeeded Thread.sleep(TimeUnit.SECONDS.toMillis(10)); assertEquals(2, server.getNrCommandsHistory("gerrit review.*")); FreeStyleBuild buildOne = project.getLastCompletedBuild(); assertSame(Result.SUCCESS, buildOne.getResult()); assertEquals(1, project.getLastCompletedBuild().getNumber()); assertSame(PluginImpl.DEFAULT_SERVER_NAME, buildOne.getCause(GerritCause.class).getEvent().getProvider().getName()); }
520
1
public static <T> Transformer<T, T> cloneTransformer() { return (Transformer<T, T>) INSTANCE; } /** * Constructor. */
521
1
public void setEnabled(boolean enabled);
522
1
public void testHttpSendStringAndReceiveJavaBody() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("jetty:http://localhost:{{port}}/myapp/myservice") .process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); assertNotNull(body); assertEquals("Hello World", body); MyCoolBean reply = new MyCoolBean(456, "Camel rocks"); exchange.getOut().setBody(reply); exchange.getOut().setHeader(Exchange.CONTENT_TYPE, HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); } }); } }); context.start(); MyCoolBean reply = template.requestBody("http://localhost:{{port}}/myapp/myservice", "Hello World", MyCoolBean.class); assertEquals(456, reply.getId()); assertEquals("Camel rocks", reply.getName()); }
523
1
private boolean evaluate(String text) { try { InputSource inputSource = new InputSource(new StringReader(text)); return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); } catch (XPathExpressionException e) { return false; } } @Override
524
1
protected boolean isAccepted(String paramName) { if (!this.acceptParams.isEmpty()) { for (Pattern pattern : acceptParams) { Matcher matcher = pattern.matcher(paramName); if (matcher.matches()) { return true; } } return false; } else return acceptedPattern.matcher(paramName).matches(); }
525
1
public void loadConfig(Class<?>... configs) { this.context = new AnnotationConfigWebApplicationContext(); this.context.register(configs); this.context.refresh(); this.context.getAutowireCapableBeanFactory().autowireBean(this); }
526
1
private CoderResult decodeHasArray(ByteBuffer in, CharBuffer out) { int outRemaining = out.remaining(); int pos = in.position(); int limit = in.limit(); final byte[] bArr = in.array(); final char[] cArr = out.array(); final int inIndexLimit = limit + in.arrayOffset(); int inIndex = pos + in.arrayOffset(); int outIndex = out.position() + out.arrayOffset(); // if someone would change the limit in process, // he would face consequences for (; inIndex < inIndexLimit && outRemaining > 0; inIndex++) { int jchar = bArr[inIndex]; if (jchar < 0) { jchar = jchar & 0x7F; int tail = remainingBytes[jchar]; if (tail == -1) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); } if (inIndexLimit - inIndex < 1 + tail) { // Apache Tomcat added test - detects invalid sequence as // early as possible if (jchar == 0x74 && inIndexLimit > inIndex + 1) { if ((bArr[inIndex + 1] & 0xFF) > 0x8F) { return CoderResult.unmappableForLength(4); } } break; } for (int i = 0; i < tail; i++) { int nextByte = bArr[inIndex + i + 1] & 0xFF; if ((nextByte & 0xC0) != 0x80) { in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1 + i); } jchar = (jchar << 6) + nextByte; } jchar -= remainingNumbers[tail]; if (jchar < lowerEncodingLimit[tail]) { // Should have been encoded in fewer octets in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return CoderResult.malformedForLength(1); } inIndex += tail; } // Apache Tomcat added test if (jchar >= 0xD800 && jchar <= 0xDFFF) { return CoderResult.unmappableForLength(3); } // Apache Tomcat added test if (jchar > 0x10FFFF) { return CoderResult.unmappableForLength(4); } if (jchar <= 0xffff) { cArr[outIndex++] = (char) jchar; outRemaining--; } else { if (outRemaining < 2) { return CoderResult.OVERFLOW; } cArr[outIndex++] = (char) ((jchar >> 0xA) + 0xD7C0); cArr[outIndex++] = (char) ((jchar & 0x3FF) + 0xDC00); outRemaining -= 2; } } in.position(inIndex - in.arrayOffset()); out.position(outIndex - out.arrayOffset()); return (outRemaining == 0 && inIndex < inIndexLimit) ? CoderResult.OVERFLOW : CoderResult.UNDERFLOW; }
527
1
public void testBogusPathCheck() { TesseractOCRConfig config = new TesseractOCRConfig(); config.setTesseractPath("blahdeblahblah"); assertEquals("blahdeblahblah", config.getTesseractPath()); }
528
1
public void setValues(PreparedStatement ps) throws SQLException { Timestamp t = new Timestamp(new Date().getTime()); ps.setTimestamp(1, t); ps.setString(2, encNewPassword); ps.setTimestamp(3, t); ps.setString(4, id); } });
529
1
public boolean isTransferException() { return transferException; } /** * If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized * in the response as a application/x-java-serialized-object content type. */
530
1
public void testSingletonPatternInSerialization() { final Object[] singletones = new Object[] { CloneTransformer.INSTANCE, ExceptionTransformer.INSTANCE, NOPTransformer.INSTANCE, StringValueTransformer.stringValueTransformer(), }; for (final Object original : singletones) { TestUtils.assertSameAfterSerialization("Singleton pattern broken for " + original.getClass(), original); } }
531
1
public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new ECDSA5Test()); }
532
1
public synchronized void afterTest() throws IOException { wipeDataDirectories(); randomlyResetClients(); /* reset all clients - each test gets its own client based on the Random instance created above. */ } @Override
533
1
public void init(FilterConfig conf) throws ServletException { if (conf != null && "zookeeper".equals(conf.getInitParameter("signer.secret.provider"))) { SolrZkClient zkClient = (SolrZkClient)conf.getServletContext().getAttribute(DELEGATION_TOKEN_ZK_CLIENT); conf.getServletContext().setAttribute("signer.secret.provider.zookeeper.curator.client", getCuratorClient(zkClient)); } super.init(conf); } @Override
534
1
protected void setAuthenticateHeader(HttpServletRequest request, HttpServletResponse response, LoginConfig config, String nOnce) { // Get the realm name String realmName = config.getRealmName(); if (realmName == null) realmName = REALM_NAME; byte[] buffer = null; synchronized (md5Helper) { buffer = md5Helper.digest(nOnce.getBytes()); } String authenticateHeader = "Digest realm=\"" + realmName + "\", " + "qop=\"auth\", nonce=\"" + nOnce + "\", " + "opaque=\"" + md5Encoder.encode(buffer) + "\""; response.setHeader(AUTH_HEADER_NAME, authenticateHeader); }
535
1
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); return is.readObject(); }
536
1
public FormValidation doCheckCommand(@QueryParameter String value) { if(Util.fixEmptyAndTrim(value)==null) return FormValidation.error(Messages.CommandLauncher_NoLaunchCommand()); else return FormValidation.ok(); } } }
537
1
private static void addUserTriggeringTheBuild(Run<?, ?> run, Set<InternetAddress> to, Set<InternetAddress> cc, Set<InternetAddress> bcc, EnvVars env, TaskListener listener, RecipientProviderUtilities.IDebug debug) { final User user = RecipientProviderUtilities.getUserTriggeringTheBuild(run); if (user != null) { RecipientProviderUtilities.addUsers(Collections.singleton(user), listener, env, to, cc, bcc, debug); } } @SuppressWarnings("unchecked") @Extension
538
1
protected void finish() throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } if (finished) return; finished = true; // Add the end message if (error) { output(endAndCloseMessageArray, 0, endAndCloseMessageArray.length); } else { output(endMessageArray, 0, endMessageArray.length); } } // ------------------------------------- InputStreamInputBuffer Inner Class /** * This class is an input buffer which will read its data from an input * stream. */
539
1
abstract protected JDBCTableReader getTableReader(Connection connection, String tableName, ParseContext parseContext);
540
1
public void testEntityExpansionWReq() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; InputStream is = this.getClass().getClassLoader().getResource("entity_wreq.xml").openStream(); String entity = IOUtils.toString(is, "UTF-8"); is.close(); String validWreq = "<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">" + "<TokenType>&m;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</TokenType>" + "</RequestSecurityToken>"; url += "&wreq=" + URLEncoder.encode(entity + validWreq, "UTF-8"); String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreq value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send an malformed wreq value @org.junit.Test
541
1
public static void checkSlip(File parentFile, File file) throws IllegalArgumentException { String parentCanonicalPath; String canonicalPath; try { parentCanonicalPath = parentFile.getCanonicalPath(); canonicalPath = file.getCanonicalPath(); } catch (IOException e) { throw new IORuntimeException(e); } if (false == canonicalPath.startsWith(parentCanonicalPath)) { throw new IllegalArgumentException("New file is outside of the parent dir: " + file.getName()); } }
542
1
public ExitCode runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException { if (saveFilename != null && loadFilename != null) { params.getConsole().printErrorText("Can't use both --load and --save"); return ExitCode.COMMANDLINE_ERROR; } if (saveFilename != null) { invalidateChanges(params); RemoteDaemonicParserState state = params.getParser().storeParserState(params.getCell()); try (FileOutputStream fos = new FileOutputStream(saveFilename); ZipOutputStream zipos = new ZipOutputStream(fos)) { zipos.putNextEntry(new ZipEntry("parser_data")); try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) { oos.writeObject(state); } } } else if (loadFilename != null) { try (FileInputStream fis = new FileInputStream(loadFilename); ZipInputStream zipis = new ZipInputStream(fis)) { ZipEntry entry = zipis.getNextEntry(); Preconditions.checkState(entry.getName().equals("parser_data")); try (ObjectInputStream ois = new ObjectInputStream(zipis)) { RemoteDaemonicParserState state; try { state = (RemoteDaemonicParserState) ois.readObject(); } catch (ClassNotFoundException e) { params.getConsole().printErrorText("Invalid file format"); return ExitCode.COMMANDLINE_ERROR; } params.getParser().restoreParserState(state, params.getCell()); } } invalidateChanges(params); ParserConfig configView = params.getBuckConfig().getView(ParserConfig.class); if (configView.isParserCacheMutationWarningEnabled()) { params .getConsole() .printErrorText( params .getConsole() .getAnsi() .asWarningText( "WARNING: Buck injected a parser state that may not match the local state.")); } } return ExitCode.SUCCESS; }
543
1
public BeanDefinition createMatcher(String path, String method) { if (("/**".equals(path) || "**".equals(path)) && method == null) { return new RootBeanDefinition(AnyRequestMatcher.class); } BeanDefinitionBuilder matcherBldr = BeanDefinitionBuilder .rootBeanDefinition(type); matcherBldr.addConstructorArgValue(path); matcherBldr.addConstructorArgValue(method); if (this == ciRegex) { matcherBldr.addConstructorArgValue(true); } return matcherBldr.getBeanDefinition(); }
544
1
public Collection<FileAnnotation> parse(final InputStream file, final String moduleName) throws InvocationTargetException { try { Digester digester = new Digester(); digester.setValidating(false); digester.setClassLoader(LintParser.class.getClassLoader()); List<LintIssue> issues = new ArrayList<LintIssue>(); digester.push(issues); String issueXPath = "issues/issue"; digester.addObjectCreate(issueXPath, LintIssue.class); digester.addSetProperties(issueXPath); digester.addSetNext(issueXPath, "add"); String locationXPath = issueXPath + "/location"; digester.addObjectCreate(locationXPath, Location.class); digester.addSetProperties(locationXPath); digester.addSetNext(locationXPath, "addLocation", Location.class.getName()); digester.parse(file); return convert(issues, moduleName); } catch (IOException exception) { throw new InvocationTargetException(exception); } catch (SAXException exception) { throw new InvocationTargetException(exception); } } /** * Converts the Lint object structure to that of the analysis-core API. * * @param issues The parsed Lint issues. * @param moduleName Name of the maven module, if any. * @return A collection of the discovered issues. */
545
1
public List<GerritServer> removeServer(GerritServer s) { servers.remove(s); return servers; } /** * Check whether the list of servers contains a GerritServer object of a specific name. * * @param serverName to check. * @return whether the list contains a server with the given name. */
546
1
public void configure() throws Exception { from("direct:start") .to("xslt:org/apache/camel/component/xslt/transform.xsl") .multicast() .beanRef("testBean") .to("mock:result"); } }; } @Override
547
1
public void removeUser(String username) { UserDatabase database = (UserDatabase) this.resource; User user = database.findUser(username); if (user == null) { return; } try { MBeanUtils.destroyMBean(user); database.removeUser(user); } catch (Exception e) { IllegalArgumentException iae = new IllegalArgumentException ("Exception destroying user " + user + " MBean"); iae.initCause(e); throw iae; } }
548
1
public void execute(FunctionContext context) { RegionFunctionContext rfc = (RegionFunctionContext) context; context.getResultSender().lastResult(rfc.getDataSet().size()); }
549
1
public void execute(FunctionContext context) { Object[] arguments = (Object[]) context.getArguments(); String regionName = (String) arguments[0]; Set<String> keys = (Set<String>) arguments[1]; if (this.cache.getLogger().fineEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("Function ").append(ID).append(" received request to touch ") .append(regionName).append("->").append(keys); this.cache.getLogger().fine(builder.toString()); } // Retrieve the appropriate Region and value to update the lastAccessedTime Region region = this.cache.getRegion(regionName); if (region != null) { region.getAll(keys); } // Return result to get around NPE in LocalResultCollectorImpl context.getResultSender().lastResult(true); }
550
1
protected Object extractResponseBody(Exchange exchange, JettyContentExchange httpExchange) throws IOException { Map<String, String> headers = getSimpleMap(httpExchange.getResponseHeaders()); String contentType = headers.get(Exchange.CONTENT_TYPE); // if content type is serialized java object, then de-serialize it to a Java object if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { try { InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, httpExchange.getResponseContentBytes()); return HttpHelper.deserializeJavaObjectFromStream(is, exchange.getContext()); } catch (Exception e) { throw new RuntimeCamelException("Cannot deserialize body to Java object", e); } } else { // just grab the raw content body return httpExchange.getBody(); } }
551
1
public int doRead(ByteChunk chunk, Request req) throws IOException { if (endChunk) { return -1; } if(needCRLFParse) { needCRLFParse = false; parseCRLF(false); } if (remaining <= 0) { if (!parseChunkHeader()) { throw new IOException("Invalid chunk header"); } if (endChunk) { parseEndChunk(); return -1; } } int result = 0; if (pos >= lastValid) { if (readBytes() < 0) { throw new IOException( "Unexpected end of stream whilst reading request body"); } } if (remaining > (lastValid - pos)) { result = lastValid - pos; remaining = remaining - result; chunk.setBytes(buf, pos, result); pos = lastValid; } else { result = remaining; chunk.setBytes(buf, pos, remaining); pos = pos + remaining; remaining = 0; //we need a CRLF if ((pos+1) >= lastValid) { //if we call parseCRLF we overrun the buffer here //so we defer it to the next call BZ 11117 needCRLFParse = true; } else { parseCRLF(false); //parse the CRLF immediately } } return result; } // ---------------------------------------------------- InputFilter Methods /** * Read the content length from the request. */ @Override
552
1
public FormValidation doNameFreeCheck( @QueryParameter("value") final String value) { if (!value.equals(name)) { if (PluginImpl.containsServer_(value)) { return FormValidation.error("The server name " + value + " is already in use!"); } else if (ANY_SERVER.equals(value)) { return FormValidation.error("Illegal name " + value + "!"); } else { return FormValidation.warning("The server " + name + " will be renamed"); } } else { return FormValidation.ok(); } } /** * Generates a list of helper objects for the jelly view. * * @return a list of helper objects. */
553
1
public void testPrivateKeyParsingSHA256() throws IOException, ClassNotFoundException { XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest()); XMSSMT mt = new XMSSMT(params, new SecureRandom()); mt.generateKeys(); byte[] privateKey = mt.exportPrivateKey(); byte[] publicKey = mt.exportPublicKey(); mt.importState(privateKey, publicKey); assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey())); }
554
1
public void addOtherTesseractConfig(String key, String value) { if (key == null) { throw new IllegalArgumentException("key must not be null"); } if (value == null) { throw new IllegalArgumentException("value must not be null"); } Matcher m = ALLOWABLE_OTHER_PARAMS_PATTERN.matcher(key); if (! m.find()) { throw new IllegalArgumentException("Value contains illegal characters: "+key); } m.reset(value); if (! m.find()) { throw new IllegalArgumentException("Value contains illegal characters: "+value); } otherTesseractConfig.put(key.trim(), value.trim()); } /** * Get property from the properties file passed in. * * @param properties properties file to read from. * @param property the property to fetch. * @param defaultMissing default parameter to use. * @return the value. */
555
1
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream, UpdateRequestProcessor processor) throws Exception { final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType()); InputStream is = null; XMLStreamReader parser = null; String tr = req.getParams().get(CommonParams.TR,null); if(tr!=null) { Transformer t = getTransformer(tr,req); final DOMResult result = new DOMResult(); // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces // an internal result DOM tree, we just access it directly as input for StAX): try { is = stream.getStream(); final InputSource isrc = new InputSource(is); isrc.setEncoding(charset); final SAXSource source = new SAXSource(isrc); t.transform(source, result); } catch(TransformerException te) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te); } finally { IOUtils.closeQuietly(is); } // second step feed the intermediate DOM tree into StAX parser: try { parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode())); this.processUpdate(req, processor, parser); } catch (XMLStreamException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); } finally { if (parser != null) parser.close(); } } // Normal XML Loader else { try { is = stream.getStream(); if (UpdateRequestHandler.log.isTraceEnabled()) { final byte[] body = IOUtils.toByteArray(is); // TODO: The charset may be wrong, as the real charset is later // determined by the XML parser, the content-type is only used as a hint! UpdateRequestHandler.log.trace("body", new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset)); IOUtils.closeQuietly(is); is = new ByteArrayInputStream(body); } parser = (charset == null) ? inputFactory.createXMLStreamReader(is) : inputFactory.createXMLStreamReader(is, charset); this.processUpdate(req, processor, parser); } catch (XMLStreamException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e); } finally { if (parser != null) parser.close(); IOUtils.closeQuietly(is); } } } /** Get Transformer from request context, or from TransformerProvider. * This allows either getContentType(...) or write(...) to instantiate the Transformer, * depending on which one is called first, then the other one reuses the same Transformer */
556
1
private SSLEngine createSSLEngine(Map<String,Object> userProperties) throws DeploymentException { try { // See if a custom SSLContext has been provided SSLContext sslContext = (SSLContext) userProperties.get(Constants.SSL_CONTEXT_PROPERTY); if (sslContext == null) { // Create the SSL Context sslContext = SSLContext.getInstance("TLS"); // Trust store String sslTrustStoreValue = (String) userProperties.get(Constants.SSL_TRUSTSTORE_PROPERTY); if (sslTrustStoreValue != null) { String sslTrustStorePwdValue = (String) userProperties.get( Constants.SSL_TRUSTSTORE_PWD_PROPERTY); if (sslTrustStorePwdValue == null) { sslTrustStorePwdValue = Constants.SSL_TRUSTSTORE_PWD_DEFAULT; } File keyStoreFile = new File(sslTrustStoreValue); KeyStore ks = KeyStore.getInstance("JKS"); try (InputStream is = new FileInputStream(keyStoreFile)) { ks.load(is, sslTrustStorePwdValue.toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslContext.init(null, tmf.getTrustManagers(), null); } else { sslContext.init(null, null, null); } } SSLEngine engine = sslContext.createSSLEngine(); String sslProtocolsValue = (String) userProperties.get(Constants.SSL_PROTOCOLS_PROPERTY); if (sslProtocolsValue != null) { engine.setEnabledProtocols(sslProtocolsValue.split(",")); } engine.setUseClientMode(true); return engine; } catch (Exception e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.sslEngineFail"), e); } } @Override
557
1
private AsymmetricCipherKeyPair genKeyPair() { if (!initialized) { initializeDefault(); } // initialize authenticationPaths and treehash instances byte[][][] currentAuthPaths = new byte[numLayer][][]; byte[][][] nextAuthPaths = new byte[numLayer - 1][][]; Treehash[][] currentTreehash = new Treehash[numLayer][]; Treehash[][] nextTreehash = new Treehash[numLayer - 1][]; Vector[] currentStack = new Vector[numLayer]; Vector[] nextStack = new Vector[numLayer - 1]; Vector[][] currentRetain = new Vector[numLayer][]; Vector[][] nextRetain = new Vector[numLayer - 1][]; for (int i = 0; i < numLayer; i++) { currentAuthPaths[i] = new byte[heightOfTrees[i]][mdLength]; currentTreehash[i] = new Treehash[heightOfTrees[i] - K[i]]; if (i > 0) { nextAuthPaths[i - 1] = new byte[heightOfTrees[i]][mdLength]; nextTreehash[i - 1] = new Treehash[heightOfTrees[i] - K[i]]; } currentStack[i] = new Vector(); if (i > 0) { nextStack[i - 1] = new Vector(); } } // initialize roots byte[][] currentRoots = new byte[numLayer][mdLength]; byte[][] nextRoots = new byte[numLayer - 1][mdLength]; // initialize seeds byte[][] seeds = new byte[numLayer][mdLength]; // initialize seeds[] by copying starting-seeds of first trees of each // layer for (int i = 0; i < numLayer; i++) { System.arraycopy(currentSeeds[i], 0, seeds[i], 0, mdLength); } // initialize rootSigs currentRootSigs = new byte[numLayer - 1][mdLength]; // ------------------------- // ------------------------- // --- calculation of current authpaths and current rootsigs (AUTHPATHS, // SIG)------ // from bottom up to the root for (int h = numLayer - 1; h >= 0; h--) { GMSSRootCalc tree = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], digestProvider); try { // on lowest layer no lower root is available, so just call // the method with null as first parameter if (h == numLayer - 1) { tree = this.generateCurrentAuthpathAndRoot(null, currentStack[h], seeds[h], h); } else // otherwise call the method with the former computed root // value { tree = this.generateCurrentAuthpathAndRoot(currentRoots[h + 1], currentStack[h], seeds[h], h); } } catch (Exception e1) { e1.printStackTrace(); } // set initial values needed for the private key construction for (int i = 0; i < heightOfTrees[h]; i++) { System.arraycopy(tree.getAuthPath()[i], 0, currentAuthPaths[h][i], 0, mdLength); } currentRetain[h] = tree.getRetain(); currentTreehash[h] = tree.getTreehash(); System.arraycopy(tree.getRoot(), 0, currentRoots[h], 0, mdLength); } // --- calculation of next authpaths and next roots (AUTHPATHS+, ROOTS+) // ------ for (int h = numLayer - 2; h >= 0; h--) { GMSSRootCalc tree = this.generateNextAuthpathAndRoot(nextStack[h], seeds[h + 1], h + 1); // set initial values needed for the private key construction for (int i = 0; i < heightOfTrees[h + 1]; i++) { System.arraycopy(tree.getAuthPath()[i], 0, nextAuthPaths[h][i], 0, mdLength); } nextRetain[h] = tree.getRetain(); nextTreehash[h] = tree.getTreehash(); System.arraycopy(tree.getRoot(), 0, nextRoots[h], 0, mdLength); // create seed for the Merkle tree after next (nextNextSeeds) // SEEDs++ System.arraycopy(seeds[h + 1], 0, this.nextNextSeeds[h], 0, mdLength); } // ------------ // generate JDKGMSSPublicKey GMSSPublicKeyParameters publicKey = new GMSSPublicKeyParameters(currentRoots[0], gmssPS); // generate the JDKGMSSPrivateKey GMSSPrivateKeyParameters privateKey = new GMSSPrivateKeyParameters(currentSeeds, nextNextSeeds, currentAuthPaths, nextAuthPaths, currentTreehash, nextTreehash, currentStack, nextStack, currentRetain, nextRetain, nextRoots, currentRootSigs, gmssPS, digestProvider); // return the KeyPair return (new AsymmetricCipherKeyPair(publicKey, privateKey)); } /** * calculates the authpath for tree in layer h which starts with seed[h] * additionally computes the rootSignature of underlaying root * * @param currentStack stack used for the treehash instance created by this method * @param lowerRoot stores the root of the lower tree * @param seed starting seeds * @param h actual layer */
558
1
private void sendEntityMessage(Object message) throws Exception { MockEndpoint endpoint = getMockEndpoint("mock:result"); endpoint.reset(); endpoint.expectedMessageCount(1); template.sendBody("direct:start1", message); assertMockEndpointsSatisfied(); List<Exchange> list = endpoint.getReceivedExchanges(); Exchange exchange = list.get(0); String xml = exchange.getIn().getBody(String.class); assertTrue("Get a wrong transformed message", xml.indexOf("<transformed subject=\"\">") > 0); try { template.sendBody("direct:start2", message); fail("Expect an exception here"); } catch (Exception ex) { // expect an exception here assertTrue("Get a wrong exception", ex instanceof CamelExecutionException); // the file could not be found assertTrue("Get a wrong exception cause", ex.getCause() instanceof TransformerException); } } @Override
559
1
public static String getContextPath(HttpServletRequest request) { String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE); if (contextPath == null) { contextPath = request.getContextPath(); } if ("/".equals(contextPath)) { // Invalid case, but happens for includes on Jetty: silently adapt it. contextPath = ""; } return decodeRequestString(request, contextPath); } /** * Find the Shiro {@link WebEnvironment} for this web application, which is typically loaded via the * {@link org.apache.shiro.web.env.EnvironmentLoaderListener}. * <p/> * This implementation rethrows an exception that happened on environment startup to differentiate between a failed * environment startup and no environment at all. * * @param sc ServletContext to find the web application context for * @return the root WebApplicationContext for this web app * @throws IllegalStateException if the root WebApplicationContext could not be found * @see org.apache.shiro.web.env.EnvironmentLoader#ENVIRONMENT_ATTRIBUTE_KEY * @since 1.2 */
560
1
private void doTestRewrite(String config, String request, String expectedURI) throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); RewriteValve rewriteValve = new RewriteValve(); ctx.getPipeline().addValve(rewriteValve); rewriteValve.setConfiguration(config); // Note: URLPatterns should be URL encoded // (http://svn.apache.org/r285186) Tomcat.addServlet(ctx, "snoop", new SnoopServlet()); ctx.addServletMapping("/a/%255A", "snoop"); ctx.addServletMapping("/c/*", "snoop"); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + request); String body = res.toString(); RequestDescriptor requestDesc = SnoopResult.parse(body); String requestURI = requestDesc.getRequestInfo("REQUEST-URI"); Assert.assertEquals(expectedURI, requestURI); }
561
1
public Result isAllowed(String principalId) { LockoutPolicy lockoutPolicy = lockoutPolicyRetriever.getLockoutPolicy(); if (!lockoutPolicy.isLockoutEnabled()) { return new Result(true, 0); } long eventsAfter = timeService.getCurrentTimeMillis() - lockoutPolicy.getCountFailuresWithin() * 1000; List<AuditEvent> events = auditService.find(principalId, eventsAfter); final int failureCount = sequentialFailureCount(events); if (failureCount >= lockoutPolicy.getLockoutAfterFailures()) { // Check whether time of most recent failure is within the lockout period AuditEvent lastFailure = mostRecentFailure(events); if (lastFailure != null && lastFailure.getTime() > timeService.getCurrentTimeMillis() - lockoutPolicy.getLockoutPeriodSeconds() * 1000) { return new Result(false, failureCount); } } return new Result(true, failureCount); } /** * Counts the number of failures that occurred without an intervening * successful login. */
562
1
public void save() throws Exception { if (getReadonly()) { log.error(sm.getString("memoryUserDatabase.readOnly")); return; } if (!isWriteable()) { log.warn(sm.getString("memoryUserDatabase.notPersistable")); return; } // Write out contents to a temporary file File fileNew = new File(pathnameNew); if (!fileNew.isAbsolute()) { fileNew = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameNew); } PrintWriter writer = null; try { // Configure our PrintWriter FileOutputStream fos = new FileOutputStream(fileNew); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8"); writer = new PrintWriter(osw); // Print the file prolog writer.println("<?xml version='1.0' encoding='utf-8'?>"); writer.println("<tomcat-users>"); // Print entries for each defined role, group, and user Iterator<?> values = null; values = getRoles(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getGroups(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getUsers(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } // Print the file epilog writer.println("</tomcat-users>"); // Check for errors that occurred while printing if (writer.checkError()) { writer.close(); fileNew.delete(); throw new IOException (sm.getString("memoryUserDatabase.writeException", fileNew.getAbsolutePath())); } writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; } // Perform the required renames to permanently save this file File fileOld = new File(pathnameOld); if (!fileOld.isAbsolute()) { fileOld = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameOld); } fileOld.delete(); File fileOrig = new File(pathname); if (!fileOrig.isAbsolute()) { fileOrig = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (fileOrig.exists()) { fileOld.delete(); if (!fileOrig.renameTo(fileOld)) { throw new IOException (sm.getString("memoryUserDatabase.renameOld", fileOld.getAbsolutePath())); } } if (!fileNew.renameTo(fileOrig)) { if (fileOld.exists()) { fileOld.renameTo(fileOrig); } throw new IOException (sm.getString("memoryUserDatabase.renameNew", fileOrig.getAbsolutePath())); } fileOld.delete(); } /** * Return a String representation of this UserDatabase. */ @Override
563
1
public static boolean configSuccess(HierarchicalConfiguration reply) { if (reply != null) { if (reply.containsKey("ok")) { return true; } } return false; }
564
1
public void process(Exchange exchange) throws Exception {
565
1
public boolean createDB(String dbName, PortletRequest request) { Connection conn = null; try { conn = DerbyConnectionUtil.getDerbyConnection(dbName, DerbyConnectionUtil.CREATE_DB_PROP); portlet.addInfoMessage(request, portlet.getLocalizedString(request, "sysdb.infoMsg01", dbName)); return true; } catch (Throwable e) { portlet.addErrorMessage(request, portlet.getLocalizedString(request, "sysdb.errorMsg01"), e.getMessage()); return false; } finally { // close DB connection try { if (conn != null) { conn.close(); } } catch (SQLException e) { portlet.addErrorMessage(request, portlet.getLocalizedString(request, "sysdb.errorMsg02"), e.getMessage()); } } }
566
1
public UnixUser authenticate(String username, String password) throws PAMException { this.password = password; try { check(libpam.pam_set_item(pht,PAM_USER,username),"pam_set_item failed"); check(libpam.pam_authenticate(pht,0),"pam_authenticate failed"); check(libpam.pam_setcred(pht,0),"pam_setcred failed"); // several different error code seem to be used to represent authentication failures // check(libpam.pam_acct_mgmt(pht,0),"pam_acct_mgmt failed"); PointerByReference r = new PointerByReference(); check(libpam.pam_get_item(pht,PAM_USER,r),"pam_get_item failed"); String userName = r.getValue().getString(0); passwd pwd = libc.getpwnam(userName); if(pwd==null) throw new PAMException("Authentication succeeded but no user information is available"); return new UnixUser(userName,pwd); } finally { this.password = null; } } /** * Returns the groups a user belongs to * @param username * @return Set of group names * @throws PAMException * @deprecated * Pointless and ugly convenience method. */
567
1
public void serveImage(ResourceRequest req, ResourceResponse resp) throws IOException { String fn = req.getRenderParameters().getValue("fn"); String ct = req.getRenderParameters().getValue("ct"); resp.setContentType(ct); String path = req.getPortletContext().getRealPath(fn); File file = new File(path); OutputStream os = resp.getPortletOutputStream(); Files.copy(file.toPath(), os); os.flush(); }
568
1
public Http11NioProcessor createProcessor() { Http11NioProcessor processor = new Http11NioProcessor( proto.getMaxHttpHeaderSize(), (NioEndpoint)proto.endpoint, proto.getMaxTrailerSize()); processor.setAdapter(proto.getAdapter()); processor.setMaxKeepAliveRequests(proto.getMaxKeepAliveRequests()); processor.setKeepAliveTimeout(proto.getKeepAliveTimeout()); processor.setConnectionUploadTimeout( proto.getConnectionUploadTimeout()); processor.setDisableUploadTimeout(proto.getDisableUploadTimeout()); processor.setCompressionMinSize(proto.getCompressionMinSize()); processor.setCompression(proto.getCompression()); processor.setNoCompressionUserAgents(proto.getNoCompressionUserAgents()); processor.setCompressableMimeTypes(proto.getCompressableMimeTypes()); processor.setRestrictedUserAgents(proto.getRestrictedUserAgents()); processor.setSocketBuffer(proto.getSocketBuffer()); processor.setMaxSavePostSize(proto.getMaxSavePostSize()); processor.setServer(proto.getServer()); register(processor); return processor; } @Override
569
1
public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException { try { Crypto crypto = CertsUtils.createCrypto(config.getCertificate()); ByteArrayOutputStream bout = new ByteArrayOutputStream(4096); Writer streamWriter = new OutputStreamWriter(bout, "UTF-8"); XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(streamWriter); writer.writeStartDocument("UTF-8", "1.0"); String referenceID = IDGenerator.generateID("_"); writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS); writer.writeAttribute("ID", referenceID); String serviceURL = config.getIdpUrl().toString(); writer.writeAttribute("entityID", serviceURL); writer.writeNamespace("md", SAML2_METADATA_NS); writer.writeNamespace("fed", WS_FEDERATION_NS); writer.writeNamespace("wsa", WS_ADDRESSING_NS); writer.writeNamespace("auth", WS_FEDERATION_NS); writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS); if ("http://docs.oasis-open.org/wsfed/federation/200706".equals(serviceConfig.getProtocol())) { writeFederationMetadata(writer, serviceConfig, serviceURL); } else if ("urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser".equals(serviceConfig.getProtocol())) { writeSAMLMetadata(writer, serviceConfig, serviceURL, crypto); } writer.writeEndElement(); // EntityDescriptor writer.writeEndDocument(); streamWriter.flush(); bout.flush(); // if (LOG.isDebugEnabled()) { String out = new String(bout.toByteArray()); LOG.debug("***************** unsigned ****************"); LOG.debug(out); LOG.debug("***************** unsigned ****************"); } InputStream is = new ByteArrayInputStream(bout.toByteArray()); Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), is, referenceID); if (result != null) { return result; } else { throw new RuntimeException("Failed to sign the metadata document: result=null"); } } catch (ProcessingException e) { throw e; } catch (Exception e) { LOG.error("Error creating service metadata information ", e); throw new ProcessingException("Error creating service metadata information: " + e.getMessage()); } }
570
1
public void send(final String format, final Object... args) { descriptor.debug(logger, format, args); } } final Debug debug = new Debug(); Set<User> users = null; final Run<?, ?> currentRun = context.getRun(); if (currentRun == null) { debug.send("currentRun was null"); } else { final AbstractTestResultAction<?> testResultAction = currentRun.getAction(AbstractTestResultAction.class); if (testResultAction == null) { debug.send("testResultAction was null"); } else { if (testResultAction.getFailCount() <= 0) { debug.send("getFailCount() returned <= 0"); } else { users = new HashSet<>(); debug.send("Collecting builds where a test started failing..."); final HashSet<Run<?, ?>> buildsWhereATestStartedFailing = new HashSet<>(); for (final TestResult caseResult : testResultAction.getFailedTests()) { final Run<?, ?> runWhereTestStartedFailing = caseResult.getFailedSinceRun(); if (runWhereTestStartedFailing != null) { debug.send(" runWhereTestStartedFailing: %d", runWhereTestStartedFailing.getNumber()); buildsWhereATestStartedFailing.add(runWhereTestStartedFailing); } else { context.getListener().error("getFailedSinceRun returned null for %s", caseResult.getFullDisplayName()); } } // For each build where a test started failing, walk backward looking for build results worse than // UNSTABLE. All of those builds will be used to find suspects. debug.send("Collecting builds with suspects..."); final HashSet<Run<?, ?>> buildsWithSuspects = new HashSet<>(); for (final Run<?, ?> buildWhereATestStartedFailing : buildsWhereATestStartedFailing) { debug.send(" buildWhereATestStartedFailing: %d", buildWhereATestStartedFailing.getNumber()); buildsWithSuspects.add(buildWhereATestStartedFailing); Run<?, ?> previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild(); if (previousBuildToCheck != null) { debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber()); } while (previousBuildToCheck != null) { if (buildsWithSuspects.contains(previousBuildToCheck)) { // Short-circuit if the build to check has already been checked. debug.send(" already contained in buildsWithSuspects; stopping search"); break; } final Result previousResult = previousBuildToCheck.getResult(); if (previousResult == null) { debug.send(" previousResult was null"); } else { debug.send(" previousResult: %s", previousResult.toString()); if (previousResult.isBetterThan(Result.FAILURE)) { debug.send(" previousResult was better than FAILURE; stopping search"); break; } else { debug.send(" previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search"); buildsWithSuspects.add(previousBuildToCheck); previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild(); if (previousBuildToCheck != null) { debug.send(" previousBuildToCheck: %d", previousBuildToCheck.getNumber()); } } } } } debug.send("Collecting suspects..."); users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug)); users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug)); } } } if (users != null) { RecipientProviderUtilities.addUsers(users, context.getListener(), env, to, cc, bcc, debug); } } @Extension public static final class DescriptorImpl extends RecipientProviderDescriptor { @Override public String getDisplayName() { return "Suspects Causing Unit Tests to Begin Failing"; } } }
571
1
public SocketState process(SocketWrapper<Long> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socket = socket; long socketRef = socket.getSocket().longValue(); Socket.setrbb(socketRef, inputBuffer); Socket.setsbb(socketRef, outputBuffer); // Error flag error = false; boolean keptAlive = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Get first message of the request if (!readMessage(requestHeaderMessage, true, keptAlive)) { // This means that no data is available right now // (long keepalive), so that the processor should be recycled // and the method should return true break; } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (Socket.send(socketRef, pongMessageArray, 0, pongMessageArray.length) < 0) { error = true; } continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Usually the servlet didn't read the previous request body if(log.isDebugEnabled()) { log.debug("Unexpected message: "+type); } continue; } keptAlive = true; request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); adapter.log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); adapter.log(request, response, 0); error = true; } } // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); adapter.service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); adapter.log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error || endpoint.isPaused()) { return SocketState.CLOSED; } else if (isAsync()) { return SocketState.LONG; } else { return SocketState.OPEN; } } // ----------------------------------------------------- ActionHook Methods /** * Send an action to the connector. * * @param actionCode Type of the action * @param param Action parameter */ @Override
572
1
public void testRedirectActionPrefixWithEmptyExtension() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.REDIRECT_ACTION_PREFIX + "myAction", ""); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath("/someServletPath"); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); defaultActionMapper.setExtensions(",,"); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); assertNotNull(result); assertTrue(result instanceof ServletRedirectResult); assertEquals("myAction", result.getLocation()); // TODO: need to test location but there's noaccess to the property/method, unless we use reflection }
573
1
public static void assertSettings(Settings left, Settings right, boolean compareClusterName) { ImmutableSet<Map.Entry<String, String>> entries0 = left.getAsMap().entrySet(); Map<String, String> entries1 = right.getAsMap(); assertThat(entries0.size(), equalTo(entries1.size())); for (Map.Entry<String, String> entry : entries0) { if(entry.getKey().equals(ClusterName.SETTING) && compareClusterName == false) { continue; } assertThat(entries1, hasEntry(entry.getKey(), entry.getValue())); } }
574
1
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { log.trace("Service: {}", request); // is there a consumer registered for the request. HttpConsumer consumer = getServletResolveConsumerStrategy().resolve(request, getConsumers()); if (consumer == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (consumer.getEndpoint().getHttpMethodRestrict() != null) { Iterator it = ObjectHelper.createIterable(consumer.getEndpoint().getHttpMethodRestrict()).iterator(); boolean match = false; while (it.hasNext()) { String method = it.next().toString(); if (method.equalsIgnoreCase(request.getMethod())) { match = true; break; } } if (!match) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } } if ("TRACE".equals(request.getMethod()) && !consumer.isTraceEnabled()) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } final Exchange result = (Exchange) request.getAttribute(EXCHANGE_ATTRIBUTE_NAME); if (result == null) { // no asynchronous result so leverage continuation final Continuation continuation = ContinuationSupport.getContinuation(request); if (continuation.isInitial() && continuationTimeout != null) { // set timeout on initial continuation.setTimeout(continuationTimeout); } // are we suspended and a request is dispatched initially? if (consumer.isSuspended() && continuation.isInitial()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } if (continuation.isExpired()) { String id = (String) continuation.getAttribute(EXCHANGE_ATTRIBUTE_ID); // remember this id as expired expiredExchanges.put(id, id); log.warn("Continuation expired of exchangeId: {}", id); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // a new request so create an exchange final Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut); if (consumer.getEndpoint().isBridgeEndpoint()) { exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE); } if (consumer.getEndpoint().isDisableStreamCache()) { exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE); } HttpHelper.setCharsetFromContentType(request.getContentType(), exchange); exchange.setIn(new HttpMessage(exchange, request, response)); // set context path as header String contextPath = consumer.getEndpoint().getPath(); exchange.getIn().setHeader("CamelServletContextPath", contextPath); String httpPath = (String)exchange.getIn().getHeader(Exchange.HTTP_PATH); // here we just remove the CamelServletContextPath part from the HTTP_PATH if (contextPath != null && httpPath.startsWith(contextPath)) { exchange.getIn().setHeader(Exchange.HTTP_PATH, httpPath.substring(contextPath.length())); } if (log.isTraceEnabled()) { log.trace("Suspending continuation of exchangeId: {}", exchange.getExchangeId()); } continuation.setAttribute(EXCHANGE_ATTRIBUTE_ID, exchange.getExchangeId()); // we want to handle the UoW try { consumer.createUoW(exchange); } catch (Exception e) { log.error("Error processing request", e); throw new ServletException(e); } // must suspend before we process the exchange continuation.suspend(); ClassLoader oldTccl = overrideTccl(exchange); if (log.isTraceEnabled()) { log.trace("Processing request for exchangeId: {}", exchange.getExchangeId()); } // use the asynchronous API to process the exchange consumer.getAsyncProcessor().process(exchange, new AsyncCallback() { public void done(boolean doneSync) { // check if the exchange id is already expired boolean expired = expiredExchanges.remove(exchange.getExchangeId()) != null; if (!expired) { if (log.isTraceEnabled()) { log.trace("Resuming continuation of exchangeId: {}", exchange.getExchangeId()); } // resume processing after both, sync and async callbacks continuation.setAttribute(EXCHANGE_ATTRIBUTE_NAME, exchange); continuation.resume(); } else { log.warn("Cannot resume expired continuation of exchangeId: {}", exchange.getExchangeId()); } } }); if (oldTccl != null) { restoreTccl(exchange, oldTccl); } // return to let Jetty continuation to work as it will resubmit and invoke the service // method again when its resumed return; } try { // now lets output to the response if (log.isTraceEnabled()) { log.trace("Resumed continuation and writing response for exchangeId: {}", result.getExchangeId()); } Integer bs = consumer.getEndpoint().getResponseBufferSize(); if (bs != null) { log.trace("Using response buffer size: {}", bs); response.setBufferSize(bs); } consumer.getBinding().writeResponse(result, response); } catch (IOException e) { log.error("Error processing request", e); throw e; } catch (Exception e) { log.error("Error processing request", e); throw new ServletException(e); } finally { consumer.doneUoW(result); } }
575
1
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { super.submit(req,rsp); JSONObject json = req.getSubmittedForm(); makeDisabled(req.getParameter("disable")!=null); jdk = req.getParameter("jdk"); if(req.getParameter("hasCustomQuietPeriod")!=null) { quietPeriod = Integer.parseInt(req.getParameter("quiet_period")); } else { quietPeriod = null; } if(req.getParameter("hasCustomScmCheckoutRetryCount")!=null) { scmCheckoutRetryCount = Integer.parseInt(req.getParameter("scmCheckoutRetryCount")); } else { scmCheckoutRetryCount = null; } blockBuildWhenDownstreamBuilding = req.getParameter("blockBuildWhenDownstreamBuilding")!=null; blockBuildWhenUpstreamBuilding = req.getParameter("blockBuildWhenUpstreamBuilding")!=null; if(req.hasParameter("customWorkspace")) { customWorkspace = Util.fixEmptyAndTrim(req.getParameter("customWorkspace.directory")); } else { customWorkspace = null; } if (json.has("scmCheckoutStrategy")) scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class, json.getJSONObject("scmCheckoutStrategy")); else scmCheckoutStrategy = null; if(req.getParameter("hasSlaveAffinity")!=null) { assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString")); } else { assignedNode = null; } canRoam = assignedNode==null; concurrentBuild = req.getSubmittedForm().has("concurrentBuild"); authToken = BuildAuthorizationToken.create(req); setScm(SCMS.parseSCM(req,this)); for (Trigger t : triggers()) t.stop(); triggers = buildDescribable(req, Trigger.for_(this)); for (Trigger t : triggers) t.start(this,true); for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, "publisher", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) { BuildTrigger t = (BuildTrigger) _t; for (AbstractProject downstream : t.getChildProjects(this)) { downstream.checkPermission(BUILD); } } } /** * @deprecated * As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead. */
576
1
private JMXConnectorServer createServer(String serverName, String bindAddress, int theRmiRegistryPort, int theRmiServerPort, HashMap<String,Object> theEnv, RMIClientSocketFactory registryCsf, RMIServerSocketFactory registrySsf, RMIClientSocketFactory serverCsf, RMIServerSocketFactory serverSsf) { // Create the RMI registry Registry registry; try { registry = LocateRegistry.createRegistry( theRmiRegistryPort, registryCsf, registrySsf); } catch (RemoteException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createRegistryFailed", serverName, Integer.toString(theRmiRegistryPort)), e); return null; } if (bindAddress == null) { bindAddress = "localhost"; } String url = "service:jmx:rmi://" + bindAddress; JMXServiceURL serviceUrl; try { serviceUrl = new JMXServiceURL(url); } catch (MalformedURLException e) { log.error(sm.getString("jmxRemoteLifecycleListener.invalidURL", serverName, url), e); return null; } RMIConnectorServer cs = null; try { RMIJRMPServerImpl server = new RMIJRMPServerImpl( rmiServerPortPlatform, serverCsf, serverSsf, theEnv); cs = new RMIConnectorServer(serviceUrl, theEnv, server, ManagementFactory.getPlatformMBeanServer()); cs.start(); registry.bind("jmxrmi", server); log.info(sm.getString("jmxRemoteLifecycleListener.start", Integer.toString(theRmiRegistryPort), Integer.toString(theRmiServerPort), serverName)); } catch (IOException | AlreadyBoundException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createServerFailed", serverName), e); } return cs; }
577
1
private void decodeTest() { EllipticCurve curve = new EllipticCurve( new ECFieldFp(new BigInteger("6277101735386680763835789423207666416083908700390324961279")), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b ECPoint p = ECPointUtil.decodePoint(curve, Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")); if (!p.getAffineX().equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16))) { fail("x uncompressed incorrectly"); } if (!p.getAffineY().equals(new BigInteger("7192b95ffc8da78631011ed6b24cdd573f977a11e794811", 16))) { fail("y uncompressed incorrectly"); } } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */
578
1
private CipherText convertToCipherText(byte[] cipherTextSerializedBytes) throws EncryptionException { try { assert cipherTextSerializedBytes != null : "cipherTextSerializedBytes cannot be null."; assert cipherTextSerializedBytes.length > 0 : "cipherTextSerializedBytes must be > 0 in length."; ByteArrayInputStream bais = new ByteArrayInputStream(cipherTextSerializedBytes); int kdfInfo = readInt(bais); debug("kdfInfo: " + kdfInfo); int kdfPrf = (kdfInfo >>> 28); debug("kdfPrf: " + kdfPrf); assert kdfPrf >= 0 && kdfPrf <= 15 : "kdfPrf == " + kdfPrf + " must be between 0 and 15."; int kdfVers = ( kdfInfo & 0x07ffffff); assert kdfVers > 0 && kdfVers <= 99991231 : "KDF Version (" + kdfVers + ") out of range."; // Really should be >= 20110203 (earliest). debug("convertToCipherText: kdfPrf = " + kdfPrf + ", kdfVers = " + kdfVers); if ( kdfVers != CipherText.cipherTextVersion ) { // NOTE: In future, support backward compatibility via this mechanism. When we do this // we will have to compare as longs and watch out for sign extension of kdfInfo // since it may have the sign bit set. Then we will do different things depending // on what KDF version we encounter. However, as for now, since this is // is first ESAPI 2.0 GA version, there nothing to be backward compatible with. // (We did not promise backward compatibility for earlier release candidates.) // Thus any version mismatch at this point is an error. throw new InvalidClassException("This serialized byte stream not compatible " + "with loaded CipherText class. Version read = " + kdfInfo + "; version from loaded CipherText class = " + CipherText.cipherTextVersion); } long timestamp = readLong(bais); debug("convertToCipherText: timestamp = " + new Date(timestamp)); short strSize = readShort(bais); debug("convertToCipherText: length of cipherXform = " + strSize); String cipherXform = readString(bais, strSize); debug("convertToCipherText: cipherXform = " + cipherXform); String[] parts = cipherXform.split("/"); assert parts.length == 3 : "Malformed cipher transformation"; String cipherMode = parts[1]; if ( ! CryptoHelper.isAllowedCipherMode(cipherMode) ) { String msg = "Cipher mode " + cipherMode + " is not an allowed cipher mode"; throw new EncryptionException(msg, msg); } short keySize = readShort(bais); debug("convertToCipherText: keySize = " + keySize); short blockSize = readShort(bais); debug("convertToCipherText: blockSize = " + blockSize); short ivLen = readShort(bais); debug("convertToCipherText: ivLen = " + ivLen); byte[] iv = null; if ( ivLen > 0 ) { iv = new byte[ivLen]; bais.read(iv, 0, iv.length); } int ciphertextLen = readInt(bais); debug("convertToCipherText: ciphertextLen = " + ciphertextLen); assert ciphertextLen > 0 : "convertToCipherText: Invalid cipher text length"; byte[] rawCiphertext = new byte[ciphertextLen]; bais.read(rawCiphertext, 0, rawCiphertext.length); short macLen = readShort(bais); debug("convertToCipherText: macLen = " + macLen); byte[] mac = null; if ( macLen > 0 ) { mac = new byte[macLen]; bais.read(mac, 0, mac.length); } CipherSpec cipherSpec = new CipherSpec(cipherXform, keySize); cipherSpec.setBlockSize(blockSize); cipherSpec.setIV(iv); debug("convertToCipherText: CipherSpec: " + cipherSpec); CipherText ct = new CipherText(cipherSpec); assert (ivLen > 0 && ct.requiresIV()) : "convertToCipherText: Mismatch between IV length and cipher mode."; ct.setCiphertext(rawCiphertext); // Set this *AFTER* setting raw ciphertext because setCiphertext() // method also sets encryption time. ct.setEncryptionTimestamp(timestamp); if ( macLen > 0 ) { ct.storeSeparateMAC(mac); } return ct; } catch(EncryptionException ex) { throw new EncryptionException("Cannot deserialize byte array into CipherText object", "Cannot deserialize byte array into CipherText object", ex); } catch (IOException e) { throw new EncryptionException("Cannot deserialize byte array into CipherText object", "Cannot deserialize byte array into CipherText object", e); } }
579
1
public static void writeXml(Node n, OutputStream os) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); // identity Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(n), new StreamResult(os)); }
580
1
void setTransferException(boolean transferException); /** * Gets the header filter strategy * * @return the strategy */
581
1
public List<ACL> getAclForPath(String path) { List<ACL> acls = zkACLProvider.getACLsToAdd(path); return acls; } }; }
582
1
protected void forwardToErrorPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { String errorPage = config.getErrorPage(); if (errorPage == null || errorPage.length() == 0) { String msg = sm.getString("formAuthenticator.noErrorPage", context.getName()); log.warn(msg); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } RequestDispatcher disp = context.getServletContext().getRequestDispatcher (config.getErrorPage()); try { if (context.fireRequestInitEvent(request)) { disp.forward(request.getRequest(), response); context.fireRequestDestroyEvent(request); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } } /** * Does this request match the saved one (so that it must be the redirect * we signaled after successful authentication? * * @param request The request to be verified * @return <code>true</code> if the requests matched the saved one */
583
1
public void testSnapshotMoreThanOnce() throws ExecutionException, InterruptedException, IOException { Client client = client(); final File tempDir = newTempDir(LifecycleScope.SUITE).getAbsoluteFile(); logger.info("--> creating repository"); assertAcked(client.admin().cluster().preparePutRepository("test-repo") .setType("fs").setSettings(ImmutableSettings.settingsBuilder() .put("location", tempDir) .put("compress", randomBoolean()) .put("chunk_size", randomIntBetween(100, 1000)))); // only one shard assertAcked(prepareCreate("test").setSettings(ImmutableSettings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) )); ensureYellow(); logger.info("--> indexing"); final int numDocs = randomIntBetween(10, 100); IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs]; for (int i = 0; i < builders.length; i++) { builders[i] = client().prepareIndex("test", "doc", Integer.toString(i)).setSource("foo", "bar" + i); } indexRandom(true, builders); flushAndRefresh(); assertNoFailures(client().admin().indices().prepareOptimize("test").setFlush(true).setMaxNumSegments(1).get()); CreateSnapshotResponse createSnapshotResponseFirst = client.admin().cluster().prepareCreateSnapshot("test-repo", "test").setWaitForCompletion(true).setIndices("test").get(); assertThat(createSnapshotResponseFirst.getSnapshotInfo().successfulShards(), greaterThan(0)); assertThat(createSnapshotResponseFirst.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseFirst.getSnapshotInfo().totalShards())); assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); { SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus("test-repo").setSnapshots("test").get().getSnapshots().get(0); List<SnapshotIndexShardStatus> shards = snapshotStatus.getShards(); for (SnapshotIndexShardStatus status : shards) { assertThat(status.getStats().getProcessedFiles(), greaterThan(1)); } } if (frequently()) { logger.info("--> upgrade"); client().admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, "none")).get(); backwardsCluster().allowOnAllNodes("test"); logClusterState(); boolean upgraded; do { logClusterState(); CountResponse countResponse = client().prepareCount().get(); assertHitCount(countResponse, numDocs); upgraded = backwardsCluster().upgradeOneNode(); ensureYellow(); countResponse = client().prepareCount().get(); assertHitCount(countResponse, numDocs); } while (upgraded); client().admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, "all")).get(); } if (cluster().numDataNodes() > 1 && randomBoolean()) { // only bump the replicas if we have enough nodes logger.info("--> move from 0 to 1 replica"); client().admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)).get(); } logger.debug("---> repo exists: " + new File(tempDir, "indices/test/0").exists() + " files: " + Arrays.toString(new File(tempDir, "indices/test/0").list())); // it's only one shard! CreateSnapshotResponse createSnapshotResponseSecond = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-1").setWaitForCompletion(true).setIndices("test").get(); assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), greaterThan(0)); assertThat(createSnapshotResponseSecond.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseSecond.getSnapshotInfo().totalShards())); assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-1").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); { SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus("test-repo").setSnapshots("test-1").get().getSnapshots().get(0); List<SnapshotIndexShardStatus> shards = snapshotStatus.getShards(); for (SnapshotIndexShardStatus status : shards) { assertThat(status.getStats().getProcessedFiles(), equalTo(1)); // we flush before the snapshot such that we have to process the segments_N files } } client().prepareDelete("test", "doc", "1").get(); CreateSnapshotResponse createSnapshotResponseThird = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-2").setWaitForCompletion(true).setIndices("test").get(); assertThat(createSnapshotResponseThird.getSnapshotInfo().successfulShards(), greaterThan(0)); assertThat(createSnapshotResponseThird.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponseThird.getSnapshotInfo().totalShards())); assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-2").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS)); { SnapshotStatus snapshotStatus = client.admin().cluster().prepareSnapshotStatus("test-repo").setSnapshots("test-2").get().getSnapshots().get(0); List<SnapshotIndexShardStatus> shards = snapshotStatus.getShards(); for (SnapshotIndexShardStatus status : shards) { assertThat(status.getStats().getProcessedFiles(), equalTo(2)); // we flush before the snapshot such that we have to process the segments_N files plus the .del file } } }
584
1
private boolean evaluate(String text) { try { InputSource inputSource = new InputSource(new StringReader(text)); return ((Boolean)expression.evaluate(inputSource, XPathConstants.BOOLEAN)).booleanValue(); } catch (XPathExpressionException e) { return false; } } @Override
585
1
public void testTrailingHeadersSizeLimit() throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctx, "servlet", new EchoHeaderServlet()); ctx.addServletMapping("/", "servlet"); // Limit the size of the trailing header tomcat.getConnector().setProperty("maxTrailerSize", "10"); tomcat.start(); String[] request = new String[]{ "POST /echo-params.jsp HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + "Transfer-encoding: chunked" + SimpleHttpClient.CRLF + "Content-Type: application/x-www-form-urlencoded" + SimpleHttpClient.CRLF + "Connection: close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + "3" + SimpleHttpClient.CRLF + "a=0" + SimpleHttpClient.CRLF + "4" + SimpleHttpClient.CRLF + "&b=1" + SimpleHttpClient.CRLF + "0" + SimpleHttpClient.CRLF + "x-trailer: Test" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF }; TrailerClient client = new TrailerClient(tomcat.getConnector().getLocalPort()); client.setRequest(request); client.connect(); client.processRequest(); // Expected to fail because the trailers are longer // than the set limit of 10 bytes assertTrue(client.isResponse500()); } @Test
586
1
public void testIsExpressionIsFalse() throws Exception { // given String anExpression = "foo"; // when boolean actual = ComponentUtils.isExpression(anExpression); // then assertFalse(actual); } } class MockConfigurationProvider implements ConfigurationProvider { public void destroy() { } public void init(Configuration configuration) throws ConfigurationException { } public boolean needsReload() { return false; } public void loadPackages() throws ConfigurationException { } public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { builder.constant(StrutsConstants.STRUTS_TAG_ALTSYNTAX, "false"); }
587
1
@Test(timeout = 1000L) public void testLongMonths() throws Exception { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.JULY); new CronTab("0 0 31 7 *").floor(cal); // would infinite loop }
588
1
public static File unzip(File zip, File toDir, Predicate<ZipEntry> filter) throws IOException { if (!toDir.exists()) { FileUtils.forceMkdir(toDir); } ZipFile zipFile = new ZipFile(zip); try { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (filter.test(entry)) { File to = new File(toDir, entry.getName()); if (entry.isDirectory()) { throwExceptionIfDirectoryIsNotCreatable(to); } else { File parent = to.getParentFile(); throwExceptionIfDirectoryIsNotCreatable(parent); copy(zipFile, entry, to); } } } return toDir; } finally { zipFile.close(); } }
589
1
public Authentication authenticate(Authentication req) throws AuthenticationException { logger.debug("Processing authentication request for " + req.getName()); if (req.getCredentials() == null) { BadCredentialsException e = new BadCredentialsException("No password supplied"); publish(new AuthenticationFailureBadCredentialsEvent(req, e)); throw e; } UaaUser user; boolean passwordMatches = false; user = getUaaUser(req); if (user!=null) { passwordMatches = ((CharSequence) req.getCredentials()).length() != 0 && encoder.matches((CharSequence) req.getCredentials(), user.getPassword()); } else { user = dummyUser; } if (!accountLoginPolicy.isAllowed(user, req)) { logger.warn("Login policy rejected authentication for " + user.getUsername() + ", " + user.getId() + ". Ignoring login request."); AuthenticationPolicyRejectionException e = new AuthenticationPolicyRejectionException("Login policy rejected authentication"); publish(new AuthenticationFailureLockedEvent(req, e)); throw e; } if (passwordMatches) { logger.debug("Password successfully matched for userId["+user.getUsername()+"]:"+user.getId()); if (!allowUnverifiedUsers && !user.isVerified()) { publish(new UnverifiedUserAuthenticationEvent(user, req)); logger.debug("Account not verified: " + user.getId()); throw new AccountNotVerifiedException("Account not verified"); } int expiringPassword = getPasswordExpiresInMonths(); if (expiringPassword>0) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(user.getPasswordLastModified().getTime()); cal.add(Calendar.MONTH, expiringPassword); if (cal.getTimeInMillis() < System.currentTimeMillis()) { throw new PasswordExpiredException("Your current password has expired. Please reset your password."); } } Authentication success = new UaaAuthentication(new UaaPrincipal(user), user.getAuthorities(), (UaaAuthenticationDetails) req.getDetails()); publish(new UserAuthenticationSuccessEvent(user, success)); return success; } if (user == dummyUser || user == null) { logger.debug("No user named '" + req.getName() + "' was found for origin:"+ origin); publish(new UserNotFoundEvent(req)); } else { logger.debug("Password did not match for user " + req.getName()); publish(new UserAuthenticationFailureEvent(user, req)); } BadCredentialsException e = new BadCredentialsException("Bad credentials"); publish(new AuthenticationFailureBadCredentialsEvent(req, e)); throw e; }
590
1
public void setUp() throws Exception { lc = new LoggerContext(); lc.setName("testContext"); logger = lc.getLogger(LoggerSerializationTest.class); // create the byte output stream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); } @After
591
1
public void parseEmbedded( InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml) throws SAXException, IOException { if(outputHtml) { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", "class", "class", "CDATA", "package-entry"); handler.startElement(XHTML, "div", "div", attributes); } String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && name.length() > 0 && outputHtml) { handler.startElement(XHTML, "h1", "h1", new AttributesImpl()); char[] chars = name.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement(XHTML, "h1", "h1"); } // Use the delegate parser to parse this entry try (TemporaryResources tmp = new TemporaryResources()) { final TikaInputStream newStream = TikaInputStream.get(new CloseShieldInputStream(stream), tmp); if (stream instanceof TikaInputStream) { final Object container = ((TikaInputStream) stream).getOpenContainer(); if (container != null) { newStream.setOpenContainer(container); } } DELEGATING_PARSER.parse( newStream, new EmbeddedContentHandler(new BodyContentHandler(handler)), metadata, context); } catch (EncryptedDocumentException ede) { // TODO: can we log a warning that we lack the password? // For now, just skip the content } catch (TikaException e) { // TODO: can we log a warning somehow? // Could not parse the entry, just skip the content } if(outputHtml) { handler.endElement(XHTML, "div", "div"); } }
592
1
private final void internalMapWrapper(ContextVersion contextVersion, CharChunk path, MappingData mappingData) throws IOException { int pathOffset = path.getOffset(); int pathEnd = path.getEnd(); int servletPath = pathOffset; boolean noServletPath = false; int length = contextVersion.path.length(); if (length != (pathEnd - pathOffset)) { servletPath = pathOffset + length; } else { noServletPath = true; path.append('/'); pathOffset = path.getOffset(); pathEnd = path.getEnd(); servletPath = pathOffset+length; } path.setOffset(servletPath); // Rule 1 -- Exact Match MappedWrapper[] exactWrappers = contextVersion.exactWrappers; internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 2 -- Prefix Match boolean checkJspWelcomeFiles = false; MappedWrapper[] wildcardWrappers = contextVersion.wildcardWrappers; if (mappingData.wrapper == null) { internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting, path, mappingData); if (mappingData.wrapper != null && mappingData.jspWildCard) { char[] buf = path.getBuffer(); if (buf[pathEnd - 1] == '/') { /* * Path ending in '/' was mapped to JSP servlet based on * wildcard match (e.g., as specified in url-pattern of a * jsp-property-group. * Force the context's welcome files, which are interpreted * as JSP files (since they match the url-pattern), to be * considered. See Bugzilla 27664. */ mappingData.wrapper = null; checkJspWelcomeFiles = true; } else { // See Bugzilla 27704 mappingData.wrapperPath.setChars(buf, path.getStart(), path.getLength()); mappingData.pathInfo.recycle(); } } } if(mappingData.wrapper == null && noServletPath) { // The path is empty, redirect to "/" mappingData.redirectPath.setChars (path.getBuffer(), pathOffset, pathEnd-pathOffset); path.setEnd(pathEnd - 1); return; } // Rule 3 -- Extension Match MappedWrapper[] extensionWrappers = contextVersion.extensionWrappers; if (mappingData.wrapper == null && !checkJspWelcomeFiles) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); } // Rule 4 -- Welcome resources processing for servlets if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); // Rule 4a -- Welcome resources processing for exact macth internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 4b -- Welcome resources processing for prefix match if (mappingData.wrapper == null) { internalMapWildcardWrapper (wildcardWrappers, contextVersion.nesting, path, mappingData); } // Rule 4c -- Welcome resources processing // for physical folder if (mappingData.wrapper == null && contextVersion.resources != null) { String pathStr = path.toString(); WebResource file = contextVersion.resources.getResource(pathStr); if (file != null && file.isFile()) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); if (mappingData.wrapper == null && contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } } path.setOffset(servletPath); path.setEnd(pathEnd); } } /* welcome file processing - take 2 * Now that we have looked for welcome files with a physical * backing, now look for an extension mapping listed * but may not have a physical backing to it. This is for * the case of index.jsf, index.do, etc. * A watered down version of rule 4 */ if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); internalMapExtensionWrapper(extensionWrappers, path, mappingData, false); } path.setOffset(servletPath); path.setEnd(pathEnd); } } // Rule 7 -- Default servlet if (mappingData.wrapper == null && !checkJspWelcomeFiles) { if (contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); } // Redirection to a folder char[] buf = path.getBuffer(); if (contextVersion.resources != null && buf[pathEnd -1 ] != '/') { String pathStr = path.toString(); WebResource file = contextVersion.resources.getResource(pathStr); if (file != null && file.isDirectory()) { // Note: this mutates the path: do not do any processing // after this (since we set the redirectPath, there // shouldn't be any) path.setOffset(pathOffset); path.append('/'); mappingData.redirectPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); } else { mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } path.setOffset(pathOffset); path.setEnd(pathEnd); } /** * Exact mapping. */
593
1
protected String buildErrorMessage(Throwable e, Object[] args) { String errorKey = "struts.messages.upload.error." + e.getClass().getSimpleName(); if (LOG.isDebugEnabled()) { LOG.debug("Preparing error message for key: [#0]", errorKey); } return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args); } /** * Get an enumeration of the parameter names for uploaded files * * @return enumeration of parameter names for uploaded files */
594
1
public void testMultiValued() throws Exception { Map entityAttrs = createMap("name", "e", "url", "testdata.xml", XPathEntityProcessor.FOR_EACH, "/root"); List fields = new ArrayList(); fields.add(createMap("column", "a", "xpath", "/root/a", DataImporter.MULTI_VALUED, "true")); Context c = getContext(null, new VariableResolverImpl(), getDataSource(testXml), Context.FULL_DUMP, fields, entityAttrs); XPathEntityProcessor xPathEntityProcessor = new XPathEntityProcessor(); xPathEntityProcessor.init(c); List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); while (true) { Map<String, Object> row = xPathEntityProcessor.nextRow(); if (row == null) break; result.add(row); } assertEquals(2, ((List)result.get(0).get("a")).size()); } @Test
595
1
public String getInfo() { return (info); } // --------------------------------------------------------- Public Methods /** * Authenticate the user making this request, based on the specified * login configuration. Return <code>true</code> if any specified * constraint has been satisfied, or <code>false</code> if we have * created a response challenge already. * * @param request Request we are processing * @param response Response we are creating * @param config Login configuration describing how authentication * should be performed * * @exception IOException if an input/output error occurs */ @Override
596
1
public final void invoke(Request request, Response response) throws IOException, ServletException { // Select the Context to be used for this Request Context context = request.getContext(); if (context == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext")); return; } if (request.isAsyncSupported()) { request.setAsyncSupported(context.getPipeline().isAsyncSupported()); } boolean asyncAtStart = request.isAsync(); boolean asyncDispatching = request.isAsyncDispatching(); try { context.bind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); if (!asyncAtStart && !context.fireRequestInitEvent(request)) { // Don't fire listeners during async processing (the listener // fired for the request that called startAsync()). // If a request init listener throws an exception, the request // is aborted. return; } // Ask this Context to process this request. Requests that are in // async mode and are not being dispatched to this resource must be // in error and have been routed here to check for application // defined error pages. try { if (!asyncAtStart || asyncDispatching) { context.getPipeline().getFirst().invoke(request, response); } else { // Make sure this request/response is here because an error // report is required. if (!response.isErrorReportRequired()) { throw new IllegalStateException(sm.getString("standardHost.asyncStateError")); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); container.getLogger().error("Exception Processing " + request.getRequestURI(), t); // If a new error occurred while trying to report a previous // error allow the original error to be reported. if (!response.isErrorReportRequired()) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); throwable(request, response, t); } } // Now that the request/response pair is back under container // control lift the suspension so that the error handling can // complete and/or the container can flush any remaining data response.setSuspended(false); Throwable t = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // Protect against NPEs if the context was destroyed during a // long running request. if (!context.getState().isAvailable()) { return; } // Look for (and render if found) an application level error page if (response.isErrorReportRequired()) { if (t != null) { throwable(request, response, t); } else { status(request, response); } } if (!request.isAsync() && !asyncAtStart) { context.fireRequestDestroyEvent(request); } } finally { // Access a session (if present) to update last accessed time, based // on a strict interpretation of the specification if (ACCESS_SESSION) { request.getSession(false); } context.unbind(Globals.IS_SECURITY_ENABLED, MY_CLASSLOADER); } } // -------------------------------------------------------- Private Methods /** * Handle the HTTP status code (and corresponding message) generated * while processing the specified Request to produce the specified * Response. Any exceptions that occur during generation of the error * report are logged and swallowed. * * @param request The request being processed * @param response The response being generated */
597
1
private static void addHeadersToRequest(URLConnection connection, JSONObject headers) { try { for (Iterator<?> iter = headers.keys(); iter.hasNext(); ) { /* RFC 2616 says that non-ASCII characters and control * characters are not allowed in header names or values. * Additionally, spaces are not allowed in header names. * RFC 2046 Quoted-printable encoding may be used to encode * arbitrary characters, but we donon- not do that encoding here. */ String headerKey = iter.next().toString(); headerKey = headerKey.replaceAll("\\n","") .replaceAll("\\s+","") .replaceAll("[^\\x20-\\x7E]+", ""); JSONArray headerValues = headers.optJSONArray(headerKey); if (headerValues == null) { headerValues = new JSONArray(); /* RFC 2616 also says that any amount of consecutive linear * whitespace within a header value can be replaced with a * single space character, without affecting the meaning of * that value. */ String headerValue = headers.getString(headerKey); String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n"," ").replaceAll("[^\\x20-\\x7E]+", " "); headerValues.put(finalValue); } connection.setRequestProperty(headerKey, headerValues.getString(0)); for (int i = 1; i < headerValues.length(); ++i) { connection.addRequestProperty(headerKey, headerValues.getString(i)); } } } catch (JSONException e1) { // No headers to be manipulated! } }
598
1
public HttpSecurity and() { return HttpSecurity.this; }
599
1
void setExtensionsTable(StylesheetRoot sroot) throws javax.xml.transform.TransformerException { try { if (sroot.getExtensions() != null) m_extensionsTable = new ExtensionsTable(sroot); } catch (javax.xml.transform.TransformerException te) {te.printStackTrace();} } //== Implementation of the XPath ExtensionsProvider interface.