Example usage for org.apache.commons.lang3 StringUtils startsWith

List of usage examples for org.apache.commons.lang3 StringUtils startsWith

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils startsWith.

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:org.goko.controller.tinyg.json.TinyGJsonUtils.java

/**
 * Determines if a string can be parsed as json object
 *
 * @param str the string//from  www. j a  va 2 s  .c  om
 * @return <code>true</code> or <code>false</code>
 */
public static boolean isJsonFormat(String str) {
    return StringUtils.startsWith(str.trim(), "{") && StringUtils.endsWith(str.trim(), "}");
}

From source file:org.goko.core.gcode.rs274ngcv3.parser.GCodeLexer.java

/**
 * Recursive method used to split the stringCommand into a list of tokens
 * @param stringCommand the string command
 * @param tokens the list of token// w w w .  j  av  a 2 s . c o  m
 * @throws GkException GkException
 */
protected List<GCodeToken> createTokens(String pStringCommand, List<GCodeToken> tokens,
        IValidationTarget validationTarget, int lineNumber, int columnNumber) throws GkException {
    String stringCommand = pStringCommand;
    int totalColumn = columnNumber + StringUtils.length(stringCommand);
    if (StringUtils.isBlank(stringCommand)) {
        return tokens;
    }
    Matcher spaceMatcher = spacePattern.matcher(stringCommand);
    if (spaceMatcher.find()) {
        String remainingString = spaceMatcher.replaceFirst(StringUtils.EMPTY);
        return createTokens(remainingString, tokens, validationTarget, lineNumber,
                totalColumn - StringUtils.length(remainingString));
    }
    Matcher multilineCommentMatcher = multilineCommentPattern.matcher(stringCommand);
    if (multilineCommentMatcher.find()) {
        String remainingString = extractToken(multilineCommentMatcher, tokens,
                GCodeTokenType.MULTILINE_COMMENT);
        return createTokens(remainingString, tokens, validationTarget, lineNumber,
                totalColumn - StringUtils.length(remainingString));
    }
    Matcher simpleCommentMatcher = simpleCommentPattern.matcher(stringCommand);
    if (simpleCommentMatcher.find()) {
        String remainingString = extractToken(simpleCommentMatcher, tokens, GCodeTokenType.SIMPLE_COMMENT);
        return createTokens(remainingString, tokens, validationTarget, lineNumber,
                totalColumn - StringUtils.length(remainingString));
    }
    // Remove all white spaces ( comments already removed )
    while (StringUtils.startsWith(stringCommand, " ")) {
        stringCommand = stringCommand.replaceFirst("\\s", StringUtils.EMPTY);
        columnNumber += 1;
    }
    Matcher lineNumberMatcher = lineNumberPattern.matcher(stringCommand);
    if (lineNumberMatcher.find()) {
        String remainingString = extractToken(lineNumberMatcher, tokens, GCodeTokenType.LINE_NUMBER);
        return createTokens(remainingString, tokens, validationTarget, lineNumber,
                totalColumn - StringUtils.length(remainingString));
    }

    Matcher wordMatcher = wordPattern.matcher(stringCommand);
    if (wordMatcher.find()) {
        String remainingString = extractToken(wordMatcher, tokens, GCodeTokenType.WORD);
        return createTokens(remainingString, tokens, validationTarget, lineNumber,
                totalColumn - StringUtils.length(remainingString));
    }

    Matcher percentMatcher = percentPattern.matcher(stringCommand);
    if (percentMatcher.find()) {
        String remainingString = extractToken(percentMatcher, tokens, GCodeTokenType.PERCENT);
        return createTokens(remainingString, tokens, validationTarget, lineNumber,
                totalColumn - StringUtils.length(remainingString));
    }
    if (validationTarget != null) {
        ValidationElement vElement = new ValidationElement(ValidationSeverity.ERROR,
                new Location(lineNumber, columnNumber), StringUtils.length(stringCommand),
                MessageFormat.format(MessageResource.getMessage("GCO-101"), stringCommand));
        validationTarget.addValidationElement(vElement);
        return tokens;
    } else {
        throw new GkFunctionalException("GCO-101", stringCommand);
    }
}

From source file:org.goko.core.rs274ngcv3.parser.advanced.tokens.abstracts.LetterTokenCommandModifier.java

/** (inheritDoc)
 * @see org.goko.core.rs274ngcv3.parser.advanced.tokens.abstracts.TokenCommandModifier#match(org.goko.core.rs274ngcv3.parser.GCodeToken)
 *//*  w  w w.  j  a v  a  2 s. co  m*/
@Override
public boolean match(GCodeToken token) throws GkException {
    return StringUtils.startsWith(token.getValue(), letter);
}

From source file:org.goko.grbl.controller.GrblCommunicator.java

