Ejemplo n.º 1
0
pbool PIni::load(const pchar *filename)
{
    //
    // Look for the file in the specified path
    //
    const pchar* pathList[] =
    {
        ".",
        pPathGetApplicationDirectory(),
        pPathGetExternalStoragePath(),
    };

    for (size_t i = 0; i < sizeof(pathList) / sizeof(pathList[0]); ++i)
    {
        if (pathList[i] != P_NULL)
        {
            PString cfgPath = PString(pathList[i]) + PString(pPathGetDelimiter()) + PString(filename);
            PFile *fp = pfopen(cfgPath.c_str(), "rb");
            if (fp != P_NULL)
            {
                if (ini_parse_file((FILE *)(fp), iniHandler_internal, this) < 0)
                {
                    PLOG_ERROR("Failed to parse %s", cfgPath.c_str());
                    pfclose(fp);
                    return false;
                }
                pfclose(fp);

                return true;
            }
        }
    }

    //
    // Look for the ini file in asset
    //
    PAsset asset = pAssetOpen(filename);
    if (pAssetIsValid(&asset))
    {
        PIniBufferObject iniBufferObject;
        iniBufferObject.m_buffer = (const pchar*)pAssetGetBuffer(&asset);
        iniBufferObject.m_bufferSize = pAssetGetSize(&asset);
        iniBufferObject.m_position = 0;
        
        if (ini_parse_buffer(&iniBufferObject, iniHandler_internal, this) < 0)
        {
            PLOG_ERROR("Failed to parse %s", filename);
            pAssetClose(&asset);
            return false;
        }

        pAssetClose(&asset);
        
        return true;
    }

    PLOG_ERROR("Failed to find %s", filename);
    
    return false;
}
Ejemplo n.º 2
0
void PStreamFile::close()
{
    if (m_file != P_NULL)
    {
        pfclose(m_file);
        m_file = P_NULL;
    }
}
Ejemplo n.º 3
0
void dyv_write_fname( char *filename, const dyv *dv)
{
  PFILE *f;
  f = sure_pfopen( filename, "wb");
  dyv_write( f, dv);
  pfclose( f);
  return;
}
Ejemplo n.º 4
0
dyv *mk_dyv_read_fname( char *filename)
{
  PFILE *f;
  dyv *dv;
  f = sure_pfopen( filename, "rb");
  dv = mk_dyv_read( f);
  pfclose( f);
  return dv;
}
Ejemplo n.º 5
0
/**
 * Destroys the logger.  This function is responsible to deallocate any
 * resources used by the logger.  In particular, if buffering is internally
 * used, it needs to flush the buffer.
 */
