Example usage for java.lang IllegalArgumentException printStackTrace

List of usage examples for java.lang IllegalArgumentException printStackTrace

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.kylinolap.rest.service.CubeService.java

/**
 * Generate cardinality for table This will trigger a hadoop job and nothing
 * The result will be merged into table exd info
 * /* w ww . jav  a2  s . com*/
 * @param tableName
 * @param delimiter
 * @param format
 */
public void generateCardinality(String tableName, String format, String delimiter) {
    TableDesc table = getMetadataManager().getTableDesc(tableName);
    Map<String, String> tableExd = getMetadataManager().getTableDescExd(tableName);
    if (tableExd == null || table == null) {
        IllegalArgumentException e = new IllegalArgumentException("Cannot find table descirptor " + tableName);
        logger.error("Cannot find table descirptor " + tableName, e);
        throw e;
    }
    Map<String, String> exd = getMetadataManager().getTableDescExd(tableName);
    if (exd == null || !Boolean.valueOf(exd.get(MetadataConstances.TABLE_EXD_STATUS_KEY))) {
        throw new IllegalArgumentException("Table " + tableName + " does not exist.");
    }
    String location = exd.get(MetadataConstances.TABLE_EXD_LOCATION);
    if (location == null || MetadataConstances.TABLE_EXD_DEFAULT_VALUE.equals(location)) {
        throw new IllegalArgumentException(
                "Cannot get table " + tableName + " location, the location is " + location);
    }
    String inputFormat = exd.get(MetadataConstances.TABLE_EXD_IF);
    if (inputFormat == null || MetadataConstances.TABLE_EXD_DEFAULT_VALUE.equals(inputFormat)) {
        throw new IllegalArgumentException(
                "Cannot get table " + tableName + " input format, the format is " + inputFormat);
    }
    String delim = exd.get(MetadataConstances.TABLE_EXD_DELIM);
    if (delimiter != null) {
        delim = delimiter;
    }
    String jarPath = getKylinConfig().getKylinJobJarPath();
    String outPath = HiveColumnCardinalityJob.OUTPUT_PATH + "/" + tableName;
    String[] args = null;
    if (delim == null) {
        args = new String[] { "-input", location, "-output", outPath, "-iformat", inputFormat };
    } else {
        args = new String[] { "-input", location, "-output", outPath, "-iformat", inputFormat, "-idelim",
                delim };
    }
    HiveColumnCardinalityJob job = new HiveColumnCardinalityJob(jarPath, null);
    int hresult = 0;
    try {
        hresult = ToolRunner.run(job, args);
    } catch (Exception e) {
        logger.error("Cardinality calculation failed. ", e);
        throw new IllegalArgumentException("Hadoop job failed with exception ", e);
    }

    // Get calculate result;
    if (hresult != 0) {
        throw new IllegalArgumentException("Hadoop job failed with result " + hresult);
    }
    List<String> columns = null;
    try {
        columns = job.readLines(new Path(outPath), job.getConf());
    } catch (IllegalArgumentException e) {
        logger.error("Failed to resolve cardinality for " + tableName + " from " + outPath, e);
        return;
    } catch (Exception e) {
        logger.error("Failed to resolve cardinality for " + tableName + " from " + outPath, e);
        return;
    }
    StringBuffer cardi = new StringBuffer();
    ColumnDesc[] cols = table.getColumns();
    if (columns.isEmpty() || cols.length != columns.size()) {
        logger.error("The hadoop cardinality column size " + columns.size()
                + " is not equal metadata column size " + cols.length + ". Table " + tableName);
    }
    Iterator<String> it = columns.iterator();
    while (it.hasNext()) {
        String string = (String) it.next();
        String[] ss = StringUtils.split(string, "\t");

        if (ss.length != 2) {
            logger.error("The hadoop cardinality value is not valid " + string);
            continue;
        }
        cardi.append(ss[1]);
        cardi.append(",");
    }
    String scardi = cardi.toString();
    scardi = scardi.substring(0, scardi.length() - 1);
    tableExd.put(MetadataConstances.TABLE_EXD_CARDINALITY, scardi);

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        JsonUtil.writeValueIndent(bos, tableExd);
        System.out.println(bos.toString());
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        String xPath = ResourceStore.TABLE_EXD_RESOURCE_ROOT + "/" + tableName.toUpperCase() + "."
                + HiveSourceTableMgmt.OUTPUT_SURFIX;
        writeResource(bis, KylinConfig.getInstanceFromEnv(), xPath);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    getMetadataManager().reload();
}

From source file:com.skytree.epubtest.BookViewActivity.java

