Handle a GET request

@param pUri URI leading to this request
@param pPathInfo path of the request
@param pParameterMap parameters of the GET request  @return the response
16601
public JSONAware handleGetRequest(String pUri, String pPathInfo, Map<String, String[]> pParameterMap) {
        String pathInfo = extractPathInfo(pUri, pPathInfo);

        JmxRequest jmxReq =
                JmxRequestFactory.createGetRequest(pathInfo,getProcessingParameter(pParameterMap));

        if (backendManager.isDebug()) {
            logHandler.debug("URI: " + pUri);
            logHandler.debug("Path-Info: " + pathInfo);
            logHandler.debug("Request: " + jmxReq.toString());
        }
        return executeRequest(jmxReq);
    }
169016
public static String getParam(HttpServletRequest req, String strParam)
    {
        return BaseHttpTask.getParam(req, strParam, Constants.BLANK);
    }
905972
public Map<String, String[]> getParameterMap() {
		// JSR 289 Section 5.6.1 Parameters :
		// For initial requests where a preloaded Route header specified the application to be invoked, the parameters are those of the SIP or SIPS URI in that Route header.
		// For initial requests where the application is invoked the parameters are those present on the request URI, 
		// if this is a SIP or a SIPS URI. For other URI schemes, the parameter set is undefined.
		// For subsequent requests in a dialog, the parameters presented to the application  are those that the application itself 
		// set on the Record-Route header for the initial request or response (see 10.4 Record-Route Parameters). 
		// These will typically be the URI parameters of the top Route header field but if the upstream SIP element is a 
		// "strict router" they may be returned in the request URI (see RFC 3261). 
		// It is the containers responsibility to recognize whether the upstream element is a strict router and determine the right parameter set accordingly.
		HashMap<String, String[]> retval = new HashMap<String, String[]>();
		if(this.getPoppedRoute() != null) {
			Iterator<String> parameterNamesIt =  this.getPoppedRoute().getURI().getParameterNames();
			while (parameterNamesIt.hasNext()) {
				String parameterName = parameterNamesIt.next();
				String [] paramsArray = {this.getPoppedRoute().getURI().getParameter(parameterName)}; //Get the parameter map value to String[]
				retval.put(parameterName, paramsArray); 
			}
		} else {
			Iterator<String> parameterNamesIt =  this.getRequestURI().getParameterNames();
			while (parameterNamesIt.hasNext()) {
				String parameterName = parameterNamesIt.next();
				String [] paramsArray = {this.getPoppedRoute().getURI().getParameter(parameterName)}; //Get the parameter map value to String[]
				retval.put(parameterName, paramsArray);
			}
		}		
		
		return retval;
	}
