Example usage for org.apache.http.entity StringEntity setContentType

List of usage examples for org.apache.http.entity StringEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:TestHTTPSource.java

@Test
public void testSimple() throws IOException, InterruptedException {

    StringEntity input = new StringEntity("[{\"headers\":{\"a\": \"b\"},\"body\": \"random_body\"},"
            + "{\"headers\":{\"e\": \"f\"},\"body\": \"random_body2\"}]");
    //if we do not set the content type to JSON, the client will use
    //ISO-8859-1 as the charset. JSON standard does not support this.
    input.setContentType("application/json");
    postRequest.setEntity(input);/*from  ww  w  . j a  va  2s.c  o  m*/

    HttpResponse response = httpClient.execute(postRequest);

    Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    Transaction tx = channel.getTransaction();
    tx.begin();
    Event e = channel.take();
    Assert.assertNotNull(e);
    Assert.assertEquals("b", e.getHeaders().get("a"));
    Assert.assertEquals("random_body", new String(e.getBody(), "UTF-8"));

    e = channel.take();
    Assert.assertNotNull(e);
    Assert.assertEquals("f", e.getHeaders().get("e"));
    Assert.assertEquals("random_body2", new String(e.getBody(), "UTF-8"));
    tx.commit();
    tx.close();
}

From source file:com.tremolosecurity.provisioning.core.providers.AlfrescoProviderREST.java

@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request)
        throws ProvisioningException {

    int approvalID = 0;

    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }//ww  w  .  j  a v a  2 s. c  o  m

    Workflow workflow = (Workflow) request.get("WORKFLOW");

    String token = "";

    try {
        token = this.login();
    } catch (Exception e) {
        throw new ProvisioningException("Could not initialize Alfresco Web Services Client", e);
    }

    AlfrescoUser userDetails;
    try {
        userDetails = userLookup(user.getUserID(), token);
    } catch (Exception e) {
        this.createUser(user, attributes, request);
        return;
    }

    for (String attrName : user.getAttribs().keySet()) {
        Attribute attr = user.getAttribs().get(attrName);

        if (!attributes.contains(attr.getName())) {
            continue;
        }

        StringBuffer b = new StringBuffer();
        b.append("set").append(attrName.toUpperCase().charAt(0)).append(attrName.substring(1));
        String methodName = b.toString();

        try {
            Method method = AlfrescoUser.class.getMethod(methodName, String.class);
            method.invoke(userDetails, attr.getValues().get(0));
        } catch (Exception e) {
            throw new ProvisioningException("Could not create user", e);
        }

    }

    Gson gson = new Gson();
    String json = gson.toJson(userDetails, AlfrescoUser.class);

    StringBuffer b = new StringBuffer();
    b.append(this.endpoint).append("/people/").append(user.getUserID()).append("?alf_ticket=").append(token);

    HttpPut httpput = new HttpPut(b.toString());
    try {
        LastMileUtil.addLastMile(cfg, loginId, HEADER_NAME, httpput, lastMileKeyAlias, useLastMile);
    } catch (Exception e) {
        throw new ProvisioningException("Error generating provisioning last mile", e);
    }
    //httpput.addHeader("X-Alfresco-Remote-User", this.loginId);

    try {
        StringEntity data = new StringEntity(json);
        data.setContentType("application/json");
        httpput.setEntity(data);

        try {
            CloseableHttpResponse response = httpclient.execute(httpput);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Exception("error");
            }

            response.close();
        } finally {

            httpput.releaseConnection();
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not sync user", e);
    }

    for (String attrName : user.getAttribs().keySet()) {
        Attribute attr = user.getAttribs().get(attrName);
        if (!attributes.contains(attr.getName())) {
            continue;
        }

        this.cfg.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID, workflow,
                attrName, user.getAttribs().get(attrName).getValues().get(0));

    }

    ArrayList<String> tmpgroups = new ArrayList<String>();
    tmpgroups.addAll(user.getGroups());
    List<String> groups = null;
    try {
        groups = this.groupUserGroups(user.getUserID(), token);
    } catch (Exception e1) {
        throw new ProvisioningException("Could not load groups", e1);
    }

    if (groups != null) {
        for (String group : groups) {

            if (tmpgroups.contains(group)) {
                tmpgroups.remove(group);
            } else {
                if (!addOnly) {
                    this.deleteUserFromGroup(token, user.getUserID(), group, approvalID, workflow);
                }
            }
        }

        for (String group : tmpgroups) {
            this.addUsertoGroup(token, user.getUserID(), group, approvalID, workflow);
        }
    }

}