static void FileLoggerDestroy(PLogger *self)
{
  FileLogger *p = STATIC_CAST(self, FileLogger, base);
  pfflush(p->fp);
  
  if (p->fp != PSTDERR && p->fp != PSTDOUT)
    pfclose(p->fp);
  FREE(p);
}
Ejemplo n.º 6
0
void P_APIENTRY pAssetClose(PAsset *asset)
{
    PASSERT(asset != P_NULL);
    if (asset != P_NULL)
    {
        PFile *fp = (PFile *)asset->pHandle;
        pfclose(fp);
        asset->pHandle = P_NULL;

        PDELETEARRAY(asset->pData);
    }
}
Ejemplo n.º 7
0
ESR_ReturnCode SR_EventLog_AudioClose(SR_EventLog* self)
{
  SR_EventLogImpl *impl = (SR_EventLogImpl*) self;
  ESR_ReturnCode rc;

  /* impl->waveform_num_bytes has likely grown so we need to update the header before closing the file */
  CHKLOG(rc, writeRiffHeader(self));
  if (pfclose(impl->waveformFile))
  {
    rc = ESR_CLOSE_ERROR;
    PLogError(ESR_rc2str(rc));
    goto CLEANUP;
  }
  impl->waveformFile = NULL;
  return ESR_SUCCESS;
CLEANUP:
  return rc;
}
Ejemplo n.º 8
0
int main (int argc, char **argv)
{
   PFILE *pf;
   int i;
   char data[1024];

   // Identify ourself and parentage
   printf("Before PFOPEN: Pid=%d, PGrp=%d, PPid=%d\n", getpid(), getpgrp(), getppid());
   fflush(stdout);

   // pfopen
   if ((pf = pfopen("pgrp", "r")) == NULL)
   {
      fprintf(stderr, "Main: pfopen failed: %s\n", strerror(errno));
      exit(1);
   }

   // Read child output
   printf("Child Output:\n");
   fflush(stdout);
   i = 0;
   while (i < 2 && fgets(data, sizeof(data), PF_OUT(pf)) != NULL)
   {
      printf("%s", data);
      i++;
   }
   printf("*** END of child output ***\n");
   fflush(stdout);

   // Terminate child process
   printf("Sending group term signal to child process group\n");
   fflush(stdout);
   pfkill(pf, SIGTERM);
   
   // Close pipe to child process
   printf("Closing connection to child process\n");
   fflush(stdout);
   pfclose(pf);

   printf("SUCCESS\n");
   fflush(stdout);

   exit(0);
}
Ejemplo n.º 9
0
ESR_ReturnCode SR_EventLog_Destroy(SR_EventLog* self)
{
  SR_EventLogImpl* impl = (SR_EventLogImpl*) self;
  ESR_ReturnCode rc;

  if (impl->logFile_state == FILE_OK)
  {
    pfflush(impl->logFile);

    pfclose(impl->logFile);
    impl->logFile = NULL;
    impl->logFile_state = NO_FILE;
  }
  CHKLOG(rc, ESR_SessionRemoveProperty(L("eventlog")));
  FREE(impl);
  return ESR_SUCCESS;
CLEANUP:
  return rc;
}
Ejemplo n.º 10
0
ESR_ReturnCode SR_NametagsLoadImpl(SR_Nametags* self, const LCHAR* filename)
{
  SR_NametagsImpl* impl = (SR_NametagsImpl*) self;
  ESR_ReturnCode rc;
  PFile* file = NULL;
  LCHAR line[256];
  LCHAR* result = NULL;
  LCHAR* id;
  LCHAR* value;
  SR_Nametag* newNametag = NULL;
  SR_Nametag* oldNametag;
  HashMap* nametags = impl->value;
  size_t size, len, i;
  LCHAR devicePath[P_PATH_MAX];
  LCHAR number[MAX_UINT_DIGITS+1];
#define NAMETAGID_LENGTH 20
  /* strlen("token\0") == 6 */
#define TOKEN_LENGTH 6 + NAMETAGID_LENGTH
  LCHAR tokenName[TOKEN_LENGTH];

  if (filename == NULL)
  {
    rc = ESR_INVALID_STATE;
    PLogError(ESR_rc2str(rc));
    goto CLEANUP;
  }
  size = P_PATH_MAX;
  CHKLOG(rc, ESR_SessionGetLCHAR(L("cmdline.nametagPath"), devicePath, &size));
  /* check if the filename has the path */
  if (LSTRNCMP(filename, devicePath, LSTRLEN(devicePath)) != 0)
    LSTRCAT(devicePath, filename);
  else
    LSTRCPY(devicePath, filename);
  file = pfopen ( devicePath, L("r"));
/*  CHKLOG(rc, PFileSystemCreatePFile(devicePath, ESR_TRUE, &file));
  CHKLOG(rc, file->open(file, L("r")));*/

  if ( file == NULL )
    goto CLEANUP;

  /* Flush collection */
  CHKLOG(rc, nametags->getSize(nametags, &size));
  for (i = 0; i < size; ++i)
  {
    CHKLOG(rc, nametags->getValueAtIndex(nametags, 0, (void **)&oldNametag));
    CHKLOG(rc, nametags->removeAtIndex(nametags, 0));
    CHKLOG(rc, oldNametag->destroy(oldNametag));
  }
  len = MAX_UINT_DIGITS + 1;
  CHKLOG(rc, lultostr(size, number, &len, 10));
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("removeCount"), number));

  while (ESR_TRUE)
  {
    result = pfgets ( line, 256, file );
    if (result == NULL)
      break;
    if (LSTRLEN(line) == 255)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    lstrtrim(line);

    /* Get the Nametag ID */
    id = line;

    /* Find next whitespace */
    for (value = id + 1; *value != L('\0') && !LISSPACE(*value); ++value);
    if (*value == L('\0'))
    {
      rc = ESR_INVALID_STATE;
      PLogError(L("%s: Cannot find end of Nametag id"), ESR_rc2str(rc));
      goto CLEANUP;
    }
    /* Delimit end of nametag ID */
    *value = L('\0');

    /* Find next non-whitespace */
    for (++value; *value != L('\0') && LISSPACE(*value); ++value);
    if (*value == L('\0'))
    {
      rc = ESR_INVALID_STATE;
      PLogError(L("%s: Cannot find Nametag value"), ESR_rc2str(rc));
      goto CLEANUP;
    }

    /* We now have both the Nametag ID and value */
	len = (LSTRLEN(value)+1) * sizeof(LCHAR) ;
    CHKLOG(rc, SR_NametagCreateFromValue(id, (const char*)value, len, &newNametag));
    /* Add Nametag to collection */
    CHKLOG(rc, impl->value->put(impl->value, id, newNametag));

    if (LSTRLEN(id) > NAMETAGID_LENGTH)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    psprintf(tokenName, L("nametag[%s]"), id);
    CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, tokenName, value));
    newNametag = NULL;
  }
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("filename"), filename));
  CHKLOG(rc, nametags->getSize(nametags, &size));
  len = MAX_UINT_DIGITS + 1;
  CHKLOG(rc, lultostr(size, number, &len, 10));
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("addCount"), number));
  CHKLOG(rc, SR_EventLogEvent_BASIC(impl->eventLog, impl->logLevel, L("SR_NametagsLoad")));
  pfclose (file);
  return ESR_SUCCESS;
