Example usage for java.util HashMap containsKey

List of usage examples for java.util HashMap containsKey

Introduction

In this page you can find the example usage for java.util HashMap containsKey.

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:me.aphymi.newbiechat.NewbieChatExecutor.java

private boolean chatters(CommandSender sender, Command cmd, String[] args) {
    if (!sender.hasPermission("newbiechat.chatters")) {
        sender.sendMessage(noPerms);/*from   w  w w  .ja va  2 s  .com*/
        return true;
    }
    HashMap<Integer, ArrayList<String>> chatterList = new HashMap<Integer, ArrayList<String>>();
    for (Player player : Bukkit.getOnlinePlayers()) {
        if (player.hasMetadata(meta)) {
            int room = player.getMetadata(meta).get(0).asInt();
            if (!chatterList.containsKey(room)) {
                chatterList.put(room, new ArrayList<String>());
            }
            chatterList.get(room).add(player.getName());
        }
    }
    if (chatterList.isEmpty()) {
        sender.sendMessage(name + "No one is currently in a chat room.");
        return true;
    }
    ArrayList<String> lines = new ArrayList<String>();
    for (Integer room : chatterList.keySet()) {
        lines.add(String.format("eRoom %s: f%s", room, StringUtils.join(chatterList.get(room), ", ")));
    }
    sender.sendMessage(StringUtils.join(lines, "\n"));
    return true;
}

From source file:csiro.pidsvc.mappingstore.action.ActionProxy.java