@SuppressLint("NewApi")
public int getRawHeight() {
    int width = 0, height = 0;
    final DisplayMetrics metrics = new DisplayMetrics();
    Display display = getWindowManager().getDefaultDisplay();
    Method mGetRawH = null, mGetRawW = null;

    try {//ww w .  ja  v a  2s . com
        // For JellyBeans and onward
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            display.getRealMetrics(metrics);
            width = metrics.widthPixels;
            height = metrics.heightPixels;
        } else {
            mGetRawH = Display.class.getMethod("getRawHeight");
            mGetRawW = Display.class.getMethod("getRawWidth");
            try {
                width = (Integer) mGetRawW.invoke(display);
                height = (Integer) mGetRawH.invoke(display);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                return 0;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return 0;
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                return 0;
            }
        }
        return height;
    } catch (NoSuchMethodException e3) {
        e3.printStackTrace();
        return 0;
    }
}

From source file:com.skytree.epubtest.BookViewActivity.java

@SuppressLint("NewApi")
public int getRawWidth() {
    int width = 0, height = 0;
    final DisplayMetrics metrics = new DisplayMetrics();
    Display display = getWindowManager().getDefaultDisplay();
    Method mGetRawH = null, mGetRawW = null;

    try {//from w  ww  . jav a  2  s.c  o m
        // For JellyBeans and onward
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            display.getRealMetrics(metrics);

            width = metrics.widthPixels;
            height = metrics.heightPixels;
        } else {
            mGetRawH = Display.class.getMethod("getRawHeight");
            mGetRawW = Display.class.getMethod("getRawWidth");

            try {
                width = (Integer) mGetRawW.invoke(display);
                height = (Integer) mGetRawH.invoke(display);
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            }
        }
        return width;
    } catch (NoSuchMethodException e3) {
        e3.printStackTrace();
        return 0;
    }
}

From source file:org.fcrepo.oai.service.OAIProviderService.java

public JAXBElement<OAIPMHtype> listIdentifiers(Session session, UriInfo uriInfo, String metadataPrefix,
        String from, String until, String set, int offset) throws RepositoryException {

    final HttpIdentifierTranslator translator = new HttpIdentifierTranslator(session, FedoraNodes.class,
            uriInfo);//from w w w.  j  av a 2  s  .  co  m
    if (metadataPrefix == null) {
        return error(VerbType.LIST_IDENTIFIERS, null, null, OAIPMHerrorcodeType.BAD_ARGUMENT,
                "metadataprefix is invalid");
    }
    final MetadataFormat mdf = metadataFormats.get(metadataPrefix);
    if (mdf == null) {
        return error(VerbType.LIST_IDENTIFIERS, null, metadataPrefix,
                OAIPMHerrorcodeType.CANNOT_DISSEMINATE_FORMAT, "Unavailable metadata format");
    }
    DateTime fromDateTime = null;
    DateTime untilDateTime = null;
    try {
        fromDateTime = (from != null && !from.isEmpty()) ? dateFormat.parseDateTime(from) : null;
        untilDateTime = (until != null && !until.isEmpty()) ? dateFormat.parseDateTime(until) : null;
    } catch (IllegalArgumentException e) {
        return error(VerbType.LIST_IDENTIFIERS, null, metadataPrefix, OAIPMHerrorcodeType.BAD_ARGUMENT,
                e.getMessage());
    }

    final StringBuilder sparql = new StringBuilder("PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> ")
            .append("SELECT ?sub ?obj WHERE { ").append("?sub <").append(mdf.getPropertyName())
            .append("> ?obj . ");

    final List<String> filters = new ArrayList<>();

    if (fromDateTime != null || untilDateTime != null) {
        sparql.append("?sub <").append(RdfLexicon.LAST_MODIFIED_DATE).append("> ?date . ");
        if (fromDateTime != null) {
            filters.add("?date >='" + from + "'^^xsd:dateTime ");
        }
        if (untilDateTime != null) {
            filters.add("?date <='" + until + "'^^xsd:dateTime ");
        }
    }

    if (set != null && !set.isEmpty()) {
        if (!setsEnabled) {
            return error(VerbType.LIST_IDENTIFIERS, null, metadataPrefix, OAIPMHerrorcodeType.NO_SET_HIERARCHY,
                    "Sets are not enabled");
        }
        sparql.append("?sub <").append(propertyIsPartOfSet).append("> ?set . ");
        filters.add("?set = '" + set + "'");
    }

    int filterCount = 0;
    for (String filter : filters) {
        if (filterCount++ == 0) {
            sparql.append("FILTER (");
        }
        sparql.append(filter).append(filterCount == filters.size() ? ")" : " && ");
    }
    sparql.append("}").append(" OFFSET ").append(offset).append(" LIMIT ").append(maxListSize);
    try {
        final JQLConverter jql = new JQLConverter(session, translator, sparql.toString());
        final ResultSet result = jql.execute();
        final OAIPMHtype oai = oaiFactory.createOAIPMHtype();
        final ListIdentifiersType ids = oaiFactory.createListIdentifiersType();
        if (!result.hasNext()) {
            return error(VerbType.LIST_IDENTIFIERS, null, metadataPrefix, OAIPMHerrorcodeType.NO_RECORDS_MATCH,
                    "No record found");
        }
        while (result.hasNext()) {
            final HeaderType h = oaiFactory.createHeaderType();
            final QuerySolution sol = result.next();
            final Resource sub = sol.get("sub").asResource();
            final Resource oaiRecordUri = sol.get("obj").asResource();
            if (!this.datastreamService.exists(session, translator.getPathFromSubject(oaiRecordUri))) {
                continue;
            }
            h.setIdentifier(sub.getURI());
            final FedoraObject obj = this.objectService.getObject(session, translator.getPathFromSubject(sub));
            h.setDatestamp(dateFormat.print(obj.getLastModifiedDate().getTime()));
            // get set names this object is part of
            final Model objModel = obj.getPropertiesDataset(translator).getDefaultModel();
            final StmtIterator setNames = objModel.listStatements(translator.getSubject(obj.getPath()),
                    objModel.createProperty(propertyIsPartOfSet), (RDFNode) null);
            while (setNames.hasNext()) {
                final FedoraObject setObject = this.objectService.getObject(session,
                        setsRootPath + "/" + setNames.next().getObject().asLiteral().getString());
                final Model setObjectModel = setObject.getPropertiesDataset(translator).getDefaultModel();
                final StmtIterator setSpec = setObjectModel.listStatements(
                        translator.getSubject(setObject.getPath()), objModel.createProperty(propertyHasSetSpec),
                        (RDFNode) null);
                if (setSpec.hasNext()) {
                    h.getSetSpec().add(setSpec.next().getObject().asLiteral().getString());
                }
            }
            ids.getHeader().add(h);
        }

        final RequestType req = oaiFactory.createRequestType();
        if (ids.getHeader().size() == maxListSize) {
            req.setResumptionToken(encodeResumptionToken(VerbType.LIST_IDENTIFIERS.value(), metadataPrefix,
                    from, until, set, offset + maxListSize));
        }
        req.setVerb(VerbType.LIST_IDENTIFIERS);
        req.setMetadataPrefix(metadataPrefix);
        oai.setRequest(req);
        oai.setListIdentifiers(ids);
        return oaiFactory.createOAIPMH(oai);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RepositoryException(e);
    }
}