/**
 * Handling of incoming data/*from  w  w w. j  av a  2s.com*/
 * @param data the received data
 * @throws GkException GkException
 */
protected void handleIncomingData(String data) throws GkException {
    String trimmedData = StringUtils.trim(data);
    if (StringUtils.isNotEmpty(trimmedData)) {
        /* Received OK response */
        if (StringUtils.equals(trimmedData, Grbl.OK_RESPONSE)) {
            grbl.handleOkResponse();

            /* Received error  */
        } else if (StringUtils.startsWith(trimmedData, "error:")) {
            grbl.handleError(trimmedData);

            /* Received status report  */
        } else if (StringUtils.startsWith(trimmedData, "<") && StringUtils.endsWith(trimmedData, ">")) {
            grbl.handleStatusReport(parseStatusReport(trimmedData));

            /* Received Grbl header */
        } else if (StringUtils.startsWith(trimmedData, "Grbl")) {
            handleHeader(trimmedData);
            grbl.initialiseConnectedState();
            //   refreshStatus();

            /* Received a configuration confirmation */
        } else if (StringUtils.defaultString(trimmedData).matches("\\$[0-9]*=.*")) {
            grbl.handleConfigurationReading(trimmedData);

            /* Received an offset position report */
        } else if (StringUtils.defaultString(trimmedData).matches("\\[(G5|G28|G30|G92).*\\]")) {
            Tuple6b targetPoint = new Tuple6b().setNull();
            String offsetName = parseCoordinateSystem(trimmedData, targetPoint);
            grbl.setOffsetCoordinate(offsetName, targetPoint);

            /* Parser state report */
        } else if (StringUtils.defaultString(trimmedData).matches("\\[(G0|G1|G2|G3).*\\]")) {
            grbl.receiveParserState(StringUtils.substringBetween(trimmedData, "[", "]"));
            /* Unkown format received */
        } else {
            LOG.error("Ignoring received data " + trimmedData);
            grbl.getApplicativeLogService().warning("Ignoring received data " + trimmedData,
                    GrblControllerService.SERVICE_ID);
        }
    }
}

From source file:org.goko.tools.viewer.jogl.service.JoglViewerServiceImpl.java

/** (inheritDoc)
 * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
 *///w  w w  .j av  a 2  s  .  c  o  m
@Override
public void propertyChange(PropertyChangeEvent event) {
    super.propertyChange(event);
    try {
        zeroRenderer.setDisplayRotaryAxis(JoglViewerPreference.getInstance().isRotaryAxisEnabled());
        zeroRenderer.setRotationAxis(JoglViewerPreference.getInstance().getRotaryAxisDirection());
        zeroRenderer.update();
        // Update the grid
        if (StringUtils.startsWith(event.getProperty(), JoglViewerPreference.GROUP_GRID)) {
            boolean xyDisplay = xyGridRenderer.isEnabled();
            boolean xzDisplay = xzGridRenderer.isEnabled();
            boolean yzDisplay = yzGridRenderer.isEnabled();
            this.xyGridRenderer.destroy();
            this.xzGridRenderer.destroy();
            this.yzGridRenderer.destroy();
            this.xyGridRenderer = new GridRenderer(JoglUtils.XY_GRID_ID, gcodeContextProvider);
            this.xyGridRenderer.setNormal(JoglUtils.Z_AXIS);
            this.xzGridRenderer = new GridRenderer(JoglUtils.XZ_GRID_ID, gcodeContextProvider);
            this.xzGridRenderer.setNormal(JoglUtils.Y_AXIS);
            this.yzGridRenderer = new GridRenderer(JoglUtils.YZ_GRID_ID, gcodeContextProvider);
            this.yzGridRenderer.setNormal(JoglUtils.X_AXIS);
            updateGridRenderer(xyGridRenderer);
            updateGridRenderer(xzGridRenderer);
            updateGridRenderer(yzGridRenderer);
            xyGridRenderer.setEnabled(xyDisplay);
            xzGridRenderer.setEnabled(xzDisplay);
            yzGridRenderer.setEnabled(yzDisplay);
            addRenderer(xyGridRenderer);
            addRenderer(xzGridRenderer);
            addRenderer(yzGridRenderer);
        }
    } catch (GkException e) {
        LOG.error(e);
    }
}

From source file:org.imsglobal.lti.toolProvider.ToolProvider.java

/**
 * Check the authenticity of the LTI launch request.
 *
 * The consumer, resource link and user objects will be initialised if the request is valid.
 *
 * @return boolean True if the request has been successfully validated.
 *///from  ww  w  .j a  v  a 2s  .  c  o m
