Example #1
0
    public synchronized Transformer getTransformer(String framework, String filename) {
      if (filename == null || filename.length() == 0) {
        throw new IllegalArgumentException("filename cannot be null or empty");
      }
      String key = framework + "-" + filename;

      Templates t = (Templates) pool.getTemplates().get(key);
      String s = null;

      if (t == null) {
        try {
          WOApplication app = WOApplication.application();
          WOResourceManager rm = app.resourceManager();

          TransformerFactory fac = TransformerFactory.newInstance();

          log.debug("creating template for file " + filename + " in framework " + framework);
          InputStream is = rm.inputStreamForResourceNamed(filename, framework, null);
          if (is == null) {
            log.debug("trying with framework = null");
            is = rm.inputStreamForResourceNamed(filename, null, null);
            if (is == null) {
              throw new IllegalArgumentException("inputStream is null");
            }
          }
          if (is.available() == 0) {
            throw new IllegalArgumentException(
                "InputStream has 0 bytes available, cannot read xsl file!");
          }
          s = ERXFileUtilities.stringFromInputStream(is);
          s = templateParser.parseTemplateWithObject(s, "@@", app);
          t = fac.newTemplates(new StreamSource(new ByteArrayInputStream(s.getBytes())));

          if (app.isCachingEnabled()) {
            templates.put(key, t);
          }
        } catch (IOException e1) {
          throw NSForwardException._runtimeExceptionForThrowable(e1);
        } catch (TransformerConfigurationException tce) {
          log.error("could not create template " + tce.getLocationAsString(), tce);
          log.error("  cause", tce.getCause());
          if (tce.getCause() != null && tce.getCause() instanceof org.xml.sax.SAXParseException) {
            org.xml.sax.SAXParseException e = (org.xml.sax.SAXParseException) tce.getCause();
            log.error(
                "SAXParseException: line " + e.getLineNumber() + ", column " + e.getColumnNumber());
          }
          log.error("this is the incorrect xsl:>>>" + s + "<<<");
          return null;
        }
      }

      try {
        return t.newTransformer();
      } catch (TransformerConfigurationException tce) {
        log.error("could not create template " + tce.getLocationAsString(), tce);
        log.error("  cause", tce.getCause());
        return null;
      }
    }
Example #2
0
 /**
  * Flushes the component cache to allow reloading components even when WOCachingEnabled=true.
  *
  * @return "OK"
  */
 public WOActionResults flushComponentCacheAction() {
   if (canPerformActionWithPasswordKey("er.extensions.ERXFlushComponentCachePassword")) {
     WOApplication.application()._removeComponentDefinitionCacheContents();
     return new ERXResponse("OK");
   }
   return forbiddenResponse();
 }
 /*
  * (non-Javadoc)
  *
  * @see
  * com.webobjects.appserver.WORequestHandler#handleRequest(com.webobjects
  * .appserver.WORequest)
  */
 @Override
 public WOResponse handleRequest(WORequest request) {
   // TODO Auto-generated method stub
   WOResponse aResponse = null;
   WOApplication anApplication = Application.app();
   if (anApplication.isRefusingNewSessions()
       && !request.isSessionIDInRequest()
       && request.isUsingWebServer()) {
     aResponse = generateRequestRefusal(request);
   } else {
     Object lock = anApplication.requestHandlingLock();
     if (lock != null)
       synchronized (lock) {
         aResponse = _handleRequest(request);
       }
     else aResponse = _handleRequest(request);
   }
   if (aResponse == null) aResponse = nullResponse();
   return aResponse;
 }
Example #4
0
  /**
   * Terminates the application when in development.
   *
   * @return "OK" if application has been shut down
   */
  public WOActionResults stopAction() {
    ERXResponse response = new ERXResponse();
    response.setHeader("text/plain", "Content-Type");

    if (ERXApplication.isDevelopmentModeSafe()) {
      WOApplication.application().terminate();
      response.setContent("OK");
    } else {
      response.setStatus(401);
    }

    return response;
  }
 /**
  * Creates a static resource handler for the given framework, which gives you nicer relative URLs
  * to work with. For instance, you could register a request handler "aj" that maps to the "Ajax"
  * framework, which would make URLs of the form "/aj/wonder.js" map onto Ajax's
  * WebServerResources/wonder.js folder.
  *
  * @param frameworkName the name of the framework to map to (or null/"app" for the application)
  */
 public ERXStaticResourceRequestHandler(String frameworkName) {
   if ("app".equals(frameworkName)) {
     frameworkName = null;
   }
   WODeployedBundle bundle =
       WOApplication.application().resourceManager()._cachedBundleForFrameworkNamed(frameworkName);
   File bundleFile = new File(bundle.bundlePath());
   if (bundle.isFramework()) {
     bundleFile = new File(bundleFile, "WebServerResources");
   } else {
     bundleFile = new File(new File(bundleFile, "Contents"), "WebServerResources");
   }
   _documentRoot = bundleFile.getAbsolutePath();
   _useRequestHandlerPath = true;
 }
 public WOResponse generateRequestRefusal(WORequest aRequest) {
   WODynamicURL aURIString = aRequest._uriDecomposed();
   String contentString =
       (new StringBuilder())
           .append(
               "D�sol�, votre demande n'a pas pu �tre imm�diatement trait�es. S'il vous pla�t essayer cette URL: <a href=\"")
           .append(aURIString)
           .append("\">")
           .append(aURIString)
           .append("</a>")
           .toString();
   aURIString.setApplicationNumber("-1");
   WOResponse aResponse = WOApplication.application().createResponseInContext(null);
   WOResponse._redirectResponse(aResponse, aURIString.toString(), contentString);
   return aResponse;
 }
 protected WOResponse _generateResponseForInputStream(InputStream is, long length, String type) {
   WOResponse response = application.createResponseInContext(null);
   if (is != null) {
     if (length != 0) {
       response.setContentStream(is, 50 * 1024, length);
     }
   } else {
     response.setStatus(404);
   }
   if (type != null) {
     response.setHeader(type, "content-type");
   }
   if (length != 0) {
     response.setHeader("" + length, "content-length");
   }
   return response;
 }
