예제 #1
0
파일: medium.cpp 프로젝트: Fat-Zer/tdebase
KURL Medium::prettyBaseURL() const
{
        if ( !baseURL().isEmpty() )
            return baseURL();

		return KURL( mountPoint() );
}
예제 #2
0
KURL CSSParserContext::completeURL(const String& url) const {
  if (url.isNull())
    return KURL();
  if (charset().isEmpty())
    return KURL(baseURL(), url);
  return KURL(baseURL(), url, charset());
}
void StyleSheetContents::parseAuthorStyleSheet(const CachedCSSStyleSheet* cachedStyleSheet, const SecurityOrigin* securityOrigin)
{
    // Check to see if we should enforce the MIME type of the CSS resource in strict mode.
    // Running in iWeb 2 is one example of where we don't want to - <rdar://problem/6099748>
    bool enforceMIMEType = isStrictParserMode(m_parserContext.mode) && m_parserContext.enforcesCSSMIMETypeInNoQuirksMode;
    bool hasValidMIMEType = false;
    String sheetText = cachedStyleSheet->sheetText(enforceMIMEType, &hasValidMIMEType);

    CSSParser p(parserContext());
    p.parseSheet(this, sheetText, 0);

    // If we're loading a stylesheet cross-origin, and the MIME type is not standard, require the CSS
    // to at least start with a syntactically valid CSS rule.
    // This prevents an attacker playing games by injecting CSS strings into HTML, XML, JSON, etc. etc.
    if (!hasValidMIMEType && !hasSyntacticallyValidCSSHeader()) {
        bool isCrossOriginCSS = !securityOrigin || !securityOrigin->canRequest(baseURL());
        if (isCrossOriginCSS) {
            clearRules();
            return;
        }
    }
    if (m_parserContext.needsSiteSpecificQuirks && isStrictParserMode(m_parserContext.mode)) {
        // Work around <https://bugs.webkit.org/show_bug.cgi?id=28350>.
        DEFINE_STATIC_LOCAL(const String, mediaWikiKHTMLFixesStyleSheet, (ASCIILiteral("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n")));
        // There are two variants of KHTMLFixes.css. One is equal to mediaWikiKHTMLFixesStyleSheet,
        // while the other lacks the second trailing newline.
        if (baseURL().string().endsWith("/KHTMLFixes.css") && !sheetText.isNull() && mediaWikiKHTMLFixesStyleSheet.startsWith(sheetText)
            && sheetText.length() >= mediaWikiKHTMLFixesStyleSheet.length() - 1)
            clearRules();
    }
예제 #4
0
KURL CSSStyleSheet::completeURL(const String& url) const
{
    // Always return a null URL when passed a null string.
    // FIXME: Should we change the KURL constructor to have this behavior?
    // See also Document::completeURL(const String&)
    if (url.isNull())
        return KURL();
    if (m_charset.isEmpty())
        return KURL(baseURL(), url);
    const TextEncoding encoding = TextEncoding(m_charset);
    return KURL(baseURL(), url, encoding);
}
예제 #5
0
void StyleSheetContents::parseAuthorStyleSheet(const CSSStyleSheetResource* cachedStyleSheet, const SecurityOrigin* securityOrigin)
{
    TRACE_EVENT0("webkit", "StyleSheetContents::parseAuthorStyleSheet");

    bool quirksMode = isQuirksModeBehavior(m_parserContext.mode());

    bool enforceMIMEType = !quirksMode;
    bool hasValidMIMEType = false;
    String sheetText = cachedStyleSheet->sheetText(enforceMIMEType, &hasValidMIMEType);

    CSSParserContext context(parserContext(), UseCounter::getFrom(this));
    BisonCSSParser p(context);
    p.parseSheet(this, sheetText, TextPosition::minimumPosition(), 0, true);

    // If we're loading a stylesheet cross-origin, and the MIME type is not standard, require the CSS
    // to at least start with a syntactically valid CSS rule.
    // This prevents an attacker playing games by injecting CSS strings into HTML, XML, JSON, etc. etc.
    if (!hasValidMIMEType && !hasSyntacticallyValidCSSHeader()) {
        bool isCrossOriginCSS = !securityOrigin || !securityOrigin->canRequest(baseURL());
        if (isCrossOriginCSS) {
            clearRules();
            return;
        }
    }
}
예제 #6
0
void
getAllImage(Buffer *buf)
{
    AnchorList *al;
    Anchor *a;
    ParsedURL *current;
    int i;

    image_buffer = buf;
    if (!buf)
	return;
    buf->image_loaded = TRUE;
    al = buf->img;
    if (!al)
	return;
    current = baseURL(buf);
    for (i = 0, a = al->anchors; i < al->nanchor; i++, a++) {
	if (a->image) {
	    a->image->cache = getImage(a->image, current, buf->image_flag);
	    if (a->image->cache &&
		a->image->cache->loaded == IMG_FLAG_UNLOADED)
		buf->image_loaded = FALSE;
	}
    }
}
예제 #7
0
void StyleSheetContents::parseAuthorStyleSheet(const CachedCSSStyleSheet* cachedStyleSheet)
{
    bool hasValidMIMEType = true;
    String sheetText = cachedStyleSheet->sheetText(&hasValidMIMEType);

    if (!hasValidMIMEType) {
        ASSERT(sheetText.isNull());
        if (auto* document = singleOwnerDocument()) {
            if (auto* page = document->page())
                page->console().addMessage(MessageSource::Security, MessageLevel::Error, "Did not parse stylesheet at '" + cachedStyleSheet->url().stringCenterEllipsizedToLength() + "' because its MIME type was invalid.");
        }
        return;
    }

    CSSParser p(parserContext());
    p.parseSheet(this, sheetText, TextPosition(), nullptr, true);

    if (m_parserContext.needsSiteSpecificQuirks && isStrictParserMode(m_parserContext.mode)) {
        // Work around <https://bugs.webkit.org/show_bug.cgi?id=28350>.
        DEPRECATED_DEFINE_STATIC_LOCAL(const String, mediaWikiKHTMLFixesStyleSheet, (ASCIILiteral("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n")));
        // There are two variants of KHTMLFixes.css. One is equal to mediaWikiKHTMLFixesStyleSheet,
        // while the other lacks the second trailing newline.
        if (baseURL().string().endsWith("/KHTMLFixes.css") && !sheetText.isNull() && mediaWikiKHTMLFixesStyleSheet.startsWith(sheetText)
            && sheetText.length() >= mediaWikiKHTMLFixesStyleSheet.length() - 1)
            clearRules();
    }
 void test(PreconnectTestCase testCase)
 {
     MockHTMLResourcePreloader preloader;
     KURL baseURL(ParsedURLString, testCase.baseURL);
     m_scanner->appendToEnd(String(testCase.inputHTML));
     m_scanner->scan(&preloader, baseURL);
     preloader.preconnectRequestVerification(testCase.preconnectedHost, testCase.crossOrigin);
 }
예제 #9
0
 void RunTest(const std::string& filename)
 {
     std::string baseURL("http://www.example.com/");
     std::string fileName(filename);
     bool executeScript = true;
     URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(baseURL.c_str()), WebString::fromUTF8(fileName.c_str()));
     webViewHelper.initializeAndLoad(baseURL + fileName, executeScript);
 }
    void test(ReferrerPolicyTestCase testCase)
    {
        MockHTMLResourcePreloader preloader;
        KURL baseURL(ParsedURLString, testCase.baseURL);
        m_scanner->appendToEnd(String(testCase.inputHTML));
        m_scanner->scan(&preloader, baseURL);

        preloader.preloadRequestVerification(testCase.type, testCase.preloadedURL, testCase.outputBaseURL, testCase.resourceWidth, testCase.referrerPolicy);
    }
예제 #11
0
KURL StyleSheet::completeURL(const String& url) const
{
    // Always return a null URL when passed a null string.
    // FIXME: Should we change the KURL constructor to have this behavior?
    // See also Document::completeURL(const String&)
    if (url.isNull())
        return KURL();
    return KURL(baseURL(), url);
}
예제 #12
0
파일: XMLURL.cpp 프로젝트: mydw/mydw
void XMLURL::makeRelativeTo(const XMLCh* const baseURLText)
{
    // If this one is not relative, don't bother
    if (!isRelative())
        return;

    XMLURL baseURL(baseURLText, fMemoryManager);
    conglomerateWithBase(baseURL);
}
예제 #13
0
bool QgsWFSDescribeFeatureType::requestFeatureType( const QString& WFSVersion,
    const QString& typeName )
{
  QUrl url( baseURL() );
  url.addQueryItem( "REQUEST", "DescribeFeatureType" );
  url.addQueryItem( "VERSION", WFSVersion );
  url.addQueryItem( "TYPENAME", typeName );

  return sendGET( url, true, false );
}
예제 #14
0
void LayoutTestController::queueLoad(JSStringRef url, JSStringRef target)
{
    WebCore::KURL baseURL(WebCore::KURL(), String::fromUTF8(ewk_frame_uri_get(browser->mainFrame())));
    WebCore::KURL absoluteURL(baseURL, WTF::String(url->characters(), url->length()));

    JSRetainPtr<JSStringRef> jsAbsoluteURL(
        Adopt, JSStringCreateWithUTF8CString(absoluteURL.string().utf8().data()));

    WorkQueue::shared()->queue(new LoadItem(jsAbsoluteURL.get(), target));
}
예제 #15
0
파일: anchor.c 프로젝트: yujiabe/w3m
static Anchor *
_put_anchor_all(Buffer *buf, char *p1, char *p2, int line, int pos)
{
    Str tmp;

    tmp = Strnew_charp_n(p1, p2 - p1);
    return registerHref(buf, url_encode(tmp->ptr, baseURL(buf),
					buf->document_charset),
			NULL, NO_REFERER, NULL,
			'\0', line, pos);
}
예제 #16
0
bool LoadHTMLStringItem::invoke() const
{
    GUniquePtr<gchar> content(JSStringCopyUTF8CString(m_content.get()));
    GUniquePtr<gchar> baseURL(JSStringCopyUTF8CString(m_baseURL.get()));

    if (m_unreachableURL) {
        GUniquePtr<gchar> unreachableURL(JSStringCopyUTF8CString(m_unreachableURL.get()));
        webkit_web_frame_load_alternate_string(mainFrame, content.get(), baseURL.get(), unreachableURL.get());
        return true;
    }
    webkit_web_frame_load_string(mainFrame, content.get(), 0, 0, baseURL.get());
    return true;
}
PassRefPtr<CSSRuleList> CSSStyleSheet::cssRules(bool omitCharsetRules)
{

#if 1
    // modified at webkit.org trunk r61391
    KURL url = finalURL();
    if (!url.isEmpty() && doc() && !doc()->securityOrigin()->canRequest(url))
#else
    if (doc() && !doc()->securityOrigin()->canRequest(baseURL()))
#endif
        return 0;
    return CSSRuleList::create(this, omitCharsetRules);
}
예제 #18
0
void WebProcessProxy::assumeReadAccessToBaseURL(const String& urlString)
{
    URL url(URL(), urlString);
    if (!url.isLocalFile())
        return;

    // There's a chance that urlString does not point to a directory.
    // Get url's base URL to add to m_localPathsWithAssumedReadAccess.
    URL baseURL(URL(), url.baseAsString());
    
    // Client loads an alternate string. This doesn't grant universal file read, but the web process is assumed
    // to have read access to this directory already.
    m_localPathsWithAssumedReadAccess.add(baseURL.fileSystemPath());
}
예제 #19
0
파일: Request.cpp 프로젝트: jld/gecko-dev
already_AddRefed<URL> ParseURLFromWorker(const GlobalObject& aGlobal,
                                         const nsAString& aInput,
                                         ErrorResult& aRv) {
  WorkerPrivate* worker = GetCurrentThreadWorkerPrivate();
  MOZ_ASSERT(worker);
  worker->AssertIsOnWorkerThread();

  NS_ConvertUTF8toUTF16 baseURL(worker->GetLocationInfo().mHref);
  RefPtr<URL> url = URL::WorkerConstructor(aGlobal, aInput, baseURL, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    aRv.ThrowTypeError<MSG_INVALID_URL>(aInput);
  }
  return url.forget();
}
//
//  This test makes sure that parsing one URL relative to another works
//  correctly. The tests used here come from one of the internet RFCs on
//  generic URI syntax. A single base URL is created, then a number of
//  relative URLs are parsed against it and the results compared to the
//  expected result.
//
static bool relativeURLTest()
{
    static struct TestEntry
    {
        const XMLCh*    relative;
        const XMLCh*    result;
    } testList[] =
    {
        { L"g"      , L"http://a/b/c/g" }
      , { L"./g"    , L"http://a/b/c/g" }
      , { L"g/"     , L"http://a/b/c/g/" }
      , { L"/g"     , L"http://a/g" }
      , { L"?y"     , L"http://a/b/c/?y" }
      , { L"g?y"    , L"http://a/b/c/g?y" }
      , { L"#s"     , L"http://a/b/c/d;p#s" }
      , { L"g#s"    , L"http://a/b/c/g#s" }
      , { L"g?y#s"  , L"http://a/b/c/g?y#s" }
      , { L";x"     , L"http://a/b/c/;x" }
      , { L"g;x"    , L"http://a/b/c/g;x" }
      , { L"g;x?y#s", L"http://a/b/c/g;x?y#s" }
      , { L"."      , L"http://a/b/c/" }
      , { L"./"     , L"http://a/b/c/" }
      , { L".."     , L"http://a/b/" }
      , { L"../"    , L"http://a/b/" }
      , { L"../g"   , L"http://a/b/g" }
      , { L"../.."  , L"http://a/" }
      , { L"../../" , L"http://a/" }
      , { L"../../g", L"http://a/g" }
    };
    const unsigned int testCount = sizeof(testList) / sizeof(testList[0]);

    // This is the base URL against which the tests are run
    XMLURL baseURL(L"http://a/b/c/d;p?q");

    bool retVal = true;
    for (unsigned int index = 0; index < testCount; index++)
    {
        XMLURL testURL(baseURL, testList[index].relative);

        if (XMLString::compareString(testURL.getURLText(), testList[index].result))
        {
            XERCES_STD_QUALIFIER wcout  << L"Expected URL: " << testList[index].result
                        << L" but got: " << testURL.getURLText() << XERCES_STD_QUALIFIER endl;
            retVal = false;
        }
    }
    return retVal;
};
예제 #21
0
파일: anchor.c 프로젝트: yujiabe/w3m
static Anchor *
_put_anchor_news(Buffer *buf, char *p1, char *p2, int line, int pos)
{
    Str tmp;

    if (*p1 == '<') {
	p1++;
	if (*(p2 - 1) == '>')
	    p2--;
    }
    tmp = Strnew_charp("news:");
    Strcat_charp_n(tmp, p1, p2 - p1);
    return registerHref(buf, url_encode(tmp->ptr, baseURL(buf),
					buf->document_charset),
			NULL, NO_REFERER, NULL, '\0', line,
			pos);
}
예제 #22
0
/**
 * Loads Server information.
 *
 * @brief ServerInfoClient::loadServerInfo
 */
bool ServerInfoClient::loadServerInfo(){
    QString url = baseURL();

    QUrl _url(url);
    QNetworkRequest request( _url );

    prepareRequest(request);
    request.setRawHeader(QByteArray("accept"), QByteArray("application/json"));

    QEventLoop loop;

    QTimer timeoutTimer;
    timeoutTimer.setSingleShot(true);
    connect(&timeoutTimer, SIGNAL(timeout()), &loop, SLOT(quit()));

    //REST request
    QNetworkReply *reply = manager->get( request );
    QObject::connect(reply, SIGNAL(readyRead()), &loop, SLOT(quit()));

    //Wait 2000 miliseconds
    timeoutTimer.start(2000);

    loop.exec();

    if(reply->bytesAvailable() == 0)
    {        
        return false;
    }

    QByteArray arr = reply->readAll();

    QJsonDocument jsonResponse = QJsonDocument::fromJson(arr);
    QJsonObject jsonObject = jsonResponse.object();

    _initializeDate = jsonObject["initializeDate"].toString().toLongLong();
    _serverBootTime = jsonObject["serverBootTime"].toString().toLongLong();
    _currentServerTime = jsonObject["currentServerTime"].toString().toLongLong();
    _icatEnabled = jsonObject["icatEnabled"].toString();
    _relVersion =  jsonObject["relVersion"].toString();
    _apiVersion =  jsonObject["apiVersion"].toString();
    _rodsZone =  jsonObject["rodsZone"].toString();

    return true;

}
예제 #23
0
bool QgsWfsCapabilities::requestCapabilities( bool synchronous )
{
  QUrl url( baseURL() );
  url.addQueryItem( "REQUEST", "GetCapabilities" );

  const QString& version = mUri.version();
  if ( version == QgsWFSConstants::VERSION_AUTO )
    // MapServer honours the order with the first value being the preferred one
    url.addQueryItem( "ACCEPTVERSIONS", "2.0.0,1.1.0,1.0.0" );
  else
    url.addQueryItem( "VERSION", version );

  if ( !sendGET( url, synchronous, false ) )
  {
    emit gotCapabilities();
    return false;
  }
  return true;
}
예제 #24
0
bool QgsWFSTransactionRequest::send( const QDomDocument& doc, QDomDocument& serverResponse )
{
  QUrl url( baseURL() );

  QgsDebugMsg( doc.toString() );

  if ( sendPOST( url, "text/xml", doc.toByteArray( -1 ) ) )
  {
    QString errorMsg;
    if ( !serverResponse.setContent( mResponse, true, &errorMsg ) )
    {
      QgsDebugMsg( mResponse );
      QgsDebugMsg( errorMsg );
      return false;
    }
    return true;
  }
  return false;
}
예제 #25
0
파일: frame.c 프로젝트: richq/w3m
struct frame_body *
newFrame(struct parsed_tag *tag, Buffer *buf)
{
    struct frame_body *body;
    char *p;

    body = New(struct frame_body);
    bzero((void *)body, sizeof(*body));
    body->attr = F_UNLOADED;
    body->flags = 0;
    body->baseURL = baseURL(buf);
    if (tag) {
	if (parsedtag_get_value(tag, ATTR_SRC, &p))
	    body->url = url_encode(remove_space(p), body->baseURL,
				   buf->document_charset);
	if (parsedtag_get_value(tag, ATTR_NAME, &p) && *p != '_')
	    body->name = url_quote_conv(p, buf->document_charset);
    }
    return body;
}
예제 #26
0
파일: map.c 프로젝트: AOSC-Dev/w3m-ng
Buffer *
follow_map_panel(Buffer *buf, char *name)
{
    Str mappage;
    MapList *ml;
    ListItem *al;
    MapArea *a;
    ParsedURL pu;
    char *p, *q;
    Buffer *newbuf;

    ml = searchMapList(buf, name);
    if (ml == NULL)
	return NULL;

    mappage = Strnew_charp(map1);
    for (al = ml->area->first; al != NULL; al = al->next) {
	a = (MapArea *) al->ptr;
	if (!a)
	    continue;
	parseURL2(a->url, &pu, baseURL(buf));
	p = parsedURL2Str(&pu)->ptr;
	q = html_quote(p);
	if (DecodeURL)
	    p = html_quote(url_unquote_conv(p, buf->document_charset));
	else
	    p = q;
	Strcat_m_charp(mappage, "<tr valign=top><td><a href=\"", q, "\">",
		       html_quote(*a->alt ? a->alt : mybasename(a->url)),
		       "</a><td>", p, NULL);
    }
    Strcat_charp(mappage, "</table></body></html>");

    newbuf = loadHTMLString(mappage);
#ifdef USE_M17N
    if (newbuf)
	newbuf->document_charset = buf->document_charset;
#endif
    return newbuf;
}
예제 #27
0
void StyleSheetContents::parseAuthorStyleSheet(
    const CSSStyleSheetResource* cachedStyleSheet,
    const SecurityOrigin* securityOrigin) {
    TRACE_EVENT1("blink,devtools.timeline", "ParseAuthorStyleSheet", "data",
                 InspectorParseAuthorStyleSheetEvent::data(cachedStyleSheet));
    SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Style.AuthorStyleSheet.ParseTime");

    bool isSameOriginRequest =
        securityOrigin && securityOrigin->canRequest(baseURL());

    // When the response was fetched via the Service Worker, the original URL may
    // not be same as the base URL.
    // TODO(horo): When we will use the original URL as the base URL, we can
    // remove this check. crbug.com/553535
    if (cachedStyleSheet->response().wasFetchedViaServiceWorker()) {
        const KURL originalURL(
            cachedStyleSheet->response().originalURLViaServiceWorker());
        // |originalURL| is empty when the response is created in the SW.
        if (!originalURL.isEmpty() && !securityOrigin->canRequest(originalURL))
            isSameOriginRequest = false;
    }

    CSSStyleSheetResource::MIMETypeCheck mimeTypeCheck =
        isQuirksModeBehavior(m_parserContext.mode()) && isSameOriginRequest
        ? CSSStyleSheetResource::MIMETypeCheck::Lax
        : CSSStyleSheetResource::MIMETypeCheck::Strict;
    String sheetText = cachedStyleSheet->sheetText(mimeTypeCheck);

    const ResourceResponse& response = cachedStyleSheet->response();
    m_sourceMapURL = response.httpHeaderField(HTTPNames::SourceMap);
    if (m_sourceMapURL.isEmpty()) {
        // Try to get deprecated header.
        m_sourceMapURL = response.httpHeaderField(HTTPNames::X_SourceMap);
    }

    CSSParserContext context(parserContext(), UseCounter::getFrom(this));
    CSSParser::parseSheet(context, this, sheetText,
                          RuntimeEnabledFeatures::lazyParseCSSEnabled());
}
예제 #28
0
	virtual void FetchChoicesFor(const BString& pattern)
	{
		int32 count = CountChoices();
		for (int32 i = 0; i < count; i++) {
			delete reinterpret_cast<BAutoCompleter::Choice*>(
				fChoices.ItemAtFast(i));
		}
		fChoices.MakeEmpty();

		// Search through BrowsingHistory for any matches.
		BrowsingHistory* history = BrowsingHistory::DefaultInstance();
		if (!history->Lock())
			return;

		BString lastBaseURL;
		int32 priority = INT_MAX;

		count = history->CountItems();
		for (int32 i = 0; i < count; i++) {
			BrowsingHistoryItem item = history->HistoryItemAt(i);
			const BString& choiceText = item.URL();
			int32 matchPos = choiceText.IFindFirst(pattern);
			if (matchPos < 0)
				continue;
			if (lastBaseURL.Length() > 0
				&& choiceText.FindFirst(lastBaseURL) >= 0) {
				priority--;
			} else
				priority = INT_MAX;
			lastBaseURL = baseURL(choiceText);
			fChoices.AddItem(new URLChoice(choiceText,
				choiceText, matchPos, pattern.Length(), priority));
		}

		history->Unlock();

		fChoices.SortItems(_CompareChoices);
	}
예제 #29
0
/**
 * @param filenames : List of files to search
 * @param exts : List of extensions to check against
 * @return list of archive locations
 */
std::string SNSDataArchive::getArchivePath(const std::set<std::string>& filenames, const std::vector<std::string>& exts) const
{
  std::set<std::string>::const_iterator iter = filenames.begin();
  std::string filename = *iter;

  //ICAT4 web service take upper case filename such as HYSA_2662
  std::transform(filename.begin(),filename.end(),filename.begin(),toupper);

  std::vector<std::string>::const_iterator iter2 = exts.begin();
  for(; iter2!=exts.end(); ++iter2)
  {
    g_log.debug() << *iter2 << ";";
  }
  g_log.debug()  << "\n";

  std::string baseURL("http://icat.sns.gov:8080/icat-rest-ws/datafile/filename/");

  std::string URL(baseURL + filename);
  g_log.debug() << "URL: " << URL << "\n";

  Poco::URI uri(URL);
  std::string path(uri.getPathAndQuery());

  Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
  Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
  session.sendRequest(req);

  Poco::Net::HTTPResponse res;
  std::istream& rs = session.receiveResponse(res);
  g_log.debug() << "res.getStatus(): " << res.getStatus() << "\n";

  // Create a DOM document from the response.
  Poco::XML::DOMParser parser;
  Poco::XML::InputSource source(rs);
  Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&source);

  std::vector<std::string> locations;

  // If everything went fine, return the XML document.
  // Otherwise look for an error message in the XML document.
  if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
  {
    std::string location;
    Poco::AutoPtr<Poco::XML::NodeList> pList = pDoc->getElementsByTagName("location");
    for(unsigned long i = 0 ; i < pList->length(); i++)
    {
      location = pList->item(i)->innerText();
      g_log.debug() << "location: " << location << "\n";
      locations.push_back(location);
    }
  }
  else
  {
    std::string error(res.getReason());
    throw Poco::ApplicationException("HTTPRequest Error", error);
  }

  std::vector<std::string>::const_iterator ext = exts.begin();
  for (; ext != exts.end(); ++ext)
  {
    std::string datafile = filename + *ext;
    std::vector<std::string>::const_iterator iter = locations.begin();
    for(; iter!=locations.end(); ++iter)
    {
      if (boost::algorithm::ends_with((*iter), datafile))
      {
        return *iter;
      } // end if
    } // end for iter

  }  // end for ext
  return "";
}
예제 #30
0
    /**
     * Calls a web service to get a full path to a file
     * @param fName :: The file name.
     * @return The path to the file or empty string in case of error.
     */
    std::string OrbiterDataArchive::getPath(const std::string& fName) const
    {

      std::string baseURL(
          "https://orbiter.sns.gov/orbiter/current/service/webservice/OrbiterFindFileService.php");
      std::string findFileWS("/operation/findFile/format/space/fileName/");
      std::string URL(baseURL + findFileWS + fName);
      g_log.debug() << "URL = \'" << URL << "\'\n";

      std::string wsResult = "";
      std::string result = "";

      //#ifdef _WIN32
      //	// Return an empty string
      //#else
      //
      //#endif

      Poco::URI uri(URL);
      std::string path(uri.getPathAndQuery());

      Poco::Net::Context::Ptr context = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "",
          "", Poco::Net::Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");

      try { // workaround for ubuntu 11.04
        Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context); // this line is broken
        HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
        session.sendRequest(req);

        HTTPResponse res;
        std::istream& rs = session.receiveResponse(res);

        char buff[300];
        std::streamsize n;

        do
        {
          rs.read(&buff[0], 300);
          n = rs.gcount();
          wsResult.append(&buff[0], n);
        } while (n == 300);
      } catch (ConnectionRefusedException &) {
        g_log.error() << "Connection refused by orbiter\n";
        throw;
      } catch(Poco::IOException &e) {
        g_log.debug() << e.name() << " thrown.\n";
        g_log.error() << e.message() << "\n";
        throw;
      }

      //Look for spaces, and split on them.
      std::vector<std::string> filenames;
      boost::split(filenames, wsResult, boost::is_any_of(" "));
      // For now just take the first result
      result = filenames[0];

      // Debug statement to print returned filename(s)
      for (std::size_t i = 0; i < filenames.size(); ++i) {
    	  g_log.debug() << "Filename[" << i << "] = \'" << filenames[i] << "\'\n";
	  }
      g_log.debug() << "Returning Filename = \'" << result << "\'\n";

      return result;
    }