code
stringlengths
73
34.1k
label
stringclasses
1 value
public void setScalarSerializer (Class type, ScalarSerializer serializer) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (serializer == null) throw new IllegalArgumentException("serializer cannot be null."); scalarSerializers.put(type, serializer); }
java
public void setPropertyElementType (Class type, String propertyName, Class elementType) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null."); if (elementType == null) throw new IllegalArgumen...
java
public void setPropertyDefaultType (Class type, String propertyName, Class defaultType) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (propertyName == null) throw new IllegalArgumentException("propertyName cannot be null."); if (defaultType == null) throw new IllegalArgumen...
java
public <T> T read (Class<T> type) throws YamlException { return read(type, null); }
java
public <T> T read (Class<T> type, Class elementType) throws YamlException { try { while (true) { Event event = parser.getNextEvent(); if (event == null) return null; if (event.type == STREAM_END) return null; if (event.type == DOCUMENT_START) break; } return (T)readValue(type, element...
java
protected Object readValue (Class type, Class elementType, Class defaultType) throws YamlException, ParserException, TokenizerException { String tag = null, anchor = null; Event event = parser.peekNextEvent(); switch (event.type) { case ALIAS: parser.getNextEvent(); anchor = ((AliasEvent)event)...
java
protected Object createObject (Class type) throws InvocationTargetException { // Use deferred construction if a non-zero-arg constructor is available. DeferredConstruction deferredConstruction = Beans.getDeferredConstruction(type, config); if (deferredConstruction != null) return deferredConstruction; retur...
java
private final void error(String message, CharSequence identifier) { if (badHtmlHandler != Handler.DO_NOTHING) { // Avoid string append. badHtmlHandler.handle(message + " : " + identifier); } }
java
static String safeName(String unsafeElementName) { String elementName = HtmlLexer.canonicalName(unsafeElementName); // Substitute a reliably non-raw-text element for raw-text and // plain-text elements. switch (elementName.length()) { case 3: if ("xmp".equals(elementName)) { return "pre";...
java
public Trie lookup(char ch) { int i = Arrays.binarySearch(childMap, ch); return i >= 0 ? children[i] : null; }
java
public Trie lookup(CharSequence s) { Trie t = this; for (int i = 0, n = s.length(); i < n; ++i) { t = t.lookup(s.charAt(i)); if (null == t) { break; } } return t; }
java
static String normalizeUri(String s) { int n = s.length(); boolean colonsIrrelevant = false; for (int i = 0; i < n; ++i) { char ch = s.charAt(i); switch (ch) { case '/': case '#': case '?': case ':': colonsIrrelevant = true; break; case '(': case ')': ...
java
public boolean canContain(int parent, int child) { if (nofeatureElements.get(parent)) { // It's hard to interrogate a browser about the behavior of // <noscript> in scriptless mode using JavaScript, and the // behavior of <noscript> is more dangerous when in that mode, // so we hardcode that...
java
int[] impliedElements(int anc, int desc) { // <style> and <script> are allowed anywhere. if (desc == SCRIPT_TAG || desc == STYLE_TAG) { return ZERO_INTS; } // It's dangerous to allow free <li> tags because of the way an <li> // implies a </li> if there is an <li> on the parse stack without a ...
java
static String canonicalName(String elementOrAttribName) { return elementOrAttribName.indexOf(':') >= 0 ? elementOrAttribName : Strings.toLowerCase(elementOrAttribName); }
java
@Override protected HtmlToken produce() { HtmlToken token = readToken(); if (token == null) { return null; } switch (token.type) { // Keep track of whether we're inside a tag or not. case TAGBEGIN: state = State.IN_TAG; break; case TAGEND: if (state == State.SAW...
java
private HtmlToken collapseSubsequent(HtmlToken token) { HtmlToken collapsed = token; for (HtmlToken next; (next= peekToken(0)) != null && next.type == token.type; readToken()) { collapsed = join(collapsed, next); } return collapsed; }
java
private static boolean isValuelessAttribute(String attribName) { boolean valueless = VALUELESS_ATTRIB_NAMES.contains( Strings.toLowerCase(attribName)); return valueless; }
java
@Override protected HtmlToken produce() { HtmlToken token = parseToken(); if (null == token) { return null; } // Handle escape-exempt blocks. // The parse() method is only dimly aware of escape-excempt blocks, so // here we detect the beginning and ends of escape exempt blocks, and // reclass...
java
public HtmlPolicyBuilder allowElements( ElementPolicy policy, String... elementNames) { invalidateCompiledState(); for (String elementName : elementNames) { elementName = HtmlLexer.canonicalName(elementName); ElementPolicy newPolicy = ElementPolicy.Util.join( elPolicies.get(elementNa...
java
public HtmlPolicyBuilder allowWithoutAttributes(String... elementNames) { invalidateCompiledState(); for (String elementName : elementNames) { elementName = HtmlLexer.canonicalName(elementName); skipIfEmpty.remove(elementName); } return this; }
java
public HtmlPolicyBuilder disallowWithoutAttributes(String... elementNames) { invalidateCompiledState(); for (String elementName : elementNames) { elementName = HtmlLexer.canonicalName(elementName); skipIfEmpty.add(elementName); } return this; }
java
public AttributeBuilder allowAttributes(String... attributeNames) { ImmutableList.Builder<String> b = ImmutableList.builder(); for (String attributeName : attributeNames) { b.add(HtmlLexer.canonicalName(attributeName)); } return new AttributeBuilder(b.build()); }
java
public HtmlPolicyBuilder withPreprocessor(HtmlStreamEventProcessor pp) { this.preprocessor = HtmlStreamEventProcessor.Processors.compose( this.preprocessor, pp); return this; }
java
public static void main(String[] args) throws IOException { if (args.length != 0) { System.err.println("Reads from STDIN and writes to STDOUT"); System.exit(-1); } System.err.println("[Reading from STDIN]"); // Fetch the HTML to sanitize. String html = CharStreams.toString( new I...
java
public static String decodeHtml(String s) { int firstAmp = s.indexOf('&'); int safeLimit = longestPrefixOfGoodCodeunits(s); if ((firstAmp & safeLimit) < 0) { return s; } StringBuilder sb; { int n = s.length(); sb = new StringBuilder(n); int pos = 0; int amp = firstAmp; ...
java
@TCB static String stripBannedCodeunits(String s) { int safeLimit = longestPrefixOfGoodCodeunits(s); if (safeLimit < 0) { return s; } StringBuilder sb = new StringBuilder(s); stripBannedCodeunits(sb, safeLimit); return sb.toString(); }
java
@TCB private static int longestPrefixOfGoodCodeunits(String s) { int n = s.length(), i; for (i = 0; i < n; ++i) { char ch = s.charAt(i); if (ch < 0x20) { if (IS_BANNED_ASCII[ch]) { return i; } } else if (0xd800 <= ch) { if (ch <= 0xdfff) { if (i+1 ...
java
private boolean canContain( int child, int container, int containerIndexOnStack) { Preconditions.checkArgument(containerIndexOnStack >= 0); int anc = container; int ancIndexOnStack = containerIndexOnStack; while (true) { if (METADATA.canContain(anc, child)) { return true; } ...
java
public static void run(Appendable out, String... inputs) throws IOException { PolicyFactory policyBuilder = new HtmlPolicyBuilder() .allowAttributes("src").onElements("img") .allowAttributes("href").onElements("a") // Allow some URLs through. .allowStandardUrlProtocols() .allowElements...
java
public PolicyFactory and(PolicyFactory f) { ImmutableMap.Builder<String, ElementAndAttributePolicies> b = ImmutableMap.builder(); // Merge this and f into a map of element names to attribute policies. for (Map.Entry<String, ElementAndAttributePolicies> e : policies.entrySet()) { String...
java
static String cssContent(String token) { int n = token.length(); int pos = 0; StringBuilder sb = null; if (n >= 2) { char ch0 = token.charAt(0); if (ch0 == '"' || ch0 == '\'') { if (ch0 == token.charAt(n - 1)) { pos = 1; --n; sb = new StringBuilder(n); ...
java
private static void quickSort(int[] order, double[] values, int start, int end, int limit) { // the while loop implements tail-recursion to avoid excessive stack calls on nasty cases while (end - start > limit) { // pivot by a random element int pivotIndex = start + prng.nextInt...
java
private static void quickSort(double[] key, double[][] values, int start, int end, int limit) { // the while loop implements tail-recursion to avoid excessive stack calls on nasty cases while (end - start > limit) { // median of three values for the pivot int a = start; ...
java
@SuppressWarnings("SameParameterValue") private static void insertionSort(double[] key, double[][] values, int start, int end, int limit) { // loop invariant: all values start ... i-1 are ordered for (int i = start + 1; i < end; i++) { double v = key[i]; int m = Math.max(i - ...
java
@SuppressWarnings("UnusedDeclaration") public static void checkPartition(int[] order, double[] values, double pivotValue, int start, int low, int high, int end) { if (order.length != values.length) { throw new IllegalArgumentException("Arguments must be same size"); } if (!(star...
java
@SuppressWarnings("SameParameterValue") private static void insertionSort(int[] order, double[] values, int start, int n, int limit) { for (int i = start + 1; i < n; i++) { int t = order[i]; double v = values[order[i]]; int m = Math.max(i - limit, start); for ...
java
static double quantile(double index, double previousIndex, double nextIndex, double previousMean, double nextMean) { final double delta = nextIndex - previousIndex; final double previousWeight = (nextIndex - index) / delta; final double nextWeight = (index - previousIndex) / delta; retur...
java
public void add(double centroid, int count, List<Double> data) { this.centroid = centroid; this.count = count; this.data = data; tree.add(); }
java
@SuppressWarnings("WeakerAccess") public void update(int node, double centroid, int count, List<Double> data, boolean forceInPlace) { if (centroid == centroids[node]||forceInPlace) { // we prefer to update in place so repeated values don't shuffle around and for merging centroids[nod...
java
@Override public int smallByteSize() { int bound = byteSize(); ByteBuffer buf = ByteBuffer.allocate(bound); asSmallBytes(buf); return buf.position(); }
java
@Override public void asBytes(ByteBuffer buf) { buf.putInt(VERBOSE_ENCODING); buf.putDouble(min); buf.putDouble(max); buf.putDouble((float) compression()); buf.putInt(summary.size()); for (Centroid centroid : summary) { buf.putDouble(centroid.mean()); ...
java
@SuppressWarnings("WeakerAccess") public static AVLTreeDigest fromBytes(ByteBuffer buf) { int encoding = buf.getInt(); if (encoding == VERBOSE_ENCODING) { double min = buf.getDouble(); double max = buf.getDouble(); double compression = buf.getDouble(); ...
java
@SuppressWarnings("WeakerAccess") public static double compareChi2(TDigest dist1, TDigest dist2, double[] qCuts) { double[][] count = new double[2][]; count[0] = new double[qCuts.length + 1]; count[1] = new double[qCuts.length + 1]; double oldQ = 0; double oldQ2 = 0; ...
java
public int find() { for (int node = root; node != NIL; ) { final int cmp = compare(node); if (cmp < 0) { node = left(node); } else if (cmp > 0) { node = right(node); } else { return node; } } ...
java
public void remove(int node) { if (node == NIL) { throw new IllegalArgumentException(); } if (left(node) != NIL && right(node) != NIL) { // inner node final int next = next(node); assert next != NIL; swap(node, next); } ...
java
public String getMessageId() { Object messageId = getHeader(JmsMessageHeaders.MESSAGE_ID); if (messageId != null) { return messageId.toString(); } return null; }
java
public String getCorrelationId() { Object correlationId = getHeader(JmsMessageHeaders.CORRELATION_ID); if (correlationId != null) { return correlationId.toString(); } return null; }
java
public Destination getReplyTo() { Object replyTo = getHeader(JmsMessageHeaders.REPLY_TO); if (replyTo != null) { return (Destination) replyTo; } return null; }
java
public String getRedelivered() { Object redelivered = getHeader(JmsMessageHeaders.REDELIVERED); if (redelivered != null) { return redelivered.toString(); } return null; }
java
public String getType() { Object type = getHeader(JmsMessageHeaders.TYPE); if (type != null) { return type.toString(); } return null; }
java
private void performSchemaValidation(Message receivedMessage, JsonMessageValidationContext validationContext) { log.debug("Starting Json schema validation ..."); ProcessingReport report = jsonSchemaValidation.validate(receivedMessage, sche...
java
private String constructErrorMessage(ProcessingReport report) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Json validation failed: "); report.forEach(processingMessage -> stringBuilder.append(processingMessage.getMessage())); return stringBuilder.toString();...
java
public static boolean isSpringInternalHeader(String headerName) { // "springintegration_" makes Citrus work with Spring Integration 1.x release if (headerName.startsWith("springintegration_")) { return true; } else if (headerName.equals(MessageHeaders.ID)) { return true; ...
java
public static SoapAttachment parseAttachment(Element attachmentElement) { SoapAttachment soapAttachment = new SoapAttachment(); if (attachmentElement.hasAttribute("content-id")) { soapAttachment.setContentId(attachmentElement.getAttribute("content-id")); } if (attachmentEle...
java
public ObjectName createObjectName() { try { if (StringUtils.hasText(objectName)) { return new ObjectName(objectDomain + ":" + objectName); } if (type != null) { if (StringUtils.hasText(objectDomain)) { return new ObjectNam...
java
public MBeanInfo createMBeanInfo() { if (type != null) { return new MBeanInfo(type.getName(), description, getAttributeInfo(), getConstructorInfo(), getOperationInfo(), getNotificationInfo()); } else { return new MBeanInfo(name, description, getAttributeInfo(), getConstructorInfo...
java
private MBeanOperationInfo[] getOperationInfo() { final List<MBeanOperationInfo> infoList = new ArrayList<>(); if (type != null) { ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws Il...
java
private MBeanConstructorInfo[] getConstructorInfo() { final List<MBeanConstructorInfo> infoList = new ArrayList<>(); if (type != null) { for (Constructor constructor : type.getConstructors()) { infoList.add(new MBeanConstructorInfo(constructor.toGenericString(), constructor)...
java
private MBeanAttributeInfo[] getAttributeInfo() { final List<MBeanAttributeInfo> infoList = new ArrayList<>(); if (type != null) { final List<String> attributes = new ArrayList<>(); if (type.isInterface()) { ReflectionUtils.doWithMethods(type, new ReflectionUtil...
java
public void finish() throws IOException { if (printWriter != null) { printWriter.close(); } if (outputStream != null) { outputStream.close(); } }
java
public void postRegisterUrlHandlers(Map<String, Object> wsHandlers) { registerHandlers(wsHandlers); for (Object handler : wsHandlers.values()) { if (handler instanceof Lifecycle) { ((Lifecycle) handler).start(); } } }
java
public AbstractMessageContentBuilder constructMessageBuilder(Element messageElement) { AbstractMessageContentBuilder messageBuilder = null; if (messageElement != null) { messageBuilder = parsePayloadTemplateBuilder(messageElement); if (messageBuilder == null...
java
private PayloadTemplateMessageBuilder parsePayloadTemplateBuilder(Element messageElement) { PayloadTemplateMessageBuilder messageBuilder; messageBuilder = parsePayloadElement(messageElement); Element xmlDataElement = DomUtils.getChildElementByTagName(messageElement, "data"); ...
java
protected void parseHeaderElements(Element actionElement, AbstractMessageContentBuilder messageBuilder, List<ValidationContext> validationContexts) { Element headerElement = DomUtils.getChildElementByTagName(actionElement, "header"); Map<String, Object> messageHeaders = new LinkedHashMap<>(); i...
java
protected void parseExtractHeaderElements(Element element, List<VariableExtractor> variableExtractors) { Element extractElement = DomUtils.getChildElementByTagName(element, "extract"); Map<String, String> extractHeaderValues = new HashMap<>(); if (extractElement != null) { List<?> he...
java
public String build() { StringBuilder scriptBuilder = new StringBuilder(); StringBuilder scriptBody = new StringBuilder(); String importStmt = "import "; try { if (scriptCode.contains(importStmt)) { BufferedReader reader = new BufferedReader(new Strin...
java
public static TemplateBasedScriptBuilder fromTemplateResource(Resource scriptTemplateResource) { try { return new TemplateBasedScriptBuilder(FileUtils.readToString(scriptTemplateResource.getInputStream())); } catch (IOException e) { throw new CitrusRuntimeException("Error loading...
java
private ResponseEntity<?> handleRequestInternal(HttpMethod method, HttpEntity<?> requestEntity) { HttpMessage request = endpointConfiguration.getMessageConverter().convertInbound(requestEntity, endpointConfiguration, null); HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextH...
java
@Override public Message buildMessageContent( final TestContext context, final String messageType, final MessageDirection direction) { final Object payload = buildMessagePayload(context, messageType); try { Message message = new DefaultMessage(payload...
java
public Map<String, Object> buildMessageHeaders(final TestContext context, final String messageType) { try { final Map<String, Object> headers = context.resolveDynamicValuesInMap(messageHeaders); headers.put(MessageHeaders.MESSAGE_TYPE, messageType); for (final Map.Entry<Stri...
java
public List<String> buildMessageHeaderData(final TestContext context) { final List<String> headerDataList = new ArrayList<>(); for (final String headerResourcePath : headerResources) { try { headerDataList.add( context.replaceDynamicContentInString( ...
java
public SoapServerFaultResponseActionBuilder attachment(String contentId, String contentType, String content) { SoapAttachment attachment = new SoapAttachment(); attachment.setContentId(contentId); attachment.setContentType(contentType); attachment.setContent(content); getAction(...
java
public SoapServerFaultResponseActionBuilder charset(String charsetName) { if (!getAction().getAttachments().isEmpty()) { getAction().getAttachments().get(getAction().getAttachments().size() - 1).setCharsetName(charsetName); } return this; }
java
public SoapServerFaultResponseActionBuilder faultDetailResource(Resource resource, Charset charset) { try { getAction().getFaultDetails().add(FileUtils.readToString(resource, charset)); } catch (IOException e) { throw new CitrusRuntimeException("Failed to read fault detail resour...
java
public static CitrusConfiguration from(Properties extensionProperties) { CitrusConfiguration configuration = new CitrusConfiguration(extensionProperties); configuration.setCitrusVersion(getProperty(extensionProperties, "citrusVersion")); if (extensionProperties.containsKey("autoPackage")) { ...
java
private static String getProperty(Properties extensionProperties, String propertyName) { if (extensionProperties.containsKey(propertyName)) { Object value = extensionProperties.get(propertyName); if (value != null) { return value.toString(); } } ...
java
private static Properties readPropertiesFromDescriptor(ArquillianDescriptor descriptor) { for (ExtensionDef extension : descriptor.getExtensions()) { if (CitrusExtensionConstants.CITRUS_EXTENSION_QUALIFIER.equals(extension.getExtensionName())) { Properties properties = new Properties...
java
protected Resource loadSchemaResources() { PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); for (String location : schemas) { try { Resource[] findings = resourcePatternResolver.getResources(location); f...
java
public boolean isLast() { Object isLast = getHeader(WebSocketMessageHeaders.WEB_SOCKET_IS_LAST); if (isLast != null) { if (isLast instanceof String) { return Boolean.valueOf(isLast.toString()); } else { return (Boolean) isLast; } ...
java
private OperationResult getOperationResult() { if (operationResult == null) { this.operationResult = (OperationResult) marshaller.unmarshal(new StringSource(getPayload(String.class))); } return operationResult; }
java
private Operation getOperation() { if (operation == null) { this.operation = (Operation) marshaller.unmarshal(new StringSource(getPayload(String.class))); } return operation; }
java
String getPayloadAsString(Message<?> message) { if (message.getPayload() instanceof com.consol.citrus.message.Message) { return ((com.consol.citrus.message.Message) message.getPayload()).getPayload(String.class); } else { return message.getPayload().toString(); } }
java
protected boolean evaluate(String value) { if (ValidationMatcherUtils.isValidationMatcherExpression(matchingValue)) { try { ValidationMatcherUtils.resolveValidationMatcher(selectKey, value, matchingValue, context); return true; } catch (ValidationException...
java
protected FtpMessage createDir(CommandType ftpCommand) { try { sftp.mkdir(ftpCommand.getArguments()); return FtpMessage.result(FTPReply.PATHNAME_CREATED, "Pathname created", true); } catch (SftpException e) { throw new CitrusRuntimeException("Failed to execute ftp com...
java
public LSParser createLSParser() { LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); configureParser(parser); return parser; }
java
protected void configureParser(LSParser parser) { for (Map.Entry<String, Object> setting : parseSettings.entrySet()) { setParserConfigParameter(parser, setting.getKey(), setting.getValue()); } }
java
protected void configureSerializer(LSSerializer serializer) { for (Map.Entry<String, Object> setting : serializeSettings.entrySet()) { setSerializerConfigParameter(serializer, setting.getKey(), setting.getValue()); } }
java
private void setDefaultParseSettings() { if (!parseSettings.containsKey(CDATA_SECTIONS)) { parseSettings.put(CDATA_SECTIONS, true); } if (!parseSettings.containsKey(SPLIT_CDATA_SECTIONS)) { parseSettings.put(SPLIT_CDATA_SECTIONS, false); } if (!parseSett...
java
private void setDefaultSerializeSettings() { if (!serializeSettings.containsKey(ELEMENT_CONTENT_WHITESPACE)) { serializeSettings.put(ELEMENT_CONTENT_WHITESPACE, true); } if (!serializeSettings.containsKey(SPLIT_CDATA_SECTIONS)) { serializeSettings.put(SPLIT_CDATA_SECTION...
java
public void addPart(AttachmentPart part) { if (attachments == null) { attachments = new BodyPart.Attachments(); } this.attachments.add(part); }
java
public static String getBinding(String resourcePath) { if (resourcePath.contains("/")) { return resourcePath.substring(resourcePath.indexOf('/') + 1); } return null; }
java
public static String getHost(String resourcePath) { String hostSpec; if (resourcePath.contains(":")) { hostSpec = resourcePath.split(":")[0]; } else { hostSpec = resourcePath; } if (hostSpec.contains("/")) { hostSpec = hostSpec.substring(0, ho...
java
public static SoapAttachment from(Attachment attachment) { SoapAttachment soapAttachment = new SoapAttachment(); String contentId = attachment.getContentId(); if (contentId.startsWith("<") && contentId.endsWith(">")) { contentId = contentId.substring(1, contentId.length() - 1); ...
java
public String getContent() { if (content != null) { return context != null ? context.replaceDynamicContentInString(content) : content; } else if (StringUtils.hasText(getContentResourcePath()) && getContentType().startsWith("text")) { try { String fileContent = Fil...
java
public String getContentResourcePath() { if (contentResourcePath != null && context != null) { return context.replaceDynamicContentInString(contentResourcePath); } else { return contentResourcePath; } }
java
public void extractVariables(Message message, TestContext context) { if (CollectionUtils.isEmpty(headerMappings)) { return; } for (Entry<String, String> entry : headerMappings.entrySet()) { String headerElementName = entry.getKey(); String targetVariableName = entry.getValue(); ...
java
public <T extends KubernetesCommand> T command(T command) { action.setCommand(command); return command; }
java
private Message receive(TestContext context) { Endpoint messageEndpoint = getOrCreateEndpoint(context); return receiveTimeout > 0 ? messageEndpoint.createConsumer().receive(context, receiveTimeout) : messageEndpoint.createConsumer().receive(context, messageEndpoint.getEndpointConfigurati...
java
private Message receiveSelected(TestContext context, String selectorString) { if (log.isDebugEnabled()) { log.debug("Setting message selector: '" + selectorString + "'"); } Endpoint messageEndpoint = getOrCreateEndpoint(context); Consumer consumer = messageEndpoint.createCon...
java