Example #8
0
 public void appendAttributesToResponse(WOResponse response, WOContext context) {
   WOComponent component = context.component();
   String href;
   if (_href != null) {
     href = (String) _href.valueInComponent(component);
   } else {
     String framework = "app";
     if (_framework != null) {
       Object val = _framework.valueInComponent(component);
       if (val != null) {
         framework = val.toString();
       }
     }
     String filename = (String) _filename.valueInComponent(component);
     WOResourceManager rs = WOApplication.application().resourceManager();
     href = rs.urlForResourceNamed(filename, framework, null, context.request());
   }
   response._appendTagAttributeAndValue("href", href, false);
   response._appendTagAttributeAndValue("rel", "SHORTCUT ICON", false);
   super.appendAttributesToResponse(response, context);
 }
  @Override
  public WOResponse handleRequest(WORequest request) {
    int bufferSize = 16384;

    WOApplication application = WOApplication.application();
    application.awake();
    try {
      WOContext context = application.createContextForRequest(request);
      WOResponse response = application.createResponseInContext(context);

      String sessionIdKey = application.sessionIdKey();
      String sessionId = (String) request.formValueForKey(sessionIdKey);
      if (sessionId == null) {
        sessionId = request.cookieValueForKey(sessionIdKey);
      }
      context._setRequestSessionID(sessionId);
      if (context._requestSessionID() != null) {
        application.restoreSessionWithID(sessionId, context);
      }

      try {
        final WODynamicURL url = request._uriDecomposed();
        final String requestPath = url.requestHandlerPath();
        final Matcher idMatcher = Pattern.compile("^id/(\\d+)/").matcher(requestPath);

        final Integer requestedAttachmentID;
        String requestedWebPath;

        final boolean requestedPathContainsAnAttachmentID = idMatcher.find();
        if (requestedPathContainsAnAttachmentID) {
          requestedAttachmentID = Integer.valueOf(idMatcher.group(1));
          requestedWebPath = idMatcher.replaceFirst("/");
        } else {
          // MS: This is kind of goofy because we lookup by path, your web path needs to
          // have a leading slash on it.
          requestedWebPath = "/" + requestPath;
          requestedAttachmentID = null;
        }

        try {
          InputStream attachmentInputStream;
          String mimeType;
          String fileName;
          long length;
          String queryString = url.queryString();
          boolean proxyAsAttachment =
              (queryString != null && queryString.contains("attachment=true"));

          EOEditingContext editingContext = ERXEC.newEditingContext();
          editingContext.lock();

          try {
            ERAttachment attachment =
                fetchAttachmentFor(editingContext, requestedAttachmentID, requestedWebPath);

            if (_delegate != null && !_delegate.attachmentVisible(attachment, request, context)) {
              throw new SecurityException("You are not allowed to view the requested attachment.");
            }
            mimeType = attachment.mimeType();
            length = attachment.size().longValue();
            fileName = attachment.originalFileName();
            ERAttachmentProcessor<ERAttachment> attachmentProcessor =
                ERAttachmentProcessor.processorForType(attachment);
            if (!proxyAsAttachment) {
              proxyAsAttachment = attachmentProcessor.proxyAsAttachment(attachment);
            }
            InputStream rawAttachmentInputStream =
                attachmentProcessor.attachmentInputStream(attachment);
            attachmentInputStream = new BufferedInputStream(rawAttachmentInputStream, bufferSize);
          } finally {
            editingContext.unlock();
          }

          response.setHeader(mimeType, "Content-Type");
          response.setHeader(String.valueOf(length), "Content-Length");

          if (proxyAsAttachment) {
            response.setHeader("attachment; filename=\"" + fileName + "\"", "Content-Disposition");
          }

          response.setStatus(200);
          response.setContentStream(attachmentInputStream, bufferSize, length);
        } catch (SecurityException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(403);
        } catch (NoSuchElementException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(404);
        } catch (FileNotFoundException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(404);
        } catch (IOException e) {
          NSLog.out.appendln(e);
          response.setContent(e.getMessage());
          response.setStatus(500);
        }

        return response;
      } finally {
        if (context._requestSessionID() != null) {
          WOApplication.application().saveSessionForContext(context);
        }
      }
    } finally {
      application.sleep();
    }
  }