private boolean authenticate() {
    boolean doSaveConsumer = false;
    //JSON Initialization
    JSONParser parser = new JSONParser();
    JSONObject tcProfile = null;

    String messageType = request.getParameter("lti_message_type");
    ok = (StringUtils.isNotEmpty(messageType) && MESSAGE_TYPES.containsKey(messageType));
    if (!ok) {
        reason = "Invalid or missing lti_message_type parameter.";
    }
    if (ok) {
        String version = request.getParameter("lti_version");
        ok = (StringUtils.isNotEmpty(version)) && (LTI_VERSIONS.contains(version));
        if (!ok) {
            reason = "Invalid or missing lti_version parameter.";
        }
    }
    if (ok) {
        if (messageType.equals("basic-lti-launch-request")) {
            String resLinkId = request.getParameter("resource_link_id");
            ok = (StringUtils.isNotEmpty(resLinkId));
            if (!ok) {
                reason = "Missing resource link ID.";
            }
        } else if (messageType.equals("ContentItemSelectionRequest")) {
            String accept = request.getParameter("accept_media_types");
            ok = (StringUtils.isNotEmpty(accept));
            if (ok) {
                String[] mediaTypes = StringUtils.split(accept, ",");
                Set<String> mTypes = new HashSet<String>();
                for (String m : mediaTypes) {
                    mTypes.add(m); //unique set of media types, no repeats
                }
                ok = mTypes.size() > 0;
                if (!ok) {
                    reason = "No accept_media_types found.";
                } else {
                    this.mediaTypes = mTypes;
                }
            } else { //no accept 
                ok = false;
            }
            String targets = request.getParameter("accept_presentation_document_targets");
            if (ok && StringUtils.isNotEmpty(targets)) {
                Set<String> documentTargets = new HashSet<String>();
                for (String t : StringUtils.split(targets, ",")) {
                    documentTargets.add(t);
                }
                ok = documentTargets.size() > 0;
                if (!ok) {
                    reason = "Missing or empty accept_presentation_document_targets parameter.";
                } else {
                    List<String> valid = Arrays.asList("embed", "frame", "iframe", "window", "popup", "overlay",
                            "none");
                    boolean thisCheck = true;
                    String problem = "";
                    for (String target : documentTargets) {
                        thisCheck = valid.contains(target);
                        if (!thisCheck) {
                            problem = target;
                            break;
                        }
                    }
                    if (!thisCheck) {
                        reason = "Invalid value in accept_presentation_document_targets parameter: " + problem;
                    }
                }
                if (ok) {
                    this.documentTargets = documentTargets;
                }
            } else {
                ok = false;
            }
            if (ok) {
                String ciReturnUrl = request.getParameter("content_item_return_url");
                ok = StringUtils.isNotEmpty(ciReturnUrl);
                if (!ok) {
                    reason = "Missing content_item_return_url parameter.";
                }
            }
        } else if (messageType.equals("ToolProxyRegistrationRequest")) {
            String regKey = request.getParameter("reg_key");
            String regPass = request.getParameter("reg_password");
            String profileUrl = request.getParameter("tc_profile_url");
            String launchReturnUrl = request.getParameter("launch_presentation_return_url");
            ok = StringUtils.isNotEmpty(regKey) && StringUtils.isNotEmpty(regPass)
                    && StringUtils.isNotEmpty(profileUrl) && StringUtils.isNotEmpty(launchReturnUrl);
            if (debugMode && !ok) {
                reason = "Missing message parameters.";
            }
        }
    }
    DateTime now = DateTime.now();
    //check consumer key
    if (ok && !messageType.equals("ToolProxyRegistrationRequest")) {
        String key = request.getParameter("oauth_consumer_key");
        ok = StringUtils.isNotEmpty(key);
        if (!ok) {
            reason = "Missing consumer key.";
        }
        if (ok) {
            this.consumer = new ToolConsumer(key, dataConnector);
            ok = consumer.getCreated() != null;
            if (!ok) {
                reason = "Invalid consumer key.";
            }
        }
        if (ok) {
            if (consumer.getLastAccess() == null) {
                doSaveConsumer = true;
            } else {
                DateTime last = consumer.getLastAccess();
                doSaveConsumer = doSaveConsumer || last.isBefore(now.withTimeAtStartOfDay());
            }
            consumer.setLastAccess(now);
            String baseString = "";
            String signature = "";
            OAuthMessage oAuthMessage = null;
            try {
                OAuthConsumer oAuthConsumer = new OAuthConsumer("about:blank", consumer.getKey(),
                        consumer.getSecret(), null);
                OAuthAccessor oAuthAccessor = new OAuthAccessor(oAuthConsumer);
                OAuthValidator oAuthValidator = new SimpleOAuthValidator();
                URL u = new URL(request.getRequestURI());
                String url = u.getProtocol() + "://" + u.getHost() + u.getPath();
                Map<String, String[]> params = request.getParameterMap();
                Map<String, List<String>> param2 = new HashMap<String, List<String>>();
                for (String k : params.keySet()) {
                    param2.put(k, Arrays.asList(params.get(k)));
                }
                List<Map.Entry<String, String>> param3 = ToolConsumer.convert(param2);
                oAuthMessage = new OAuthMessage(request.getMethod(), url, param3);
                baseString = OAuthSignatureMethod.getBaseString(oAuthMessage);
                signature = oAuthMessage.getSignature();
                oAuthValidator.validateMessage(oAuthMessage, oAuthAccessor);
            } catch (Exception e) {
                System.err.println(e.getMessage());
                OAuthProblemException oe = null;
                if (e instanceof OAuthProblemException) {
                    oe = (OAuthProblemException) e;
                    for (String p : oe.getParameters().keySet()) {
                        System.err.println(p + ": " + oe.getParameters().get(p).toString());
                    }
                }
                this.ok = false;
                if (StringUtils.isEmpty(reason)) {
                    if (debugMode) {
                        reason = e.getMessage();
                        if (StringUtils.isEmpty(reason)) {
                            reason = "OAuth exception.";
                        }
                        details.add("Timestamp: " + request.getParameter("oauth_timestamp"));
                        details.add("Current system time: " + System.currentTimeMillis());
                        details.add("Signature: " + signature);
                        details.add("Base string: " + baseString);
                    } else {
                        reason = "OAuth signature check failed - perhaps an incorrect secret or timestamp.";
                    }
                }
            }
        }
        if (ok) {
            DateTime today = DateTime.now();
            if (consumer.getLastAccess() == null) {
                doSaveConsumer = true;
            } else {
                DateTime last = consumer.getLastAccess();
                doSaveConsumer = doSaveConsumer || last.isBefore(today.withTimeAtStartOfDay());
            }
            consumer.setLastAccess(today);
            if (consumer.isThisprotected()) {
                String guid = request.getParameter("tool_consumer_instance_guid");
                if (StringUtils.isNotEmpty(consumer.getConsumerGuid())) {
                    ok = StringUtils.isEmpty(guid) || consumer.getConsumerGuid().equals(guid);
                    if (!ok) {
                        reason = "Request is from an invalid tool consumer.";
                    }
                } else {
                    ok = StringUtils.isEmpty(guid);
                    if (!ok) {
                        reason = "A tool consumer GUID must be included in the launch request.";
                    }
                }
            }
            if (ok) {
                ok = consumer.isEnabled();
                if (!ok) {
                    reason = "Tool consumer has not been enabled by the tool provider.";
                }
            }
            if (ok) {
                ok = consumer.getEnableFrom() == null || consumer.getEnableFrom().isBefore(today);
                if (ok) {
                    ok = consumer.getEnableUntil() == null || consumer.getEnableUntil().isAfter(today);
                    if (!ok) {
                        reason = "Tool consumer access has expired.";
                    }
                } else {
                    reason = "Tool consumer access is not yet available.";
                }
            }
        }

        // Validate other message parameter values
        if (ok) {
            List<String> boolValues = Arrays.asList("true", "false");
            String acceptUnsigned = request.getParameter("accept_unsigned");
            String acceptMultiple = request.getParameter("accept_multiple");
            String acceptCopyAdvice = request.getParameter("accept_copy_advice");
            String autoCreate = request.getParameter("auto_create");
            String canConfirm = request.getParameter("can_confirm");
            String lpdt = request.getParameter("launch_presentation_document_target");
            if (messageType.equals("ContentItemSelectionRequest")) {
                if (StringUtils.isNotEmpty(acceptUnsigned)) {
                    ok = boolValues.contains(acceptUnsigned);
                    if (!ok) {
                        reason = "Invalid value for accept_unsigned parameter: " + acceptUnsigned + ".";
                    }
                }
                if (ok && StringUtils.isNotEmpty(acceptMultiple)) {
                    ok = boolValues.contains(acceptMultiple);
                    if (!ok) {
                        reason = "Invalid value for accept_multiple parameter: " + acceptMultiple + ".";
                    }
                }
                if (ok && StringUtils.isNotEmpty(acceptCopyAdvice)) {
                    ok = boolValues.contains(acceptCopyAdvice);
                    if (!ok) {
                        reason = "Invalid value for accept_copy_advice parameter: " + acceptCopyAdvice + ".";
                    }
                }
                if (ok && StringUtils.isNotEmpty(autoCreate)) {
                    ok = boolValues.contains(autoCreate);
                    if (!ok) {
                        reason = "Invalid value for auto_create parameter: " + autoCreate + ".";
                    }
                }
                if (ok && StringUtils.isNotEmpty(canConfirm)) {
                    ok = boolValues.contains(canConfirm);
                    if (!ok) {
                        reason = "Invalid value for can_confirm parameter: " + canConfirm + ".";
                    }
                }
            } else if (StringUtils.isNotEmpty(lpdt)) {
                List<String> valid = Arrays.asList("embed", "frame", "iframe", "window", "popup", "overlay",
                        "none");
                ok = valid.contains(lpdt);
                if (!ok) {
                    reason = "Invalid value for launch_presentation_document_target parameter: " + lpdt + ".";
                }
            }
        }
    }

    if (ok && (messageType.equals("ToolProxyRegistrationRequest"))) {

        ok = request.getParameter("lti_version").equals(LTI_VERSION2);
        if (!ok) {
            reason = "Invalid lti_version parameter";
        }
        if (ok) {
            HttpClient client = HttpClientBuilder.create().build();
            String tcProfUrl = request.getParameter("tc_profile_url");
            HttpGet get = new HttpGet(tcProfUrl);
            get.addHeader("Accept", "application/vnd.ims.lti.v2.toolconsumerprofile+json");
            HttpResponse response = null;
            try {
                response = client.execute(get);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response == null) {
                reason = "Tool consumer profile not accessible.";
            } else {
                try {
                    String json_string = EntityUtils.toString(response.getEntity());
                    tcProfile = (JSONObject) parser.parse(json_string);
                    ok = tcProfile != null;
                    if (!ok) {
                        reason = "Invalid JSON in tool consumer profile.";
                    } else {
                        JSONContext jsonContext = new JSONContext();
                        jsonContext.parse(tcProfile);
                        consumer.getProfile().setContext(jsonContext);
                    }
                } catch (Exception je) {
                    je.printStackTrace();
                    ok = false;
                    reason = "Invalid JSON in tool consumer profile.";
                }
            }
        }
        // Check for required capabilities
        if (ok) {
            String regKey = request.getParameter("reg_key");
            consumer = new ToolConsumer(regKey, dataConnector);
            ConsumerProfile profile = new ConsumerProfile();
            JSONContext context = new JSONContext();
            context.parse(tcProfile);
            profile.setContext(context);
            consumer.setProfile(profile);
            List<String> capabilities = consumer.getProfile().getCapabilityOffered();
            List<String> missing = new ArrayList<String>();
            for (ProfileResourceHandler handler : resourceHandlers) {
                for (ProfileMessage message : handler.getRequiredMessages()) {
                    String type = message.getType();
                    if (!capabilities.contains(type)) {
                        missing.add(type);
                    }
                }
            }
            for (String name : constraints.keySet()) {
                ParameterConstraint constraint = constraints.get(name);
                if (constraint.isRequired()) {
                    if (!capabilities.contains(name)) {
                        missing.add(name);
                    }
                }
            }
            if (!missing.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (String cap : missing) {
                    sb.append(cap).append(", ");
                }
                reason = "Required capability not offered - \"" + sb.toString() + "\"";
                ok = false;
            }
        }
        // Check for required services
        if (ok) {
            for (ToolService tService : requiredServices) {
                for (String format : tService.getFormats()) {
                    ServiceDefinition sd = findService(format, tService.getActions());
                    if (sd == null) {
                        if (ok) {
                            reason = "Required service(s) not offered - ";
                            ok = false;
                        } else {
                            reason += ", ";
                        }
                        StringBuilder sb = new StringBuilder();
                        for (String a : tService.getActions()) {
                            sb.append(a).append(", ");
                        }
                        reason += format + "[" + sb.toString() + "]";
                    }
                }
            }
        }
        if (ok) {
            if (messageType.equals("ToolProxyRegistrationRequest")) {
                ConsumerProfile profile = new ConsumerProfile();
                JSONContext context = new JSONContext();
                context.parse(tcProfile);
                profile.setContext(context);
                consumer.setProfile(profile);
                consumer.setSecret(request.getParameter("reg_password"));
                consumer.setLtiVersion(request.getParameter("lti_version"));
                consumer.setName(profile.getProduct().getProductInfo().getProductName().get("default_name"));
                consumer.setConsumerName(consumer.getName());
                consumer.setConsumerVersion(
                        "{tcProfile.product_instance.product_info.product_family.code}-{tcProfile.product_instance.product_info.product_version}");
                consumer.setConsumerGuid(profile.getProduct().getGuid());
                consumer.setEnabled(true);
                consumer.setThisprotected(true);
                doSaveConsumer = true;
            }
        }
    } else if (ok && !request.getParameter("custom_tc_profile_url").isEmpty()
            && consumer.getProfile() == null) {
        String tcProfUrl = request.getParameter("custom_tc_profile_url");
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(tcProfUrl);
        get.addHeader("Accept", "application/vnd.ims.lti.v2.toolconsumerprofile+json");
        HttpResponse response = null;
        try {
            response = client.execute(get);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response == null) {
            reason = "Tool consumer profile not accessible.";
        } else {
            try {
                String json_string = EntityUtils.toString(response.getEntity());
                tcProfile = (JSONObject) parser.parse(json_string);
                ok = tcProfile != null;
                if (!ok) {
                    reason = "Invalid JSON in tool consumer profile.";
                } else {
                    JSONContext jsonContext = new JSONContext();
                    jsonContext.parse(tcProfile);
                    consumer.getProfile().setContext(jsonContext);
                    doSaveConsumer = true;
                }
            } catch (Exception je) {
                je.printStackTrace();
                ok = false;
                reason = "Invalid JSON in tool consumer profile.";
            }
        }
    }

    // Validate message parameter constraints
    if (ok) {
        List<String> invalidParameters = new ArrayList<String>();
        for (String name : constraints.keySet()) {
            ParameterConstraint constraint = constraints.get(name);
            if (constraint.getMessageTypes().isEmpty() || constraint.getMessageTypes().contains(messageType)) {
                ok = true;
                String n = request.getParameter("name");
                if (constraint.isRequired()) {
                    n = n.trim();
                    if (StringUtils.isBlank(n)) {
                        invalidParameters.add(name + " (missing)");
                        ok = false;
                    }
                }
                if (ok && constraint.getMaxLength() > 0 && StringUtils.isNotBlank(n)) {
                    if (n.trim().length() > constraint.getMaxLength()) {
                        invalidParameters.add(name + " (too long)");
                    }
                }
            }
        }
        if (invalidParameters.size() > 0) {
            ok = false;
            if (StringUtils.isEmpty(reason)) {
                StringBuilder sb = new StringBuilder();
                for (String ip : invalidParameters) {
                    sb.append(ip).append(", ");
                }
                reason = "Invalid parameter(s): " + sb.toString() + ".";
            }
        }
    }

    if (ok) {

        // Set the request context
        String cId = request.getParameter("context_id");
        if (StringUtils.isNotEmpty(cId)) {
            context = Context.fromConsumer(consumer, cId.trim());
            String title = request.getParameter("context_title");
            if (StringUtils.isNotEmpty(title)) {
                title = title.trim();
            }
            if (StringUtils.isBlank(title)) {
                title = "Course " + context.getId();
            }
            context.setTitle(title);
        }

        // Set the request resource link
        String rlId = request.getParameter("resource_link_id");
        if (StringUtils.isNotEmpty(rlId)) {
            String contentItemId = request.getParameter("custom_content_item_id");
            resourceLink = ResourceLink.fromConsumer(consumer, rlId, contentItemId);
            if (context != null) {
                resourceLink.setContextId(context.getRecordId());
            }
            String title = request.getParameter("resource_link_title");
            if (StringUtils.isEmpty(title)) {
                title = "Resource " + resourceLink.getId();
            }
            resourceLink.setTitle(title);
            // Delete any existing custom parameters
            for (String name : consumer.getSettings().keySet()) {
                if (StringUtils.startsWith(name, "custom_")) {
                    consumer.setSetting(name);
                    doSaveConsumer = true;
                }
            }
            if (context != null) {
                for (String name : context.getSettings().keySet()) {
                    if (StringUtils.startsWith(name, "custom_")) {
                        context.setSetting(name, "");
                    }
                }
            }
            for (String name : resourceLink.getSettings().keySet()) {
                if (StringUtils.startsWith(name, "custom_")) {
                    resourceLink.setSetting(name, "");
                }
            }
            // Save LTI parameters
            for (String name : LTI_CONSUMER_SETTING_NAMES) {
                String s = request.getParameter(name);
                if (StringUtils.isNotBlank(s)) {
                    consumer.setSetting(name, s);
                } else {
                    consumer.setSetting(name);
                }
            }
            if (context != null) {
                for (String name : LTI_CONTEXT_SETTING_NAMES) {
                    String s = request.getParameter(name);
                    if (StringUtils.isNotBlank(s)) {
                        context.setSetting(name, s);
                    } else {
                        context.setSetting(name, "");
                    }
                }
            }
            for (String name : LTI_RESOURCE_LINK_SETTING_NAMES) {
                String sn = request.getParameter(name);
                if (StringUtils.isNotEmpty(sn)) {
                    resourceLink.setSetting(name, sn);
                } else {
                    resourceLink.setSetting(name, "");
                }
            }
            // Save other custom parameters
            ArrayList<String> combined = new ArrayList<String>();
            combined.addAll(Arrays.asList(LTI_CONSUMER_SETTING_NAMES));
            combined.addAll(Arrays.asList(LTI_CONTEXT_SETTING_NAMES));
            combined.addAll(Arrays.asList(LTI_RESOURCE_LINK_SETTING_NAMES));
            for (String name : request.getParameterMap().keySet()) {
                String value = request.getParameter(name);
                if (StringUtils.startsWith(name, "custom_") && !combined.contains(name)) {
                    resourceLink.setSetting(name, value);
                }
            }
        }

        // Set the user instance
        String userId = request.getParameter("user_id");
        if (StringUtils.isNotEmpty(userId)) {
            userId = userId.trim();
        }

        user = User.fromResourceLink(resourceLink, userId);

        // Set the user name
        String firstname = request.getParameter("lis_person_name_given");
        String lastname = request.getParameter("lis_person_name_family");
        String fullname = request.getParameter("lis_person_name_full");
        user.setNames(firstname, lastname, fullname);

        // Set the user email
        String email = request.getParameter("lis_person_contact_email_primary");
        user.setEmail(email, defaultEmail);

        // Set the user image URI
        String img = request.getParameter("user_image");
        if (StringUtils.isNotEmpty(img)) {
            try {
                URL imgUrl = new URL(img);
                user.setImage(imgUrl);
            } catch (Exception e) {
                //bad url
            }
        }

        // Set the user roles
        String roles = request.getParameter("roles");
        if (StringUtils.isNotEmpty(roles)) {
            user.setRoles(parseRoles(roles));
        }

        // Initialise the consumer and check for changes
        consumer.setDefaultEmail(defaultEmail);
        String ltiV = request.getParameter("lti_version");
        if (!ltiV.equals(consumer.getLtiVersion())) {
            consumer.setLtiVersion(ltiV);
            doSaveConsumer = true;
        }
        String instanceName = request.getParameter("tool_consumer_instance_name");
        if (StringUtils.isNotEmpty(instanceName)) {
            if (!instanceName.equals(consumer.getConsumerName())) {
                consumer.setConsumerName(instanceName);
                doSaveConsumer = true;
            }
        }
        String familyCode = request.getParameter("tool_consumer_info_product_family_code");
        String extLMS = request.getParameter("ext_lms");
        if (StringUtils.isNotBlank(familyCode)) {
            String version = familyCode;
            String infoVersion = request.getParameter("tool_consumer_info_version");
            if (StringUtils.isNotEmpty(infoVersion)) {
                version += "-" + infoVersion;
            }
            // do not delete any existing consumer version if none is passed
            if (!version.equals(consumer.getConsumerVersion())) {
                consumer.setConsumerVersion(version);
                doSaveConsumer = true;
            }
        } else if (StringUtils.isNotEmpty(extLMS) && !consumer.getConsumerName().equals(extLMS)) {
            consumer.setConsumerVersion(extLMS);
            doSaveConsumer = true;
        }
        String tciGuid = request.getParameter("tool_consumer_instance_guid");
        if (StringUtils.isNotEmpty(tciGuid)) {
            if (StringUtils.isNotEmpty(consumer.getConsumerGuid())) {
                consumer.setConsumerGuid(tciGuid);
                doSaveConsumer = true;
            } else if (!consumer.isThisprotected()) {
                doSaveConsumer = (!tciGuid.equals(consumer.getConsumerGuid()));
                if (doSaveConsumer) {
                    consumer.setConsumerGuid(tciGuid);
                }
            }
        }
        String css = request.getParameter("launch_presentation_css_url");
        String extCss = request.getParameter("ext_launch_presentation_css_url");
        if (StringUtils.isNotEmpty(css)) {
            if (!css.equals(consumer.getCssPath())) {
                consumer.setCssPath(css);
                doSaveConsumer = true;
            }
        } else if (StringUtils.isNotEmpty(extCss) && !consumer.getCssPath().equals(extCss)) {
            consumer.setCssPath(extCss);
            doSaveConsumer = true;
        } else if (StringUtils.isNotEmpty(consumer.getCssPath())) {
            consumer.setCssPath(null);
            doSaveConsumer = true;
        }
    }

    // Persist changes to consumer
    if (doSaveConsumer) {
        consumer.save();
    }
    if (ok && context != null) {
        context.save();
    }
    if (ok && resourceLink != null) {

        // Check if a share arrangement is in place for this resource link
        ok = checkForShare();

        // Persist changes to resource link
        resourceLink.save();

        // Save the user instance
        String lrsdid = request.getParameter("lis_result_sourcedid");
        if (StringUtils.isNotEmpty(lrsdid)) {
            if (!lrsdid.equals(user.getLtiResultSourcedId())) {
                user.setLtiResultSourcedId(lrsdid);
                user.save();
            }
        } else if (StringUtils.isNotEmpty(user.getLtiResultSourcedId())) {
            user.setLtiResultSourcedId("");
            user.save();
        }
    }

    return ok;

}