From source file:at.alladin.rmbt.controlServer.SettingsResource.java

/**
 * //  w w w . ja  va 2  s  . co  m
 * @param entity
 * @return
 */
@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_SETTINGS_REQUEST"), clientIpRaw));

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            String lang = request.optString("language");

            // Load Language Files for Client
            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

            // System.out.println(request.toString(4));

            if (conn != null) {

                final Client client = new Client(conn);
                int typeId = 0;

                if (request.optString("type").length() > 0) {
                    typeId = client.getTypeId(request.getString("type"));
                    if (client.hasError())
                        errorList.addError(client.getError());
                }

                final List<String> clientNames = Arrays
                        .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*"));

                final JSONArray settingsList = new JSONArray();
                final JSONObject jsonItem = new JSONObject();

                if (clientNames.contains(request.optString("name")) && typeId > 0) {

                    // String clientName = request.getString("name");
                    // String clientVersionCode =
                    // request.getString("version_name");
                    // String clientVersionName =
                    // request.optString("version_code", "");

                    UUID uuid = null;
                    long clientUid = 0;

                    final String uuidString = request.optString("uuid", "");
                    try {
                        if (!Strings.isNullOrEmpty(uuidString))
                            uuid = UUID.fromString(uuidString);
                    } catch (IllegalArgumentException e) // not a valid uuid
                    {
                    }

                    if (uuid != null && errorList.getLength() == 0) {
                        clientUid = client.getClientByUuid(uuid);
                        if (client.hasError())
                            errorList.addError(client.getError());
                    }

                    boolean tcAccepted = request.optInt("terms_and_conditions_accepted_version", 0) > 0; // accept any version for now
                    if (!tcAccepted) // allow old non-version parameter
                        tcAccepted = request.optBoolean("terms_and_conditions_accepted", false);
                    {
                        if (tcAccepted && (uuid == null || clientUid == 0)) {

                            final Timestamp tstamp = java.sql.Timestamp
                                    .valueOf(new Timestamp(System.currentTimeMillis()).toString());

                            final Calendar timeWithZone = Helperfunctions
                                    .getTimeWithTimeZone(Helperfunctions.getTimezoneId());

                            client.setTimeZone(timeWithZone);
                            client.setTime(tstamp);
                            client.setClient_type_id(typeId);
                            client.setTcAccepted(tcAccepted);

                            uuid = client.storeClient();

                            if (client.hasError())
                                errorList.addError(client.getError());
                            else
                                jsonItem.put("uuid", uuid.toString());
                        }

                        if (client.getUid() > 0) {
                            /* map server */

                            final Series<Parameter> ctxParams = getContext().getParameters();
                            final String host = ctxParams.getFirstValue("RMBT_MAP_HOST");
                            final String sslStr = ctxParams.getFirstValue("RMBT_MAP_SSL");
                            final String portStr = ctxParams.getFirstValue("RMBT_MAP_PORT");
                            if (host != null && sslStr != null && portStr != null) {
                                JSONObject mapServer = new JSONObject();
                                mapServer.put("host", host);
                                mapServer.put("port", Integer.parseInt(portStr));
                                mapServer.put("ssl", Boolean.parseBoolean(sslStr));
                                jsonItem.put("map_server", mapServer);
                            }

                            // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                            // HISTORY / FILTER

                            final JSONObject subItem = new JSONObject();

                            final JSONArray netList = new JSONArray();

                            try {

                                // deviceList:

                                subItem.put("devices", getSyncGroupDeviceList(errorList, client));

                                // network_type:

                                final PreparedStatement st = conn.prepareStatement("SELECT DISTINCT group_name"
                                        + " FROM test t" + " JOIN network_type nt ON t.network_type=nt.uid"
                                        + " WHERE t.deleted = false AND t.status = 'FINISHED' "
                                        + " AND (t.client_id IN (SELECT ? UNION SELECT uid FROM client WHERE sync_group_id = ? ))"
                                        + " AND group_name IS NOT NULL ORDER BY group_name;");

                                st.setLong(1, client.getUid());
                                st.setInt(2, client.getSync_group_id());

                                final ResultSet rs = st.executeQuery();

                                if (rs != null)
                                    while (rs.next())
                                        // netList.put(Helperfunctions.getNetworkTypeName(rs.getInt("network_type")));
                                        netList.put(rs.getString("group_name"));
                                else
                                    errorList.addError("ERROR_DB_GET_SETTING_HISTORY_NETWORKS_SQL");

                                rs.close();
                                st.close();

                                subItem.put("networks", netList);

                            } catch (final SQLException e) {
                                e.printStackTrace();
                                errorList.addError("ERROR_DB_GET_SETTING_HISTORY_SQL");
                                // errorList.addError("ERROR_DB_GET_CLIENT_SQL");
                            }

                            if (errorList.getLength() == 0)
                                jsonItem.put("history", subItem);

                        } else
                            errorList.addError("ERROR_CLIENT_UUID");
                    }

                    //also put there: basis-urls for all services
                    final JSONObject jsonItemURLs = new JSONObject();
                    jsonItemURLs.put("open_data_prefix", getSetting("url_open_data_prefix", lang));
                    jsonItemURLs.put("statistics", getSetting("url_statistics", lang));
                    jsonItemURLs.put("control_ipv4_only", getSetting("control_ipv4_only", lang));
                    jsonItemURLs.put("control_ipv6_only", getSetting("control_ipv6_only", lang));
                    jsonItemURLs.put("url_ipv4_check", getSetting("url_ipv4_check", lang));
                    jsonItemURLs.put("url_ipv6_check", getSetting("url_ipv6_check", lang));

                    jsonItem.put("urls", jsonItemURLs);

                    final JSONObject jsonControlServerVersion = new JSONObject();
                    jsonControlServerVersion.put("control_server_version", RevisionHelper.getVerboseRevision());
                    jsonItem.put("versions", jsonControlServerVersion);

                    try {
                        final Locale locale = new Locale(lang);
                        final QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale);
                        final JSONArray testTypeDescArray = new JSONArray();
                        for (QoSTestTypeDesc desc : testTypeDao.getAll()) {
                            JSONObject json = new JSONObject();
                            json.put("test_type", desc.getTestType().name());
                            json.put("name", desc.getName());
                            testTypeDescArray.put(json);
                        }
                        jsonItem.put("qostesttype_desc", testTypeDescArray);
                    } catch (SQLException e) {
                        errorList.addError("ERROR_DB_CONNECTION");
                    }

                    settingsList.put(jsonItem);
                    answer.put("settings", settingsList);

                    //debug: print settings response (JSON)
                    //System.out.println(settingsList);

                } else
                    errorList.addError("ERROR_CLIENT_VERSION");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();

    //        try
    //        {
    //            System.out.println(answer.toString(4));
    //        }
    //        catch (final JSONException e)
    //        {
    //            e.printStackTrace();
    //        }

    answerString = answer.toString();
    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_SETTINGS_REQUEST_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:com.nest5.businessClient.Initialactivity.java