Example #10
0
 public static WOActionResults exportJournalZPU(
     NSArray journal, WOContext context, String filename) {
   WOSession ses = context.session();
   if (journal == null || journal.count() == 0) {
     WOResponse response = WOApplication.application().createResponseInContext(context);
     response.appendContentString(
         (String) ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Tabel.noData"));
     response.setHeader("application/octet-stream", "Content-Type");
     response.setHeader("attachment; filename=\"noData.txt\"", "Content-Disposition");
     return response;
   }
   Export export = new ExportCSV(context, filename);
   export.beginRow();
   export.addValue(ses.valueForKeyPath("strings.Reusables_Strings.dataTypes.Date"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.OrigTeacher"));
   export.addValue(ses.valueForKeyPath("strings.RujelInterfaces_Names.EduCycle.subject"));
   export.addValue(ses.valueForKeyPath("strings.RujelInterfaces_Names.EduGroup.this"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Reason.Reason"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Reason.verification"));
   export.addValue(
       ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Substitute.Substitutor"));
   export.addValue(ses.valueForKeyPath("strings.RujelInterfaces_Names.EduCycle.subject"));
   export.addValue(ses.valueForKeyPath("strings.RujelCurriculum_Curriculum.Substitute.factor"));
   Enumeration enu = journal.objectEnumerator();
   StringBuilder buf = new StringBuilder();
   while (enu.hasMoreElements()) {
     NSDictionary dict = (NSDictionary) enu.nextElement();
     export.beginRow();
     export.addValue(MyUtility.dateFormat().format(dict.valueForKey("date")));
     EduCourse course = (EduCourse) dict.valueForKey("minusCourse");
     if (course != null) {
       Teacher teacher = (Teacher) dict.valueForKey("minusTeacher");
       if (teacher != null) export.addValue(Person.Utility.fullName(teacher, true, 2, 1, 1));
       else export.addValue(ses.valueForKeyPath("strings.RujelBase_Base.vacant"));
       if (course.comment() == null) {
         export.addValue(course.cycle().subject());
       } else {
         buf.delete(0, buf.length());
         buf.append(course.cycle().subject());
         buf.append(' ').append('(').append(course.comment()).append(')');
         export.addValue(buf.toString());
       }
     } else {
       export.addValue(null);
       export.addValue(null);
     }
     if (dict.valueForKey("eduGroup") != null)
       export.addValue(dict.valueForKeyPath("eduGroup.name"));
     else export.addValue(dict.valueForKey("grade"));
     export.addValue(dict.valueForKeyPath("reason.title"));
     export.addValue(dict.valueForKeyPath("reason.verification"));
     course = (EduCourse) dict.valueForKey("plusCourse");
     if (course != null) {
       Teacher teacher = (Teacher) dict.valueForKey("plusTeacher");
       export.addValue(Person.Utility.fullName(teacher, true, 2, 1, 1));
       if (course.comment() == null) {
         export.addValue(course.cycle().subject());
       } else {
         buf.delete(0, buf.length());
         buf.append(course.cycle().subject());
         buf.append(' ').append('(').append(course.comment()).append(')');
         export.addValue(buf.toString());
       }
     } else {
       export.addValue(null);
       export.addValue(null);
     }
     export.addValue(dict.valueForKey("value"));
   }
   return export;
 }
Example #11
0
 public boolean showDetails() {
   return WOApplication.application().isDebuggingEnabled();
 }
 public static Application myApp() {
   return (Application) WOApplication.application();
 }
Example #13
0
public class WOTaskdHandler {

  public interface ErrorCollector {
    public void addObjectsFromArrayIfAbsentToErrorMessageArray(NSArray<String> errors);
  }

  private static _NSCollectionReaderWriterLock _lock = new _NSCollectionReaderWriterLock();

  private static MSiteConfig _siteConfig;

  public static MSiteConfig siteConfig() {
    return _siteConfig;
  }

  public static void createSiteConfig() {

    _siteConfig = MSiteConfig.unarchiveSiteConfig(false);
    if (_siteConfig == null) {
      NSLog.err.appendln("The Site Configuration could not be loaded from the local filesystem");
      System.exit(1);
    }

    for (Enumeration e = _siteConfig.hostArray().objectEnumerator(); e.hasMoreElements(); ) {
      _siteConfig.hostErrorArray.addObjectIfAbsent(e.nextElement());
    }
    if (_siteConfig.localHost() != null)
      _siteConfig.hostErrorArray.removeObject(_siteConfig.localHost());
  }

  public Application _theApplication = (Application) WOApplication.application();

  ErrorCollector _session;

  public WOTaskdHandler(ErrorCollector session) {
    _session = session;
  }

  private ErrorCollector mySession() {
    return _session;
  }

  private static _NSCollectionReaderWriterLock lock() {
    return _lock;
  }

  public void startReading() {
    lock().startReading();
  }

  public void endReading() {
    lock().endReading();
  }

  public void startWriting() {
    lock().startWriting();
  }

  public void endWriting() {
    lock().endWriting();
  }

  public void updateForPage(String aName) {
    // KH - we should probably set the instance information as we get the
    // responses, to avoid waiting, then doing it in serial! (not that it's
    // _that_ slow)
    MSiteConfig siteConfig = WOTaskdHandler.siteConfig();
    startReading();
    try {
      aName = ERXStringUtilities.lastPropertyKeyInKeyPath(aName);
      if (siteConfig.hostArray().count() != 0) {
        if (ApplicationsPage.class.getName().endsWith(aName)
            && (siteConfig.applicationArray().count() != 0)) {

          for (Enumeration e = siteConfig.applicationArray().objectEnumerator();
              e.hasMoreElements(); ) {
            MApplication anApp = (MApplication) e.nextElement();
            anApp.setRunningInstancesCount(0);
          }
          NSArray<MHost> hostArray = siteConfig.hostArray();
          getApplicationStatusForHosts(hostArray);
        } else if (AppDetailPage.class.getName().endsWith(aName)) {
          NSArray<MHost> hostArray = siteConfig.hostArray();

          getInstanceStatusForHosts(hostArray);
        } else if (HostsPage.class.getName().endsWith(aName)) {
          NSArray<MHost> hostArray = siteConfig.hostArray();

          getHostStatusForHosts(hostArray);
        }
      }
    } finally {
      endReading();
    }
  }

  /* ******** Common Functionality ********* */
  private static NSMutableDictionary createUpdateRequestDictionary(
      MSiteConfig _Config,
      MHost _Host,
      MApplication _Application,
      NSArray _InstanceArray,
      String requestType) {
    NSMutableDictionary monitorRequest = new NSMutableDictionary(1);
    NSMutableDictionary updateWotaskd = new NSMutableDictionary(1);
    NSMutableDictionary requestTypeDict = new NSMutableDictionary();

    if (_Config != null) {
      NSDictionary site = new NSDictionary(_Config.values());
      requestTypeDict.takeValueForKey(site, "site");
    }
    if (_Host != null) {
      NSArray hostArray = new NSArray(_Host.values());
      requestTypeDict.takeValueForKey(hostArray, "hostArray");
    }
    if (_Application != null) {
      NSArray applicationArray = new NSArray(_Application.values());
      requestTypeDict.takeValueForKey(applicationArray, "applicationArray");
    }
    if (_InstanceArray != null) {
      int instanceCount = _InstanceArray.count();
      NSMutableArray instanceArray = new NSMutableArray(instanceCount);
      for (int i = 0; i < instanceCount; i++) {
        MInstance anInst = (MInstance) _InstanceArray.objectAtIndex(i);
        instanceArray.addObject(anInst.values());
      }
      requestTypeDict.takeValueForKey(instanceArray, "instanceArray");
    }

    updateWotaskd.takeValueForKey(requestTypeDict, requestType);
    monitorRequest.takeValueForKey(updateWotaskd, "updateWotaskd");

    return monitorRequest;
  }

  public WOResponse[] sendRequest(
      NSDictionary monitorRequest, NSArray wotaskdArray, boolean willChange) {
    String encodedRootObjectForKey =
        (new _JavaMonitorCoder()).encodeRootObjectForKey(monitorRequest, "monitorRequest");
    NSData content = new NSData(encodedRootObjectForKey.getBytes());
    return MHost.sendRequestToWotaskdArray(content, wotaskdArray, willChange);
  }

  /* ******* */

  /* ******** ADDING (UPDATE) ********* */
  public void sendAddInstancesToWotaskds(NSArray newInstancesArray, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(null, null, null, newInstancesArray, "add"),
            wotaskdArray,
            true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "add", false, false, true, false);
  }

  public void sendAddApplicationToWotaskds(MApplication newApplication, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(null, null, newApplication, null, "add"),
            wotaskdArray,
            true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "add", false, true, false, false);
  }

  public void sendAddHostToWotaskds(MHost newHost, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(null, newHost, null, null, "add"), wotaskdArray, true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "add", true, false, false, false);
  }

  /* ******* */

  /* ******** REMOVING (UPDATE) ********* */
  protected void sendRemoveInstancesToWotaskds(NSArray exInstanceArray, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(null, null, null, exInstanceArray, "remove"),
            wotaskdArray,
            true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "remove", false, false, true, false);
  }

  public void sendRemoveApplicationToWotaskds(MApplication exApplication, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(null, null, exApplication, null, "remove"),
            wotaskdArray,
            true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "remove", false, true, false, false);
  }

  protected void sendRemoveHostToWotaskds(MHost exHost, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(null, exHost, null, null, "remove"), wotaskdArray, true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "remove", true, false, false, false);
  }

  /* ******* */

  /* ******** CONFIGURE (UPDATE) ********* */
  public void sendUpdateInstancesToWotaskds(
      NSArray<MInstance> changedInstanceArray, NSArray wotaskdArray) {
    if (wotaskdArray.count() != 0 && changedInstanceArray.count() != 0) {
      WOResponse[] responses =
          sendRequest(
              createUpdateRequestDictionary(null, null, null, changedInstanceArray, "configure"),
              wotaskdArray,
              true);
      NSDictionary[] responseDicts = generateResponseDictionaries(responses);
      getUpdateErrors(responseDicts, "configure", false, false, true, false);
    }
  }

  public void sendUpdateApplicationToWotaskds(
      MApplication changedApplication, NSArray wotaskdArray) {
    if (wotaskdArray.count() != 0) {
      WOResponse[] responses =
          sendRequest(
              createUpdateRequestDictionary(null, null, changedApplication, null, "configure"),
              wotaskdArray,
              true);
      NSDictionary[] responseDicts = generateResponseDictionaries(responses);
      getUpdateErrors(responseDicts, "configure", false, true, false, false);
    }
  }

  public void sendUpdateApplicationAndInstancesToWotaskds(
      MApplication changedApplication, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(
                null, null, changedApplication, changedApplication.instanceArray(), "configure"),
            wotaskdArray,
            true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "configure", false, true, true, false);
  }

  protected void sendUpdateHostToWotaskds(MHost changedHost, NSArray wotaskdArray) {
    WOResponse[] responses =
        sendRequest(
            createUpdateRequestDictionary(null, changedHost, null, null, "configure"),
            wotaskdArray,
            true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, "configure", true, false, false, false);
  }

  public void sendUpdateSiteToWotaskds() {
    startReading();
    try {
      NSMutableArray hostArray = siteConfig().hostArray();
      if (hostArray.count() != 0) {
        NSMutableDictionary updateRequestDictionary =
            createUpdateRequestDictionary(siteConfig(), null, null, null, "configure");
        WOResponse[] responses = sendRequest(updateRequestDictionary, hostArray, true);
        NSDictionary[] responseDicts = generateResponseDictionaries(responses);
        getUpdateErrors(responseDicts, "configure", false, false, false, true);
      }
    } finally {
      endReading();
    }
  }

  /* ******* */

  /* ******** OVERWRITE / CLEAR (UPDATE) ********* */
  public void sendOverwriteToWotaskd(MHost aHost) {
    NSDictionary SiteConfig = siteConfig().dictionaryForArchive();
    NSMutableDictionary data = new NSMutableDictionary(SiteConfig, "SiteConfig");
    _sendOverwriteClearToWotaskd(aHost, "overwrite", data);
  }

  protected void sendClearToWotaskd(MHost aHost) {
    String data = new String("SITE");
    _sendOverwriteClearToWotaskd(aHost, "clear", data);
  }

  private void _sendOverwriteClearToWotaskd(MHost aHost, String type, Object data) {
    NSMutableDictionary updateWotaskd = new NSMutableDictionary(data, type);
    NSMutableDictionary monitorRequest = new NSMutableDictionary(updateWotaskd, "updateWotaskd");

    WOResponse[] responses = sendRequest(monitorRequest, new NSArray(aHost), true);
    NSDictionary[] responseDicts = generateResponseDictionaries(responses);
    getUpdateErrors(responseDicts, type, false, false, false, false);
  }

  /* ******* */

  /* ******** COMMANDING ********* */
  private static Object[] commandInstanceKeys =
      new Object[] {"applicationName", "id", "hostName", "port"};

  public static void sendCommandInstancesToWotaskds(
      String command, NSArray instanceArray, NSArray wotaskdArray, WOTaskdHandler collector) {
    if (instanceArray.count() > 0 && wotaskdArray.count() > 0) {
      int instanceCount = instanceArray.count();

      NSMutableDictionary monitorRequest = new NSMutableDictionary(1);
      NSMutableArray commandWotaskd = new NSMutableArray(instanceArray.count() + 1);

      commandWotaskd.addObject(command);

      for (int i = 0; i < instanceCount; i++) {
        MInstance anInst = (MInstance) instanceArray.objectAtIndex(i);
        commandWotaskd.addObject(
            new NSDictionary(
                new Object[] {
                  anInst.applicationName(), anInst.id(), anInst.hostName(), anInst.port()
                },
                commandInstanceKeys));
      }
      monitorRequest.takeValueForKey(commandWotaskd, "commandWotaskd");

      WOResponse[] responses = collector.sendRequest(monitorRequest, wotaskdArray, false);
      NSDictionary[] responseDicts = collector.generateResponseDictionaries(responses);
      if (NSLog.debugLoggingAllowedForLevelAndGroups(
          NSLog.DebugLevelDetailed, NSLog.DebugGroupDeployment)) {
        NSLog.debug.appendln(
            "OUT: "
                + NSPropertyListSerialization.stringFromPropertyList(monitorRequest)
                + "\n\nIN: "
                + NSPropertyListSerialization.stringFromPropertyList(new NSArray(responseDicts)));
      }
      collector.getCommandErrors(responseDicts);
    }
  }

  protected void sendCommandInstancesToWotaskds(
      String command, NSArray<MInstance> instanceArray, NSArray<MHost> wotaskdArray) {
    sendCommandInstancesToWotaskds(command, instanceArray, wotaskdArray, this);
  }

  public void sendQuitInstancesToWotaskds(
      NSArray<MInstance> instanceArray, NSArray<MHost> wotaskdArray) {
    sendCommandInstancesToWotaskds("QUIT", instanceArray, wotaskdArray, this);
  }

  public void sendStartInstancesToWotaskds(
      NSArray<MInstance> instanceArray, NSArray<MHost> wotaskdArray) {
    sendCommandInstancesToWotaskds("START", instanceArray, wotaskdArray, this);
  }

  public void sendClearDeathsToWotaskds(
      NSArray<MInstance> instanceArray, NSArray<MHost> wotaskdArray) {
    sendCommandInstancesToWotaskds("CLEAR", instanceArray, wotaskdArray, this);
  }

  public void sendStopInstancesToWotaskds(
      NSArray<MInstance> instanceArray, NSArray<MHost> wotaskdArray) {
    sendCommandInstancesToWotaskds("STOP", instanceArray, wotaskdArray, this);
  }

  public void sendRefuseSessionToWotaskds(
      NSArray<MInstance> instanceArray, NSArray<MHost> wotaskdArray, boolean doRefuse) {
    for (MInstance instance : instanceArray) {
      instance.setRefusingNewSessions(doRefuse);
    }
    sendCommandInstancesToWotaskds((doRefuse ? "REFUSE" : "ACCEPT"), instanceArray, wotaskdArray);
  }

  /* ******* */

  /* ******** QUERIES ********* */
  private NSMutableDictionary createQuery(String queryString) {
    NSMutableDictionary monitorRequest = new NSMutableDictionary(queryString, "queryWotaskd");
    return monitorRequest;
  }

  protected WOResponse[] sendQueryToWotaskds(String queryString, NSArray wotaskdArray) {
    return sendRequest(createQuery(queryString), wotaskdArray, false);
  }

  /* ******* */

  /* ******** Response Handling ********* */
  public static NSDictionary responseParsingFailed =
      new NSDictionary(
          new NSDictionary(
              new NSArray("INTERNAL ERROR: Failed to parse response XML"), "errorResponse"),
          "monitorResponse");

  public static NSDictionary emptyResponse =
      new NSDictionary(
          new NSDictionary(
              new NSArray("INTERNAL ERROR: Response returned was null or empty"), "errorResponse"),
          "monitorResponse");

  private NSDictionary[] generateResponseDictionaries(WOResponse[] responses) {
    NSDictionary[] responseDicts = new NSDictionary[responses.length];
    for (int i = 0; i < responses.length; i++) {
      if ((responses[i] != null) && (responses[i].content() != null)) {
        try {
          responseDicts[i] =
              (NSDictionary) (new _JavaMonitorDecoder()).decodeRootObject(responses[i].content());
        } catch (WOXMLException wxe) {
          responseDicts[i] = responseParsingFailed;
        }
      } else {
        responseDicts[i] = emptyResponse;
      }
    }
    return responseDicts;
  }

  /* ******* */

  /* ******** Error Handling ********* */
  public NSMutableArray getUpdateErrors(
      NSDictionary[] responseDicts,
      String updateType,
      boolean hasHosts,
      boolean hasApplications,
      boolean hasInstances,
      boolean hasSite) {
    NSMutableArray errorArray = new NSMutableArray();

    boolean clearOverwrite = false;
    if ((updateType.equals("overwrite")) || (updateType.equals("clear"))) clearOverwrite = true;

    for (int i = 0; i < responseDicts.length; i++) {
      if (responseDicts[i] != null) {
        NSDictionary responseDict = responseDicts[i];
        getGlobalErrorFromResponse(responseDict, errorArray);

        NSDictionary updateWotaskdResponseDict =
            (NSDictionary) responseDict.valueForKey("updateWotaskdResponse");

        if (updateWotaskdResponseDict != null) {
          NSDictionary updateTypeResponse =
              (NSDictionary) updateWotaskdResponseDict.valueForKey(updateType);
          if (updateTypeResponse != null) {
            if (clearOverwrite) {
              String errorMessage = (String) updateTypeResponse.valueForKey("errorMessage");
              if (errorMessage != null) {
                errorArray.addObject(errorMessage);
              }
            } else {
              if (hasSite) {
                NSDictionary aDict = (NSDictionary) updateTypeResponse.valueForKey("site");
                String errorMessage = (String) aDict.valueForKey("errorMessage");
                if (errorMessage != null) {
                  errorArray.addObject(errorMessage);
                }
              }
              if (hasHosts)
                _addUpdateResponseToErrorArray(updateTypeResponse, "hostArray", errorArray);
              if (hasApplications)
                _addUpdateResponseToErrorArray(updateTypeResponse, "applicationArray", errorArray);
              if (hasInstances)
                _addUpdateResponseToErrorArray(updateTypeResponse, "instanceArray", errorArray);
            }
          }
        }
      }
    }
    if (NSLog.debugLoggingAllowedForLevelAndGroups(
        NSLog.DebugLevelDetailed, NSLog.DebugGroupDeployment))
      NSLog.debug.appendln("##### getUpdateErrors: " + errorArray);
    mySession().addObjectsFromArrayIfAbsentToErrorMessageArray(errorArray);
    return errorArray;
  }

  protected void _addUpdateResponseToErrorArray(
      NSDictionary updateTypeResponse, String responseKey, NSMutableArray errorArray) {
    NSArray aResponse = (NSArray) updateTypeResponse.valueForKey(responseKey);
    if (aResponse != null) {
      for (Enumeration e = aResponse.objectEnumerator(); e.hasMoreElements(); ) {
        NSDictionary aDict = (NSDictionary) e.nextElement();
        String errorMessage = (String) aDict.valueForKey("errorMessage");
        if (errorMessage != null) {
          errorArray.addObject(errorMessage);
        }
      }
    }
  }

  public NSMutableArray getCommandErrors(NSDictionary[] responseDicts) {
    NSMutableArray errorArray = new NSMutableArray();

    for (int i = 0; i < responseDicts.length; i++) {
      if (responseDicts[i] != null) {
        NSDictionary responseDict = responseDicts[i];
        getGlobalErrorFromResponse(responseDict, errorArray);

        NSArray commandWotaskdResponse =
            (NSArray) responseDict.valueForKey("commandWotaskdResponse");
        if ((commandWotaskdResponse != null) && (commandWotaskdResponse.count() > 0)) {
          int count = commandWotaskdResponse.count();
          for (int j = 1; j < count; j++) {
            NSDictionary aDict = (NSDictionary) commandWotaskdResponse.objectAtIndex(j);
            String errorMessage = (String) aDict.valueForKey("errorMessage");
            if (errorMessage != null) {
              errorArray.addObject(errorMessage);
              if (j == 0) break; // the command produced an error,
              // parsing didn't finish
            }
          }
        }
      }
    }
    if (NSLog.debugLoggingAllowedForLevelAndGroups(
        NSLog.DebugLevelDetailed, NSLog.DebugGroupDeployment))
      NSLog.debug.appendln("##### getCommandErrors: " + errorArray);
    mySession().addObjectsFromArrayIfAbsentToErrorMessageArray(errorArray);
    return errorArray;
  }

  protected NSMutableArray getQueryErrors(NSDictionary[] responseDicts) {
    NSMutableArray errorArray = new NSMutableArray();

    for (int i = 0; i < responseDicts.length; i++) {
      if (responseDicts[i] != null) {
        NSDictionary responseDict = responseDicts[i];
        getGlobalErrorFromResponse(responseDict, errorArray);

        NSArray commandWotaskdResponse =
            (NSArray) responseDict.valueForKey("commandWotaskdResponse");
        if ((commandWotaskdResponse != null) && (commandWotaskdResponse.count() > 0)) {
          int count = commandWotaskdResponse.count();
          for (int j = 1; j < count; j++) {
            NSDictionary aDict = (NSDictionary) commandWotaskdResponse.objectAtIndex(j);
            String errorMessage = (String) aDict.valueForKey("errorMessage");
            if (errorMessage != null) {
              errorArray.addObject(errorMessage);
              if (j == 0) break; // the command produced an error,
              // parsing didn't finish
            }
          }
        }
      }
    }
    if (NSLog.debugLoggingAllowedForLevelAndGroups(
        NSLog.DebugLevelDetailed, NSLog.DebugGroupDeployment))
      NSLog.debug.appendln("##### getQueryErrors: " + errorArray);
    mySession().addObjectsFromArrayIfAbsentToErrorMessageArray(errorArray);
    return errorArray;
  }

  protected void getGlobalErrorFromResponse(NSDictionary responseDict, NSMutableArray errorArray) {
    NSArray errorResponse = (NSArray) responseDict.valueForKey("errorResponse");
    if (errorResponse != null) {
      errorArray.addObjectsFromArray(errorResponse);
    }
  }

  public void getInstanceStatusForHosts(NSArray<MHost> hostArray) {
    if (hostArray.count() != 0) {

      WOResponse[] responses = sendQueryToWotaskds("INSTANCE", hostArray);

      NSMutableArray errorArray = new NSMutableArray();
      NSArray responseArray = null;
      NSDictionary responseDictionary = null;
      NSDictionary queryResponseDictionary = null;
      for (int i = 0; i < responses.length; i++) {
        if ((responses[i] == null) || (responses[i].content() == null)) {
          responseDictionary = emptyResponse;
        } else {
          try {
            responseDictionary =
                (NSDictionary) new _JavaMonitorDecoder().decodeRootObject(responses[i].content());
          } catch (WOXMLException wxe) {
            NSLog.err.appendln(
                "MonitorComponent pageWithName(AppDetailPage) Error decoding response: "
                    + responses[i].contentString());
            responseDictionary = responseParsingFailed;
          }
        }
        getGlobalErrorFromResponse(responseDictionary, errorArray);

        queryResponseDictionary =
            (NSDictionary) responseDictionary.valueForKey("queryWotaskdResponse");
        if (queryResponseDictionary != null) {
          responseArray = (NSArray) queryResponseDictionary.valueForKey("instanceResponse");
          if (responseArray != null) {
            for (int j = 0; j < responseArray.count(); j++) {
              responseDictionary = (NSDictionary) responseArray.objectAtIndex(j);

              String host = (String) responseDictionary.valueForKey("host");
              Integer port = (Integer) responseDictionary.valueForKey("port");
              String runningState = (String) responseDictionary.valueForKey("runningState");
              Boolean refusingNewSessions =
                  (Boolean) responseDictionary.valueForKey("refusingNewSessions");
              NSDictionary statistics = (NSDictionary) responseDictionary.valueForKey("statistics");
              NSArray deaths = (NSArray) responseDictionary.valueForKey("deaths");
              String nextShutdown = (String) responseDictionary.valueForKey("nextShutdown");

              MInstance anInstance = siteConfig().instanceWithHostnameAndPort(host, port);
              if (anInstance != null) {
                for (int k = 0; k < MObject.stateArray.length; k++) {
                  if (MObject.stateArray[k].equals(runningState)) {
                    anInstance.state = k;
                    break;
                  }
                }
                anInstance.setRefusingNewSessions(String_Extensions.boolValue(refusingNewSessions));
                anInstance.setStatistics(statistics);
                anInstance.setDeaths(new NSMutableArray(deaths));
                anInstance.setNextScheduledShutdownString_M(nextShutdown);
              }
            }
          }
        }
      } // For Loop
      if (NSLog.debugLoggingAllowedForLevelAndGroups(
          NSLog.DebugLevelDetailed, NSLog.DebugGroupDeployment))
        NSLog.debug.appendln("##### pageWithName(AppDetailPage) errors: " + errorArray);
      mySession().addObjectsFromArrayIfAbsentToErrorMessageArray(errorArray);
    }
  }

  public void getHostStatusForHosts(NSArray<MHost> hostArray) {
    WOResponse[] responses = sendQueryToWotaskds("HOST", hostArray);

    NSMutableArray errorArray = new NSMutableArray();
    NSDictionary responseDict = null;
    for (int i = 0; i < responses.length; i++) {
      MHost aHost = siteConfig().hostArray().objectAtIndex(i);

      if ((responses[i] == null) || (responses[i].content() == null)) {
        responseDict = emptyResponse;
      } else {
        try {
          responseDict =
              (NSDictionary) new _JavaMonitorDecoder().decodeRootObject(responses[i].content());
        } catch (WOXMLException wxe) {
          NSLog.err.appendln(
              "MonitorComponent pageWithName(HostsPage) Error decoding response: "
                  + responses[i].contentString());
          responseDict = responseParsingFailed;
        }
      }
      getGlobalErrorFromResponse(responseDict, errorArray);

      NSDictionary queryResponse = (NSDictionary) responseDict.valueForKey("queryWotaskdResponse");
      if (queryResponse != null) {
        NSDictionary hostResponse = (NSDictionary) queryResponse.valueForKey("hostResponse");
        aHost._setHostInfo(hostResponse);
        aHost.isAvailable = true;
      } else {
        aHost.isAvailable = false;
      }
    } // for
    if (NSLog.debugLoggingAllowedForLevelAndGroups(
        NSLog.DebugLevelDetailed, NSLog.DebugGroupDeployment))
      NSLog.debug.appendln("##### pageWithName(HostsPage) errors: " + errorArray);
    mySession().addObjectsFromArrayIfAbsentToErrorMessageArray(errorArray);
  }

  public void getApplicationStatusForHosts(NSArray<MHost> hostArray) {

    WOResponse[] responses = sendQueryToWotaskds("APPLICATION", hostArray);

    NSMutableArray errorArray = new NSMutableArray();
    NSDictionary applicationResponseDictionary;
    NSDictionary queryResponseDictionary;
    NSArray responseArray = null;
    NSDictionary responseDictionary = null;
    for (int i = 0; i < responses.length; i++) {
      if ((responses[i] == null) || (responses[i].content() == null)) {
        queryResponseDictionary = emptyResponse;
      } else {
        try {
          queryResponseDictionary =
              (NSDictionary) new _JavaMonitorDecoder().decodeRootObject(responses[i].content());
        } catch (WOXMLException wxe) {
          NSLog.err.appendln(
              "MonitorComponent pageWithName(ApplicationsPage) Error decoding response: "
                  + responses[i].contentString());
          queryResponseDictionary = responseParsingFailed;
        }
      }
      getGlobalErrorFromResponse(queryResponseDictionary, errorArray);

      applicationResponseDictionary =
          (NSDictionary) queryResponseDictionary.valueForKey("queryWotaskdResponse");
      if (applicationResponseDictionary != null) {
        responseArray = (NSArray) applicationResponseDictionary.valueForKey("applicationResponse");
        if (responseArray != null) {
          for (int j = 0; j < responseArray.count(); j++) {
            responseDictionary = (NSDictionary) responseArray.objectAtIndex(j);
            String appName = (String) responseDictionary.valueForKey("name");
            Integer runningInstances = (Integer) responseDictionary.valueForKey("runningInstances");
            MApplication anApplication = siteConfig().applicationWithName(appName);
            if (anApplication != null) {
              anApplication.setRunningInstancesCount(
                  anApplication.runningInstancesCount() + runningInstances.intValue());
            }
          }
        }
      }
    } // for
    if (NSLog.debugLoggingAllowedForLevelAndGroups(
        NSLog.DebugLevelDetailed, NSLog.DebugGroupDeployment))
      NSLog.debug.appendln("##### pageWithName(ApplicationsPage) errors: " + errorArray);
    mySession().addObjectsFromArrayIfAbsentToErrorMessageArray(errorArray);
  }
}
Example #14
0
 public static void main(String argv[]) {
   WOApplication.main(argv, Application.class);
 }