From source file:org.jamwiki.parser.LinkUtil.java

/**
 * Utility method for determining if a topic name is valid for use on the Wiki,
 * meaning that it is not empty and does not contain any invalid characters.  This
 * method offers improved performance for cases where a WikiLink object is
 * already available.//from   w w w  .  j  ava 2 s  .com
 *
 * @param wikiLink The WikiLink object to validate.
 * @param allowSpecial Set to <code>true</code> if topics in the Special: namespace
 *  should be considered valid.  These topics cannot be created, so (for example)
 *  this method should not allow them when editing topics.
 * @throws WikiException Thrown if the topic name is invalid.
 */
public static void validateTopicName(WikiLink wikiLink, boolean allowSpecial) throws WikiException {
    if (StringUtils.isBlank(wikiLink.getVirtualWiki())) {
        throw new WikiException(new WikiMessage("common.exception.novirtualwiki"));
    }
    if (StringUtils.isBlank(wikiLink.getDestination())) {
        throw new WikiException(new WikiMessage("common.exception.notopic"));
    }
    if (!allowSpecial && PseudoTopicHandler.isPseudoTopic(wikiLink.getDestination())) {
        throw new WikiException(new WikiMessage("common.exception.pseudotopic", wikiLink.getDestination()));
    }
    if (StringUtils.startsWith(wikiLink.getArticle().trim(), "/")) {
        throw new WikiException(new WikiMessage("common.exception.name", wikiLink.getDestination()));
    }
    if (!allowSpecial && wikiLink.getNamespace().getId().equals(Namespace.SPECIAL_ID)) {
        throw new WikiException(new WikiMessage("common.exception.name", wikiLink.getDestination()));
    }
    Matcher m = LinkUtil.INVALID_TOPIC_NAME_PATTERN.matcher(wikiLink.getDestination());
    if (m.find()) {
        throw new WikiException(new WikiMessage("common.exception.name", wikiLink.getDestination()));
    }
}