public void resetData() {
    if (deviceText != null) {
        isConnecting = false;/*from  w  w w.j  av a 2 s.c om*/
        isConnected = false;
        Toast.makeText(mContext, "Comandas Desconectadas", Toast.LENGTH_LONG).show();

        deviceText.setText("Desconectado.");
        statusText.setText("Desconectado.");
        connectedIp = null;
        try {
            playSound(mContext);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation//from   w  w  w .  j  a va 2 s.  co  m
 * 
 * @param data
 * 
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("surveys")
@Summary("create new survey.")
@Notes("Requires authentication.")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Survey URL & ID (TODO: introduce Swagger models)"),
        @ApiResponse(code = 400, message = "Survey data invalid."),
        @ApiResponse(code = 401, message = "Survey creation requires authentication."),
        @ApiResponse(code = 409, message = "Survey already exists.") })
public HttpResponse createSurvey(@ContentParam String data) {
    if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) {
        HttpResponse noauth = new HttpResponse("Please authenticate to create surveys!");
        noauth.setStatus(401);
    }

    String onAction = "creating new survey";

    try {
        JSONObject o;

        // first parse survey data passed by user
        try {
            o = parseSurvey(data);
        } catch (IllegalArgumentException e) {
            // if passed content is invalid for some reason, notify user

            HttpResponse result = new HttpResponse("Invalid survey data! " + e.getMessage());
            result.setStatus(400);
            return result;
        }

        try {
            // if passed content is valid, store as new survey
            int sid = storeNewSurvey(o);

            // respond to user with newly generated survey id/URL
            JSONObject r = new JSONObject();
            r.put("id", sid);
            r.put("url", epUrl + "surveys/" + sid);

            HttpResponse result = new HttpResponse(r.toJSONString());
            result.setHeader("Content-Type", MediaType.APPLICATION_JSON);
            result.setStatus(201);
            return result;
        } catch (SQLException e) {

            if (0 <= e.getMessage().indexOf("Duplicate")) {
                HttpResponse result = new HttpResponse("Survey already exists.");
                result.setStatus(409);
                return result;
            } else {
                e.printStackTrace();
                return internalError(onAction);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction);
    }
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation // w  w  w.j  a  v a 2 s . c o m
 * 
 * Creates a new questionnaire.
 * @param content
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("questionnaires")
@Summary("create new questionnaire.")
@Notes("Requires authentication.")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Questionnaire created successfully."),
        @ApiResponse(code = 400, message = "Questionnaire data invalid."),
        @ApiResponse(code = 401, message = "Questionnaire creation requires authentication."),
        @ApiResponse(code = 409, message = "Questionnaire already exists.") })