Example #15
0
/** CoreSession */
public class CoreSession extends ERXSession {
  /** */
  private static final long serialVersionUID = 2137928448342423580L;

  private static final Logger logger = Logger.getLogger(CoreSession.class);

  public static CoreProperties properties = null;
  protected CoreConfiguration configuration = null;

  protected CoreApplication application = (CoreApplication) WOApplication.application();
  protected NSMutableDictionary<String, Object> sessionInfo = null;

  public CoreSession() {
    super();
    logger.trace("-----+ constructor");

    NSNotificationCenter.defaultCenter()
        .addObserver(
            this,
            new NSSelector<Object>("sessionWillAwake", new Class[] {NSNotification.class}),
            ERXSession.SessionWillAwakeNotification,
            null);

    NSNotificationCenter.defaultCenter()
        .addObserver(
            this,
            new NSSelector<Object>("sessionDidCreate", new Class[] {NSNotification.class}),
            WOSession.SessionDidCreateNotification,
            null);

    NSNotificationCenter.defaultCenter()
        .addObserver(
            this,
            new NSSelector<Object>("sessionDidTimeOut", new Class[] {NSNotification.class}),
            WOSession.SessionDidTimeOutNotification,
            null);

    CoreSession.properties = new CoreProperties(System.getProperties());
  }