From source file:org.jodconverter.office.OfficeProcessTest.java

@Test
public void deleteProfileDir_WhenCannotBeDeletedButCanBeRenamed_DirectoryIRenamed() throws Exception {

    mockStatic(FileUtils.class);

    final File workingDir = testFolder.newFolder("deleteProfileDir_WhenCannotBeDeleted_RenameDirectory");

    doThrow(new IOException()).when(FileUtils.class, "deleteDirectory", isA(File.class));

    final OfficeProcessConfig config = new OfficeProcessConfig(null, workingDir, null);
    final OfficeProcess process = new OfficeProcess(new OfficeUrl(2002), config);
    final File instanceProfileDir = Whitebox.invokeMethod(process, "getInstanceProfileDir");
    instanceProfileDir.mkdirs();//www .j a  v  a 2  s .co  m
    Whitebox.invokeMethod(process, "deleteInstanceProfileDir");

    assertThat(workingDir.listFiles(new FileFilter() {

        @Override
        public boolean accept(final File pathname) {
            return pathname.isDirectory()
                    && StringUtils.startsWith(pathname.getName(), instanceProfileDir.getName() + ".old.");
        }
    })).hasSize(1);

    FileUtils.deleteQuietly(workingDir);
}

From source file:org.jodconverter.office.OfficeProcessTest.java