865366
public static HttpResponse executeGet(final String url,
                                          final String basicAuthUsername,
                                          final String basicAuthPassword,
                                          final Map<String, Object> parameters) {
        try {
            return executeGet(url, basicAuthUsername, basicAuthPassword, parameters, new HashMap<>());
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }
1285585
protected HttpGet generateGetRequest(final String path, final Map<String, Object> paramMap) {
        final List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (final String key : paramMap.keySet()) {
            pairs.add(new BasicNameValuePair(key, paramMap.get(key).toString()));
        }
        final URI uri = buildUri(path, pairs);
        return new HttpGet(uri);
    }
339534
@Override
	public <T extends Resource> T get(final String uri) {
		return doRequest(uri).get();
	}
1102999
protected void executePutRequest(URI uri, Object obj)
    {
        executePutRequest(uri, obj, null, null);
    }
964153
@Provides
    @Named(JanusConfig.PUB_URI)
    public static URI getPubURIAsURI() {
        final String v = getPUBURIAsString();
        try {
            return NetworkUtil.toURI(v);
        } catch (URISyntaxException e) {
            throw new IOError(e);
        }
    }
188882
public void handle(String pathInContext, String pathParams, HttpRequest request,
            HttpResponse response) throws HttpException, IOException
    {

        // exempt error pages
        // TODO This probably should be more general?
        if (request.getAttribute("javax.servlet.error.status_code") != null) return;

        try
        {

            String ip = request.getRemoteAddr();
            boolean authorized = checkIP(ip);

            if (!authorized)
            {
                // The IP is NOT allowed
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }
            else
            {
                // The IP is allowed
                return;
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
            response.sendError(HttpResponse.__500_Internal_Server_Error);
            request.setHandled(true);
        }
    }
149147
public static RequestResponse callHttpGet(String url, Map<String, Object> headers,
            Map<String, Object> urlParams) {
        return callHttpGet(httpJsonRpcClient, url, headers, urlParams);
    }
1263184
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
            throws HttpException,IOException
    {
        String user=null;
        String password=null;
        boolean IPValid=true;

        if(log.isDebugEnabled())log.debug("HTAccessHandler pathInContext="+pathInContext);

        String credentials=request.getField(HttpFields.__Authorization);

        if (credentials!=null)
        {
            credentials=credentials.substring(credentials.indexOf(' ')+1);
            credentials=B64Code.decode(credentials,StringUtil.__ISO_8859_1);
            int i=credentials.indexOf(':');
            user=credentials.substring(0,i);
            password=credentials.substring(i+1);

            if(log.isDebugEnabled())log.debug("User="+user+", password="+
                    "******************************".substring(0,password.length()));
        }

        HTAccess ht=null;

        try
        {
            Resource resource=null;
            String directory=pathInContext.endsWith("/")
                    ?pathInContext:
                    URI.parentPath(pathInContext);

            // Look for htAccess resource
            while (directory!=null)
            {
                String htPath=directory+_accessFile;
                resource=getHttpContext().getResource(htPath);
                if(log.isDebugEnabled())log.debug("directory="+directory+" resource="+resource);

                if (resource!=null && resource.exists() && !resource.isDirectory())
                    break;
                resource=null;
                directory=URI.parentPath(directory);
            }

            // Try default directory
            if (resource==null && _default!=null)
            {
                resource=Resource.newResource(_default);
                if (!resource.exists() || resource.isDirectory())
                    return;
            }
            if (resource==null)
                return;

            if(log.isDebugEnabled())log.debug("HTACCESS="+resource);

            ht=(HTAccess)_htCache.get(resource);
            if (ht==null || ht.getLastModified()!=resource.lastModified())
            {
                ht=new HTAccess(resource);
                _htCache.put(resource,ht);
                if(log.isDebugEnabled())log.debug("HTCache loaded "+ht);
            }

            // prevent access to htaccess files
            if (pathInContext.endsWith(_accessFile))
            {
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            // See if there is a config problem
            if (ht.isForbidden())
            {
                log.warn("Mis-configured htaccess: "+ht);
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            //first see if we need to handle based on method type
            Map methods=ht.getMethods();
            if (methods.size()>0 && !methods.containsKey(request.getMethod()))
                return; //Nothing to check

            // Check the accesss
            int satisfy=ht.getSatisfy();

            // second check IP address
            IPValid=ht.checkAccess("",request.getRemoteAddr());
            if(log.isDebugEnabled())log.debug("IPValid = "+IPValid);

            // If IP is correct and satify is ANY then access is allowed
            if (IPValid==true && satisfy==HTAccess.ANY)
                return;

            // If IP is NOT correct and satify is ALL then access is forbidden
            if (IPValid==false && satisfy==HTAccess.ALL)
            {
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            // set required page
            if (!ht.checkAuth(user,password,getHttpContext(),request))
            {
                log.debug("Auth Failed");
                response.setField(HttpFields.__WwwAuthenticate,"basic realm="+ht.getName());
                response.sendError(HttpResponse.__401_Unauthorized);
                response.commit();
                request.setHandled(true);
                return;
            }

            // set user
            if (user!=null)
            {
                request.setAuthType(SecurityConstraint.__BASIC_AUTH);
                request.setAuthUser(user);
            }

        }
        catch (Exception ex)
        {
            log.warn(LogSupport.EXCEPTION,ex);
            if (ht!=null)
            {
                response.sendError(HttpResponse.__500_Internal_Server_Error);
                request.setHandled(true);
            }
        }
    }
815636
protected Response getCalls(final String accountSid, UriInfo info,
                                MediaType responseType,
                                UserIdentityContext userIdentityContex) {
        Account account = daos.getAccountsDao().getAccount(accountSid);
        permissionEvaluator.secure(account, "RestComm:Read:Calls", userIdentityContex);

        boolean localInstanceOnly = true;
        try {
            String localOnly = info.getQueryParameters().getFirst("localOnly");
            if (localOnly != null && localOnly.equalsIgnoreCase("false"))
                localInstanceOnly = false;
        } catch (Exception e) {
        }
        // shall we include sub-accounts cdrs in our query ?
        boolean querySubAccounts = false; // be default we don't
        String querySubAccountsParam = info.getQueryParameters().getFirst("SubAccounts");
        if (querySubAccountsParam != null && querySubAccountsParam.equalsIgnoreCase("true"))
            querySubAccounts = true;

        String pageSize = info.getQueryParameters().getFirst("PageSize");
        String page = info.getQueryParameters().getFirst("Page");
        // String afterSid = info.getQueryParameters().getFirst("AfterSid");
        String recipient = info.getQueryParameters().getFirst("To");
        String sender = info.getQueryParameters().getFirst("From");
        String status = info.getQueryParameters().getFirst("Status");
        String startTime = info.getQueryParameters().getFirst("StartTime");
        String endTime = info.getQueryParameters().getFirst("EndTime");
        String parentCallSid = info.getQueryParameters().getFirst("ParentCallSid");
        String conferenceSid = info.getQueryParameters().getFirst("ConferenceSid");
        String reverse = info.getQueryParameters().getFirst("Reverse");

        // Format for sorting URL parameter is '?SortBy=<field>:<direction>', for example: '?SortBy=date_created:asc'. In the
        // future we can extend it to multiple sort fields, like ?SortBy=<field1>:<direction1>,<field2>:<direction2>
        String sortParameters = info.getQueryParameters().getFirst("SortBy");

        // Even though 'Reverse=true/false' URL query parameter isn't documented, old console is using it, so we need
        // to make sure we are backwards compatible:
        // - If 'Reverse' is found in the URL but SortBy is not found then we deem that we are servicing an old version of Console
        //   and we should support sorting only for Date field and translate as follows:
        //   > 'Reverse=true': corresponds to SortBy=DateCreated:desc
        //   > 'Reverse=false': corresponds to SortBy=DateCreated:asc
        // - If Reverse is found in the URL but SortBy is also found we just discard 'Reverse' and service request normally
        // - If only 'SortBy' is found in the URL then we service the request normally
        if (reverse != null && sortParameters == null) {
            if (reverse.equalsIgnoreCase("true")) {
                sortParameters = SORTING_URL_PARAM_DATE_CREATED + ":" + Sorting.Direction.DESC.name();
            }
            else {
                sortParameters = SORTING_URL_PARAM_DATE_CREATED + ":" + Sorting.Direction.ASC.name();
            }
        }

        CallDetailRecordFilter.Builder filterBuilder = CallDetailRecordFilter.Builder.builder();

        String sortBy = null;
        String sortDirection = null;

        if (sortParameters != null && !sortParameters.isEmpty()) {
            try {
                Map<String, String> sortMap = Sorting.parseUrl(sortParameters);
                sortBy = sortMap.get(Sorting.SORT_BY_KEY);
                sortDirection = sortMap.get(Sorting.SORT_DIRECTION_KEY);
            }
            catch (Exception e) {
                return status(BAD_REQUEST).entity(buildErrorResponseBody(e.getMessage(), responseType)).build();
            }
        }

        if (sortBy != null) {
            if (sortBy.equals(SORTING_URL_PARAM_DATE_CREATED)) {
                if (sortDirection != null) {
                    if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) {
                        filterBuilder.sortedByDate(Sorting.Direction.ASC);
                    } else {
                        filterBuilder.sortedByDate(Sorting.Direction.DESC);
                    }
                }
            }
            if (sortBy.equals(SORTING_URL_PARAM_FROM)) {
                if (sortDirection != null) {
                    if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) {
                        filterBuilder.sortedByFrom(Sorting.Direction.ASC);
                    } else {
                        filterBuilder.sortedByFrom(Sorting.Direction.DESC);
                    }
                }
            }
            if (sortBy.equals(SORTING_URL_PARAM_TO)) {
                if (sortDirection != null) {
                    if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) {
                        filterBuilder.sortedByTo(Sorting.Direction.ASC);
                    } else {
                        filterBuilder.sortedByTo(Sorting.Direction.DESC);
                    }
                }
            }
            if (sortBy.equals(SORTING_URL_PARAM_DIRECTION)) {
                if (sortDirection != null) {
                    if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) {
                        filterBuilder.sortedByDirection(Sorting.Direction.ASC);
                    } else {
                        filterBuilder.sortedByDirection(Sorting.Direction.DESC);
                    }
                }
            }
            if (sortBy.equals(SORTING_URL_PARAM_STATUS)) {
                if (sortDirection != null) {
                    if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) {
                        filterBuilder.sortedByStatus(Sorting.Direction.ASC);
                    } else {
                        filterBuilder.sortedByStatus(Sorting.Direction.DESC);
                    }
                }
            }
            if (sortBy.equals(SORTING_URL_PARAM_DURATION)) {
                if (sortDirection != null) {
                    if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) {
                        filterBuilder.sortedByDuration(Sorting.Direction.ASC);
                    } else {
                        filterBuilder.sortedByDuration(Sorting.Direction.DESC);
                    }
                }
            }
            if (sortBy.equals(SORTING_URL_PARAM_PRICE)) {
                if (sortDirection != null) {
                    if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) {
                        filterBuilder.sortedByPrice(Sorting.Direction.ASC);
                    } else {
                        filterBuilder.sortedByPrice(Sorting.Direction.DESC);
                    }
                }
            }
        }

        if (pageSize == null) {
            pageSize = "50";
        }

        if (page == null) {
            page = "0";
        }

        int limit = Integer.parseInt(pageSize);
        int offset = (page == "0") ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer
                .parseInt(pageSize));

        // Shall we query cdrs of sub-accounts too ?
        // if we do, we need to find the sub-accounts involved first
        List<String> ownerAccounts = null;
        if (querySubAccounts) {
            ownerAccounts = new ArrayList<String>();
            ownerAccounts.add(accountSid); // we will also return parent account cdrs
            ownerAccounts.addAll(accountsDao.getSubAccountSidsRecursive(new Sid(accountSid)));
        }

        CallDetailRecordsDao dao = daos.getCallDetailRecordsDao();

        filterBuilder.byAccountSid(accountSid)
                .byAccountSidSet(ownerAccounts)
                .byRecipient(recipient)
                .bySender(sender)
                .byStatus(status)
                .byStartTime(startTime)
                .byEndTime(endTime)
                .byParentCallSid(parentCallSid)
                .byConferenceSid(conferenceSid)
                .limited(limit, offset);
        if (!localInstanceOnly) {
            filterBuilder.byInstanceId(instanceId);
        }

        CallDetailRecordFilter filter;
        try {
            filter = filterBuilder.build();
        } catch (ParseException e) {
            return status(BAD_REQUEST).build();
        }

        final int total = dao.getTotalCallDetailRecords(filter);

        if (Integer.parseInt(page) > (total / limit)) {
            return status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build();
        }

        final List<CallDetailRecord> cdrs = dao.getCallDetailRecords(filter);

        listConverter.setCount(total);
        listConverter.setPage(Integer.parseInt(page));
        listConverter.setPageSize(Integer.parseInt(pageSize));
        listConverter.setPathUri("/" + getApiVersion(null) + "/" + info.getPath());

        if (APPLICATION_XML_TYPE.equals(responseType)) {
            final RestCommResponse response = new RestCommResponse(new CallDetailRecordList(cdrs));
            return ok(xstream.toXML(response), APPLICATION_XML).build();
        } else if (APPLICATION_JSON_TYPE.equals(responseType)) {
            return ok(gson.toJson(new CallDetailRecordList(cdrs)), APPLICATION_JSON).build();
        } else {
            return null;
        }
    }