  @Override
  public void awake() {
    super.awake();

    if (!SessionInfoDict.any_SessionInfo(sessionID())) {
      logger.error(
          "     | unknown sessionID :" + sessionID() + ".  We are terminating this session.");
      terminate();
    }
  }

  /* ----------------------------------------------------------------------------------- */

  /**
   * Called when the session posts the notification "SessionDidCreateNotification". Note, since this
   * notification reports EVERY session creation, we need to check that the one we react to is our
   * own.
   *
   * <p>This method calls subclasses' {@link #didCreateSession} method.
   *
   * @param n - the Session instance.
   */
  public final void sessionWillAwake(NSNotification n) {
    if (((WOSession) n.object()).sessionID().equals(sessionID())) {
      logger.trace(
          "!-- "
              + ERXSession.SessionWillAwakeNotification
              + " ["
              + ((WOSession) n.object()).sessionID()
              + "]");

      if (null == this.sessionInfo) {
        this.sessionInfo = new NSMutableDictionary<String, Object>();
        this.sessionInfo.takeValueForKey(0, "HitCount");
        SessionInfoDict.add_SessionInfo(sessionID(), this.sessionInfo);
      }

      sessionWillAwake();
      this.application.addSession(this, sessionID());
    }
  }

  /** Override this to perform session initialization. (optional) */
  public void sessionWillAwake() {}