@Override
public void run() {
    HttpClient httpClient = new DefaultHttpClient();
    try {//from w  w w. j a  v a 2  s . c  o  m
        HttpServletRequest originalHttpRequest = _controller.getRequest();
        HttpServletResponse originalHttpResponse = _controller.getResponse();
        HttpGet httpGet = new HttpGet(getExpandedActionValue());

        if (isTraceMode())
            trace(httpGet.getRequestLine().toString());

        // Pass-through HTTP headers.
        HashMap<String, String> hmHeaders = _controller.getHttpHeaders();
        for (String header : hmHeaders.keySet()) {
            httpGet.addHeader(header, hmHeaders.get(header));
            if (isTraceMode())
                trace("\t" + header + ": " + hmHeaders.get(header));
        }

        // Handle X-Original-URI HTTP header.
        if (!hmHeaders.containsKey("X-Original-URI")) {
            String originalUri = originalHttpRequest.getScheme() + "://" + originalHttpRequest.getServerName();
            if (originalHttpRequest.getServerPort() != 80)
                originalUri += ":" + originalHttpRequest.getServerPort();
            originalUri += _controller.getUri().getOriginalUriAsString();

            httpGet.addHeader("X-Original-URI", originalUri);
            if (isTraceMode())
                trace("\tX-Original-URI: " + originalUri);
        }

        // Get the data.
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (isTraceMode())
            trace(response.getStatusLine().toString());

        // Pass HTTP headers through.
        if (!isTraceMode())
            originalHttpResponse.setStatus(response.getStatusLine().getStatusCode());
        if (entity.getContentType() != null) {
            if (isTraceMode()) {
                trace("\tContent-Type: " + entity.getContentType().getValue());
                trace("\tContent-Length: " + EntityUtils.toString(entity).getBytes().length);
            } else
                originalHttpResponse.setContentType(entity.getContentType().getValue());
        }

        String headerName;
        for (Header header : response.getAllHeaders()) {
            headerName = header.getName();
            if (headerName.equalsIgnoreCase("Expires") || headerName.equalsIgnoreCase("Cache-Control")
                    || headerName.equalsIgnoreCase("Content-Type") || headerName.equalsIgnoreCase("Set-Cookie")
                    || headerName.equalsIgnoreCase("Transfer-Encoding"))
                continue;
            if (isTraceMode())
                trace("\t" + header.getName() + ": " + header.getValue());
            else
                originalHttpResponse.addHeader(header.getName(), header.getValue());
        }

        // Pass content through.
        if (!isTraceMode())
            originalHttpResponse.getWriter().write(EntityUtils.toString(entity));
    } catch (Exception e) {
        _logger.trace("Exception occurred while proxying HTTP request.", e);
        if (isTraceMode()) {
            Throwable cause = e.getCause();
            trace("Set response status: 500; exception: "
                    + (cause == null ? e.getMessage() : cause.getMessage()));
        } else
            Http.returnErrorCode(_controller.getResponse(), 500, e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.krawler.spring.companyDetails.companyDetailsDAOImpl.java

@Override
public KwlReturnObject updateCompany(HashMap hm) throws ServiceException {
    String companyid = "";
    DateFormat dateformat = null;
    List ll = null;/*from w w  w.  j  a  v  a  2 s . c o m*/
    int dl = 0;
    try {
        Company company = null;
        if (hm.containsKey("companyid") && hm.get("companyid") != null) {
            companyid = hm.get("companyid").toString();
            if (hm.containsKey("addCompany") && (Boolean) hm.get("addCompany")) {
                company = new Company();
                company.setCompanyID(companyid);

                if (hm.containsKey("companyId") && hm.get("companyId") != null) {
                    Long companyId = (Long) hm.get("companyId");
                    company.setCompanyId(companyId);
                }
            } else {
                company = (Company) get(Company.class, companyid);
            }
        }
        if (hm.containsKey("dateformat") && hm.get("dateformat") != null) {
            dateformat = (DateFormat) hm.get("dateformat");
        }
        if (hm.containsKey("creater") && hm.get("creater") != null) {
            company.setCreator((User) get(User.class, (String) hm.get("creater")));
        }
        if (hm.containsKey("companyname") && hm.get("companyname") != null) {
            company.setCompanyName((String) hm.get("companyname"));
        }
        if (hm.containsKey("address") && hm.get("address") != null) {
            company.setAddress((String) hm.get("address"));
        }
        if (hm.containsKey("city") && hm.get("city") != null) {
            company.setCity((String) hm.get("city"));
        }
        if (hm.containsKey("state") && hm.get("state") != null) {
            company.setState((String) hm.get("state"));
        }
        if (hm.containsKey("zip") && hm.get("zip") != null) {
            company.setZipCode((String) hm.get("zip"));
        }
        if (hm.containsKey("phone") && hm.get("phone") != null) {
            company.setPhoneNumber((String) hm.get("phone"));
        }
        if (hm.containsKey("fax") && hm.get("fax") != null) {
            company.setFaxNumber((String) hm.get("fax"));
        }
        if (hm.containsKey("website") && hm.get("website") != null) {
            company.setWebsite((String) hm.get("website"));
        }
        if (hm.containsKey("mail") && hm.get("mail") != null) {
            company.setEmailID((String) hm.get("mail"));
        }
        if (hm.containsKey("domainname") && hm.get("domainname") != null) {
            company.setSubDomain((String) hm.get("domainname"));
        }
        if (hm.containsKey("country") && hm.get("country") != null) {
            company.setCountry((Country) get(Country.class, hm.get("country").toString()));
        }
        if (hm.containsKey("currency") && hm.get("currency") != null) {
            company.setCurrency((KWLCurrency) get(KWLCurrency.class, (String) hm.get("currency")));
        }
        if (hm.containsKey("timezone") && hm.get("timezone") != null) {
            KWLTimeZone timeZone = (KWLTimeZone) get(KWLTimeZone.class, (String) hm.get("timezone"));
            company.setTimeZone(timeZone);
        }
        if (hm.containsKey("deleteflag") && hm.get("deleteflag") != null) {
            company.setDeleted((Integer) hm.get("deleteflag"));
        }
        if (hm.containsKey("createdon") && hm.get("createdon") != null) {
            company.setCreatedOn(new Date());
        }
        if (hm.containsKey("activated") && hm.get("activated") != null) {
            company.setActivated(Boolean.TRUE.getBoolean(hm.get("activated").toString()));
        }
        company.setModifiedOn(new Date());
        if (hm.containsKey("holidays") && hm.get("holidays") != null) {
            JSONArray jArr = new JSONArray((String) hm.get("holidays"));
            Set<CompanyHoliday> holidays = company.getHolidays();
            holidays.clear();
            DateFormat formatter = dateformat;
            for (int i = 0; i < jArr.length(); i++) {
                CompanyHoliday day = new CompanyHoliday();
                JSONObject obj = jArr.getJSONObject(i);
                day.setDescription(obj.getString("description"));
                day.setHolidayDate(formatter.parse(obj.getString("day")));
                day.setCompany(company);
                holidays.add(day);
            }
        }
        if (hm.containsKey("logo") && hm.get("logo") != null
                && !StringUtil.isNullOrEmpty(hm.get("logo").toString())) {
            String imageName = ((FileItem) (hm.get("logo"))).getName();
            if (imageName != null && imageName.length() > 0) {
                String fileName = companyid + FileUploadHandler.getCompanyImageExt();
                company.setCompanyLogo(Constants.ImgBasePath + fileName);
                new FileUploadHandler().uploadImage((FileItem) hm.get("logo"), fileName,
                        storageHandlerImpl.GetProfileImgStorePath(), 130, 25, true, false);
            }
        }
        save(company);
        ll = new ArrayList();
        ll.add(company);
        dl = ll.size();
    } catch (Exception e) {
        throw ServiceException.FAILURE("companyDetailsDAOImpl.updateCompany", e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl);
}

From source file:org.droidparts.http.CookieJar.java

private Collection<Cookie> getCookies(URI uri) {
    HashMap<String, Cookie> map = new HashMap<String, Cookie>();
    for (Cookie cookie : getCookies()) {
        boolean suitable = uri.getHost().equals(cookie.getDomain())
                && uri.getPath().startsWith(cookie.getPath());
        if (suitable) {
            boolean put = true;
            if (map.containsKey(cookie.getName())) {
                Cookie otherCookie = map.get(cookie.getName());
                boolean betterMatchingPath = cookie.getPath().length() > otherCookie.getPath().length();
                put = betterMatchingPath;
            }// ww w.j a v  a  2 s  . c om
            if (put) {
                map.put(cookie.getName(), cookie);
            }
        }
    }
    return map.values();
}

From source file:at.pcgamingfreaks.Bukkit.RegisterablePluginCommand.java

/**
 * Un-Register command from Bukkit. Command will no longer get executed.
 *//* w  w w. j  av a2  s.  co  m*/
public void unregisterCommand() {
    try {
        Field result = owningPlugin.getServer().getPluginManager().getClass().getDeclaredField("commandMap");
        result.setAccessible(true);
        @SuppressWarnings("unchecked")
        HashMap<String, Command> knownCommands = (HashMap<String, Command>) FIELD_KNOWN_COMMANDS
                .get(result.get(owningPlugin.getServer().getPluginManager()));
        knownCommands.remove(getName());
        for (String alias : getAliases()) {
            if (knownCommands.containsKey(alias) && knownCommands.get(alias).toString().contains(getName())) {
                knownCommands.remove(alias);
            }
        }
    } catch (Exception e) {
        owningPlugin.getLogger().warning("Failed unregistering command!");
        e.printStackTrace();
    }
}

From source file:morphy.user.SocketChannelUserSession.java

public void send(String message) {
    try {/*from w ww. ja  v a2  s  . c  om*/
        /* this logic block should be commented out to get rid of multiple-login implementation. */
        if (multipleLoginsParent != null) {
            List<SocketChannelUserSession> list = multipleLoginsParent.multipleLogins;
            multipleLoginsParent.multipleLogins = null;
            multipleLoginsParent.send(message);
            multipleLoginsParent.multipleLogins = list;
        } else {
            if (multipleLogins != null) {
                for (SocketChannelUserSession sess : multipleLogins) {
                    if (sess != null)
                        sess.send(message);
                }
            }
        }

        if (isConnected()) {
            String prompt = "fics% ";
            HashMap<String, String> map = getUser().getUserVars().getVariables();
            if (map.containsKey("prompt") && map.containsKey("ptime") && map.containsKey("tzone")) {
                prompt = map.get("prompt");
                boolean useptime = map.get("ptime").equals("1");
                if (useptime) {
                    Date d = new Date();
                    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("HH:mm");
                    String tzone = getUser().getUserVars().getVariables().get("tzone").toUpperCase();
                    TimeZone tz = TimeZone.getDefault();
                    if (tzone.equals("SERVER"))
                        tzone = tz.getDisplayName(tz.inDaylightTime(d), TimeZone.SHORT);
                    sdf.setTimeZone(TimeZoneUtils.getTimeZone(tzone));
                    prompt = sdf.format(d) + "_" + prompt;
                }
            }

            ByteBuffer buffer = BufferUtils.createBuffer(
                    SocketConnectionService.getInstance().formatMessage(this, message + "\n" + prompt + " "));
            System.out.println((message + "\n\r" + prompt + " ").replace("\n", "\\n").replace("\r", "\\r"));
            try {
                channel.write(buffer);
            } catch (java.io.IOException e) {
                Morphy.getInstance().onError("IOException while trying to write to channel.", e);
            }
        } else {
            if (LOG.isInfoEnabled()) {
                LOG.info("Tried to send message to a logged off user " + user.getUserName() + " " + message);
            }
            disconnect();
        }
    } catch (Throwable t) {
        if (LOG.isErrorEnabled())
            LOG.error("Error sending message to user " + user.getUserName() + " " + message, t);
        disconnect();
    }
}

From source file:com.pablog178.pdfcreator.android.PdfcreatorModule.java

private void generateiTextPDFfunction(HashMap args) {
    if (args.containsKey("fileName")) {
        Object fileName = args.get("fileName");
        if (fileName instanceof String) {
            this.fileName = (String) fileName;
            Log.i(PROXY_NAME, "fileName: " + this.fileName);
        }/*from   ww w.j a  v  a 2 s . co m*/
    } else
        return;

    if (args.containsKey("view")) {
        Object viewObject = args.get("view");
        if (viewObject instanceof TiViewProxy) {
            TiViewProxy viewProxy = (TiViewProxy) viewObject;
            this.view = viewProxy.getOrCreateView();
            if (this.view == null) {
                Log.e(PROXY_NAME, "NO VIEW was created!!");
                return;
            }
            Log.i(PROXY_NAME, "view: " + this.view.toString());
        }
    } else
        return;

    if (args.containsKey("quality")) {
        this.quality = TiConvert.toInt(args.get("quality"));
    }

    if (args.containsKey("pageSize")) {
        Object pageSize = args.get("pageSize");
        if (pageSize instanceof String) {
            if (pageSize.equals("letter")) {
                this.pageSize = PageSize.LETTER;
            } else if (pageSize.equals("A4")) {
                this.pageSize = PageSize.A4;
            } else {
                this.pageSize = PageSize.LETTER;
            }
        }
    }

    TiBaseFile file = TiFileFactory.createTitaniumFile(this.fileName, true);
    Log.i(PROXY_NAME, "file full path: " + file.nativePath());
    try {

        Resources appResources = app.getResources();
        OutputStream outputStream = file.getOutputStream();
        final int MARGIN = 0;
        final float PDF_WIDTH = this.pageSize.getWidth() - MARGIN * 2; // A4: 595 //Letter: 612
        final float PDF_HEIGHT = this.pageSize.getHeight() - MARGIN * 2; // A4: 842 //Letter: 792
        final int DEFAULT_VIEW_WIDTH = 980;
        final int DEFAULT_VIEW_HEIGHT = 1384;
        int viewWidth = DEFAULT_VIEW_WIDTH;
        int viewHeight = DEFAULT_VIEW_HEIGHT;

        Document pdfDocument = new Document(this.pageSize, MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);

        Log.i(PROXY_NAME, "PDF_WIDTH: " + PDF_WIDTH);
        Log.i(PROXY_NAME, "PDF_HEIGHT: " + PDF_HEIGHT);

        WebView view = (WebView) this.view.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = DEFAULT_VIEW_WIDTH;
            }

            if (viewHeight <= 0) {
                viewHeight = DEFAULT_VIEW_HEIGHT;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
            viewWidth = DEFAULT_VIEW_WIDTH;
            viewHeight = DEFAULT_VIEW_HEIGHT;
        }

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Log.i(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.i(PROXY_NAME, "viewHeight: " + viewHeight);

        float scaleFactorWidth = 1 / ((float) viewWidth / PDF_WIDTH);
        float scaleFactorHeight = 1 / ((float) viewHeight / PDF_HEIGHT);

        Log.i(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.i(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);

        // Paint paintAntialias = new Paint();
        // paintAntialias.setAntiAlias(true);
        // paintAntialias.setFilterBitmap(true);

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(viewCanvas);
        } else {
            viewCanvas.drawColor(Color.WHITE);
        }
        view.draw(viewCanvas);

        TiBaseFile pdfImg = createTempFile();

        // ByteArrayOutputStream stream = new ByteArrayOutputStream(32);
        // viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, stream);
        viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, pdfImg.getOutputStream());

        FileInputStream pdfImgInputStream = new FileInputStream(pdfImg.getNativeFile());
        byte[] pdfImgBytes = IOUtils.toByteArray(pdfImgInputStream);
        pdfImgInputStream.close();

        // ByteBuffer      buffer         = ByteBuffer.allocate(viewBitmap.getByteCount());
        // viewBitmap.copyPixelsToBuffer(buffer);

        pdfDocument.open();
        float yFactor = viewHeight * scaleFactorWidth;
        int pageNumber = 1;

        do {
            if (pageNumber > 1) {
                pdfDocument.newPage();
            }
            pageNumber++;
            yFactor -= PDF_HEIGHT;

            Image pageImage = Image.getInstance(pdfImgBytes, true);
            // Image pageImage = Image.getInstance(buffer.array());
            pageImage.scalePercent(scaleFactorWidth * 100);
            pageImage.setAbsolutePosition(0f, -yFactor);
            pdfDocument.add(pageImage);

            Log.i(PROXY_NAME, "yFactor: " + yFactor);
        } while (yFactor > 0);

        pdfDocument.close();

        sendCompleteEvent();

    } catch (Exception exception) {
        Log.e(PROXY_NAME, "Error: " + exception.toString());
        sendErrorEvent(exception.toString());
    }
}

From source file:com.facebook.tsdb.tsdash.server.model.Metric.java

/**
 * create a new metric with rows aggregated after dissolving the given tags.
 * The resulted metric will not be able to accept filters on this tag
 * anymore./*from ww w .  ja  v  a 2 s  .  c  o m*/
 *
 * @param tagName
 * @param aggregatorName
 *            'sum', 'max', 'min' or 'avg'
 * @return a new Metric object that contains the aggregated rows
 * @throws IDNotFoundException
 * @throws IOException
 */
public Metric dissolveTags(ArrayList<String> tagsName, String aggregatorName)
        throws IOException, IDNotFoundException {
    if (tagsName.size() == 0) {
        return this;
    }
    HashMap<String, HashSet<String>> tagsSet = getTagsSet();
    for (String tagName : tagsName) {
        if (!tagsSet.containsKey(tagName)) {
            // TODO: throw an exception here
            logger.error("Dissolve error: tag '" + tagName + "' is not part of the tag set");
            return null;
        }
        // we can only dissolve once a given tag
        if (dissolvedTags.contains(tagName)) {
            // TODO: throw an exception here
            logger.error("Metric already dissolved tag " + tagName);
            return null;
        }
    }
    // this aligns the time series in a perfect grid
    alignAllTimeSeries();

    Metric newData = new Metric(id, name, idMap);
    Tag[] toDissolve = new Tag[tagsName.size()];
    for (int i = 0; i < toDissolve.length; i++) {
        toDissolve[i] = new Tag(tagsName.get(i), idMap);
        newData.dissolvedTags.add(tagsName.get(i));
    }
    TreeMap<TagsArray, ArrayList<ArrayList<DataPoint>>> dissolved = new TreeMap<TagsArray, ArrayList<ArrayList<DataPoint>>>(
            Tag.arrayComparator());
    // sort the tags we will dissolve for calling disableTags()
    Arrays.sort(toDissolve, Tag.keyComparator());
    for (TagsArray header : timeSeries.keySet()) {
        TagsArray dissolvedRowTags = header.copy();
        if (toDissolve.length == 1) {
            dissolvedRowTags.disableTag(toDissolve[0]);
        } else {
            dissolvedRowTags.disableTags(toDissolve);
        }
        if (!dissolved.containsKey(dissolvedRowTags)) {
            dissolved.put(dissolvedRowTags, new ArrayList<ArrayList<DataPoint>>());
        }
        dissolved.get(dissolvedRowTags).add(timeSeries.get(header));
    }
    Aggregator aggregator = getAggregator(aggregatorName);
    newData.aggregatorName = aggregatorName;
    for (TagsArray header : dissolved.keySet()) {
        newData.timeSeries.put(header, TimeSeries.aggregate(dissolved.get(header), aggregator));
    }
    return newData;
}

From source file:com.groupdocs.sdk.common.ApiInvoker.java

@SuppressWarnings("unchecked")
public <T> T invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body,
        Map<String, String> headerParams, Class<T> returnType) throws ApiException {
    Client client = getClient(host);/*from www. j a v  a2 s.  co m*/

    StringBuilder b = new StringBuilder();

    for (String key : queryParams.keySet()) {
        String value = queryParams.get(key);
        if (value != null) {
            if (b.toString().length() == 0)
                b.append("?");
            else
                b.append("&");
            b.append(escapeString(key)).append("=").append(escapeString(value));
        }
    }
    String querystring = b.toString();

    boolean isFileUpload = false;
    MediaType contentType;
    if (body == null) {
        contentType = MediaType.TEXT_HTML_TYPE;
    } else {
        contentType = MediaType.APPLICATION_JSON_TYPE;
        if (body instanceof FileStream) {
            isFileUpload = true;
            contentType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
        }
    }

    String requestUri = encodeURI(signer.signUrl(host + path + querystring)); //TODO incorrect for redirects
    Builder builder = client.resource(requestUri).type(contentType);
    builder.header("Groupdocs-Referer", PACKAGE_NAME + "/" + PACKAGE_VERSION);
    for (String key : headerParams.keySet()) {
        builder.header(key, headerParams.get(key));
    }

    for (String key : defaultHeaderMap.keySet()) {
        if (!headerParams.containsKey(key)) {
            builder.header(key, defaultHeaderMap.get(key));
        }
    }
    ClientResponse response = null;

    if ("GET".equals(method)) {
        response = (ClientResponse) builder.get(ClientResponse.class);
    } else if ("POST".equals(method)) {
        Object requestBody;
        if (isFileUpload) {
            requestBody = ((FileStream) body).getInputStream();
        } else {
            requestBody = signer.signContent(serialize(body), builder);
        }
        response = builder.post(ClientResponse.class, requestBody);
    } else if ("PUT".equals(method)) {
        Object requestBody;
        if (isFileUpload) {
            requestBody = ((FileStream) body).getInputStream();
        } else {
            requestBody = signer.signContent(serialize(body), builder);
        }
        response = builder.put(ClientResponse.class, requestBody);
    } else if ("DELETE".equals(method)) {
        response = builder.delete(ClientResponse.class);
    } else {
        throw new ApiException(500, "unknown method type " + method);
    }
    if (response.getClientResponseStatus() == ClientResponse.Status.OK
            || response.getClientResponseStatus() == ClientResponse.Status.CREATED
            || response.getClientResponseStatus() == ClientResponse.Status.ACCEPTED) {
        T toReturn;
        if (FileStream.class.equals(returnType)) {
            if (response.getHeaders().containsKey("Transfer-Encoding") || response.getLength() > 0) {
                toReturn = (T) new FileStream(requestUri, response);
            } else {
                toReturn = null;
            }
        } else {
            toReturn = (T) response.getEntity(String.class);
        }
        return toReturn;
    } else {
        String errMsg = response.getEntity(String.class);
        try {
            HashMap<String, Object> props = JsonUtil.getJsonMapper().readValue(errMsg,
                    new TypeReference<HashMap<String, Object>>() {
                    });
            if (props.containsKey("error_message")) {
                errMsg = (String) props.get("error_message");
            }
        } catch (IOException e) {
        }
        throw new ApiException(response.getClientResponseStatus().getStatusCode(), errMsg);
    }
}

From source file:org.dataconservancy.ui.services.EZIDServiceIT.java

/**
 * Tests that an ID can be deleted without exception. Tests that the id can no longer be retrieved after it is deleted.
 * @throws IOException //from   ww w . jav  a  2  s.  c om
 * @throws ClientProtocolException 
 */
@Test
public void testDelete() throws ClientProtocolException, IOException {
    boolean caughtException = false;
    String id = "";
    HttpGet getID = null;
    try {
        id = ezidService.createID(ezidMetadata);
        getID = new HttpGet(id);
        //Assert that the id can be found after being created.
        HttpResponse resp = httpClient.execute(getID);
        assertEquals(200, resp.getStatusLine().getStatusCode());

        HttpEntity respEntity = resp.getEntity();

        StringWriter writer = new StringWriter();
        IOUtils.copy(respEntity.getContent(), writer);
        String response = writer.toString();
        HashMap<String, String> metadata = parseResponse(response);

        assertTrue(metadata.containsKey("_status"));
        assertEquals("reserved", metadata.get("_status"));

        ezidService.deleteID(id);

    } catch (EZIDServiceException e) {
        caughtException = true;
    }

    assertFalse(caughtException);

    HttpResponse resp = httpClient.execute(getID);
    assertEquals(400, resp.getStatusLine().getStatusCode());

    HttpEntity respEntity = resp.getEntity();

    StringWriter writer = new StringWriter();
    IOUtils.copy(respEntity.getContent(), writer);
    String response = writer.toString();

    assertTrue(response.contains("no such identifier"));
}