665600
public RestResponse post(final String uri, final Map<String, Object> params)
            throws IOException, AppPlatformException {
        return request(getPath(uri), HttpPost.METHOD_NAME, params);
    }
559667
function getURLParameter( name ) {
    return decodeURI(
        ( new RegExp( name + '=' + '(.+?)(&|$)' ).exec( location.search ) || [ null, null ] )[ 1 ]
    );
}
131253
public void process(final String uri, final String hostAddress, RequestHandler requestHandler)
          throws IOException {
    // Prepare the response headers.

    /**
     * Parse the query parameters into an announce request message.
     *
     * We need to rely on our own query parsing function because
     * SimpleHTTP's Query map will contain UTF-8 decoded parameters, which
     * doesn't work well for the byte-encoded strings we expect.
     */
    HTTPAnnounceRequestMessage announceRequest;
    try {
      announceRequest = this.parseQuery(uri, hostAddress);
    } catch (MessageValidationException mve) {
      LoggerUtils.warnAndDebugDetails(logger, "Unable to parse request message. Request url is {}", uri, mve);
      serveError(Status.BAD_REQUEST, mve.getMessage(), requestHandler);
      return;
    }

    AnnounceRequestMessage.RequestEvent event = announceRequest.getEvent();

    if (event == null) {
      event = AnnounceRequestMessage.RequestEvent.NONE;
    }
    TrackedTorrent torrent = myTorrentsRepository.getTorrent(announceRequest.getHexInfoHash());

    // The requested torrent must be announced by the tracker if and only if myAcceptForeignTorrents is false
    if (!myAcceptForeignTorrents && torrent == null) {
      logger.warn("Requested torrent hash was: {}", announceRequest.getHexInfoHash());
      serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.UNKNOWN_TORRENT, requestHandler);
      return;
    }

    final boolean isSeeder = (event == AnnounceRequestMessage.RequestEvent.COMPLETED)
            || (announceRequest.getLeft() == 0);

    if (myAddressChecker.isBadAddress(announceRequest.getIp())) {
      if (torrent == null) {
        writeEmptyResponse(announceRequest, requestHandler);
      } else {
        writeAnnounceResponse(torrent, null, isSeeder, requestHandler);
      }
      return;
    }

    final Peer peer = new Peer(announceRequest.getIp(), announceRequest.getPort());

    try {
      torrent = myTorrentsRepository.putIfAbsentAndUpdate(announceRequest.getHexInfoHash(),
              new TrackedTorrent(announceRequest.getInfoHash()),
              event,
              ByteBuffer.wrap(announceRequest.getPeerId()),
              announceRequest.getHexPeerId(),
              announceRequest.getIp(),
              announceRequest.getPort(),
              announceRequest.getUploaded(),
              announceRequest.getDownloaded(),
              announceRequest.getLeft());
    } catch (IllegalArgumentException iae) {
      LoggerUtils.warnAndDebugDetails(logger, "Unable to update peer torrent. Request url is {}", uri, iae);
      serveError(Status.BAD_REQUEST, ErrorMessage.FailureReason.INVALID_EVENT, requestHandler);
      return;
    }

    // Craft and output the answer
    writeAnnounceResponse(torrent, peer, isSeeder, requestHandler);
  }
1159071
@SuppressWarnings("rawtypes")
    public static List<Map<String, Object>> query(final Uri uri, Map<String, Class> projectionTypeMap) {
        return query(uri, projectionTypeMap, null, null, null);
    }
230141
protected RestResponse request(final String path, final String method, Map<String, Object> paramList)
            throws IOException, AppPlatformException {
        if (paramList == null) {
            paramList = Collections.emptyMap();
        }

        final HttpUriRequest request = setupRequest(path, method, paramList);
        return performRequest(request);
    }