From source file:com.tremolosecurity.provisioning.core.providers.AlfrescoProviderREST.java

@Override
public void createUser(User user, Set<String> attributes, Map<String, Object> request)
        throws ProvisioningException {

    int approvalID = 0;

    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }//from w ww .ja  v  a  2  s  . co  m

    Workflow workflow = (Workflow) request.get("WORKFLOW");

    String token = "";

    try {
        token = this.login();
    } catch (Exception e) {
        throw new ProvisioningException("Could not initialize Alfresco Web Services Client", e);
    }

    AlfrescoUser newUser = new AlfrescoUser();
    AlfrescoUser createdUser = null;

    for (String attrName : user.getAttribs().keySet()) {
        Attribute attr = user.getAttribs().get(attrName);

        if (!attributes.contains(attr.getName())) {

            continue;
        }

        StringBuffer b = new StringBuffer();
        b.append("set").append(attrName.toUpperCase().charAt(0)).append(attrName.substring(1));
        String methodName = b.toString();

        try {
            Method method = AlfrescoUser.class.getMethod(methodName, String.class);
            method.invoke(newUser, attr.getValues().get(0));
        } catch (Exception e) {
            throw new ProvisioningException("Could not create user", e);
        }

    }

    newUser.setEnabled(true);

    Gson gson = new Gson();
    String json = gson.toJson(newUser, AlfrescoUser.class);

    StringBuffer b = new StringBuffer();
    b.append(this.endpoint).append("/people?alf_ticket=").append(token);
    HttpPost httppost = new HttpPost(b.toString());
    try {
        LastMileUtil.addLastMile(cfg, loginId, HEADER_NAME, httppost, lastMileKeyAlias, useLastMile);
    } catch (Exception e) {
        throw new ProvisioningException("Error generating provisioning last mile", e);
    }
    //httppost.addHeader("X-Alfresco-Remote-User", this.loginId);

    try {
        StringEntity data = new StringEntity(json);
        data.setContentType("application/json");
        httppost.setEntity(data);

        StringBuffer sb = new StringBuffer();
        String line = null;

        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() != 200) {

                response.close();
                httppost.releaseConnection();
                //
                throw new Exception("error");
            } else {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                while ((line = in.readLine()) != null) {
                    sb.append(line).append('\n');
                }
                in.close();
                createdUser = gson.fromJson(sb.toString(), AlfrescoUser.class);
            }

            response.close();

            this.cfg.getProvisioningEngine().logAction(this.name, true, ActionType.Add, approvalID, workflow,
                    "userName", createdUser.getUserName());
        } finally {

            httppost.releaseConnection();
        }
    } catch (Exception e) {

        //

        throw new ProvisioningException("Could not create user", e);

    }

    for (String attrName : user.getAttribs().keySet()) {
        Attribute attr = user.getAttribs().get(attrName);

        if (!attributes.contains(attr.getName())) {

            continue;
        }

        this.cfg.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow,
                attrName, user.getAttribs().get(attrName).getValues().get(0));

    }

    for (String group : user.getGroups()) {
        addUsertoGroup(token, createdUser.getUserName(), group, approvalID, workflow);
    }

    //

}

From source file:com.semagia.cassa.client.GraphClient.java

/**
 * Modifies a graph on the server using a query.
 * //from   ww  w.ja  v  a  2s .  co m
 * @param graphURI The graph URI.
 * @param query A query, i.e. SPARQL 1.1 Update.
 * @param mediaType The the content type of the query.
 * @return {@code true} indicating that the graph was updated sucessfully,
 *          otherwise {@code false}.
 * @throws IOException In case of an error.
 */