public HttpResponse createQuestionnaire(@ContentParam String content) {

    if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) {
        HttpResponse noauth = new HttpResponse("Please authenticate to create questionnaires!");
        noauth.setStatus(401);
    }
    String onAction = "creating new questionnaire";

    try {
        JSONObject o;

        // first parse passed questionnaire data 
        try {
            o = parseQuestionnaire(content);
        } catch (IllegalArgumentException e) {
            // if passed data is invalid, respond error to user
            HttpResponse result = new HttpResponse("Invalid questionnaire! " + e.getMessage());
            result.setHeader("Content-Type", MediaType.TEXT_PLAIN);
            result.setStatus(400);
            return result;
        }

        // store valid questionnaire to database
        try {
            int qid = storeNewQuestionnaire(o);

            // respond to user with newly created id/URL
            JSONObject r = new JSONObject();
            r.put("id", qid);
            r.put("url", epUrl + "questionnaires/" + qid);
            HttpResponse result = new HttpResponse(r.toJSONString());
            result.setHeader("Content-Type", MediaType.APPLICATION_JSON);
            result.setStatus(201);

            return result;
        } catch (SQLException e) {
            if (0 <= e.getMessage().indexOf("Duplicate")) {
                HttpResponse result = new HttpResponse("Questionnaire already exists.");
                result.setStatus(409);
                return result;
            } else {
                e.printStackTrace();
                return internalError(onAction);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction);
    }
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation/*from  w w  w  .  ja va2  s  .  c  o m*/
 * 
 * Updates a survey with a given id. The respective survey may only be deleted, if the active agent is the survey's owner.
 * 
 * @param id
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("questionnaires/{id}")
@Summary("update given questionnaire.")
@Notes("Requires authentication. Use parent resource to retrieve list of existing questionnaires.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Questionnaire updated successfully."),
        @ApiResponse(code = 400, message = "Questionnaire data invalid."),
        @ApiResponse(code = 401, message = "Questionnaire may only be updated by its owner."),
        @ApiResponse(code = 404, message = "Questionnaire does not exist.") })