  /**
   * Called when the session posts the notification "SessionDidCreateNotification". Note, since this
   * notification reports EVERY session creation, we need to check that the one we react to is our
   * own.
   *
   * <p>This method calls subclasses' {@link #didCreateSession} method.
   *
   * @param n - the Session instance.
   */
  public final void sessionDidCreate(NSNotification n) {
    if (((WOSession) n.object()).sessionID().equals(sessionID())) {
      logger.trace(
          "!-- "
              + WOSession.SessionDidCreateNotification
              + " ["
              + ((WOSession) n.object()).sessionID()
              + "]");
      sessionDidCreate();
      this.application.addSession(this, sessionID());
    }
  }

  /** Override this to perform session initialization. (optional) */
  public void sessionDidCreate() {}

  /**
   * Called when the session posts the notification "SessionDidTimeOutNotification". This method
   * calls subclasses' {@link #didTimeOutSession} method.
   *
   * @param n - the Session instance.
   */
  public final void sessionDidTimeOut(NSNotification n) {
    if (n.object().equals(sessionID())) {
      logger.trace("!-- " + WOSession.SessionDidTimeOutNotification + " [" + n.object() + "]");
      sessionDidTimeOut();
      this.application.addSession(this, sessionID());
    }
  }

  /** Override this to perform session timeout processing. (optional) */
  public void sessionDidTimeOut() {}

  @Override
  public void terminate() {
    logger.trace("-->--> terminate()  [id=" + sessionID() + "]");

    this.application.delSession(sessionID());
    SessionInfoDict.log_SessionInfo();
    SessionInfoDict.sub_SessionInfo(sessionID());
    super.terminate();
  }

  // ----------------------------------------------------------------------------------------------------------------

  /** Finds the session in SessionInfo with key sessionID and +1 its count of actions. */
  protected void incHitCount() {
    final Integer clicks = getHitCount();
    if (clicks != null) {
      this.sessionInfo.takeValueForKey(clicks + 1, "HitCount");
    }
  }

