private static void doBundle(ResourceImpl resource, Headers headers) { CapabilityImpl capability = new CapabilityImpl(Capability.BUNDLE); capability.addProperty(Resource.SYMBOLIC_NAME, getSymbolicName(headers)); if (headers.getHeader(Constants.BUNDLE_NAME) != null) { capability.addProperty(Resource.PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME)); } capability.addProperty(Resource.VERSION, Property.VERSION, getVersion(headers)); capability.addProperty(Resource.MANIFEST_VERSION, getManifestVersion(headers)); resource.addCapability(capability); }
public static Conditionals valueOf(Headers headers) { ImmutableList<Tag> ifMatch = makeTags(headers.getFirstHeaderValue(HeaderConstants.IF_MATCH)); ImmutableList<Tag> ifNoneMatch = makeTags(headers.getFirstHeaderValue(HeaderConstants.IF_NONE_MATCH)); DateTime modifiedSince = HeaderUtils.fromHttpDate(headers.getFirstHeader(HeaderConstants.IF_MODIFIED_SINCE)); DateTime unModifiedSince = HeaderUtils.fromHttpDate(headers.getFirstHeader(HeaderConstants.IF_UNMODIFIED_SINCE)); return new Conditionals(ifMatch, ifNoneMatch, modifiedSince, unModifiedSince); }
@Override public HttpUriRequest apply(String dsPrsID, String mmeAuthToken) { String authorization = Headers.basicToken(dsPrsID, mmeAuthToken); HttpPost request = new HttpPost(url); request.setHeader(headers.get(Headers.userAgent)); request.setHeader(headers.get(Headers.xMmeClientInfo)); request.setHeader("Authorization", authorization); return request; }
private static String getSymbolicName(Headers headers) { String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); if (bsn == null) { bsn = headers.getHeader(Constants.BUNDLE_NAME); if (bsn == null) { bsn = "Untitled-" + headers.hashCode(); } } Clause[] clauses = Parser.parseHeader(bsn); return clauses[0].getName(); }
public static HTTPResponse createResponse( final StatusLine line, final Headers responseHeaders, final Optional<InputStream> stream) { Optional<String> contentLengthHeader = responseHeaders.getFirstHeaderValue(HeaderConstants.CONTENT_LENGTH); MIMEType type = responseHeaders.getContentType().orElse(MIMEType.APPLICATION_OCTET_STREAM); Optional<Long> length = responseHeaders.getContentLength(); Optional<Payload> payload = stream .filter(is -> line.getStatus().isBodyContentAllowed()) .map(is -> new InputStreamPayload(is, type, length.orElse(-1L))); return new HTTPResponse(payload, line, responseHeaders); }
/** * Uploads the image to the server * * @param b * @param listener */ public void uploadImage(final Bitmap b, final OnResponseListener listener) { OkHttpClient httpClient = new OkHttpClient(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); // encode image as PNG, re-encoding as JPG may cause compression artefacts to be visible b.compress(Bitmap.CompressFormat.PNG, 0, bos); RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addPart( // the filename parameter is needed to specify that this is indeed a file and not an // inline // attachment Headers.of( "Content-Disposition", "form-data; name=\"image\"; filename=\"image.png\""), RequestBody.create(MediaType.parse("image/png"), bos.toByteArray())) .build(); Request request = new Request.Builder().url(UPLOAD_ENDPOINT).post(requestBody).build(); Call call = httpClient.newCall(request); call.enqueue( new Callback() { @Override public void onFailure(Request request, IOException e) {} @Override public void onResponse(Response response) throws IOException { listener.onResponse(new ServerResponse(response.code(), response.body().string())); } }); }
private static String getManifestVersion(Headers headers) { String v = headers.getHeader(Constants.BUNDLE_MANIFESTVERSION); if (v == null) { v = "1"; } return v; }
private static void doExports(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.EXPORT_PACKAGE)); for (int i = 0; clauses != null && i < clauses.length; i++) { CapabilityImpl capability = createCapability(Capability.PACKAGE, clauses[i]); resource.addCapability(capability); } }
private static void doFragment(ResourceImpl resource, Headers headers) { // Check if we are a fragment Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.FRAGMENT_HOST)); if (clauses != null && clauses.length == 1) { // We are a fragment, create a requirement // to our host. RequirementImpl r = new RequirementImpl(Capability.BUNDLE); StringBuffer sb = new StringBuffer(); sb.append("(&(symbolicname="); sb.append(clauses[0].getName()); sb.append(")"); appendVersion( sb, VersionRange.parseVersionRange( clauses[0].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE))); sb.append(")"); r.setFilter(sb.toString()); r.addText("Required Host " + clauses[0].getName()); r.setExtend(true); r.setOptional(false); r.setMultiple(false); resource.addRequire(r); // And insert a capability that we are available // as a fragment. ### Do we need that with extend? CapabilityImpl capability = new CapabilityImpl(Capability.FRAGMENT); capability.addProperty("host", clauses[0].getName()); capability.addProperty("version", Property.VERSION, getVersion(clauses[0])); resource.addCapability(capability); } }
@Test @SuppressWarnings("unchecked") public void readFileRemovedEntry() throws Exception { String sha = sha256("myconf.conf"); String changeset = "1\n" + "1\n" + "file-removed-test\n" + "myresource\n" + "C\n" + "1\n" + "R 0 " + sha + " conf/myconf.conf"; ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset)); Headers actualHeaders = reader.getHeaders(); Headers expectedHeaders = new Headers(); expectedHeaders.setResourceId(1); expectedHeaders.setDriftDefinitionId(1); expectedHeaders.setDriftDefinitionName("file-removed-test"); expectedHeaders.setBasedir("myresource"); expectedHeaders.setType(COVERAGE); expectedHeaders.setVersion(1); assertHeadersEquals(actualHeaders, expectedHeaders); FileEntry expectedFileEntry = new FileEntry("0", sha, "conf/myconf.conf", "R"); FileEntry actualFileEntry = reader.read(); reader.close(); assertFileEntryEquals(actualFileEntry, expectedFileEntry); }
@Override public Request withHeaders(Map<String, String> additionalHeaders) { LinkedHashMap<String, String> newHeaders = new LinkedHashMap<>(headers().asMap()); newHeaders.putAll(additionalHeaders); return create( method(), uri(), parameters(), Headers.of(newHeaders), service(), payload(), ttl()); }
public ResourceImpl createResource(Headers headers) { String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); if (bsn == null) { return null; } ResourceImpl resource = new ResourceImpl(); populate(headers, resource); return resource; }
public DataType getDataType(Message message) { final String dataTypeHeader = Headers.get(message, Headers.DATATYPE); final String typeHeader = Headers.get(message, Headers.TYPE); // we have two possible header sets here // legacy: there is Headers.DATATYPE .Headers.TYPE // contains either the string "mms" or an integer which is the internal type of the sms // current: there IS a Headers.DATATYPE containing a string representation of Headers.DataType // Headers.TYPE then contains the type of the sms, mms or calllog entry // The current header set was introduced in version 1.2.00 if (dataTypeHeader == null) { return MmsConsts.LEGACY_HEADER.equalsIgnoreCase(typeHeader) ? DataType.MMS : DataType.SMS; } else { try { return DataType.valueOf(dataTypeHeader.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { return DataType.SMS; // whateva } } }
public void sendResponseHeaders(int rCode, long contentLen) throws IOException { if (sentHeaders) { throw new IOException("headers already sent"); } this.rcode = rCode; String statusLine = "HTTP/1.1 " + rCode + Code.msg(rCode) + "\r\n"; OutputStream tmpout = new BufferedOutputStream(ros); PlaceholderOutputStream o = getPlaceholderResponseBody(); tmpout.write(bytes(statusLine, 0), 0, statusLine.length()); boolean noContentToSend = false; // assume there is content rspHdrs.set("Date", df.format(new Date())); if (contentLen == 0) { if (http10) { o.setWrappedStream(new UndefLengthOutputStream(this, ros)); close = true; } else { rspHdrs.set("Transfer-encoding", "chunked"); o.setWrappedStream(new ChunkedOutputStream(this, ros)); } } else { if (contentLen == -1) { noContentToSend = true; contentLen = 0; } /* content len might already be set, eg to implement HEAD resp */ if (rspHdrs.getFirst("Content-length") == null) { rspHdrs.set("Content-length", Long.toString(contentLen)); } o.setWrappedStream(new FixedLengthOutputStream(this, ros, contentLen)); } write(rspHdrs, tmpout); this.rspContentLen = contentLen; tmpout.flush(); tmpout = null; sentHeaders = true; if (noContentToSend) { WriteFinishedEvent e = new WriteFinishedEvent(this); server.addEvent(e); closed = true; } server.logReply(rCode, req.requestLine(), null); }
@Override public String toString() { StringBuilder builder = new StringBuilder(); Headers headers = getHeaders(); if (headers != null) { Set<String> keys = headers.keySet(); for (String key : keys) { List<String> values = headers.getValues(key); for (String value : values) { if (key != null) { builder.append(key).append(": "); } builder.append(value).append("\n"); } } } T result = get(); if (result != null) builder.append(result.toString()); return builder.toString(); }
private static void doImportExportServices(ResourceImpl resource, Headers headers) { Clause[] imports = Parser.parseHeader(headers.getHeader(Constants.IMPORT_SERVICE)); for (int i = 0; imports != null && i < imports.length; i++) { RequirementImpl ri = new RequirementImpl(Capability.SERVICE); ri.setFilter(createServiceFilter(imports[i])); ri.addText("Import Service " + imports[i].getName()); String avail = imports[i].getDirective("availability"); String mult = imports[i].getDirective("multiple"); ri.setOptional("optional".equalsIgnoreCase(avail)); ri.setMultiple(!"false".equalsIgnoreCase(mult)); resource.addRequire(ri); } Clause[] exports = Parser.parseHeader(headers.getHeader(Constants.EXPORT_SERVICE)); for (int i = 0; exports != null && i < exports.length; i++) { CapabilityImpl cap = createServiceCapability(exports[i]); resource.addCapability(cap); } }
public Set<Cookie> getCookies() { if (cookies == null) { String header = headers.get(HttpHeaderNames.COOKIE); if (header == null || header.length() == 0) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(header); } } return cookies; }
/** Converts the Conditionals into real headers. */ public Headers toHeaders() { Headers headers = new Headers(); if (!getMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch()))); } if (!getNoneMatch().isEmpty()) { headers = headers.add( new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch()))); } if (modifiedSince != null) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince)); } if (unModifiedSince != null) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince)); } return headers; }
@Override public void handle(HttpExchange t) throws IOException { if (RemoteUtil.deny(t)) { throw new IOException("Access denied"); } String id = RemoteUtil.getId("thumb/", t); LOGGER.trace("web thumb req " + id); if (id.contains("logo")) { RemoteUtil.sendLogo(t); return; } RootFolder root = parent.getRoot(RemoteUtil.userName(t), t); if (root == null) { LOGGER.debug("weird root in thumb req"); throw new IOException("Unknown root"); } final DLNAResource r = root.getDLNAResource(id, root.getDefaultRenderer()); if (r == null) { // another error LOGGER.debug("media unknown"); throw new IOException("Bad id"); } InputStream in; if (!configuration.isShowCodeThumbs() && !r.isCodeValid(r)) { // we shouldn't show the thumbs for coded objects // unless the code is entered in = r.getGenericThumbnailInputStream(null); } else { r.checkThumbnail(); in = r.getThumbnailInputStream(); } Headers hdr = t.getResponseHeaders(); hdr.add("Content-Type", r.getThumbnailContentType()); hdr.add("Accept-Ranges", "bytes"); hdr.add("Connection", "keep-alive"); t.sendResponseHeaders(200, in.available()); OutputStream os = t.getResponseBody(); LOGGER.trace("input is {} output is {}", in, os); RemoteUtil.dump(in, os); }
public Result authenticate(HttpExchange t) { Headers rmap = t.getRequestHeaders(); /* * look for auth token */ String auth = rmap.getFirst("Authorization"); if (auth == null) { Headers map = t.getResponseHeaders(); map.set("WWW-Authenticate", "Basic realm=" + "\"" + realm + "\""); return new Authenticator.Retry(401); } int sp = auth.indexOf(' '); if (sp == -1 || !auth.substring(0, sp).equals("Basic")) { return new Authenticator.Failure(401); } byte[] b = Base64.getDecoder().decode(auth.substring(sp + 1)); String userpass = new String(b); int colon = userpass.indexOf(':'); String uname = userpass.substring(0, colon); String pass = userpass.substring(colon + 1); if (checkCredentials(uname, pass)) { return new Authenticator.Success(new HttpPrincipal(uname, realm)); } else { /* reject the request again with 401 */ Headers map = t.getResponseHeaders(); map.set("WWW-Authenticate", "Basic realm=" + "\"" + realm + "\""); return new Authenticator.Failure(401); } }
private static void doImports(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.IMPORT_PACKAGE)); for (int i = 0; clauses != null && i < clauses.length; i++) { RequirementImpl requirement = new RequirementImpl(Capability.PACKAGE); createImportFilter(requirement, Capability.PACKAGE, clauses[i]); requirement.addText("Import package " + clauses[i]); requirement.setOptional( Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase( clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE))); resource.addRequire(requirement); } }
private void readHeaders() throws IOException { sendCommand("top " + String.valueOf(number) + " 0"); String currentName = null; String currentValue = ""; for (String s = readLine(); s != null && !s.equals("."); s = readLine()) { if (!s.trim().equals("")) { if (Character.isWhitespace(s.charAt(0)) || s.indexOf(':') <= 0) { currentValue += "\n" + s; } else { if (currentName != null) { headers.set(currentName, currentValue); } currentName = s.substring(0, s.indexOf(':')).trim(); currentValue = s.substring(s.indexOf(':') + 1).trim(); } } } if (currentName != null) { headers.set(currentName, currentValue); } if (headers.get("X-UIDL").length == 0) { StringTokenizer tokenizer = new StringTokenizer(sendCommand("uidl " + String.valueOf(number)), " "); if (tokenizer.countTokens() == 3) { tokenizer.nextToken(); tokenizer.nextToken(); headers.set("X-UIDL", tokenizer.nextToken()); } } }
private void init( Headers h, long lastMod, long fileLength, String url, int blocksize, int[] hashLengths, String sha1) { h.version = "jazsync"; h.mTime = lastMod; h.url = url; h.length = fileLength; if (isPowerOfTwo(blocksize)) { h.blocksize = blocksize; } else { throw new IllegalArgumentException("Blocksize must be a power of 2 (512, 1024, 2048, ...)"); } h.setSeqNum(hashLengths[0]); h.setRsumBytes(hashLengths[1]); h.setChecksumBytes(hashLengths[2]); h.sha1 = sha1; }
private static void doExecutionEnvironment(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); if (clauses != null && clauses.length > 0) { StringBuffer sb = new StringBuffer(); sb.append("(|"); for (int i = 0; i < clauses.length; i++) { sb.append("("); sb.append(Capability.EXECUTIONENVIRONMENT); sb.append("="); sb.append(clauses[i].getName()); sb.append(")"); } sb.append(")"); RequirementImpl req = new RequirementImpl(Capability.EXECUTIONENVIRONMENT); req.setFilter(sb.toString()); req.addText("Execution Environment " + sb.toString()); resource.addRequire(req); } }
void write(Headers map, OutputStream os) throws IOException { Set<Map.Entry<String, List<String>>> entries = map.entrySet(); for (Map.Entry<String, List<String>> entry : entries) { String key = entry.getKey(); byte[] buf; List<String> values = entry.getValue(); for (String val : values) { int i = key.length(); buf = bytes(key, 2); buf[i++] = ':'; buf[i++] = ' '; os.write(buf, 0, i); buf = bytes(val, 2); i = val.length(); buf[i++] = '\r'; buf[i++] = '\n'; os.write(buf, 0, i); } } os.write('\r'); os.write('\n'); }
private static void doRequires(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.REQUIRE_BUNDLE)); for (int i = 0; clauses != null && i < clauses.length; i++) { RequirementImpl r = new RequirementImpl(Capability.BUNDLE); VersionRange v = VersionRange.parseVersionRange( clauses[i].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE)); StringBuffer sb = new StringBuffer(); sb.append("(&(symbolicname="); sb.append(clauses[i].getName()); sb.append(")"); appendVersion(sb, v); sb.append(")"); r.setFilter(sb.toString()); r.addText("Require Bundle " + clauses[i].getName() + "; " + v); r.setOptional( Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase( clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE))); resource.addRequire(r); } }
@Override public boolean isChunkedTransfer() { return Iterables.any( headers.getAll(HttpHeaderNames.TRANSFER_ENCODING), HttpHeaderValues.CHUNKED::contentEqualsIgnoreCase); }
@Override public boolean isExpectsContinue() { return Iterables.any( headers.getAll(HttpHeaderNames.EXPECT), HttpHeaderValues.CONTINUE::contentEqualsIgnoreCase); }
@Override public MediaType getContentType() { return DefaultMediaType.get(headers.get(HttpHeaderNames.CONTENT_TYPE)); }
public boolean isAjaxRequest() { return HttpHeaderConstants.XML_HTTP_REQUEST.equalsIgnoreCase( headers.get(HttpHeaderConstants.X_REQUESTED_WITH)); }