public HttpResponse updateQuestionnaire(@PathParam("id") int id, @ContentParam String content) {

    if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) {
        HttpResponse noauth = new HttpResponse("Please authenticate to update questionnaire!");
        noauth.setStatus(401);
    }

    String onAction = "updating questionnaire " + id;

    try {
        Connection c = null;
        PreparedStatement s = null;
        ResultSet rs = null;

        // +++ dsi 
        try {

            int exown;
            exown = checkExistenceOwnership(id, 1);

            // check if questionnaire exists; if not, return 404.
            if (exown == -1) {
                HttpResponse result = new HttpResponse("Questionnaire " + id + " does not exist.");
                result.setStatus(404);
                return result;
            }
            // if questionnaire exists, check if active agent is owner. if not, return 401.
            else if (exown == 0) {
                HttpResponse result = new HttpResponse(
                        "Questionnaire " + id + " may only be updated by its owner.");
                result.setStatus(401);
                return result;
            }

            // Proceed, if survey exists and active agent is owner 

            // parse and validate content. If invalid, return 400 (bad request)
            JSONObject o;

            try {
                o = parseQuestionnaire(content);
            } catch (IllegalArgumentException e) {
                // respond with 400, if content for updated questionnaire is not valid
                HttpResponse result = new HttpResponse("Invalid questionnaire data! " + e.getMessage());
                result.setStatus(400);
                return result;
            }

            // if parsed content is ok, execute update
            c = dataSource.getConnection();
            s = c.prepareStatement("update " + jdbcSchema
                    + ".questionnaire set organization=?, logo=?, name=?, description=?, lang=? where id = ?");

            s.setString(1, (String) o.get("organization"));
            s.setString(2, (String) o.get("logo"));
            s.setString(3, (String) o.get("name"));
            s.setString(4, (String) o.get("description"));
            s.setString(5, (String) o.get("lang"));
            s.setInt(6, id);

            s.executeUpdate();

            HttpResponse result = new HttpResponse("Questionnaire " + id + " updated successfully.");
            result.setStatus(200);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return internalError(onAction);
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (s != null)
                    s.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (c != null)
                    c.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
        }
        // --- dsi

    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction);
    }
}

From source file:de.biomedical_imaging.traj.math.TrajectorySplineFitLegacy.java

/**
 * Calculates a spline to a trajectory. Attention: The spline is fitted through a rotated version of the trajectory.
 * To fit the spline the trajectory is rotated into its main direction. You can access this rotated trajectory by 
 * {@link #getRotatedTrajectory() getRotatedTrajectory}.
 * @return The fitted spline/*from   w  w  w. j  a v  a  2 s. c o  m*/
 */