public boolean modifyGraph(final URI graphURI, final String query, final MediaType mediaType)
        throws IOException {
    final HttpPatch request = new HttpPatch(getGraphURI(graphURI));
    final StringEntity entity = new StringEntity(query);
    // From the spec it's unclear if a media type is required
    // <http://www.w3.org/TR/2012/WD-sparql11-http-rdf-update-20120501/#http-patch>
    // Other methods do not require a media type and the server should guess it/assume a default
    // so we don't mandate a media type here.
    entity.setContentType(mediaType != null ? mediaType.toString() : null);
    request.setEntity(entity);
    final int status = getStatusCode(request);
    return status == 200 || status == 204;
}

From source file:ea.compoment.http.BaseAsyncHttpClient.java

/**
 * TODO ?gson/* ww w.ja  v a2  s  .com*/
 * 
 * @param map
 * @return
 */
private HttpEntity mapParamsToEntity(HashMap<String, Object> map) {

    Gson gson = new Gson();

    String requestStr = gson.toJson(map);

    LogUtil.d(TAGLOG.TAG_HTTP, "request-->" + requestStr.toString());

    StringEntity entity = null;
    try {
        entity = new StringEntity(requestStr, HTTP.UTF_8);
        entity.setContentType("application/json");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } finally {
        gson = null;
    }

    return entity;
}

From source file:org.alfresco.test.util.UserService.java

/**
 * Add dashlet to user dashboard//from  w  ww  .  j  av  a 2  s.co  m
 * 
 * @param userName String identifier
 * @param password
 * @param dashlet
 * @param layout
 * @param column
 * @param position
 * @return true if the dashlet is added
 * @throws Exception if error
 */
public boolean addDashlet(final String userName, final String password, final UserDashlet dashlet,
        final DashletLayout layout, final int column, final int position) throws Exception {
    login(userName, password);
    AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject();
    String url = client.getAlfrescoUrl() + DashboardCustomization.ADD_DASHLET_URL;
    org.json.JSONObject body = new org.json.JSONObject();
    org.json.JSONArray array = new org.json.JSONArray();
    body.put("dashboardPage", "user/" + userName + "/dashboard");
    body.put("templateId", layout.id);

    // keep default dashlets
    Hashtable<String, String> defaultDashlets = new Hashtable<String, String>();
    defaultDashlets.put(UserDashlet.MY_SITES.id, "component-1-1");
    defaultDashlets.put(UserDashlet.MY_TASKS.id, "component-1-2");
    defaultDashlets.put(UserDashlet.MY_ACTIVITIES.id, "component-2-1");
    defaultDashlets.put(UserDashlet.MY_DOCUMENTS.id, "component-2-2");

    Iterator<Map.Entry<String, String>> entries = defaultDashlets.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        org.json.JSONObject jDashlet = new org.json.JSONObject();
        jDashlet.put("url", entry.getKey());
        jDashlet.put("regionId", entry.getValue());
        jDashlet.put("originalRegionId", entry.getValue());
        array.put(jDashlet);
    }

    org.json.JSONObject newDashlet = new org.json.JSONObject();
    newDashlet.put("url", dashlet.id);
    String region = "component-" + column + "-" + position;
    newDashlet.put("regionId", region);
    array.put(newDashlet);
    body.put("dashlets", array);

    HttpPost post = new HttpPost(url);
    StringEntity se = new StringEntity(body.toString(), AlfrescoHttpClient.UTF_8_ENCODING);
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON));
    post.setEntity(se);
    try {
        HttpResponse response = client.executeRequest(post);
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            if (logger.isTraceEnabled()) {
                logger.trace("Dashlet " + dashlet.name + " was added on user: " + userName + " dashboard");
            }
            return true;
        } else {
            logger.error("Unable to add dashlet to user dashboard " + userName);
        }
    } finally {
        post.releaseConnection();
        client.close();
    }
    return false;
}