CLEANUP:
  if (file != NULL)
    pfclose (file);
  if (newNametag != NULL)
    newNametag->destroy(newNametag);
  return rc;
}
Ejemplo n.º 11
0
ESR_ReturnCode SR_NametagsSaveImpl(SR_Nametags* self, const LCHAR* filename)
{
  SR_NametagsImpl* impl = (SR_NametagsImpl*) self;
  ESR_ReturnCode rc;
  PFile* file = NULL;
  size_t size, i;
  HashMap* nametags = impl->value;
  SR_NametagImpl* nametag;
  LCHAR* id;
  size_t len;
  LCHAR devicePath[P_PATH_MAX];
#define NAMETAG_LENGTH 200
  LCHAR nametagBuffer[NAMETAG_LENGTH];
  LCHAR number[MAX_UINT_DIGITS+1];
#define NAMETAGID_LENGTH 20
  /* "token\0" == 6 */
#define TOKEN_LENGTH 6 + NAMETAGID_LENGTH
  LCHAR tokenName[TOKEN_LENGTH];
  size_t num_written;

  if (filename == NULL)
  {
    rc = ESR_INVALID_STATE;
    PLogError(ESR_rc2str(rc));
    goto CLEANUP;
  }
  size = P_PATH_MAX;
  CHKLOG(rc, ESR_SessionGetLCHAR(L("cmdline.nametagPath"), devicePath, &size));

  if (LSTRNCMP(filename, devicePath, LSTRLEN(devicePath)) != 0)
    LSTRCAT(devicePath, filename);
  else
    LSTRCPY(devicePath, filename);

  file = pfopen ( devicePath, L("w"));
/*  CHKLOG(rc, PFileSystemCreatePFile(devicePath, ESR_TRUE, &file));
  CHKLOG(rc, file->open(file, L("w")));*/
  CHKLOG(rc, nametags->getSize(nametags, &size));

  if ( file == NULL )
    goto CLEANUP;

  for (i = 0; i < size; ++i)
  {
    CHKLOG(rc, nametags->getValueAtIndex(nametags, i, (void **)&nametag));

    CHKLOG(rc, nametag->Interface.getID(&nametag->Interface, &id));

    if (LSTRLEN(id) + 1 + LSTRLEN(nametag->value) + 2 >= NAMETAG_LENGTH)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    psprintf(nametagBuffer, L("%s %s\n"), id, nametag->value);
    len = LSTRLEN(nametagBuffer);
/*    CHKLOG(rc, file->write(file, nametagBuffer, sizeof(LCHAR), &len));*/
    num_written = pfwrite ( nametagBuffer, sizeof ( LCHAR ), len, file );

    if ( num_written != len )
        goto CLEANUP;

    if (LSTRLEN(id) > NAMETAGID_LENGTH)
    {
      rc = ESR_BUFFER_OVERFLOW;
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }
    psprintf(tokenName, L("nametag[%s]"), id);
    CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, tokenName, nametag->value));
  }
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("filename"), filename));
  len = MAX_UINT_DIGITS + 1;
  CHKLOG(rc, lultostr(size, (LCHAR*) &number, &len, 10));
  CHKLOG(rc, SR_EventLogToken_BASIC(impl->eventLog, impl->logLevel, L("saveCount"), number));
  CHKLOG(rc, SR_EventLogEvent_BASIC(impl->eventLog, impl->logLevel, L("SR_NametagsSave")));
  pfclose (file);
  return ESR_SUCCESS;