@Test
public void deleteProfileDir_WhenCannotBeDeleted_OperationIgnored() throws Exception {

    mockStatic(FileUtils.class);

    final File workingDir = testFolder.newFolder("deleteProfileDir_WhenCannotBeDeleted_OperationIgnored");

    doThrow(new IOException()).when(FileUtils.class, "deleteDirectory", isA(File.class));

    final OfficeProcessConfig config = new OfficeProcessConfig(null, workingDir, null);
    final OfficeProcess process = new OfficeProcess(new OfficeUrl(2002), config);
    final File instanceProfileDir = Whitebox.invokeMethod(process, "getInstanceProfileDir");
    Whitebox.invokeMethod(process, "deleteInstanceProfileDir");

    assertThat(workingDir.listFiles(new FileFilter() {

        @Override/*www.  ja  v a 2  s.c  o  m*/
        public boolean accept(final File pathname) {
            return pathname.isDirectory()
                    && StringUtils.startsWith(pathname.getName(), instanceProfileDir.getName() + ".old.");
        }
    })).isNullOrEmpty();
}

From source file:org.kuali.coeus.common.committee.impl.web.struts.action.CommitteeMembershipActionBase.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionForward actionForward = super.execute(mapping, form, request, response);

    ((CommitteeFormBase) form).getCommitteeHelper().prepareView();

    // reset member index for multi value lookups unless the multi value lookup is performed
    if (!StringUtils.equals((String) request.getAttribute("methodToCallAttribute"), "methodToCall.refresh.x")
            && (!StringUtils.startsWith((String) request.getAttribute("methodToCallAttribute"),
                    "methodToCall.performLookup."))) {
        ((CommitteeFormBase) form).getCommitteeHelper().setMemberIndex(-1);
    }/*from  w  ww .  j a  va2s .c  o m*/

    return actionForward;
}