  /**
   * Returns a count of the number of times the session indicated by sessionID has been through the
   * request-response loop. Used to set the session timeout to a sensible length after the user has
   * clicked at east once in Marketplace and may be used to stop showing a splash panel after a
   * couple of hits.
   *
   * @return the number of actions recorded for sessionID
   */
  public Integer getHitCount() {
    return (Integer) this.sessionInfo.valueForKey("HitCount");
  }
}
Example #16
0
 /**
  * Registers the JSONRequestHandler with your application using the default key.
  *
  * @return the request handler instance
  */
 public static JSONRequestHandler register() {
   JSONRequestHandler requestHandler = new JSONRequestHandler();
   WOApplication.application()
       .registerRequestHandler(requestHandler, JSONRequestHandler.RequestHandlerKey);
   return requestHandler;
 }
  // @Override
  public WOResponse handleRequest(WORequest request) {
    if (!ERSelenium.testsEnabled()) {
      return new WOResponse();
    }

    NSArray pathElements = request.requestHandlerPathArray();

    StringBuilder builder = new StringBuilder();
    Iterator iter = pathElements.iterator();
    while (iter.hasNext()) {
      builder.append(iter.next());
      if (iter.hasNext()) builder.append("/");
    }

    String filePath = builder.toString();
    log.debug("Processing file '" + filePath + "'");

    /*
     * Syncrhonization mistakes are possible here, but not fatal at all.
     * At the worst case the file will be read 2-or-more times instead of 1 (if process 1
     * checks that the file is not cached and process 2 does the same check before
     * process 1 has updated the cache).
     */

    CachedFile cachedFile;
    synchronized (_cache) {
      cachedFile = (CachedFile) _cache.objectForKey(filePath);
    }

    if (cachedFile == null) {
      cachedFile = new CachedFile();

      URL fileUrl =
          WOApplication.application()
              .resourceManager()
              .pathURLForResourceNamed(filePath, "ERSelenium", null);
      if (fileUrl == null) {
        throw new RuntimeException("Can't find specified resource ('" + filePath + "')");
      }
      cachedFile.mimeType =
          WOApplication.application().resourceManager().contentTypeForResourceNamed(filePath);
      if (cachedFile.mimeType == null) {
        throw new RuntimeException("Can't determine resource mime type ('" + filePath + "')");
      }

      try {
        cachedFile.data = new NSData(ERXFileUtilities.bytesFromInputStream(fileUrl.openStream()));
      } catch (Exception e) {
        throw new RuntimeException("Error reading file '" + fileUrl.getPath() + "'", e);
      }

      synchronized (_cache) {
        _cache.setObjectForKey(cachedFile, filePath);
      }
    }

    WOResponse response = new WOResponse();
    response.setHeader(cachedFile.mimeType, "content-type");
    response.setContent(cachedFile.data);

    NSNotificationCenter.defaultCenter()
        .postNotification(WORequestHandler.DidHandleRequestNotification, response);
    return response;
  }
  public WOResponse handleRequest(WORequest request) {
    WOResponse response = null;
    FileInputStream is = null;
    long length = 0;
    String contentType = null;
    String uri = request.uri();
    if (uri.charAt(0) == '/') {
      WOResourceManager rm = application.resourceManager();
      String documentRoot = documentRoot();
      File file = null;
      StringBuffer sb = new StringBuffer(documentRoot.length() + uri.length());
      String wodataKey = request.stringFormValueForKey("wodata");
      if (uri.startsWith("/cgi-bin") && wodataKey != null) {
        uri = wodataKey;
        if (uri.startsWith("file:")) {
          // remove file:/
          uri = uri.substring(5);
        } else {

        }
      } else {
        int index = uri.indexOf("/wodata=");

        if (index >= 0) {
          uri = uri.substring(index + "/wodata=".length());
        } else {
          sb.append(documentRoot);
        }
      }

      if (_useRequestHandlerPath) {
        try {
          WODynamicURL dynamicURL = new WODynamicURL(uri);
          String requestHandlerPath = dynamicURL.requestHandlerPath();
          if (requestHandlerPath == null || requestHandlerPath.length() == 0) {
            sb.append(uri);
          } else {
            sb.append("/");
            sb.append(requestHandlerPath);
          }
        } catch (Exception e) {
          throw new RuntimeException("Failed to parse URL '" + uri + "'.", e);
        }
      } else {
        sb.append(uri);
      }

      String path = sb.toString();
      try {
        path = path.replaceAll("\\?.*", "");
        if (request.userInfo() != null && !request.userInfo().containsKey("HttpServletRequest")) {
          /* PATH_INFO is already decoded by the servlet container */
          path = path.replace('+', ' ');
          path = URLDecoder.decode(path, CharEncoding.UTF_8);
        }
        file = new File(path);
        length = file.length();
        is = new FileInputStream(file);

        contentType = rm.contentTypeForResourceNamed(path);
        log.debug("Reading file '" + file + "' for uri: " + uri);
      } catch (IOException ex) {
        if (!uri.toLowerCase().endsWith("/favicon.ico")) {
          log.info("Unable to get contents of file '" + file + "' for uri: " + uri);
        }
      }
    } else {
      log.error("Can't fetch relative path: " + uri);
    }
    response = _generateResponseForInputStream(is, length, contentType);
    NSNotificationCenter.defaultCenter()
        .postNotification(WORequestHandler.DidHandleRequestNotification, response);
    response._finalizeInContext(null);
    return response;
  }
/**
 * Simple static resource request handler. Allows for better debugging and you can set the document
 * root via the system property <code>WODocumentRoot</code>.
 *
 * @author ak
 */
public class ERXStaticResourceRequestHandler extends WORequestHandler {

  private static Logger log = Logger.getLogger(ERXStaticResourceRequestHandler.class);

  private static WOApplication application = WOApplication.application();

  private String _documentRoot;

  private boolean _useRequestHandlerPath;

  public ERXStaticResourceRequestHandler() {
    _documentRoot = null;
  }

  /**
   * Creates a static resource handler for the given framework, which gives you nicer relative URLs
   * to work with. For instance, you could register a request handler "aj" that maps to the "Ajax"
   * framework, which would make URLs of the form "/aj/wonder.js" map onto Ajax's
   * WebServerResources/wonder.js folder.
   *
   * @param frameworkName the name of the framework to map to (or null/"app" for the application)
   */
  public ERXStaticResourceRequestHandler(String frameworkName) {
    if ("app".equals(frameworkName)) {
      frameworkName = null;
    }
    WODeployedBundle bundle =
        WOApplication.application().resourceManager()._cachedBundleForFrameworkNamed(frameworkName);
    File bundleFile = new File(bundle.bundlePath());
    if (bundle.isFramework()) {
      bundleFile = new File(bundleFile, "WebServerResources");
    } else {
      bundleFile = new File(new File(bundleFile, "Contents"), "WebServerResources");
    }
    _documentRoot = bundleFile.getAbsolutePath();
    _useRequestHandlerPath = true;
  }

  protected WOResponse _generateResponseForInputStream(InputStream is, long length, String type) {
    WOResponse response = application.createResponseInContext(null);
    if (is != null) {
      if (length != 0) {
        response.setContentStream(is, 50 * 1024, length);
      }
    } else {
      response.setStatus(404);
    }
    if (type != null) {
      response.setHeader(type, "content-type");
    }
    if (length != 0) {
      response.setHeader("" + length, "content-length");
    }
    return response;
  }

  private String documentRoot() {
    if (_documentRoot == null) {
      _documentRoot = ERXProperties.stringForKey("WODocumentRoot");
      if (_documentRoot == null) {
        NSBundle bundle = NSBundle.bundleForName("JavaWebObjects");
        NSDictionary dict =
            ERXDictionaryUtilities.dictionaryFromPropertyList("WebServerConfig", bundle);
        _documentRoot = (String) dict.objectForKey("DocumentRoot");
      }
    }
    return _documentRoot;
  }