From source file:org.forgerock.openam.authentication.modules.impersonation.ImpersonationModule.java

/**
 * {@inheritDoc}//from  w  ww.  j  a va 2 s.c  o  m
 */
@Override
public int process(Callback[] callbacks, int state) throws LoginException {

    System.out.println("INSIDE process of ImpersonationModule, state: " + state);

    if (debug.messageEnabled()) {
        debug.message("ImpersonationModule::process state: " + state);
    }
    int nextState = ISAuthConstants.LOGIN_SUCCEED;
    switch (state) {
    case 4:
        System.out.println("state 4");
        // error condition, show page
        throw new AuthLoginException("Incorrect authorization!");
    case 1:
        substituteUIStrings();
        //nextState = ISAuthConstants.LOGIN_SUCCEED;
        nextState = 2;
        break;
    case 3:
        userName = ((NameCallback) callbacks[0]).getName();
        String userPassword = String.valueOf(((PasswordCallback) callbacks[1]).getPassword());
        if (userPassword == null || userPassword.length() == 0) {
            if (debug.messageEnabled()) {
                debug.message("Impersonation.process: Password is null/empty");
            }
            throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
        }
        //store username password both in success and failure case
        storeUsernamePasswd(userName, userPassword);

        AMIdentityRepository idrepo = getAMIdentityRepository(getRequestOrg());
        Callback[] idCallbacks = new Callback[2];
        try {
            idCallbacks = callbacks;
            boolean success = idrepo.authenticate(idCallbacks);
            // proceed if admin authenticated
            if (success) {

                validatedUserID = null;
                // 1. Search for group membership
                if (checkGroupMembership.equalsIgnoreCase("true")) {

                    AMIdentity amIdentity = getGroupIdentity(groupName);
                    Set<String> attr = (Set<String>) amIdentity.getAttribute("uniqueMember");
                    Iterator<String> i = attr.iterator();
                    // check if sign on user is memberof group 
                    while (i.hasNext()) {
                        try {
                            String member = (String) i.next();
                            System.out.println("value of attribute: " + member);
                            // check previously authenticated user is a memberof
                            userName = (String) sharedState.get(getUserKey());
                            System.out.println("userName to check: " + userName);
                            if (member.indexOf(userName) != -1) {
                                System.out.println("match found! admin: " + userName
                                        + " allowed to impersonate user: " + userResponse);

                                // for sanity, ensure the supplied userid is a valid one
                                try {
                                    validatedUserID = userResponse; // create session for the userid provided by admin 
                                    AMIdentity impersonatedId = getIdentity(validatedUserID);
                                    // optionally, we default to LOGIN_SUCCEED
                                    //nextState = ISAuthConstants.LOGIN_SUCCEED;

                                } catch (Exception ex) {
                                    System.out.println("Exception thrown validating impersonated userid " + ex);
                                    throw new AuthLoginException(
                                            "EImpersonationModule: Exception thrown validating impersonated userid");
                                }
                                break;
                            }
                        } catch (Exception e) {
                            System.out.println("Cannot parse json. " + e);
                            throw new AuthLoginException(
                                    "Cannot parse json..unable to read attribtue value using amIdentity");
                        }
                    }
                    if (checkGroupMembership.equalsIgnoreCase("true") && validatedUserID == null) {
                        // Admin was not authorized to impersonate other users
                        nextState = 4;
                        throw new AuthLoginException("Admin was not authorized to impersonate other users");
                    }
                }

                // 2. Check for policy evaluation
                // get the ssoToken first, for use with the REST call
                String url = openamServer + "/json/" + authnRealm + "/authenticate";
                HttpClient httpClient = HttpClientBuilder.create().build();
                HttpPost postRequest = new HttpPost(url);
                String cookie = "";
                try {

                    System.out.println("BEFORE policy1 eval...");

                    postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

                    // TBD: replace with admin provided username and password- stick this code into the impersonate auth module
                    postRequest.setHeader("X-OpenAM-Username", userName);
                    postRequest.setHeader("X-OpenAM-Password", userPassword);

                    StringEntity input = new StringEntity("{}");
                    input.setContentType("application/json");
                    postRequest.setEntity(input);

                    HttpResponse response = httpClient.execute(postRequest);

                    String json = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println("json/" + authnRealm + "/authenticate response-> " + json);
                    try {
                        JSONParser parser = new JSONParser();
                        Object resultObject = parser.parse(json);

                        if (resultObject instanceof JSONArray) {
                            JSONArray array = (JSONArray) resultObject;
                            for (Object object : array) {
                                JSONObject obj = (JSONObject) object;
                                System.out.println("jsonarray-> " + obj);
                            }

                        } else if (resultObject instanceof JSONObject) {
                            JSONObject obj = (JSONObject) resultObject;
                            System.out.println("tokenId-> " + obj.get("tokenId"));
                            cookie = (String) obj.get("tokenId");
                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                        nextState = 4;
                    }
                    System.out.println("AFTER policy1 eval...");
                    // Headers
                    org.apache.http.Header[] headers = response.getAllHeaders();
                    for (int j = 0; j < headers.length; j++) {
                        System.out.println(headers[j]);
                    }

                } catch (Exception e) {
                    System.err.println("Fatal  error: " + e.getMessage());
                    e.printStackTrace();
                    nextState = 4;
                }

                System.out.println("BEFORE policy2 eval...");

                /*Cookie[] cookies = getHttpServletRequest().getCookies();
                        
                        
                if (cookies != null) {
                  for (int m = 0; m < cookies.length; m++) {
                     System.out.println(cookies[m].getName() +":"+cookies[m].getValue());
                    if (cookies[m].getName().equalsIgnoreCase("iPlanetDirectoryPro")) {
                      cookie = cookies[m].getValue();
                      break;
                    }
                  }
                }*/
                url = openamServer + "/json/" + policyRealm + "/policies?_action=evaluate";
                //httpClient = HttpClientBuilder.create().build();
                postRequest = new HttpPost(url);
                try {

                    postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                    postRequest.setHeader("iPlanetDirectoryPro", cookie);

                    StringEntity input = new StringEntity(
                            "{\"resources\": [\"" + new URL(resourceSet) + "\"],\"application\":\"" + policySet
                                    + "\", \"subject\": {\"ssoToken\":\"" + cookie + "\"}}");

                    System.out.println("stringentity-> " + getStringFromInputStream(input.getContent()));
                    input.setContentType("application/json");
                    postRequest.setEntity(input);

                    HttpResponse response = httpClient.execute(postRequest);

                    String json = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println("json/" + policyRealm + "/policies?_action=evaluate response-> " + json);
                    try {
                        JSONParser parser = new JSONParser();
                        Object resultObject = parser.parse(json);

                        if (resultObject instanceof JSONArray) {
                            JSONArray array = (JSONArray) resultObject;
                            for (Object object : array) {
                                JSONObject obj = (JSONObject) object;
                                System.out.println("jsonarray-> " + obj);

                                JSONObject actions = (JSONObject) obj.get("actions");
                                Boolean actionGet = (Boolean) actions.get("GET");
                                Boolean actionPost = (Boolean) actions.get("POST");
                                System.out.println("actionGet : " + actionGet);
                                System.out.println("actionPost : " + actionPost);

                                if (actionGet != null && actionGet.equals(true) && actionPost != null
                                        && actionPost.equals(true)) {
                                    nextState = ISAuthConstants.LOGIN_SUCCEED;
                                } else {
                                    System.out.println("actionget and actionpost are not true");
                                    nextState = 4;
                                }
                            }

                        } else {
                            // something went wrong!
                            System.out.println("resultObject is not a JSONArray");
                            nextState = 4;
                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                        nextState = 4;
                        System.out.println("exception invoking json parsing routine");
                        e.printStackTrace();
                    }
                    System.out.println("AFTER policy2 eval...");
                    // Headers
                    org.apache.http.Header[] headers = response.getAllHeaders();
                    for (int j = 0; j < headers.length; j++) {
                        System.out.println(headers[j]);
                    }

                    // logout the administrator
                    url = openamServer + "/json/" + authnRealm + "/sessions/?_action=logout";
                    System.out.println("destroying admin session: " + url);
                    postRequest = new HttpPost(url);
                    try {
                        postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                        postRequest.setHeader("iPlanetDirectoryPro", cookie);
                        response = httpClient.execute(postRequest);
                        try {
                            JSONParser parser = new JSONParser();
                            Object resultObject = parser.parse(json);
                            if (resultObject instanceof JSONArray) {
                                JSONArray array = (JSONArray) resultObject;
                                for (Object object : array) {
                                    JSONObject obj = (JSONObject) object;
                                    System.out.println("logout response-array-> " + obj);
                                }
                            } else {
                                JSONObject obj = (JSONObject) resultObject;
                                System.out.println("logout response-> " + obj);
                            }
                        } catch (Exception e) {
                            System.out.println("unable to read logout json response");
                            e.printStackTrace();
                        }

                    } catch (Exception e) {
                        System.out.println(
                                "Issue destroying administrator's session, still proceeding with impersonation");
                        e.printStackTrace();

                    }

                } catch (Exception e) {
                    System.err.println("Fatal  error: " + e.getMessage());
                    e.printStackTrace();
                    nextState = 4;
                }

                // else of admin successful login   
            } else {
                System.out.println("username:password read from callback: " + userName + " : " + userPassword);
                nextState = 4;
                throw new AuthLoginException(amAuthImpersonation, "authFailed", null);
            }
        } catch (com.sun.identity.idm.IdRepoException idrepox) {
            System.out.println("IdRepoException thrown " + idrepox);
            nextState = 4;
            throw new AuthLoginException("IdRepoException thrown from Impersonation module");
        } catch (SSOException ssoe) {
            System.out.println("SSOException thrown " + ssoe);
            nextState = 4;
            throw new AuthLoginException("SSOException thrown from ImpersonationModule module");
        }

        break;
    case 2:
        javax.security.auth.callback.NameCallback response = (javax.security.auth.callback.NameCallback) callbacks[0];
        userResponse = new String(response.getName());
        // check the response against OpenDJ
        System.out.println("user to impersonate : state 2: " + userResponse);

        nextState = 3;

        break;
    default:
        throw new AuthLoginException("invalid state");

    }
    return nextState;
}

From source file:de.geeksfactory.opacclient.apis.Open.java

protected SearchRequestResult parse_search(Document doc, int page) throws OpacErrorException {
    searchResultDoc = doc;/*from w  ww .j ava2  s. c om*/

    if (doc.select("#Label1, span[id$=LblInfoMessage]").size() > 0) {
        String message = doc.select("#Label1, span[id$=LblInfoMessage]").text();
        if (message.contains("keine Treffer")) {
            return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1, page);
        } else {
            throw new OpacErrorException(message);
        }
    }

    int totalCount = Integer.parseInt(doc.select("span[id$=TotalItemsLabel]").first().text());

    Elements elements = doc.select("div[id$=divMedium], div[id$=divComprehensiveItem]");
    List<SearchResult> results = new ArrayList<>();
    int i = 0;
    for (Element element : elements) {
        SearchResult result = new SearchResult();
        // Cover
        if (element.select("input[id$=mediumImage]").size() > 0) {
            result.setCover(element.select("input[id$=mediumImage]").first().attr("src"));
        } else if (element.select("img[id$=CoverView_Image]").size() > 0) {
            result.setCover(getCoverUrl(element.select("img[id$=CoverView_Image]").first()));
        }

        Element catalogueContent = element.select(".catalogueContent").first();
        // Media Type
        if (catalogueContent.select("#spanMediaGrpIcon").size() > 0) {
            String mediatype = catalogueContent.select("#spanMediaGrpIcon").attr("class");
            if (mediatype.startsWith("itemtype ")) {
                mediatype = mediatype.substring("itemtype ".length());
            }

            SearchResult.MediaType defaulttype = defaulttypes.get(mediatype);
            if (defaulttype == null)
                defaulttype = SearchResult.MediaType.UNKNOWN;

            if (data.has("mediatypes")) {
                try {
                    result.setType(SearchResult.MediaType
                            .valueOf(data.getJSONObject("mediatypes").getString(mediatype)));
                } catch (JSONException e) {
                    result.setType(defaulttype);
                }
            } else {
                result.setType(defaulttype);
            }
        } else {
            result.setType(SearchResult.MediaType.UNKNOWN);
        }

        // Text
        String title = catalogueContent.select("a[id$=LbtnShortDescriptionValue], a[id$=LbtnTitleValue]")
                .text();
        String subtitle = catalogueContent.select("span[id$=LblSubTitleValue]").text();
        String author = catalogueContent.select("span[id$=LblAuthorValue]").text();
        String year = catalogueContent.select("span[id$=LblProductionYearValue]").text();
        String publisher = catalogueContent
                .select("span[id$=LblManufacturerValue], span[id$=LblPublisherValue]").text();
        String series = catalogueContent.select("span[id$=LblSeriesValue]").text();

        StringBuilder text = new StringBuilder();
        text.append("<b>").append(title).append("</b>");
        if (!subtitle.equals(""))
            text.append("<br/>").append(subtitle);
        if (!author.equals(""))
            text.append("<br/>").append(author);
        if (!year.equals(""))
            text.append("<br/>").append(year);
        if (!publisher.equals(""))
            text.append("<br/>").append(publisher);
        if (!series.equals(""))
            text.append("<br/>").append(series);

        result.setInnerhtml(text.toString());

        // ID
        Pattern idPattern = Pattern.compile("\\$mdv(\\d+)\\$");
        Matcher matcher = idPattern.matcher(catalogueContent.html());
        if (matcher.find()) {
            result.setId(matcher.group(1));
        }

        // Availability
        if (result.getId() != null) {
            String url = opac_url + "/DesktopModules/OCLC.OPEN.PL.DNN.SearchModule/SearchService"
                    + ".asmx/GetAvailability";
            String culture = element.select("input[name$=culture]").val();
            JSONObject data = new JSONObject();
            try {
                // Determine portalID value
                int portalId = 1;
                for (Element scripttag : doc.select("script")) {
                    String scr = scripttag.html();
                    if (scr.contains("LoadSharedCatalogueViewAvailabilityAsync")) {
                        Pattern portalIdPattern = Pattern
                                .compile(".*LoadSharedCatalogueViewAvailabilityAsync\\([^,]*,[^,]*,"
                                        + "[^0-9,]*([0-9]+)[^0-9,]*,.*\\).*");
                        Matcher portalIdMatcher = portalIdPattern.matcher(scr);
                        if (portalIdMatcher.find()) {
                            portalId = Integer.parseInt(portalIdMatcher.group(1));
                        }
                    }
                }

                data.put("portalId", portalId).put("mednr", result.getId()).put("culture", culture)
                        .put("requestCopyData", false).put("branchFilter", "");
                StringEntity entity = new StringEntity(data.toString());
                entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
                String json = httpPost(url, entity, getDefaultEncoding());
                JSONObject availabilityData = new JSONObject(json);
                String isAvail = availabilityData.getJSONObject("d").getString("IsAvail");
                switch (isAvail) {
                case "true":
                    result.setStatus(SearchResult.Status.GREEN);
                    break;
                case "false":
                    result.setStatus(SearchResult.Status.RED);
                    break;
                case "digital":
                    result.setStatus(SearchResult.Status.UNKNOWN);
                    break;
                }

            } catch (JSONException | IOException e) {
                e.printStackTrace();
            }
        }

        result.setNr(i);
        results.add(result);
    }
    return new SearchRequestResult(results, totalCount, page);
}