public PolynomialSplineFunction calculateSpline() {

    /*
     * 1.Calculate the minimum bounding rectangle
     */
    ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>();
    for (int i = 0; i < t.size(); i++) {
        Point2D.Double p = new Point2D.Double();
        p.setLocation(t.get(i).x, t.get(i).y);
        points.add(p);
    }
    Point2D.Double[] rect = null;
    try {
        rect = RotatingCalipers.getMinimumBoundingRectangle(points);
    } catch (IllegalArgumentException e) {

    } catch (EmptyStackException e) {

    }

    /*
     * 1.1 Rotate that the major axis is parallel with the xaxis
     */

    Point2D.Double majorDirection = null;

    Point2D.Double p1 = rect[2]; //top left
    Point2D.Double p2 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[1] : rect[3]; //Point to long side
    Point2D.Double p3 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[3] : rect[1]; //Point to short side
    majorDirection = new Point2D.Double(p2.x - p1.x, p2.y - p1.y);
    double width = p1.distance(p2);
    double inRad = -1 * Math.atan2(majorDirection.y, majorDirection.x);

    boolean doTransform = (Math.abs(Math.abs(inRad) - Math.PI) > 0.001);

    if (doTransform) {
        angleRotated = inRad;
        for (int i = 0; i < t.size(); i++) {
            double x = t.get(i).x;
            double y = t.get(i).y;
            double newX = x * Math.cos(inRad) - y * Math.sin(inRad);
            double newY = x * Math.sin(inRad) + y * Math.cos(inRad);
            rotatedTrajectory.add(newX, newY, 0);
            points.get(i).setLocation(newX, newY);
        }
        for (int i = 0; i < rect.length; i++) {
            rect[i].setLocation(rect[i].x * Math.cos(inRad) - rect[i].y * Math.sin(inRad),
                    rect[i].x * Math.sin(inRad) + rect[i].y * Math.cos(inRad));
        }

        p1 = rect[2]; //top left
        p2 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[1] : rect[3]; //Point to long side
        p3 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[3] : rect[1]; //Point to short side
    } else {
        angleRotated = 0;
        rotatedTrajectory = t;
    }

    /*
     * 2. Divide the rectangle in n equal segments
     * 2.1 Calculate line in main direction
     * 2.2 Project the points in onto this line
     * 2.3 Calculate the distance between the start of the line and the projected point
     * 2.4 Assign point to segment according to distance of (2.3)
     */
    List<List<Point2D.Double>> pointsInSegments = null;
    boolean allSegmentsContainingAtLeastTwoPoints = true;
    do {

        allSegmentsContainingAtLeastTwoPoints = true;
        double segmentWidth = p1.distance(p2) / nSegments;
        pointsInSegments = new ArrayList<List<Point2D.Double>>(nSegments);
        for (int i = 0; i < nSegments; i++) {
            pointsInSegments.add(new ArrayList<Point2D.Double>());
        }
        for (int i = 0; i < points.size(); i++) {
            Point2D.Double projPoint = projectPointToLine(p1, p2, points.get(i));
            int index = (int) (p1.distance(projPoint) / segmentWidth);

            if (index > (nSegments - 1)) {
                index = (nSegments - 1);
            }
            pointsInSegments.get(index).add(points.get(i));
        }

        for (int i = 0; i < pointsInSegments.size(); i++) {
            if (pointsInSegments.get(i).size() < 2) {
                if (nSegments > 2) {
                    nSegments--;
                    i = pointsInSegments.size();
                    allSegmentsContainingAtLeastTwoPoints = false;

                }
            }
        }
    } while (allSegmentsContainingAtLeastTwoPoints == false);

    /*
     * 3. Calculate the mean standard deviation over each segment: <s>
     */

    Point2D.Double eMajorP1 = new Point2D.Double(p1.x - (p3.x - p1.x) / 2.0, p1.y - (p3.y - p1.y) / 2.0);
    Point2D.Double eMajorP2 = new Point2D.Double(p2.x - (p3.x - p1.x) / 2.0, p2.y - (p3.y - p1.y) / 2.0);
    double sumMean = 0;
    int Nsum = 0;
    for (int i = 0; i < nSegments; i++) {
        StandardDeviation sd = new StandardDeviation();
        double[] distances = new double[pointsInSegments.get(i).size()];
        for (int j = 0; j < pointsInSegments.get(i).size(); j++) {
            int factor = 1;
            if (isLeft(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j))) {
                factor = -1;
            }
            distances[j] = factor * distancePointLine(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j));
        }
        if (distances.length > 0) {
            sd.setData(distances);

            sumMean += sd.evaluate();

            Nsum++;
        }
    }
    double s = sumMean / Nsum;
    if (s < 0.000000000001) {
        s = width / nSegments;
    }

    /*
     * 4. Build a kd-tree
     */
    KDTree<Point2D.Double> kdtree = new KDTree<Point2D.Double>(2);

    for (int i = 0; i < points.size(); i++) {
        try {
            //To ensure that all points have a different key, add small random number

            kdtree.insert(new double[] { points.get(i).x, points.get(i).y }, points.get(i));
        } catch (KeySizeException e) {
            e.printStackTrace();
        } catch (KeyDuplicateException e) {
            //Do nothing! It is not important
        }

    }

    /*
     * 5. Using the first point f in trajectory and calculate the center of mass
     * of all points around f (radius: 3*<s>))
     */
    List<Point2D.Double> near = null;

    Point2D.Double first = minDistancePointToLine(p1, p3, points);
    double r1 = 3 * s;
    try {

        near = kdtree.nearestEuclidean(new double[] { first.x, first.y }, r1);

    } catch (KeySizeException e) {
        e.printStackTrace();
    }

    double cx = 0;
    double cy = 0;
    for (int i = 0; i < near.size(); i++) {
        cx += near.get(i).x;
        cy += near.get(i).y;
    }
    cx /= near.size();
    cy /= near.size();

    splineSupportPoints = new ArrayList<Point2D.Double>();
    splineSupportPoints.add(new Point2D.Double(cx, cy));

    /* 
     * 6. The second point is determined by finding the center-of-mass of particles in the p/2 radian 
     * section of an annulus, r1 < r < 2r1, that is directed toward the angle with the highest number 
     * of particles within p/2 radians.
     * 7. This second point is then used as the center of the annulus for choosing the third point, and the process is repeated (6. & 7.).
     */

    /*
     * 6.1 Find all points in the annolous
     */

    /*
     * 6.2 Write each point in a coordinate system centered at the center of the sphere, calculate direction and
     * check if it in the allowed bounds
     */
    int nCircleSegments = 100;
    double deltaRad = 2 * Math.PI / nCircleSegments;
    boolean stop = false;
    int minN = 7;
    double tempr1 = r1;
    double allowedDeltaDirection = 0.5 * Math.PI;

    while (stop == false) {
        List<Point2D.Double> nearestr1 = null;
        List<Point2D.Double> nearest2xr1 = null;
        try {
            nearestr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, tempr1);
            nearest2xr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, 2 * tempr1);
        } catch (KeySizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        nearest2xr1.removeAll(nearestr1);

        double lThreshRad = 0;
        double hThreshRad = Math.PI / 2;
        double stopThresh = 2 * Math.PI;
        if (splineSupportPoints.size() > 1) {
            double directionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            lThreshRad = directionInRad - allowedDeltaDirection / 2 - Math.PI / 4;
            if (lThreshRad < 0) {
                lThreshRad = 2 * Math.PI + lThreshRad;
            }
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            hThreshRad = directionInRad + allowedDeltaDirection / 2 + Math.PI / 4;
            if (hThreshRad < 0) {
                hThreshRad = 2 * Math.PI + hThreshRad;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            stopThresh = directionInRad + allowedDeltaDirection / 2 - Math.PI / 4;
            if (stopThresh > 2 * Math.PI) {
                stopThresh = stopThresh - 2 * Math.PI;
            }

        }

        double newCx = 0;
        double newCy = 0;
        int newCN = 0;
        int candN = 0;

        //Find center with highest density of points
        double lastDist = 0;
        double newDist = 0;
        do {
            lastDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

            candN = 0;
            double candCx = 0;
            double candCy = 0;

            for (int i = 0; i < nearest2xr1.size(); i++) {
                Point2D.Double centerOfCircle = splineSupportPoints.get(splineSupportPoints.size() - 1);
                Vector2d relativeToCircle = new Vector2d(nearest2xr1.get(i).x - centerOfCircle.x,
                        nearest2xr1.get(i).y - centerOfCircle.y);
                relativeToCircle.normalize();
                double angleInRadians = Math.atan2(relativeToCircle.y, relativeToCircle.x) + Math.PI;

                if (lThreshRad < hThreshRad) {
                    if (angleInRadians > lThreshRad && angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                } else {
                    if (angleInRadians > lThreshRad || angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                }

            }

            if (candN > 0 && candN > newCN) {
                candCx /= candN;
                candCy /= candN;
                newCx = candCx;
                newCy = candCy;
                newCN = candN;
            }
            lThreshRad += deltaRad;
            hThreshRad += deltaRad;
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            newDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

        } while ((newDist - lastDist) > 0);

        //Check if the new center is valid
        if (splineSupportPoints.size() > 1) {
            double currentDirectionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            double candDirectionInRad = Math.atan2(
                    newCy - splineSupportPoints.get(splineSupportPoints.size() - 1).y,
                    newCx - splineSupportPoints.get(splineSupportPoints.size() - 1).x) + Math.PI;
            double dDir = Math.max(currentDirectionInRad, candDirectionInRad)
                    - Math.min(currentDirectionInRad, candDirectionInRad);
            if (dDir > 2 * Math.PI) {
                dDir = 2 * Math.PI - dDir;
            }
            if (dDir > allowedDeltaDirection) {

                stop = true;
            }
        }
        boolean enoughPoints = (newCN < minN);
        boolean isNormalRadius = Math.abs(tempr1 - r1) < Math.pow(10, -18);
        boolean isExtendedRadius = Math.abs(tempr1 - 3 * r1) < Math.pow(10, -18);

        if (enoughPoints && isNormalRadius) {
            //Not enough points, extend search radius
            tempr1 = 3 * r1;
        } else if (enoughPoints && isExtendedRadius) {
            //Despite radius extension: Not enough points!
            stop = true;
        } else if (stop == false) {
            splineSupportPoints.add(new Point2D.Double(newCx, newCy));
            tempr1 = r1;
        }

    }

    //Sort
    Collections.sort(splineSupportPoints, new Comparator<Point2D.Double>() {

        public int compare(Point2D.Double o1, Point2D.Double o2) {
            if (o1.x < o2.x) {
                return -1;
            }
            if (o1.x > o2.x) {
                return 1;
            }
            return 0;
        }
    });

    //Add endpoints
    if (splineSupportPoints.size() > 1) {
        Vector2d start = new Vector2d(splineSupportPoints.get(0).x - splineSupportPoints.get(1).x,
                splineSupportPoints.get(0).y - splineSupportPoints.get(1).y);
        start.normalize();
        start.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + start.x,
                splineSupportPoints.get(0).y + start.y));

        Vector2d end = new Vector2d(
                splineSupportPoints.get(splineSupportPoints.size() - 1).x
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).x,
                splineSupportPoints.get(splineSupportPoints.size() - 1).y
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).y);
        end.normalize();
        end.scale(r1 * 6);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + end.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + end.y));
    } else {
        Vector2d majordir = new Vector2d(-1, 0);
        majordir.normalize();
        majordir.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + majordir.x,
                splineSupportPoints.get(0).y + majordir.y));
        majordir.scale(-1);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + majordir.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + majordir.y));

    }

    //Interpolate spline
    double[] supX = new double[splineSupportPoints.size()];
    double[] supY = new double[splineSupportPoints.size()];
    for (int i = 0; i < splineSupportPoints.size(); i++) {
        supX[i] = splineSupportPoints.get(i).x;
        supY[i] = splineSupportPoints.get(i).y;
    }

    SplineInterpolator sIinter = new SplineInterpolator();
    spline = sIinter.interpolate(supX, supY);

    return spline;
}