  public WOResponse handleRequest(WORequest request) {
    WOResponse response = null;
    FileInputStream is = null;
    long length = 0;
    String contentType = null;
    String uri = request.uri();
    if (uri.charAt(0) == '/') {
      WOResourceManager rm = application.resourceManager();
      String documentRoot = documentRoot();
      File file = null;
      StringBuffer sb = new StringBuffer(documentRoot.length() + uri.length());
      String wodataKey = request.stringFormValueForKey("wodata");
      if (uri.startsWith("/cgi-bin") && wodataKey != null) {
        uri = wodataKey;
        if (uri.startsWith("file:")) {
          // remove file:/
          uri = uri.substring(5);
        } else {

        }
      } else {
        int index = uri.indexOf("/wodata=");

        if (index >= 0) {
          uri = uri.substring(index + "/wodata=".length());
        } else {
          sb.append(documentRoot);
        }
      }

      if (_useRequestHandlerPath) {
        try {
          WODynamicURL dynamicURL = new WODynamicURL(uri);
          String requestHandlerPath = dynamicURL.requestHandlerPath();
          if (requestHandlerPath == null || requestHandlerPath.length() == 0) {
            sb.append(uri);
          } else {
            sb.append("/");
            sb.append(requestHandlerPath);
          }
        } catch (Exception e) {
          throw new RuntimeException("Failed to parse URL '" + uri + "'.", e);
        }
      } else {
        sb.append(uri);
      }

      String path = sb.toString();
      try {
        path = path.replaceAll("\\?.*", "");
        if (request.userInfo() != null && !request.userInfo().containsKey("HttpServletRequest")) {
          /* PATH_INFO is already decoded by the servlet container */
          path = path.replace('+', ' ');
          path = URLDecoder.decode(path, CharEncoding.UTF_8);
        }
        file = new File(path);
        length = file.length();
        is = new FileInputStream(file);

        contentType = rm.contentTypeForResourceNamed(path);
        log.debug("Reading file '" + file + "' for uri: " + uri);
      } catch (IOException ex) {
        if (!uri.toLowerCase().endsWith("/favicon.ico")) {
          log.info("Unable to get contents of file '" + file + "' for uri: " + uri);
        }
      }
    } else {
      log.error("Can't fetch relative path: " + uri);
    }
    response = _generateResponseForInputStream(is, length, contentType);
    NSNotificationCenter.defaultCenter()
        .postNotification(WORequestHandler.DidHandleRequestNotification, response);
    response._finalizeInContext(null);
    return response;
  }
}
Example #20
0
  @SuppressWarnings("unchecked")
  @Override
  public WOResponse handleRequest(WORequest request) {
    WOApplication application = WOApplication.application();
    application.awake();
    try {
      WOContext context = application.createContextForRequest(request);
      WOResponse response = application.createResponseInContext(context);

      Object output;
      try {
        String inputString = request.contentString();
        JSONObject input = new JSONObject(inputString);
        String wosid = request.cookieValueForKey("wosid");
        if (wosid == null) {
          ERXMutableURL url = new ERXMutableURL();
          url.setQueryParameters(request.queryString());
          wosid = url.queryParameter("wosid");
          if (wosid == null && input.has("wosid")) {
            wosid = input.getString("wosid");
          }
        }
        context._setRequestSessionID(wosid);
        WOSession session = null;
        if (context._requestSessionID() != null) {
          session = WOApplication.application().restoreSessionWithID(wosid, context);
        }
        if (session != null) {
          session.awake();
        }
        try {
          JSONComponentCallback componentCallback = null;

          ERXDynamicURL url = new ERXDynamicURL(request._uriDecomposed());
          String requestHandlerPath = url.requestHandlerPath();
          JSONRPCBridge jsonBridge;
          if (requestHandlerPath != null && requestHandlerPath.length() > 0) {
            String componentNameAndInstance = requestHandlerPath;
            String componentInstance;
            String componentName;
            int slashIndex = componentNameAndInstance.indexOf('/');
            if (slashIndex == -1) {
              componentName = componentNameAndInstance;
              componentInstance = null;
            } else {
              componentName = componentNameAndInstance.substring(0, slashIndex);
              componentInstance = componentNameAndInstance.substring(slashIndex + 1);
            }

            if (session == null) {
              session = context.session();
            }

            String bridgesKey =
                (componentInstance == null) ? "_JSONGlobalBridges" : "_JSONInstanceBridges";
            Map<String, JSONRPCBridge> componentBridges =
                (Map<String, JSONRPCBridge>) session.objectForKey(bridgesKey);
            if (componentBridges == null) {
              int limit =
                  ERXProperties.intForKeyWithDefault(
                      (componentInstance == null)
                          ? "er.ajax.json.globalBacktrackCacheSize"
                          : "er.ajax.json.backtrackCacheSize",
                      WOApplication.application().pageCacheSize());
              componentBridges = new LRUMap<String, JSONRPCBridge>(limit);
              session.setObjectForKey(componentBridges, bridgesKey);
            }
            jsonBridge = componentBridges.get(componentNameAndInstance);
            if (jsonBridge == null) {
              Class componentClass = _NSUtilities.classWithName(componentName);
              JSONComponent component;
              if (JSONComponent.class.isAssignableFrom(componentClass)) {
                component =
                    (JSONComponent)
                        _NSUtilities.instantiateObject(
                            componentClass,
                            new Class[] {WOContext.class},
                            new Object[] {context},
                            true,
                            false);
              } else {
                throw new SecurityException(
                    "There is no JSON component named '" + componentName + "'.");
              }
              jsonBridge =
                  createBridgeForComponent(
                      component, componentName, componentInstance, componentBridges);
            }

            componentCallback = new JSONComponentCallback(context);
            jsonBridge.registerCallback(componentCallback, WOContext.class);
          } else {
            jsonBridge = _sharedBridge;
          }

          try {
            output = jsonBridge.call(new Object[] {request, response, context}, input);
          } finally {
            if (componentCallback != null) {
              jsonBridge.unregisterCallback(componentCallback, WOContext.class);
            }
          }

          if (context._session() != null) {
            WOSession contextSession = context._session();
            // If this is a new session, then we have to force it to be a cookie session
            if (wosid == null) {
              boolean storesIDsInCookies = contextSession.storesIDsInCookies();
              try {
                contextSession.setStoresIDsInCookies(true);
                contextSession._appendCookieToResponse(response);
              } finally {
                contextSession.setStoresIDsInCookies(storesIDsInCookies);
              }
            } else {
              contextSession._appendCookieToResponse(response);
            }
          }
          if (output != null) {
            response.appendContentString(output.toString());
          }

          if (response != null) {
            response._finalizeInContext(context);
            response.disableClientCaching();
          }
        } finally {
          try {
            if (session != null) {
              session.sleep();
            }
          } finally {
            if (context._session() != null) {
              WOApplication.application().saveSessionForContext(context);
            }
          }
        }
      } catch (NoSuchElementException e) {
        e.printStackTrace();
        output =
            new JSONRPCResult(
                JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
      } catch (JSONException e) {
        e.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
      } catch (Throwable t) {
        t.printStackTrace();
        output = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, t.getMessage());
      }

      return response;
    } finally {
      application.sleep();
    }
  }
Example #21
0
 /** Retourne la reference vers la session de travail d'utilisateur. */
 public Application dtApp() {
   return (Application) WOApplication.application();
 }
Example #22
0
 public WOActionResults offlineAction() {
   LOG.info("offlineAction: ");
   Application application = (Application) WOApplication.application();
   ((Application) application).setOffline(true);
   return pageWithName(PachydermOffline.class);
 }
Example #23
0
 public WOActionResults onlineAction() {
   LOG.info("onlineAction: ");
   Application application = (Application) WOApplication.application();
   ((Application) application).setOffline(false);
   return defaultAction();
 }
  public WOResponse _handleRequest(WORequest request) {
    // Retrieve the application object. We need to inform it of awake/sleep
    // and use some of its helper methods.
    WOApplication application = Application.app();

    WOResponse response;
    WOContext context;

    application.awake();
    try {
      // Instantiate the action object for this request.
      // The WOAction sets up the context and restores the session and so
      // on.
      WOAction action = new ContentAction(request);

      // Retrieve the context object from the action.
      context = action.context();

      // Retrieve the content path. e.g. blog or blog/2009/10/10/foobar or
      // whatever.
      String contentPath = request.requestHandlerPath();

      // TODO: We probably could use some exception handling here.
      // 1. performActionNamed throws generating the WOActionResults
      // 2. performActionNamed returns null
      // 3. generateResponse throws
      // 4. generateResponse returns null (although we do kind of handle
      // this already).

      // Ask the action object to handle the request. Unlike normal action
      // objects the
      // ContentAction object takes a path instead of the first part of a
      // method name.
      WOActionResults actionResults = action.performActionNamed(contentPath);

      // Generate the response object.
      if (actionResults != null) response = actionResults.generateResponse();
      else response = null;

      // FIXME: When we do add error handling, do we or don't we save the
      // session in the
      // event of an error?
      if (context != null) {
        // Check the session in to the session store. Particularly
        // important if the
        // session store is out of process.
        application.saveSessionForContext(context);
      }
    } finally {
      // End of request.
      application.sleep();
    }

    // Ah, the joys of calling private APIs. For some reason both
    // WOActionRequestHandler
    // and WOComponentRequestHandler know about and call this method as
    // virtually the
    // last thing before returning the response. I am somewhat unclear as to
    // why this
    // method is private and why it isn't called by our caller instead of
    // within the
    // request handler.
    // It is imperative that this method be called because it generates HTTP
    // Set-Cookie
    // headers from the NSArray<WOCookie>. Without this no cookies will ever
    // function.
    if (response != null) response._finalizeInContext(context);

    return response;
  }
 /**
  * Registers an ERXRestRequestHandler with the WOApplication for the handler key "rest".
  *
  * @param requestHandler the rest request handler to register
  */
 public static void register(ERXRouteRequestHandler requestHandler) {
   WOApplication.application().registerRequestHandler(requestHandler, ERXRouteRequestHandler.Key);
 }