CLEANUP:
  if (file != NULL)
    pfclose (file);
  return rc;
}
Ejemplo n.º 12
0
ESR_ReturnCode SR_EventLogCreate(SR_EventLog** self)
{
  SR_EventLogImpl *impl, *any_existing_eventlog;
  ESR_ReturnCode rc;
  LCHAR* dataCaptureDir;
#define TIMESTAMP_LENGTH 18
  LCHAR timeStr[TIMESTAMP_LENGTH];
  struct tm *ct, ct_r;
  PTimeStamp timestamp;
#ifdef ANDROID
  struct timeval dir_stamp;
#endif

  if (self == NULL)
  {
    PLogError(L("ESR_INVALID_ARGUMENT"));
    return ESR_INVALID_ARGUMENT;
  }

  any_existing_eventlog = NULL;
  rc = ESR_SessionGetProperty(L("eventlog"), (void **)&any_existing_eventlog, TYPES_SR_EVENTLOG);
  if (rc == ESR_SUCCESS && any_existing_eventlog)
  {
    *self = (SR_EventLog*)any_existing_eventlog;
    PLogError("eventlog was already created");
    return ESR_SUCCESS;
  }

  impl = NEW(SR_EventLogImpl, MTAG);
  if (impl == NULL)
  {
    PLogError(L("ESR_OUT_OF_MEMORY"));
    return ESR_OUT_OF_MEMORY;
  }

  impl->Interface.destroy = &SR_EventLog_Destroy;
  impl->Interface.event = &SR_EventLog_Event;
  impl->Interface.token = &SR_EventLog_Token;
  impl->Interface.tokenInt = &SR_EventLog_TokenInt;
  impl->Interface.tokenPointer = &SR_EventLog_TokenPointer;
  impl->Interface.tokenUint16_t = &SR_EventLog_TokenUint16_t;
  impl->Interface.tokenSize_t = &SR_EventLog_TokenSize_t;
  impl->Interface.tokenBool = &SR_EventLog_TokenBool;
  impl->Interface.tokenFloat = &SR_EventLog_TokenFloat;
  impl->Interface.eventSession = &SR_EventLogEventSessionImpl;
  impl->Interface.audioOpen = &SR_EventLog_AudioOpen;
  impl->Interface.audioClose = &SR_EventLog_AudioClose;
  impl->Interface.audioWrite = &SR_EventLog_AudioWrite;
  impl->Interface.audioGetFilename = &SR_EventLog_AudioGetFilename;
  impl->sessionListenerPair.data = NULL;
  impl->sessionListenerPair.listener = &impl->sessionListener;
  impl->sessionListener.propertyChanged = &propertyChanged;
  impl->waveformCounter = 0;
  impl->logFile = NULL;
  impl->tokenBuf[0] = 0;
  impl->logFile_state = NO_FILE;
  impl->logLevel = 0;
  impl->waveformFile = NULL;
  LSTRCPY(impl->logFilename, L(""));

  CHKLOG(rc, ESR_SessionSetProperty(L("eventlog"), impl, TYPES_SR_EVENTLOG));
  rc = ESR_SessionGetSize_t(L("SREC.Recognizer.osi_log_level"), &impl->logLevel);
  if (rc == ESR_NO_MATCH_ERROR)
  {
    impl->logLevel = 7;
    CHKLOG(rc, ESR_SessionSetSize_t(L("SREC.Recognizer.osi_log_level"), impl->logLevel));
  }
  else if (rc != ESR_SUCCESS)
  {
    PLogError(ESR_rc2str(rc));
    goto CLEANUP;
  }

  if (impl->logLevel > 0)
  {
    CHKLOG(rc, ESR_SessionGetProperty(L("cmdline.DataCaptureDirectory"), (void**) &dataCaptureDir, TYPES_PLCHAR));

    LSTRCPY(impl->logFilename, dataCaptureDir);
#ifdef ANDROID
/*
 * The existing functions did not work on the desired platform, hence this code for the device.
 */
    gettimeofday ( &dir_stamp, NULL );
    sprintf(timeStr, "%lu", (unsigned long) dir_stamp.tv_sec );
#else
    PTimeStampSet(&timestamp);
    ct = localtime_r(&timestamp.secs, &ct_r);
    sprintf(timeStr, "%04d%02d%02d%02d%02d%02d",
            ct->tm_year + 1900, ct->tm_mon + 1, ct->tm_mday, ct->tm_hour,
            ct->tm_min, ct->tm_sec);
#endif
    /* create capture directory if it doesn't already exist */
    rc = pf_make_dir (impl->logFilename);
    if (rc != ESR_SUCCESS && rc != ESR_IDENTIFIER_COLLISION)
    {
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }

    /* create the directory for today's log if it doesn't already exist */
    LSTRCAT(impl->logFilename, L("/"));
    LSTRCAT(impl->logFilename, timeStr);
/*
 * There used to be a while forever loop here with a break, but that caused an infinite loop
 * for the customer. With 1 second resolution, a pre-existing directory probably means a bug.
 * It's not worth trying to handle this.
 */
    rc = pf_make_dir (impl->logFilename);
    if (rc != ESR_SUCCESS)
    {
      PLogError(ESR_rc2str(rc));
      goto CLEANUP;
    }

    /* create the log file */
    LSTRCAT(impl->logFilename, L("/SWIevent-"));
    LSTRCAT(impl->logFilename, timeStr);
    LSTRCAT(impl->logFilename, L(".log"));

    impl->logFile = pfopen ( impl->logFilename, L("w") );
/*    CHKLOG(rc, PFileSystemCreatePFile(impl->logFilename, ESR_TRUE, &impl->logFile));
    CHKLOG(rc, PFileOpen(impl->logFile, L("w")));*/

    if ( impl->logFile != NULL )
        impl->logFile_state = FILE_OK;
    else
        goto CLEANUP;
  }

  *self = (SR_EventLog*) impl;
  return ESR_SUCCESS;
CLEANUP:
  if (impl->logFile)
    pfclose (impl->logFile);
  return rc;
}
Ejemplo n.º 13
0
int init_newton_transform(preprocessed *prep, float reqscale,
                          char *filename, int dimen)
