Examples of MIMETypedStream


Examples of org.fcrepo.server.storage.types.MIMETypedStream

                                                          authzAux_objState,
                                                          "A",
                                                          "fedora-system:4",
                                                          "A",
                                                          "A");
            MIMETypedStream retVal =
                    m_dynamicAccess.getDissemination(context,
                                                     PID,
                                                     sDefPID,
                                                     methodName,
                                                     userParms,
                                                     asOfDateTime);
            stopTime = new Date().getTime();
            interval = stopTime - startTime;
            logger.debug("Roundtrip DynamicDisseminator: " + interval
                         + " milliseconds.");
            return retVal;
        }

        /*
         * Find the service deployment that is contractor for a model this
         * object has, and deploys the requested service. If object<->model
         * mappings are ever stored in the registry, this may be simplified.
         */
        String serviceDeploymentPID = null;
        for (String cModelURI: reader.getContentModels()){
            String cModelPID = cModelURI.substring("info:fedora/".length());

/*
        for (RelationshipTuple rel : reader.getRelationships(MODEL.HAS_MODEL,
                                                             null)) {
            String cModelPID = rel.getObjectPID();
*/
            String foundDeploymentPID =
                    m_manager.lookupDeploymentForCModel(cModelPID, sDefPID);

            if (foundDeploymentPID != null) {
                if (serviceDeploymentPID != null
                    && !foundDeploymentPID.equals(serviceDeploymentPID)) {
                    throw new DisseminationException("More than one deployment ("
                                                     + foundDeploymentPID
                                                     + ", "
                                                     + serviceDeploymentPID
                                                     + ") found for service "
                                                     + sDefPID
                                                     + " in model "
                                                     + cModelPID);

                }

                serviceDeploymentPID = foundDeploymentPID;
            } else {
                logger.debug("No deployment for (" + cModelPID + ", " + sDefPID
                             + ")");
            }
        }

        if (serviceDeploymentPID != null) {
            deploymentReader =
                    m_manager.getServiceDeploymentReader(false,
                                                         context,
                                                         serviceDeploymentPID);
        }

        ServiceDefinitionReader sDefReader =
                m_manager.getServiceDefinitionReader(asOfDateTime == null,
                                                     context,
                                                     sDefPID);

        String authzAux_sdefState = sDefReader.GetObjectState();

        String authzAux_dissState = "unknown";

        /*
         * if reader is null, it means that no suitable deployments have been
         * found. This can happen if (a), the object does not have any models
         * that have that service, or (b) the object has a suitable model, but
         * no implementation of that service has been deployed. We do a bit of
         * checking here to determine which case this represents, as the error
         * message could be very useful.
         */
        if (deploymentReader == null) {

            boolean suitableModelFound = false;
            String cModelPID = null;
            String message = null;

/*
            models: for (RelationshipTuple rel : reader
                    .getRelationships(MODEL.HAS_MODEL, null)) {
                cModelPID = rel.getObjectPID();
*/
            models: for (String cm:reader.getContentModels()){
                cModelPID = cm.substring(12);

                /* Skip over system models */
                if (Models.contains("info:fedora/" + cModelPID)) {
                    continue;
                }

                /* Open up each model and peek at its sDefs for a match */
                for (RelationshipTuple r : m_manager.getReader(false,
                                                               context,
                                                               cModelPID)
                        .getRelationships(MODEL.HAS_SERVICE, null)) {
                    if (sDefPID.equals(r.getObjectPID())) {
                        suitableModelFound = true;
                        break models;
                    }
                }
            }

            if (suitableModelFound) {
                message =
                        "Unable to find deployment for service " + sDefPID
                        + " on " + reader.GetObjectPID() + " in model "
                        + cModelPID;
            } else {
                message =
                        reader.GetObjectPID()
                        + " does not have a model with service "
                        + sDefPID;
            }
            throw new DisseminatorNotFoundException(message);
        }
        stopTime = new Date().getTime();
        interval = stopTime - startTime;
        logger.debug("Roundtrip Looping Diss: " + interval + " milliseconds.");

        // Check deployment object state
        String authzAux_sDepState = deploymentReader.GetObjectState();
        String authzAux_sDepPID = deploymentReader.GetObjectPID();

        m_authorizationModule.enforceGetDissemination(context,
                                                      PID,
                                                      sDefPID,
                                                      methodName,
                                                      asOfDateTime,
                                                      authzAux_objState,
                                                      authzAux_sdefState,
                                                      authzAux_sDepPID,
                                                      authzAux_sDepState,
                                                      authzAux_dissState);

        // Get method parms
        Hashtable<String, String> h_userParms = new Hashtable<String, String>();
        MIMETypedStream dissemination = null;
        MethodParmDef[] defaultMethodParms = null;

        startTime = new Date().getTime();
        // Put any user-supplied method parameters into hash table
        if (userParms != null) {
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

        PID = Server.getPID(PID).toString();
        m_authorizationModule.enforceGetDatastreamDissemination(context,
                                                                PID,
                                                                dsID,
                                                                asOfDateTime);
        MIMETypedStream mimeTypedStream = null;
        long startTime = new Date().getTime();
        DOReader reader =
                m_manager.getReader(Server.USE_DEFINITIVE_STORE, context, PID);

        Datastream ds = reader.GetDatastream(dsID, asOfDateTime);
        if (ds == null) {
            String message =
                    "[DefaulAccess] No datastream could be returned. "
                    + "Either there is no datastream for the digital "
                    + "object \""
                    + PID
                    + "\" with datastream ID of \""
                    + dsID
                    + " \"  OR  there are no datastreams that match the specified "
                    + "date/time value of \""
                    + DateUtility.convertDateToString(asOfDateTime)
                    + " \"  .";
            throw new DatastreamNotFoundException(message);
        }

        if (ds.DSControlGrp.equalsIgnoreCase("E")) {
            DatastreamReferencedContent drc =
                    (DatastreamReferencedContent) reader
                            .GetDatastream(dsID, asOfDateTime);
            ContentManagerParams params = new ContentManagerParams(drc.DSLocation,
                                                                   drc.DSMIME, null, null);
            params.setContext(context);
            mimeTypedStream = m_externalContentManager.getExternalContent(params);
        } else if (ds.DSControlGrp.equalsIgnoreCase("M")) {
            DatastreamManagedContent dmc =
                    (DatastreamManagedContent) reader
                            .GetDatastream(dsID, asOfDateTime);

            mimeTypedStream = new MIMETypedStream(ds.DSMIME, dmc.getContentStream(context), null,ds.DSSize);
        } else if (ds.DSControlGrp.equalsIgnoreCase("X")) {
            DatastreamXMLMetadata dxm =
                    (DatastreamXMLMetadata) reader.GetDatastream(dsID,
                                                                 asOfDateTime);
            mimeTypedStream = new MIMETypedStream(ds.DSMIME, dxm.getContentStream(context), null, ds.DSSize);
        } else if (ds.DSControlGrp.equalsIgnoreCase("R")) {
            DatastreamReferencedContent drc =
                    (DatastreamReferencedContent) reader
                            .GetDatastream(dsID, asOfDateTime);
            // The dsControlGroupType of Redirect("R") is a special control type
            // used primarily for streaming media. Datastreams of this type are
            // not mediated (proxied by Fedora) and their physical dsLocation is
            // simply redirected back to the client. Therefore, the contents
            // of the MIMETypedStream returned for dissemination requests will
            // contain the raw URL of the dsLocation and will be assigned a
            // special fedora-specific MIME type to identify the stream as
            // a MIMETypedStream whose contents contain a URL to which the client
            // should be redirected.
            try {
                InputStream inStream =
                        new ByteArrayInputStream(drc.DSLocation
                                                         .getBytes("UTF-8"));
                mimeTypedStream =
                        new MIMETypedStream("application/fedora-redirect",
                                            inStream,
                                            null);
            } catch (UnsupportedEncodingException uee) {
                String message =
                        "[DefaultAccess] An error has occurred. "
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

                    source = new StreamSource(schemaStream);

                } else if ("url".equalsIgnoreCase(type)){
                    InputStream schemaStream;
                    ContentManagerParams params = new ContentManagerParams(value);
                    MIMETypedStream externalContent = m_exExternalContentManager.getExternalContent(params);
                    schemaStream = externalContent.getStream();
                    source = new StreamSource(schemaStream);
                } else { //reference used, but type not recognized
                    List<String> validationProblems = validation.getDatastreamProblems(objectDatastream.DatastreamID);
                    validationProblems.add(Errors.schemaNotFound(contentmodelReader.GetObjectPID()));
                    validation.setValid(false);
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

                                           Date asOfDateTime,
                                           HttpServletResponse response,
                                           HttpServletRequest request)
            throws IOException, ServerException {
        ServletOutputStream out = null;
        MIMETypedStream dissemination = null;
        dissemination =
                m_access.getDatastreamDissemination(context,
                                                    PID,
                                                    dsID,
                                                    asOfDateTime);
        try {
            // testing to see what's in request header that might be of interest
            if (logger.isDebugEnabled()) {
                for (Enumeration<?> e = request.getHeaderNames(); e
                        .hasMoreElements();) {
                    String name = (String) e.nextElement();
                    Enumeration<?> headerValues = request.getHeaders(name);
                    StringBuffer sb = new StringBuffer();
                    while (headerValues.hasMoreElements()) {
                        sb.append((String) headerValues.nextElement());
                    }
                    String value = sb.toString();
                    logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: "
                            + name + " : " + value);
                }
            }

            // Dissemination was successful;
            // Return MIMETypedStream back to browser client
            if (dissemination.MIMEType
                    .equalsIgnoreCase("application/fedora-redirect")) {
                // A MIME type of application/fedora-redirect signals that
                // the MIMETypedStream returned from the dissemination is
                // a special Fedora-specific MIME type. In this case, the
                // Fedora server will not proxy the datastream, but
                // instead perform a simple redirect to the URL contained
                // within the body of the MIMETypedStream. This special
                // MIME type is used primarily for streaming media where
                // it is more efficient to stream the data directly
                // between the streaming server and the browser client
                // rather than proxy it through the Fedora server.

                BufferedReader br =
                        new BufferedReader(new InputStreamReader(dissemination
                                .getStream()));
                StringBuffer sb = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                response.sendRedirect(sb.toString());
            } else {

                response.setContentType(dissemination.MIMEType);
                Property[] headerArray = dissemination.header;
                if (headerArray != null) {
                    for (int i = 0; i < headerArray.length; i++) {
                        if (headerArray[i].name != null
                                && !headerArray[i].name
                                        .equalsIgnoreCase("transfer-encoding")
                                && !headerArray[i].name
                                        .equalsIgnoreCase("content-type")) {
                            response.addHeader(headerArray[i].name,
                                               headerArray[i].value);
                            logger.debug("THIS WAS ADDED TO FEDORASERVLET "
                                    + "RESPONSE HEADER FROM ORIGINATING "
                                    + "PROVIDER " + headerArray[i].name + " : "
                                    + headerArray[i].value);
                        }
                    }
                }
                out = response.getOutputStream();
                int byteStream = 0;
                logger.debug("Started reading dissemination stream");
                InputStream dissemResult = dissemination.getStream();
                byte[] buffer = new byte[BUF];
                while ((byteStream = dissemResult.read(buffer)) != -1) {
                    out.write(buffer, 0, byteStream);
                }
                buffer = null;
                dissemResult.close();
                dissemResult = null;
                out.flush();
                out.close();
                logger.debug("Finished reading dissemination stream");
            }
        } finally {
            dissemination.close();
        }
    }
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

                                 Date asOfDateTime,
                                 HttpServletResponse response,
                                 HttpServletRequest request)
            throws IOException, ServerException {
        ServletOutputStream out = null;
        MIMETypedStream dissemination = null;
        dissemination =
                m_access.getDissemination(context,
                                          PID,
                                          sDefPID,
                                          methodName,
                                          userParms,
                                          asOfDateTime);
        out = response.getOutputStream();
        try {
            // testing to see what's in request header that might be of interest
            if (logger.isDebugEnabled()) {
                for (Enumeration<?> e = request.getHeaderNames(); e
                        .hasMoreElements();) {
                    String name = (String) e.nextElement();
                    Enumeration<?> headerValues = request.getHeaders(name);
                    StringBuffer sb = new StringBuffer();
                    while (headerValues.hasMoreElements()) {
                        sb.append((String) headerValues.nextElement());
                    }
                    String value = sb.toString();
                    logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: "
                            + name + " : " + value);
                }
            }

            // Dissemination was successful;
            // Return MIMETypedStream back to browser client
            if (dissemination.MIMEType
                    .equalsIgnoreCase("application/fedora-redirect")) {
                // A MIME type of application/fedora-redirect signals that
                // the MIMETypedStream returned from the dissemination is
                // a special Fedora-specific MIME type. In this case, the
                // Fedora server will not proxy the datastream, but
                // instead perform a simple redirect to the URL contained
                // within the body of the MIMETypedStream. This special
                // MIME type is used primarily for streaming media where
                // it is more efficient to stream the data directly between
                // the streaming server and the browser client rather than
                // proxy it through the Fedora server.

                BufferedReader br =
                        new BufferedReader(new InputStreamReader(dissemination
                                .getStream()));
                StringBuffer sb = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                response.sendRedirect(sb.toString());
            } else {
                response.setContentType(dissemination.MIMEType);
                Property[] headerArray = dissemination.header;
                if (headerArray != null) {
                    for (int i = 0; i < headerArray.length; i++) {
                        if (headerArray[i].name != null
                                && !headerArray[i].name
                                        .equalsIgnoreCase("transfer-encoding")
                                && !headerArray[i].name
                                        .equalsIgnoreCase("content-type")) {
                            response.addHeader(headerArray[i].name,
                                               headerArray[i].value);
                            logger.debug("THIS WAS ADDED TO FEDORASERVLET "
                                    + "RESPONSE HEADER FROM ORIGINATING "
                                    + "PROVIDER " + headerArray[i].name + " : "
                                    + headerArray[i].value);
                        }
                    }
                }
                int byteStream = 0;
                logger.debug("Started reading dissemination stream");
                InputStream dissemResult = dissemination.getStream();
                byte[] buffer = new byte[BUF];
                while ((byteStream = dissemResult.read(buffer)) != -1) {
                    out.write(buffer, 0, byteStream);
                }
                buffer = null;
                dissemResult.close();
                dissemResult = null;
                out.flush();
                out.close();
                logger.debug("Finished reading dissemination stream");
            }
        } finally {
            dissemination.close();
        }
    }
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

                                  @QueryParam(RestParam.DOWNLOAD) String download,
                                  @QueryParam(RestParam.FLASH) @DefaultValue("false") boolean flash) {
        Context context = getContext();
        try {
            Date asOfDateTime = DateUtility.parseDateOrNull(dateTime);
            MIMETypedStream stream =
                    m_access.getDatastreamDissemination(context,
                                                           pid,
                                                           dsID,
                                                           asOfDateTime);
            if (m_datastreamFilenameHelper != null) {
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

        String id = null;
        String dsPhysicalLocation = null;
        String dsControlGroupType = null;
        String user = null;
        String pass = null;
        MIMETypedStream mimeTypedStream = null;
        DisseminationService ds = null;
        Timestamp keyTimestamp = null;
        Timestamp currentTimestamp = null;
        PrintWriter out = null;
        ServletOutputStream outStream = null;
        String requestURI =
                request.getRequestURL().toString() + "?"
                        + request.getQueryString();

        id = request.getParameter("id").replaceAll("T", " ");
        logger.debug("Datastream tempID=" + id);

        logger.debug("DRS doGet()");

        try {
            // Check for required id parameter.
            if (id == null || id.equalsIgnoreCase("")) {
                String message =
                        "[DatastreamResolverServlet] No datastream ID "
                                + "specified in servlet request: "
                                + request.getRequestURI();
                logger.error(message);
                response
                        .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response
                        .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                   message);
                return;
            }
            id = id.replaceAll("T", " ").replaceAll("/", "").trim();

            // Get in-memory hashtable of mappings from Fedora server.
            ds = new DisseminationService(m_server);
            DatastreamMediation dm = DisseminationService.dsRegistry.get(id);
            if (dm == null) {
                StringBuffer entries = new StringBuffer();
                Iterator eIter = DisseminationService.dsRegistry.keySet().iterator();
                while (eIter.hasNext()) {
                    entries.append("'" + (String) eIter.next() + "' ");
                }
                throw new IOException("Cannot find datastream in temp registry by key: "
                        + id + "\n" + "Reg entries: " + entries.toString());
            }
            dsPhysicalLocation = dm.dsLocation;
            dsControlGroupType = dm.dsControlGroupType;
            user = dm.callUsername;
            pass = dm.callPassword;
            if (logger.isDebugEnabled()) {
                logger.debug("**************************** DatastreamResolverServlet dm.dsLocation: {}", dm.dsLocation);
                logger.debug("**************************** DatastreamResolverServlet dm.dsControlGroupType: {}", dm.dsControlGroupType);
                logger.debug("**************************** DatastreamResolverServlet dm.callUsername: {}", dm.callUsername);
                logger.debug("**************************** DatastreamResolverServlet dm.Password: {}", dm.callPassword);
                logger.debug("**************************** DatastreamResolverServlet dm.callbackRole: {}", dm.callbackRole);
                logger.debug("**************************** DatastreamResolverServlet dm.callbackBasicAuth: {}", dm.callbackBasicAuth);
                logger.debug("**************************** DatastreamResolverServlet dm.callBasicAuth: {}", dm.callBasicAuth);
                logger.debug("**************************** DatastreamResolverServlet dm.callbackSSl: {}", dm.callbackSSL);
                logger.debug("**************************** DatastreamResolverServlet dm.callSSl: {}", dm.callSSL);
                logger.debug("**************************** DatastreamResolverServlet non ssl port: {}", fedoraServerPort);
                logger.debug("**************************** DatastreamResolverServlet ssl port: {}", fedoraServerRedirectPort);
            }

            // DatastreamResolverServlet maps to two distinct servlet mappings
            // in fedora web.xml.
            // getDS - is used when the backend service is incapable of
            // basicAuth or SSL
            // getDSAuthenticated - is used when the backend service has
            // basicAuth and SSL enabled
            // Since both the getDS and getDSAuthenticated servlet targets map
            // to the same servlet
            // code and the Context used to initialize policy enforcement is
            // based on the incoming
            // HTTPRequest, the code must provide special handling for requests
            // using the getDS
            // target. When the incoming URL to DatastreamResolverServlet
            // contains the getDS target,
            // there are several conditions that must be checked to insure that
            // the correct role is
            // assigned to the request before policy enforcement occurs.
            // 1) if the mapped dsPhysicalLocation of the request is actually a
            // callback to the
            // Fedora server itself, then assign the role as
            // BACKEND_SERVICE_CALL_UNSECURE so
            // the basicAuth and SSL constraints will match those of the getDS
            // target.
            // 2) if the mapped dsPhysicalLocation of the request is actually a
            // Managed Content
            // or Inline XML Content datastream, then assign the role as
            // BACKEND_SERVICE_CALL_UNSECURE so
            // the basicAuth and SSL constraints will match the getDS target.
            // 3) Otherwise, leave the targetrole unchanged.
            if (request.getRequestURI().endsWith("getDS")
                    && (ServerUtility.isURLFedoraServer(dsPhysicalLocation)
                            || dsControlGroupType.equals("M") || dsControlGroupType
                            .equals("X"))) {
                if (logger.isDebugEnabled()) {
                    logger.debug("*********************** Changed role from: "
                            + dm.callbackRole + "  to: "
                            + BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE);
                }
                dm.callbackRole = BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE;
            }

            // If callback is to fedora server itself and callback is over SSL,
            // adjust the protocol and port
            // on the URL to match settings of Fedora server. This is necessary
            // since the SSL settings for the
            // backend service may have specified basicAuth=false, but contained
            // datastreams that are callbacks
            // to the local Fedora server which requires SSL. The version of
            // HttpClient currently in use does
            // not handle autoredirecting from http to https so it is necessary
            // to set the protocol and port
            // to the appropriate secure port.
            if (dm.callbackRole.equals(BackendPolicies.FEDORA_INTERNAL_CALL)) {
                if (dm.callbackSSL) {
                    dsPhysicalLocation =
                            dsPhysicalLocation.replaceFirst("http:", "https:");
                    dsPhysicalLocation =
                            dsPhysicalLocation
                                    .replaceFirst(fedoraServerPort,
                                                  fedoraServerRedirectPort);
                    if (logger.isDebugEnabled()) {
                        logger
                                .debug("*********************** DatastreamResolverServlet -- Was Fedora-to-Fedora call -- modified dsPhysicalLocation: "
                                        + dsPhysicalLocation);
                    }
                }
            }
            keyTimestamp = Timestamp.valueOf(ds.extractTimestamp(id));
            currentTimestamp = new Timestamp(new Date().getTime());
            logger.debug("dsPhysicalLocation=" + dsPhysicalLocation
                    + "dsControlGroupType=" + dsControlGroupType);

            // Deny mechanism requests that fall outside the specified time
            // interval.
            // The expiration limit can be adjusted using the Fedora config
            // parameter
            // named "datastreamMediationLimit" which is in milliseconds.
            long diff = currentTimestamp.getTime() - keyTimestamp.getTime();
            logger.debug("Timestamp diff for mechanism's reponse: " + diff
                    + " ms.");
            if (diff > datastreamMediationLimit) {
                out = response.getWriter();
                response.setContentType(HTML_CONTENT_TYPE);
                out
                        .println("<br><b>[DatastreamResolverServlet] Error:</b>"
                                + "<font color=\"red\"> Deployment has failed to respond "
                                + "to the DatastreamResolverServlet within the specified "
                                + "time limit of \""
                                + datastreamMediationLimit
                                + "\""
                                + "milliseconds. Datastream access denied.");
                logger.error("Deployment failed to respond to "
                        + "DatastreamResolverServlet within time limit of "
                        + datastreamMediationLimit);
                out.close();
                return;
            }

            if (dm.callbackRole == null) {
                throw new AuthzOperationalException("no callbackRole for this ticket");
            }
            String targetRole = //Authorization.FEDORA_ROLE_KEY + "=" +
                    dm.callbackRole; // restrict access to role of this
            // ticket
            String[] targetRoles = {targetRole};
            Context context =
                    ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
                                               request); // , targetRoles);
            if (request.getRemoteUser() == null) {
                // non-authn: must accept target role of ticket
                logger.debug("DatastreamResolverServlet: unAuthenticated request");
            } else {
                // authn: check user roles for target role of ticket
                /*
                 * logger.debug("DatastreamResolverServlet: Authenticated request
                 * getting user"); String[] roles = null; Principal principal =
                 * request.getUserPrincipal(); if (principal == null) { // no
                 * principal to grok roles from!! } else { try { roles =
                 * ReadOnlyContext.getRoles(principal); } catch (Throwable t) { } }
                 * if (roles == null) { roles = new String[0]; }
                 */
                //XXXXXXXXXXXXXXXXXXXXXXxif (contains(roles, targetRole)) {
                logger.debug("DatastreamResolverServlet: user=="
                        + request.getRemoteUser());
                /*
                 * if
                 * (((ExtendedHttpServletRequest)request).isUserInRole(targetRole)) {
                 * logger.debug("DatastreamResolverServlet: user has required
                 * role"); } else { logger.debug("DatastreamResolverServlet: authZ
                 * exception in validating user"); throw new
                 * AuthzDeniedException("wrong user for this ticket"); }
                 */
            }

            if (logger.isDebugEnabled()) {
                logger.debug("debugging backendService role");
                logger.debug("targetRole=" + targetRole);
                int targetRolesLength = targetRoles.length;
                logger.debug("targetRolesLength=" + targetRolesLength);
                if (targetRolesLength > 0) {
                    logger.debug("targetRoles[0]=" + targetRoles[0]);
                }
                int nSubjectValues = context.nSubjectValues(targetRole);
                logger.debug("nSubjectValues=" + nSubjectValues);
                if (nSubjectValues > 0) {
                    logger.debug("context.getSubjectValue(targetRole)="
                            + context.getSubjectValue(targetRole));
                }
                Iterator it = context.subjectAttributes();
                while (it.hasNext()) {
                    String name = (String) it.next();
                    int n = context.nSubjectValues(name);
                    switch (n) {
                        case 0:
                            logger.debug("no subject attributes for " + name);
                            break;
                        case 1:
                            String value = context.getSubjectValue(name);
                            logger.debug("single subject attributes for " + name
                                    + "=" + value);
                            break;
                        default:
                            String[] values = context.getSubjectValues(name);
                            for (String element : values) {
                                logger
                                        .debug("another subject attribute from context "
                                                + name + "=" + element);
                            }
                    }
                }
                it = context.environmentAttributes();
                while (it.hasNext()) {
                    String name = (String) it.next();
                    String value = context.getEnvironmentValue(name);
                    logger.debug("another environment attribute from context "
                            + name + "=" + value);
                }
            }
            /*
             * // Enforcement of Backend Security is temporarily disabled
             * pending refactoring. // logger.debug("DatastreamResolverServlet:
             * about to do final authZ check"); Authorization authorization =
             * (Authorization) s_server
             * .getModule("org.fcrepo.server.security.Authorization");
             * authorization.enforceResolveDatastream(context, keyTimestamp);
             * logger.debug("DatastreamResolverServlet: final authZ check
             * suceeded.....");
             */

            if (dsControlGroupType.equalsIgnoreCase("E")) {
                // testing to see what's in request header that might be of
                // interest
                if (logger.isDebugEnabled()) {
                    for (Enumeration e = request.getHeaderNames(); e
                            .hasMoreElements();) {
                        String name = (String) e.nextElement();
                        Enumeration headerValues = request.getHeaders(name);
                        StringBuffer sb = new StringBuffer();
                        while (headerValues.hasMoreElements()) {
                            sb.append((String) headerValues.nextElement());
                        }
                        String value = sb.toString();
                        logger
                                .debug("DATASTREAMRESOLVERSERVLET REQUEST HEADER CONTAINED: "
                                        + name + " : " + value);
                    }
                }

                // Datastream is ReferencedExternalContent so dsLocation is a
                // URL string
                ExternalContentManager externalContentManager =
                        (ExternalContentManager) m_server
                                .getModule("org.fcrepo.server.storage.ExternalContentManager");
                ContentManagerParams params = new ContentManagerParams(dsPhysicalLocation);
                params.setContext(context);
                mimeTypedStream = externalContentManager.getExternalContent(params);

                // had substituted context:
                // ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
                // request));
                outStream = response.getOutputStream();
                response.setContentType(mimeTypedStream.MIMEType);
                Property[] headerArray = mimeTypedStream.header;
                if (headerArray != null) {
                    for (int i = 0; i < headerArray.length; i++) {
                        if (headerArray[i].name != null
                                && !headerArray[i].name
                                        .equalsIgnoreCase("content-type")) {
                            response.addHeader(headerArray[i].name,
                                               headerArray[i].value);
                            logger
                                    .debug("THIS WAS ADDED TO DATASTREAMRESOLVERSERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER "
                                            + headerArray[i].name
                                            + " : "
                                            + headerArray[i].value);
                        }
                    }
                }
                int byteStream = 0;
                byte[] buffer = new byte[255];
                while ((byteStream = mimeTypedStream.getStream().read(buffer)) != -1) {
                    outStream.write(buffer, 0, byteStream);
                }
                buffer = null;
                outStream.flush();
                mimeTypedStream.close();
            } else if (dsControlGroupType.equalsIgnoreCase("M")
                    || dsControlGroupType.equalsIgnoreCase("X")) {
                // Datastream is either XMLMetadata or ManagedContent so
                // dsLocation
                // is in the form of an internal Fedora ID using the syntax:
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

    logger.debug("Started assembling dissemination");

    String dissURL = null;
    String protocolType = null;
    DisseminationBindingInfo dissBindInfo = null;
    MIMETypedStream dissemination = null;
    boolean isRedirect = false;

    if (logger.isDebugEnabled()) {
      printBindingInfo(dissBindInfoArray);
    }

    if (dissBindInfoArray != null && dissBindInfoArray.length > 0) {
      String replaceString = null;
      int numElements = dissBindInfoArray.length;

      // Get row(s) of binding info and perform string substitution
      // on DSBindingKey and method parameter values in WSDL
      // Note: In case where more than one datastream matches the
      // DSBindingKey or there are multiple DSBindingKeys for the
      // method, multiple rows will be present; otherwise there is only
      // a single row.
      for (int i = 0; i < dissBindInfoArray.length; i++) {
        m_authorization
            .enforce_Internal_DSState(context,
                dissBindInfoArray[i].dsID,
                dissBindInfoArray[i].dsState);
        dissBindInfo = dissBindInfoArray[i];

        // Before doing anything, check whether we can replace any
        // placeholders in the datastream url with parameter values from
        // the request. This supports the special case where a
        // datastream's URL is dependent on user parameters, such
        // as when the datastream is actually a dissemination that
        // takes parameters.
        if (dissBindInfo.dsLocation != null
            && (dissBindInfo.dsLocation.startsWith("http://") || dissBindInfo.dsLocation
                .startsWith("https://"))) {
          String[] parts = dissBindInfo.dsLocation.split("=\\("); // regex
                                      // for
                                      // =(
          if (parts.length > 1) {
            StringBuffer replaced = new StringBuffer();
            replaced.append(parts[0]);
            for (int x = 1; x < parts.length; x++) {
              replaced.append('=');
              int rightParenPos = parts[x].indexOf(")");
              if (rightParenPos != -1 && rightParenPos > 0) {
                String key = parts[x].substring(0,
                    rightParenPos);
                String val = h_userParms.get(key);
                if (val != null) {
                  // We have a match... so insert the
                  // urlencoded value.
                  try {
                    replaced.append(URLEncoder.encode(val,
                        "UTF-8"));
                  } catch (UnsupportedEncodingException uee) {
                    // won't happen: java always supports
                    // UTF-8
                  }
                  if (rightParenPos < parts[x].length()) {
                    replaced.append(parts[x]
                        .substring(rightParenPos + 1));
                  }
                } else {
                  replaced.append('(');
                  replaced.append(parts[x]);
                }
              } else {
                replaced.append('(');
                replaced.append(parts[x]);
              }
            }
            dissBindInfo.dsLocation = replaced.toString();
          }
        }

        // Match DSBindingKey pattern in WSDL which is a string of the
        // form:
        // (DSBindingKey). Rows in DisseminationBindingInfo are sorted
        // alphabetically on binding key.
        String bindingKeyPattern = "\\(" + dissBindInfo.DSBindKey
            + "\\)";
        if (i == 0) {
          // If addressLocation has a value of "LOCAL", this indicates
          // the associated operationLocation requires no
          // addressLocation.
          // i.e., the operationLocation contains all information
          // necessary
          // to perform the dissemination request. This is a special
          // case
          // used when the web services are generally mechanisms like
          // cgi-scripts,
          // java servlets, and simple HTTP GETs. Using the value of
          // LOCAL
          // in the address location also enables one to have
          // different methods
          // serviced by different hosts. In true web services like
          // SOAP, the
          // addressLocation specifies the host name of the service
          // and all
          // methods are served from that single host location.
          if (dissBindInfo.AddressLocation
              .equalsIgnoreCase(LOCAL_ADDRESS_LOCATION)) {
            dissURL = dissBindInfo.OperationLocation;
          } else {
            dissURL = dissBindInfo.AddressLocation
                + dissBindInfo.OperationLocation;

            /*
             * Substitute real app server context if we detect
             * '/fedora'. This is necessary here because
             * DOTranslator does not scrub URLs that result from
             * concatenating fragments from different locations in
             * the file
             */
            dissURL = dissURL.replaceAll(m_fedoraServerHost + ":"
                + m_fedoraServerPort + "/fedora/",
                m_fedoraServerHost + ":" + m_fedoraServerPort
                    + "/" + m_fedoraAppServerContext + "/");
          }
          protocolType = dissBindInfo.ProtocolType;
        }

        // Assess beSecurity for backend service and for datastreams
        // that may be parameters for the
        // backend service.
        //
        // dsMediatedCallbackHost - when dsMediation is in effect, all
        // M, X, and E type datastreams
        // are encoded as callbacks to the Fedora server to obtain the
        // datastream's contents. dsMediatedCallbackHost contains
        // protocol,
        // host, and port used for this type of backendservice-to-fedora
        // callback.
        // The specifics of protocol, host, and port are obtained from
        // the
        // beSecurity configuration file.
        // dsMediatedServletPath - when dsMediation is in effect, all M,
        // X, and E type datastreams
        // are encoded as callbacks to the Fedora server to obtain the
        // datastream's contents. dsMediatedServletPath contains the
        // servlet
        // path info for this type of backendservice-to-fedora callback.
        // The specifics of servlet path are obtained from the
        // beSecurity configuration
        // file and determines whether the backedservice-to-fedora
        // callback
        // will use authentication or not.
        // callbackRole - contains the role of the backend service (the
        // deploymentPID of the service).

        String callbackRole = deploymentPID;
        Hashtable<String, String> beHash = m_beSS.getSecuritySpec(
            callbackRole, methodName);
        boolean callbackBasicAuth = new Boolean(
            beHash.get("callbackBasicAuth")).booleanValue();
        boolean callbackSSL = new Boolean(beHash.get("callbackSSL"))
            .booleanValue();
        String dsMediatedServletPath = null;
        if (callbackBasicAuth) {
          dsMediatedServletPath = "/" + m_fedoraAppServerContext
              + "/getDSAuthenticated?id=";
        } else {
          dsMediatedServletPath = "/" + m_fedoraAppServerContext
              + "/getDS?id=";
        }
        String dsMediatedCallbackHost = null;
        if (callbackSSL) {
          dsMediatedCallbackHost = "https://" + m_fedoraServerHost
              + ":" + m_fedoraServerRedirectPort;
        } else {
          dsMediatedCallbackHost = "http://" + m_fedoraServerHost
              + ":" + m_fedoraServerPort;
        }
        String datastreamResolverServletURL = dsMediatedCallbackHost
            + dsMediatedServletPath;
        if (logger.isDebugEnabled()) {
          logger.debug(
              "******************Checking backend service dsLocation: {}",
              dissBindInfo.dsLocation);
          logger.debug(
              "******************Checking backend service dsControlGroupType: {}",
              dissBindInfo.dsControlGroupType);
          logger.debug(
              "******************Checking backend service callbackBasicAuth: {}",
              callbackBasicAuth);
          logger.debug(
              "******************Checking backend service callbackSSL: {}",
              callbackSSL);
          logger.debug(
              "******************Checking backend service callbackRole: {}",
              callbackRole);
          logger.debug(
              "******************DatastreamResolverServletURL: {}",
              datastreamResolverServletURL);
        }

        String currentKey = dissBindInfo.DSBindKey;
        String nextKey = "";
        if (i != numElements - 1) {
          // Except for last row, get the value of the next binding
          // key
          // to compare with the value of the current binding key.
          nextKey = dissBindInfoArray[i + 1].DSBindKey;
        }
        logger.debug("currentKey: '" + currentKey + "', nextKey: '"
            + nextKey + "'");
        // In most cases, there is only a single datastream that matches
        // a
        // given DSBindingKey so the substitution process is to just
        // replace
        // the occurrence of (BINDING_KEY) with the value of the
        // datastream
        // location. However, when multiple datastreams match the same
        // DSBindingKey, the occurrence of (BINDING_KEY) is replaced
        // with the
        // value of the datastream location and the value +(BINDING_KEY)
        // is
        // appended so that subsequent datastreams matching the binding
        // key
        // will be substituted. The end result is that the binding key
        // will
        // be replaced by a series of datastream locations separated by
        // a
        // plus(+) sign. For example, in the case where 3 datastreams
        // match
        // the binding key for PHOTO:
        //
        // file=(PHOTO) becomes
        // file=dslocation1+dslocation2+dslocation3
        //
        // It is the responsibility of the Service Deployment to know
        // how to
        // handle an input parameter with multiple datastream locations.
        //
        // In the case of a method containing multiple binding keys,
        // substitutions are performed on each binding key. For example,
        // in
        // the case where there are 2 binding keys named PHOTO and
        // WATERMARK
        // where each matches a single datastream:
        //
        // image=(PHOTO)&watermark=(WATERMARK) becomes
        // image=dslocation1&watermark=dslocation2
        //
        // In the case with multiple binding keys and multiple
        // datastreams,
        // the substitution might appear like the following:
        //
        // image=(PHOTO)&watermark=(WATERMARK) becomes
        // image=dslocation1+dslocation2&watermark=dslocation3
        if (nextKey.equalsIgnoreCase(currentKey) & i != numElements) {
          // Case where binding keys are equal which means that
          // multiple
          // datastreams matched the same binding key.
          if (m_doDatastreamMediation
              && !dissBindInfo.dsControlGroupType
                  .equalsIgnoreCase("R")) {
            // Use Datastream Mediation (except for redirected
            // datastreams).

            replaceString = datastreamResolverServletURL
                + registerDatastreamLocation(
                    dissBindInfo.dsLocation,
                    dissBindInfo.dsControlGroupType,
                    callbackRole, methodName) + "+("
                + dissBindInfo.DSBindKey + ")";
          } else {
            // Bypass Datastream Mediation.
            if (dissBindInfo.dsControlGroupType
                .equalsIgnoreCase("M")
                || dissBindInfo.dsControlGroupType
                    .equalsIgnoreCase("X")) {
              // Use the Default Disseminator syntax to resolve
              // the internal
              // datastream location for Managed and XML
              // datastreams.
              replaceString = resolveInternalDSLocation(context,
                  dissBindInfo.dsLocation,
                  dissBindInfo.dsCreateDT,
                  dsMediatedCallbackHost)
                  + "+(" + dissBindInfo.DSBindKey + ")";
              ;
            } else {
              replaceString = dissBindInfo.dsLocation + "+("
                  + dissBindInfo.DSBindKey + ")";
            }
            if (dissBindInfo.dsControlGroupType
                .equalsIgnoreCase("R")
                && dissBindInfo.AddressLocation
                    .equals(LOCAL_ADDRESS_LOCATION)) {
              isRedirect = true;
            }
          }
        } else {
          // Case where there are one or more binding keys.
          if (m_doDatastreamMediation
              && !dissBindInfo.dsControlGroupType
                  .equalsIgnoreCase("R")) {
            // Use Datastream Mediation (except for Redirected
            // datastreams)
            replaceString = datastreamResolverServletURL
                + registerDatastreamLocation(
                    dissBindInfo.dsLocation,
                    dissBindInfo.dsControlGroupType,
                    callbackRole, methodName); // this is
                                  // generic,
                                  // should be
                                  // made
                                  // specific
                                  // per
                                  // service
          } else {
            // Bypass Datastream Mediation.
            if (dissBindInfo.dsControlGroupType
                .equalsIgnoreCase("M")
                || dissBindInfo.dsControlGroupType
                    .equalsIgnoreCase("X")) {
              // Use the Default Disseminator syntax to resolve
              // the internal
              // datastream location for Managed and XML
              // datastreams.
              replaceString = resolveInternalDSLocation(context,
                  dissBindInfo.dsLocation,
                  dissBindInfo.dsCreateDT,
                  dsMediatedCallbackHost);
            } else {
              replaceString = dissBindInfo.dsLocation;
            }
            if (dissBindInfo.dsControlGroupType
                .equalsIgnoreCase("R")
                && dissBindInfo.AddressLocation
                    .equals(LOCAL_ADDRESS_LOCATION)) {
              isRedirect = true;
            }
          }
        }
        try {
         
          // Here we choose between two different tests for deciding
          // whether to URL-encode the datastream URL:
         
          //Old method:
          // If the operationLocation contains datastreamInputParms and also
          // contains a "=(" sequence, then
                    // URLEncode each parameter before substitution. Otherwise, the
                    // operationLocation has no parameters (i.e., it is a simple URL )
                    // so bypass URLencoding.
         
          // New Method:
          // If the operationLocation contains datastreamInputParms
          // URLEncode each parameter before substitution, except when
          // the parameter comprises the first part of the the URL.

          boolean useUrlEncoding = m_useNewUrlEncodingTest ? dissURL.indexOf("("
              + bindingKeyPattern + ")") > 0 : dissURL
              .indexOf("=(") != -1;

          if (useUrlEncoding) {
            dissURL = substituteString(dissURL, bindingKeyPattern,
                URLEncoder.encode(replaceString, "UTF-8"));
          } else {
            dissURL = substituteString(dissURL, bindingKeyPattern,
                replaceString);
          }
        } catch (UnsupportedEncodingException uee) {
          String message = "[DisseminationService] An error occured. The error "
              + "was \""
              + uee.getClass().getName()
              + "\"  . The Reason was \""
              + uee.getMessage()
              + "\"  . String value: " + replaceString + "  . ";
          logger.error(message);
          throw new GeneralException(message);
        }
        logger.debug("Replaced dissURL: " + dissURL.toString()
            + " DissBindingInfo index: " + i);
      }

      DeploymentDSBindSpec dsBindSpec = bmReader
          .getServiceDSInputSpec(null);
      DeploymentDSBindRule rules[] = dsBindSpec.dsBindRules;
      for (DeploymentDSBindRule element : rules) {
        String rulePattern = "(" + element.bindingKeyName + ")";
        if (dissURL.indexOf(rulePattern) != -1) {
          throw new DisseminationException(null, "Data Object " + PID
              + " missing required datastream: "
              + element.bindingKeyName, null, null, null);
        }
      }

      // Substitute method parameter values in dissemination URL
      Enumeration<String> e = h_userParms.keys();
      while (e.hasMoreElements()) {
        String name = null;
        String value = null;
        try {
          name = URLEncoder.encode(e.nextElement(), "UTF-8");
          value = URLEncoder.encode(h_userParms.get(name), "UTF-8");
        } catch (UnsupportedEncodingException uee) {
          String message = "[DisseminationService] An error occured. The error "
              + "was \""
              + uee.getClass().getName()
              + "\"  . The Reason was \""
              + uee.getMessage()
              + "\"  . Parameter name: "
              + name
              + "  . "
              + "Parameter value: " + value + "  .";
          logger.error(message);
          throw new GeneralException(message);
        }
        String pattern = "\\(" + name + "\\)";
        dissURL = substituteString(dissURL, pattern, value);
        logger.debug("User parm substituted in URL: " + dissURL);
      }

      // FIXME Need a more elegant means of handling optional
      // userInputParm
      // method parameters that are not supplied by the invoking client;
      // for now, any optional parms that were not supplied are removed
      // from
      // the outgoing URL. This works because parms are validated in
      // DefaultAccess to insure all required parms are present and all
      // parm
      // names match parm names defined for the specific method. The only
      // unsubstituted parms left in the operationLocation string at this
      // point
      // are those for optional parameters that the client omitted in the
      // initial request so they can safely be removed from the outgoing
      // dissemination URL. This step is only needed when optional
      // parameters
      // are not supplied by the client.
      if (dissURL.indexOf("(") != -1) {
        dissURL = stripParms(dissURL);
        logger.debug("Non-supplied optional userInputParm values removed "
            + "from URL: " + dissURL);
      }

      if (dissURL.indexOf("(") != -1) {
        String datastreamName = dissURL.substring(
            dissURL.indexOf("(") + 1, dissURL.indexOf(")"));
        throw new DisseminationException(null, "Data Object " + PID
            + " missing required datastream: " + datastreamName,
            null, null, null);
      }

      // Resolve content referenced by dissemination result.
      logger.debug("ProtocolType: " + protocolType);
      if (protocolType.equalsIgnoreCase("http")) {

        if (isRedirect) {
          // The dsControlGroupType of Redirect("R") is a special
          // control type
          // used primarily for streaming media. Datastreams of this
          // type are
          // not mediated (proxied by Fedora) and their physical
          // dsLocation is
          // simply redirected back to the client. Therefore, the
          // contents
          // of the MIMETypedStream returned for dissemination
          // requests will
          // contain the raw URL of the dsLocation and will be
          // assigned a
          // special fedora-specific MIME type to identify the stream
          // as
          // a MIMETypedStream whose contents contain a URL to which
          // the client
          // should be redirected.

          InputStream is = null;
          try {
            is = new ByteArrayInputStream(dissURL.getBytes("UTF-8"));
          } catch (UnsupportedEncodingException uee) {
            String message = "[DisseminationService] An error has occurred. "
                + "The error was a \""
                + uee.getClass().getName()
                + "\"  . The "
                + "Reason was \""
                + uee.getMessage()
                + "\"  . String value: " + dissURL + "  . ";
            logger.error(message);
            throw new GeneralException(message);
          }
          logger.debug("Finished assembling dissemination");
          dissemination = new MIMETypedStream(
              "application/fedora-redirect", is, null);
        } else {
          // For all non-redirected disseminations, Fedora captures
          // and returns
          // the MIMETypedStream resulting from the dissemination
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

            transformer.setParameter("fedora", context
                    .getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME));
            transformer.transform(new StreamSource(in), new StreamResult(out));
            byte [] bytes = out.toByteArray();
            in = new ByteArrayInputStream(bytes);
            return new MIMETypedStream("text/html", in, null, bytes.length);
        } catch (TransformerException e) {
            throw new DisseminationException("[DefaultDisseminatorImpl] had an error "
                    + "in transforming xml for viewObjectProfile. "
                    + "Underlying exception was: " + e.getMessage());
        }
View Full Code Here

Examples of org.fcrepo.server.storage.types.MIMETypedStream

            transformer.setParameter("fedora", context
                    .getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME));
            transformer.transform(new StreamSource(in), new StreamResult(out));
            byte [] bytes = out.toByteArray();
            in = new ByteArrayInputStream(bytes);
            return new MIMETypedStream("text/html", in, null, bytes.length);
        } catch (TransformerException e) {
            throw new DisseminationException("[DefaultDisseminatorImpl] had an error "
                    + "in transforming xml for viewItemIndex. "
                    + "Underlying exception was: " + e.getMessage());
        }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.