/*
*/
{
  int  ii, jj;
  unsigned short matdim;
  double scale, onerow[MAX_DIMEN];
  PFile* dfpt;
  long foffset;
  double xfp;
  /* Open file
  */
  ASSERT(prep);
  ASSERT(filename);
  dfpt = file_must_open(NULL, filename, ("rb"), ESR_TRUE);
  prep->post_proc |= LIN_TRAN;
  prep->use_dim = dimen;
  pfread(&matdim, sizeof(short), 1, dfpt);
  if (matdim > MAX_DIMEN)
    SERVICE_ERROR(BAD_IMELDA);

  create_linear_transform(prep, matdim, 1);
  pfread(&scale, sizeof(double), 1, dfpt);

  if (reqscale != 0) scale = reqscale;
#if DEBUG
  PLogMessage("L: LDA Suggested scale is %.1f\n", scale);
#endif
  if (!prep->dim) prep->dim = matdim;
  else if (prep->dim != matdim)
  {
    log_report("Data (%d) and LDA (%d) dimensions don't match\n",
               prep->dim, matdim);
    SERVICE_ERROR(BAD_IMELDA);
  }

  /*  Eigenvalues, ignored
  */
  pfread(onerow, sizeof(double), matdim, dfpt);

  /*  Translation Vector
  */
  pfread(onerow, sizeof(double), matdim, dfpt);
  for (ii = 0; ii < matdim; ii++)
  {
    xfp = scale * (onerow[ii] - UTB_MEAN) + UTB_MEAN;
    if (xfp > 0.0)
      xfp += 0.5;
    else if (xfp < 0.0)
      xfp -= 0.5;

    prep->offset[ii] = (imeldata) xfp;
  }

  /*  The imelda matrix
  */
  for (ii = 0; ii < matdim; ii++)
  {
    pfread(onerow, sizeof(double), matdim, dfpt);
    for (jj = 0; jj < matdim; jj++)
      prep->imelda[ii][jj] = (covdata)(scale * onerow[jj]);
  }

  prep->imel_shift = scale_matrix_for_fixedpoint(prep->matrix,
                     prep->imelda, matdim);

  /* The inverse imelda matrix
   */
  foffset = pftell(dfpt);
  pfread(onerow, sizeof(double), matdim, dfpt);

  if (pfeof(dfpt) != 0)
  {
#ifdef SREC_ENGINE_VERBOSE_LOGGING
    PLogMessage("W: Inverting imelda matrix");
#endif
    invert_matrix(prep->imelda, prep->inverse, prep->dim);
  }
  else
  {
    pfseek(dfpt, foffset, SEEK_SET);

    for (ii = 0; ii < matdim; ii++)
    {
      pfread(onerow, sizeof(double), matdim, dfpt);
      for (jj = 0; jj < matdim; jj++)
        prep->inverse[ii][jj] = (covdata)(onerow[jj] / scale);
    }
  }

  prep->inv_shift = scale_matrix_for_fixedpoint(prep->invmat,
                    prep->inverse, matdim);

  pfclose(dfpt);
  return (0);
}
Ejemplo n.º 14
0
/*
 *  When we come here, we've already matched either a location block or an extension
 */
static int run(request_rec *r) 
{
    EjsDirConfig        *dir;
    EjsServerConfig     *server;
    cchar               *ext;

    MaRequest       *req;
    MaResponse      *resp;
    MaConn          *conn;
    MaAlias         *alias;
    MaLocation      *location;
    EjsWeb          *web;
    cchar           *sep, *prefix;
    char            *urlBase, *dir, *app, *url, *cp;
    int             flags, locFlags;

    if (!r->handler || strcasecmp(r->handler, "ejs") != 0) {
        return DECLINED;
    }

    dir = getDir(r)
    server = getServer(r->XXX);

    //  EjsAlias should probably be creating a directory block. These flags should probably be in a directory
    if (loc->flags & (MA_LOC_APP | MA_LOC_APP_DIR)) {

        /*
         *  Send non-ejs content under web to another handler, typically the file handler.
         */
        if (strncmp(&req->url[loc->prefixLen], "web/", 4) == 0) {
            if (!(ext && strcmp(ext, "ejs") == 0)) {
                return DECLINED;
            }

        } else {
            if (ext && strcmp(ext, "ejs") == 0) {
                maFormatBody(conn, "Bad Request", "Can't serve *.ejs files outside web directory");
                maFailRequest(conn, MPR_HTTP_CODE_BAD_REQUEST, "Can't server *.ejs files outside web directory");
                return HTTP_XXX;
            }
        }
    }

    flags = 0;
    url = 0;

    locFlags = location->flags;
    
    if (locFlags & MA_LOC_APP) {
        app = mprStrTrim(mprStrdup(q, prefix), "/");
        url = &req->url[alias->prefixLen];
        dir = mprStrdup(resp, alias->filename);
        if (*url != '/') {
            url--;
        }
        urlBase = mprStrdup(resp, prefix);
        
    } else if (locFlags & MA_LOC_APP_DIR) {
        url = &req->url[alias->prefixLen];
        app = mprStrdup(resp, url);
        if ((cp = strchr(app, '/')) != 0) {
            url = mprStrdup(resp, cp);
            *cp = '\0';
        }
        sep = prefix[strlen(prefix) - 1] == '/' ? "" : "/";
        dir = mprStrcat(resp, &dir, alias->filename, sep, app, NULL);
        urlBase = mprStrcat(resp, prefix, sep, app, NULL);

    } else {
        app = 0;
        dir = mprStrdup(resp, alias->filename);
        url = &req->url[alias->prefixLen];
        flags |= EJS_WEB_FLAG_SOLO;
        if (*url != '/') {
            url--;
        }        
        urlBase = mprStrdup(resp, prefix);
    }
    mprStrTrim(urlBase, "/");
    mprStrTrim(dir, "/");
    
    if (location->flags & MA_LOC_BROWSER) {
        flags |= EJS_WEB_FLAG_BROWSER_ERRORS;
    }
    if (location->flags & MA_LOC_AUTO_SESSION) {
        flags |= EJS_WEB_FLAG_SESSION;
    }

    /*
     *  Var         Stand-Alone             App                         AppDir
     *  app         0                       carmen                      carmen
     *  dir         /Users/mob/....         /Users/mob/hg/carmen        /Users/mob/hg/carmen
     *  urlBase                             /xg/carmen                  /carmen
     *  url                                 stock                       stock
     */
    web = ejsCreateWebRequest(req, q->stage->stageData, conn, app, dir, urlBase, url, req->cookie, flags);
    if (web == 0) {
        maFailRequest(conn, MPR_HTTP_CODE_INTERNAL_SERVER_ERROR, "Can't create Ejs web object for %s", req->url);
        return;
    }
    q->queueData = web;
    maSetHeader(conn, 0, "Last-Modified", req->host->currentDate);
    maDontCacheResponse(conn);

    if (r->method_number != M_GET) {
        return HTTP_METHOD_NOT_ALLOWED;
    }

    if (ejsProcessWebRequest((EjsWeb*) r, &msg) < 0) {
        if (web->flags & EJS_WEB_FLAG_BROWSER_ERRORS) {
            maFormatBody(conn, "Request Failed", "%s", msg);
        }
        maFailRequest(conn, MPR_HTTP_CODE_BAD_GATEWAY, msg);
        mprFree(msg);
    }

    ap_set_content_type(r, "text/html");
    ap_rputs("<html><title>Hello World!</title><body><p>Hello World</p></body></html>\r\n", r);

#if 0
    if ((err = set_content_length(r, r->finfo.st_stize)) || (err = set_last_modified(r, r->finfo.st_mtime)))
        return err;
    if (r->finof.st_mode == 0) 
        return NOT_FOUND;
    fopen(r->filename, "r");

    if (!r->main) {
        /* Not internal redirect */
        apr_table_set(r->headers_out, "X-ejs", "Under construction");
    }
    register_timeout("send", r);
    send_http_header(r);
    if (!r->header_only)
        send_fd(f, r);
    pfclose(r->pool, f);
#endif

    return OK;
}
Ejemplo n.º 15
0
int main(int argc, char **argv)
{
  LCHAR phrase[MAX_LINE_LENGTH];
  SR_Vocabulary *vocab = 0;
  LCHAR vocabfile[MAX_LINE_LENGTH];
  LCHAR outfilename[MAX_LINE_LENGTH];
  LCHAR testfilename[MAX_LINE_LENGTH];
  LCHAR parfilename[MAX_LINE_LENGTH];
  LCHAR wordfile[MAX_LINE_LENGTH];
  LCHAR locale[MAX_LINE_LENGTH];
  LCHAR ptemp[MAX_LINE_LENGTH];
  LCHAR* p;
  ESR_ReturnCode rc;
  int i;
  PFile* fin = 0;
  FILE* fout = stdout;
  size_t len;
  ESR_BOOL bSession = ESR_FALSE;

  LCHAR *env_sdk_path;
  LCHAR *env_lang;

  CHKLOG(rc, PMemInit());
/*  CHKLOG(rc, PFileSystemCreate());
    CHKLOG(rc, PANSIFileSystemCreate());
    CHKLOG(rc, PANSIFileSystemAddPath(L("/dev/ansi"), L("/")));*/

    /* Set ANSI file-system as default file-system */
/*  CHKLOG(rc, PANSIFileSystemSetDefault(ESR_TRUE));*/
    /* Set virtual current working directory to native current working directory */
/*  len = P_PATH_MAX;
    CHKLOG(rc, PANSIFileSystemGetcwd(cwd, &len));
    CHKLOG(rc, PFileSystemChdir(cwd));*/

    fout = stdout;
  *vocabfile = 0;
  *wordfile = 0;
  *locale = 0;
  *outfilename = 0;
  *testfilename = 0;
  *parfilename = 0;

  /* get some phrases from the user */
  LPRINTF("\nDictation Test Program for esr (Nuance Communications, 2007)\n");

  if(argc != 1 && argc != 3 && argc != 5 && argc != 7 && argc != 9)
  {
    usage();
        rc = 1;
    goto CLEANUP;
  }

  for(i=1; i<argc; i++)
  {
    if(!LSTRCMP(argv[i], L("-words")))
      LSTRCPY(wordfile, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-vocab")))
      LSTRCPY(vocabfile, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-locale")))
      LSTRCPY(locale, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-out")))
      LSTRCPY(outfilename, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-itest")))
      LSTRCPY(testfilename, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-parfile")) || !LSTRCMP(argv[i], L("-par")) )
      LSTRCPY(parfilename, argv[++i]);
    else {
      usage();
      rc = 1;
      goto CLEANUP;
    }
  }

  if ( *parfilename == L('\0') )
  {
    LPRINTF ( "Warning: No parfile defined in the command line.\n" );
    LPRINTF ( "Looking for the default parfile, $ESRSDK/config/$ESRLANG/baseline.par...\n" );

    env_sdk_path =  LGETENV(L("ESRSDK"));
    if ( env_sdk_path != NULL )
    {
      LSPRINTF ( parfilename, L("%s/config/"), env_sdk_path );
      env_lang = LGETENV(L("ESRLANG"));
      if ( env_lang != NULL )
      {
         LSTRCAT ( parfilename, env_lang );
         LSTRCAT ( parfilename, L("/baseline.par") );
      }
      else
      {
        LPRINTF("Error: An environment variable ESRLANG should be defined.\n");
        goto CLEANUP;
      }
    }
    else
    {
      LPRINTF("Error: An environment variable ESRSDK should be defined.\n");
      goto CLEANUP;
    }
  }

  rc = InitSession( parfilename );
  if ( rc != ESR_SUCCESS )
  {
    LPRINTF("Error: %s\n", ESR_rc2str(rc));
    goto CLEANUP;
  }
  bSession = ESR_TRUE;

  if (*vocabfile == 0)
  {
    len = sizeof(vocabfile);
    rc = ESR_SessionGetLCHAR ( L("cmdline.vocabulary"), vocabfile, &len );
    env_sdk_path =  LGETENV(L("ESRSDK"));
    if ( env_sdk_path != NULL )
      {
	LSPRINTF ( parfilename, L("%s/config/"), env_sdk_path );
	env_lang = LGETENV(L("ESRLANG"));
	if ( env_lang != NULL )
	  {
	    LSTRCAT ( parfilename, env_lang );
	    LSTRCAT ( parfilename, L("/baseline.par") );
	  }
	else
	  {
	    LPRINTF("Error: An environment variable ESRLANG should be defined.\n");
	    goto CLEANUP;
	  }
      }
    else
      {
	LPRINTF("Error: An environment variable ESRSDK should be defined.\n");
	goto CLEANUP;
      }

    strcpy(ptemp, env_sdk_path);
    strcat(ptemp,"/config/");
    strcat(ptemp,env_lang);
    strcat(ptemp,"/");
    strcat(ptemp,vocabfile);
    strcpy(vocabfile,ptemp);
    if ( rc == ESR_SUCCESS )
    {
      len = sizeof(vocabfile);
       rc = ESR_SessionPrefixWithBaseDirectory(vocabfile, &len);
    }
    else
    {
       *vocabfile = 0;
    }
  }

  if (*vocabfile)
    rc = SR_VocabularyLoad(vocabfile, &vocab);
  else if (*locale)
  {
    ESR_Locale localeTag;

    rc = ESR_str2locale(locale, &localeTag);
    if (rc != ESR_SUCCESS)
    {
      LPRINTF("Error: %s\n",ESR_rc2str(rc));
      goto CLEANUP;
    }
    rc = SR_VocabularyCreate(localeTag, &vocab);
  }
  else
    rc = SR_VocabularyCreate(ESR_LOCALE_EN_US, &vocab);

  if (rc != ESR_SUCCESS)
  {
    LPRINTF("Error: %s\n",ESR_rc2str(rc));
    goto CLEANUP;
  }

  if (*outfilename) /* output file */
  {
    if  ((fout = fopen(outfilename,"w")) == NULL)
    {
      LPRINTF("Could not open file: %s\n",outfilename);
      rc = 1;
      goto CLEANUP;
    }
  }

  if (*wordfile) /* file mode */
  {
    if ((fin = pfopen(wordfile,"r")) == NULL)
    {
      LPRINTF("Could not open file: %s\n", wordfile);
      goto CLEANUP;
    }
    while (pfgets(phrase, MAX_LINE_LENGTH, fin)!=NULL)
    {
      lstrtrim(phrase);
      doGetProns(vocab, phrase, MAX_PRONS_LENGTH, fout);
    }

  }
  else if (*testfilename) /* test file mode */
  {
    if ((fin = pfopen(testfilename,"r")) == NULL)
    {
      LPRINTF("Could not open file: %s\n", testfilename);
      rc = 1;
      goto CLEANUP;
    }
    doInputTestPhonemes(vocab, fin, fout);
  }
  else /* interactive mode */
  {
    LPRINTF("'qqq' to quit\n");
    while (ESR_TRUE)
    {
      LPRINTF("> ");
      if(! pfgets(phrase, MAX_LINE_LENGTH, PSTDIN ))
        break;
      // remove trailing whitespace
      for(p=&phrase[0]; *p!=0 && *p!='\n' && *p!='\r'; p++) {}
      *p=0;
      lstrtrim(phrase);
      if(!LSTRCMP("qqq",phrase))
        break;
      else
        doGetProns(vocab, phrase, MAX_PRONS_LENGTH, fout);
     }
  }

CLEANUP:
  if(vocab)
    vocab->destroy(vocab);

  if(bSession)
    ShutdownSession();

  if(fin)
    pfclose(fin);

  if(fout && fout != stdout)
    fclose(fout);

/*  PANSIFileSystemDestroy();
  PFileSystemDestroy();*/
  PMemShutdown();
  return rc;
}