List of usage examples for org.apache.commons.lang ArrayUtils toPrimitive
public static boolean[] toPrimitive(Boolean[] array)
Converts an array of object Booleans to primitives.
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.rdata.RDATAFileReader.java
/** * Get Variable Type List/*from ww w . j av a 2s . co m*/ * * Categorize the columns of a data-set according to data-type. Returns a list * of integers corresponding to: (-1) String (0) Integer (1) Double-precision. * The numbers do not directly correspond with anything used by UNF5Util, * however this convention is seen throughout the DVN data-file readers. * * This function essentially matches R data-types with those understood by * DVN: * * integer => "Integer" * * numeric (non-integer), double => "Double" * * Date => "Date" * * Other => "String" * * @param dataTypes an array of strings where index corresponds to data-set * column and string corresponds to the class of the R-object. * @return */ private List<Integer> getVariableTypeList(String[] dataTypes) { /* * TODO: * * Clean up this code; for example, the VariableMetaData variable "columnData" * is created below, but never saved or used. A vector of VariableMetaData * values actually gets created somewhere else in the code of the reader, and those * are the values that could be used elsewhere. Need to pick the one we want * to use and remove the other one - for clarity. * * The whole setup with the "minimalTypeList" and "normalTypeList" is * kinda confusing. One is used for the UNF and stats, the other one for * metadata processing; which is ok. But then it is actually the "normal" * one that is used for the "minimal" inside the SDIOMetadata object... * Just renaming these to something that's more intuitive - types_for_UNF vs. * types_for_METADATA - should be enough. * * --L.A. */ // Map<String, HashMap<String, String>> valueLabelTable = new HashMap<String, HashMap<String, String>>(); // mFormatTable = new int[mVarQuantity]; // Okay. List<Integer> minimalTypeList = new ArrayList<Integer>(), normalTypeList = new ArrayList<Integer>(); Set<Integer> decimalVariableSet = new HashSet<Integer>(); int k = 0; for (String type : dataTypes) { VariableMetaData columnMetaData; // Log String variableName = variableNameList.get(k); // Convention is that integer is zero, right? if (type.equals("integer")) { minimalTypeList.add(0); normalTypeList.add(0); mFormatTable[k] = FORMAT_INTEGER; mPrintFormatList.add(1); // mPrintFormatNameTable.put(variableName, "N"); columnMetaData = new VariableMetaData(1); } // Double-precision data-types else if (type.equals("numeric") || type.equals("double")) { LOG.fine("RDATAfilereader: getVariableTypeList: double variable;"); minimalTypeList.add(1); normalTypeList.add(0); decimalVariableSet.add(k); mFormatTable[k] = FORMAT_NUMERIC; mPrintFormatList.add(1); columnMetaData = new VariableMetaData(1); } // If date else if (type.equals("Date")) { minimalTypeList.add(-1); normalTypeList.add(1); mFormatTable[k] = FORMAT_DATE; mPrintFormatList.add(0); mPrintFormatNameTable.put(variableName, "DATE10"); mFormatCategoryTable.put(variableName, "date"); columnMetaData = new VariableMetaData(0); LOG.fine("date variable detected. format: " + FORMAT_DATE); } else if (type.equals("POSIXct") || type.equals("POSIXlt") || type.equals("POSIXt")) { minimalTypeList.add(-1); normalTypeList.add(1); mFormatTable[k] = FORMAT_DATETIME; mPrintFormatList.add(0); mPrintFormatNameTable.put(variableName, "DATETIME23.3"); mFormatCategoryTable.put(variableName, "time"); columnMetaData = new VariableMetaData(0); LOG.fine("POSIXt variable detected. format: " + FORMAT_DATETIME); } else if (type.equals("factor")) { /* * This is the counter-intuitive part: in R, factors always have * internal integer values and character labels. However, we will * always treat them as character/string variables, i.e. on the DVN * side they will be ingested as string-type categorical variables * (with both the "value" and the "label" being the same string - the * R factor label). Yes, this means we are dropping the numeric value * completely. Why not do what we do in SPSS, i.e. use the numeric for * the value (and the TAB file entry)? - well, this is in fact a very * different case: in SPSS, a researcher creating a categorical variable * with numeric values would be hand-picking these numeric variables; * so we assume that the chosen values are in fact meaningful. If they * had some sort of a reason to assign 0 = "Male" and 7 = "Female", we * assume that they wanted to do this. So we use the numeric codes for * storage in the TAB file and for calculation of the UNF. In R however, * the user has no control over the internal numeric codes; they are * always created automatically and are in fact considered meaningless. * So we are going to assume that it is the actual values of the labels * that are meaningful. * -- L.A. * */ minimalTypeList.add(-1); normalTypeList.add(1); mFormatTable[k] = FORMAT_STRING; mPrintFormatList.add(0); mPrintFormatNameTable.put(variableName, "other"); mFormatCategoryTable.put(variableName, "other"); columnMetaData = new VariableMetaData(0); } else if (type.equals("logical")) { minimalTypeList.add(0); normalTypeList.add(0); mFormatTable[k] = FORMAT_INTEGER; mPrintFormatList.add(1); // mPrintFormatNameTable.put(variableName, "N"); columnMetaData = new VariableMetaData(1); columnMetaData.setBoolean(true); // Everything else is a string } else { minimalTypeList.add(-1); normalTypeList.add(1); mFormatTable[k] = FORMAT_STRING; mPrintFormatList.add(0); mPrintFormatNameTable.put(variableName, "other"); mFormatCategoryTable.put(variableName, "other"); columnMetaData = new VariableMetaData(0); } k++; } // Decimal Variables smd.setVariableTypeMinimal( ArrayUtils.toPrimitive(normalTypeList.toArray(new Integer[normalTypeList.size()]))); smd.setDecimalVariables(decimalVariableSet); smd.setVariableStorageType(null); smd.setVariableFormat(mPrintFormatList); smd.setVariableFormatName(mPrintFormatNameTable); smd.setVariableFormatCategory(mFormatCategoryTable); // smd.set LOG.fine("minimalTypeList = " + Arrays.deepToString(minimalTypeList.toArray())); LOG.fine("normalTypeList = " + Arrays.deepToString(normalTypeList.toArray())); LOG.fine("decimalVariableSet = " + Arrays.deepToString(decimalVariableSet.toArray())); LOG.fine("mPrintFormatList = " + mPrintFormatList); LOG.fine("mPrintFormatNameTable = " + mPrintFormatNameTable); LOG.fine("mFormatCategoryTable = " + mFormatCategoryTable); LOG.fine("mFormatTable = " + mFormatTable); // Return the variable type list return minimalTypeList; }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.rdata.RDATAFileReader.java
/** * Create UNF from Tabular File/* ww w . jav a2 s . c o m*/ * This methods iterates through each column of the supplied data table and * invoked the * @param DataTable table a rectangular data table * @return void */ private void createUNF(DataTable table) throws IOException { List<Integer> variableTypeList = getVariableTypeList(mDataTypes); String[] dateFormats = new String[mCaseQuantity]; String[] unfValues = new String[mVarQuantity]; String fileUNFvalue = null; // Set variable types // smd.setVariableTypeMinimal(ArrayUtils.toPrimitive(variableTypeList.toArray(new Integer[variableTypeList.size()]))); int[] x = ArrayUtils.toPrimitive(variableTypeList.toArray(new Integer[variableTypeList.size()])); for (int k = 0; k < mVarQuantity; k++) { String unfValue, name = variableNameList.get(k); int varType = variableTypeList.get(k); Object[] varData = table.getData()[k]; LOG.fine(String.format("RDATAFileReader: Column \"%s\" = %s", name, Arrays.deepToString(varData))); try { switch (varType) { case 0: Long[] integerEntries = new Long[varData.length]; LOG.fine(k + ": " + name + " is numeric (integer)"); if (smd.isBooleanVariable()[k]) { // This is not a regular integer - but a boolean! LOG.fine(k + ": " + name + " is NOT a simple integer - it's a logical (boolean)!"); Boolean[] booleanEntries = new Boolean[varData.length]; for (int i = 0; i < varData.length; i++) { if (varData[i] == null || varData[i].equals("")) { // Missing Value: booleanEntries[i] = null; } else if (((String) varData[i]).equals("0")) { booleanEntries[i] = false; } else if (((String) varData[i]).equals("1")) { booleanEntries[i] = true; } else { // Treat it as a missing value? booleanEntries[i] = null; // TODO: // Should we throw an exception here instead? } // We'll also need the integer values, to calculate // the summary statistics: try { integerEntries[i] = new Long((String) varData[i]); } catch (Exception ex) { integerEntries[i] = null; } } unfValue = UNF5Util.calculateUNF(booleanEntries); // TODO: // we've never calculated UNFs for Booleans before - // need to QA and verify that the values produced are correct. // -- L.A. } else { // Regular integer; // Treat it as an array of Longs: LOG.fine(k + ": " + name + " is a simple integer."); for (int i = 0; i < varData.length; i++) { try { integerEntries[i] = new Long((String) varData[i]); } catch (Exception ex) { integerEntries[i] = null; } } unfValue = UNF5Util.calculateUNF(integerEntries); // UNF5Util.cal } // Summary/category statistics smd.getSummaryStatisticsTable().put(k, ArrayUtils.toObject(StatHelper.calculateSummaryStatistics(integerEntries))); Map<String, Integer> catStat = StatHelper.calculateCategoryStatistics(integerEntries); smd.getCategoryStatisticsTable().put(variableNameList.get(k), catStat); smd.getNullValueCounts().put(variableNameList.get(k), StatHelper.countNullValues(integerEntries)); break; // If double case 1: LOG.fine(k + ": " + name + " is numeric (double)"); // Convert array of Strings to array of Doubles Double[] doubleEntries = new Double[varData.length]; for (int i = 0; i < varData.length; i++) { try { // Check for the special case of "NaN" - this is the R and DVN // notation for the "Not A Number" value: if (varData[i] != null && ((String) varData[i]).equals("NaN")) { doubleEntries[i] = Double.NaN; // "Inf" is another special case, notation for infinity, // positive and negative: } else if (varData[i] != null && (((String) varData[i]).equals("Inf") || ((String) varData[i]).equals("+Inf"))) { doubleEntries[i] = Double.POSITIVE_INFINITY; } else if (varData[i] != null && ((String) varData[i]).equals("-Inf")) { doubleEntries[i] = Double.NEGATIVE_INFINITY; } else { // Missing Values don't need to be treated separately; these // are represented as empty strings in the TAB file; so // attempting to create a Double object from one will // throw an exception - which we are going to intercept // below. For the UNF and Summary Stats purposes, missing // values are represented as NULLs. doubleEntries[i] = new Double((String) varData[i]); } } catch (Exception ex) { LOG.fine(k + ": " + name + " dropping value " + (String) varData[i] + " (" + i + "); replacing with null"); doubleEntries[i] = null; } } LOG.fine("sumstat:double case=" + Arrays.deepToString(ArrayUtils .toObject(StatHelper.calculateSummaryStatisticsContDistSample(doubleEntries)))); // Save summary statistics: smd.getSummaryStatisticsTable().put(k, ArrayUtils .toObject(StatHelper.calculateSummaryStatisticsContDistSample(doubleEntries))); unfValue = UNF5Util.calculateUNF(doubleEntries); break; case -1: LOG.fine(k + ": " + name + " is string"); String[] stringEntries = new String[varData.length];//Arrays.asList(varData).toArray(new String[varData.length]); LOG.fine("string array passed to calculateUNF: " + Arrays.deepToString(stringEntries)); // if (mFormatTable[k] == FORMAT_DATE || mFormatTable[k] == FORMAT_DATETIME) { DateFormatter dateFormatter = new DateFormatter(); dateFormatter.setDateFormats(DATE_FORMATS); dateFormatter.setTimeFormats(TIME_FORMATS); for (int i = 0; i < varData.length; i++) { DateWithFormatter entryDateWithFormat; // If data is missing, treat this entry as just that - // a missing value. Just like for all the other data types, // this is represented by a null: if (dateFormats[i] != null && (varData[i].equals("") || varData[i].equals(" "))) { stringEntries[i] = dateFormats[i] = null; } else { entryDateWithFormat = dateFormatter.getDateWithFormat((String) varData[i]); if (entryDateWithFormat == null) { LOG.fine("ATTENTION: the supplied date/time string could not be parsed (" + (String) varData[i]); throw new IOException( "Could not parse supplied date/time string: " + (String) varData[i]); } // Otherwise get the pattern // entryDateWithFormat = dateFormatter.getDateWithFormat(stringEntries[i]); stringEntries[i] = (String) varData[i]; dateFormats[i] = entryDateWithFormat.getFormatter().toPattern(); } } // Compute UNF try { LOG.fine("RDATAFileReader: strdata = " + Arrays.deepToString(stringEntries)); LOG.fine("RDATAFileReader: dateFormats = " + Arrays.deepToString(dateFormats)); unfValue = UNF5Util.calculateUNF(stringEntries, dateFormats); } catch (Exception ex) { LOG.warning("RDATAFileReader: UNF for variable " + name + " could not be computed!"); //unfValue = UNF5Util.calculateUNF(stringEntries); //ex.printStackTrace(); throw ex; } } else { for (int i = 0; i < varData.length; i++) { if (varData[i] == null) { // Missing Value stringEntries[i] = null; } else { stringEntries[i] = (String) varData[i]; } } unfValue = UNF5Util.calculateUNF(stringEntries); } smd.getSummaryStatisticsTable().put(k, StatHelper.calculateSummaryStatistics(stringEntries)); Map<String, Integer> StrCatStat = StatHelper.calculateCategoryStatistics(stringEntries); smd.getCategoryStatisticsTable().put(variableNameList.get(k), StrCatStat); smd.getNullValueCounts().put(variableNameList.get(k), StatHelper.countNullValues(stringEntries)); break; default: unfValue = null; } //LOG.fine(String.format("RDATAFileReader: Column \"%s\" (UNF) = %s", name, unfValue)); // Store UNF value unfValues[k] = unfValue; } catch (Exception ex) { LOG.fine("Exception caught while calculating UNF! " + ex.getMessage()); ex.printStackTrace(); throw new IOException("Exception caught while calculating UNF! " + ex.getMessage()); } LOG.fine(String.format("RDATAFileReader: Column \"%s\" (UNF) = %s", name, unfValues[k])); } try { fileUNFvalue = UNF5Util.calculateUNF(unfValues); } catch (Exception ex) { ex.printStackTrace(); LOG.fine("Exception caught while calculating the combined UNF for the data set! " + ex.getMessage()); throw new IOException( "Exception caught while calculating the combined UNF for the data set! " + ex.getMessage()); } mCsvDataTable.setUnf(unfValues); mCsvDataTable.setFileUnf(fileUNFvalue); // Set meta-data to make it look like a SAV file // smd.setVariableStorageType(null); // smd.setDecimalVariables(mDecimalVariableSet); boolean[] b = smd.isContinuousVariable(); for (int k = 0; k < b.length; k++) { String s = b[k] ? "True" : "False"; LOG.fine(k + " = " + s); } smd.setVariableUNF(unfValues); smd.getFileInformation().put("fileUNF", fileUNFvalue); }
From source file:de.Keyle.MyPet.skill.skills.Beacon.java
@Override public TagCompound save() { TagCompound nbtTagCompound = new TagCompound(); nbtTagCompound.getCompoundData().put("Buffs", new TagIntArray(ArrayUtils.toPrimitive(selectedBuffs.toArray(new Integer[selectedBuffs.size()])))); nbtTagCompound.getCompoundData().put("Active", new TagByte(this.active)); nbtTagCompound.getCompoundData().put("Reciever", new TagString(this.receiver.name())); return nbtTagCompound; }
From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.AngleDirectController.java
/** * Compute number of bins for the angle histogram for a plate condition, so * that bin size is always of 10 degrees. * * @param singleCellConditionDataHolder//from ww w.j a va 2 s.co m * @return the number of bins, integer. */ private int getNumberOfBins(SingleCellConditionDataHolder singleCellConditionDataHolder) { double[] toPrimitive = ArrayUtils.toPrimitive( AnalysisUtils.excludeNullValues(singleCellConditionDataHolder.getTurningAnglesVector())); double range = Arrays.stream(toPrimitive).max().getAsDouble() - Arrays.stream(toPrimitive).min().getAsDouble(); return (int) range / 10; }
From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.AngleDirectController.java
/** * Same as previous method, but for a single well. * * @param singleCellWellDataHolder//from w w w. ja v a2s. c o m * @return */ private int getNumberOfBins(SingleCellWellDataHolder singleCellWellDataHolder) { double[] toPrimitive = ArrayUtils .toPrimitive(AnalysisUtils.excludeNullValues(singleCellWellDataHolder.getTurningAnglesVector())); double range = Arrays.stream(toPrimitive).max().getAsDouble() - Arrays.stream(toPrimitive).min().getAsDouble(); return (int) range / 10; }
From source file:com.runwaysdk.dataaccess.database.BusinessDAOFactory.java
private static int[] executeStatementBatch(List<PreparedStatement> _statements, boolean _ignoreOnDatabaseException) { if (_ignoreOnDatabaseException) { List<Integer> results = new LinkedList<Integer>(); for (PreparedStatement statement : _statements) { Savepoint savepoint = Database.setSavepoint(); try { List<PreparedStatement> temp = new LinkedList<PreparedStatement>(); temp.add(statement);//from www . j a v a 2 s .c o m int[] result = Database.executeStatementBatch(temp); results.add(result[0]); Database.releaseSavepoint(savepoint); } catch (DuplicateGraphPathException e) { // Do nothing Database.rollbackSavepoint(savepoint); } } return ArrayUtils.toPrimitive(results.toArray(new Integer[results.size()])); } else { return Database.executeStatementBatch(_statements); } }
From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java
public void handlerBrowse(HttpServletRequest request, HttpServletResponse response, HttpSession session, AdminService admin, ExtendedMap formItems, ExtendedMap parameters, User oldUser, Document verticalDoc) throws VerticalAdminException { UserEntity user = securityService.getUser(oldUser); String op = formItems.getString("op"); String subop = formItems.getString("subop", "browse"); String contenthandler = formItems.getString("contenthandler", ""); int submittetCategoryKey = formItems.getInt("categorykey", -1); if (submittetCategoryKey == -1) { submittetCategoryKey = formItems.getInt("cat", -1); }/*ww w. j a v a 2 s .co m*/ CategoryKey categoryKey = CategoryKey.parse(submittetCategoryKey); boolean categoryDisabled_which_means_user_do_not_have_read_access = formItems.getBoolean("disabled", false); String[] contentTypeStringArray = formItems.getStringArray("contenttypestring"); int[] contentTypes = resolveContentTypes(contentTypeStringArray); StringBuffer contentTypesString = createContentTypesString(contentTypes); if (!"browse".equals(subop)) { String deploymentPath = DeploymentPathResolver.getAdminDeploymentPath(request); CookieUtil.setCookie(response, getPopupCookieName(contentTypesString.toString()), categoryKey != null ? categoryKey.toString() : "-1", COOKIE_TIMEOUT, deploymentPath); } int contentTypeKey = -1; boolean hasAdminReadOnCategory = true; boolean hasCategoryRead = false; boolean hasCategoryCreate = false; boolean hasCategoryPublish = false; boolean hasCategoryAdministrate = false; CategoryAccessResolver categoryAccessResolver = new CategoryAccessResolver(groupDao); if (categoryKey != null) { CategoryEntity category = categoryDao.findByKey(categoryKey); hasAdminReadOnCategory = categoryAccessResolver.hasAdminBrowseCategoryAccess(user, category); hasCategoryRead = categoryAccessResolver.hasReadCategoryAccess(user, category); hasCategoryCreate = categoryAccessResolver.hasCreateContentAccess(user, category); hasCategoryPublish = categoryAccessResolver.hasApproveContentAccess(user, category); hasCategoryAdministrate = categoryAccessResolver.hasAdministrateCategoryAccess(user, category); ContentTypeEntity contentType = category.getContentType(); if (contentType != null) { contentTypeKey = contentType.getKey(); } } String sortBy = formItems.getString("sortby", "@timestamp"); String sortByDirection = formItems.getString("sortby-direction", "DESC"); StringBuffer orderBy = new StringBuffer(); orderBy.append(sortBy); orderBy.append(" "); orderBy.append(sortByDirection); final String cookieName = "archiveBrowseItemsPerPage"; int index = formItems.getInt("index", 0); int count = ListCountResolver.resolveCount(request, formItems, cookieName); CookieUtil.setCookie(response, cookieName, Integer.toString(count), COOKIE_TIMEOUT, DeploymentPathResolver.getAdminDeploymentPath(request)); XMLDocument xmlContent = null; String searchType = formItems.getString("searchtype", null); // Get contents if (searchType != null) { if (searchType.equals("simple")) { xmlContent = new SearchUtility(userDao, groupDao, securityService, contentService).simpleSearch( oldUser, formItems, categoryKey, contentTypes, orderBy.toString(), index, count); parameters.put("searchtext", formItems.getString("searchtext", "")); parameters.put("scope", formItems.getString("scope")); } else { String ownerGroupKey = formItems.getString("owner", ""); if (!"".equals(ownerGroupKey)) { User ownerUser = getUserFromUserGroupKey(ownerGroupKey); parameters.put("owner.uid", ownerUser.getName()); parameters.put("owner.fullName", ownerUser.getDisplayName()); parameters.put("owner.qualifiedName", ownerUser.getQualifiedName()); addUserKeyToFormItems(formItems, "owner.key", ownerUser); } String modifierGroupKey = formItems.getString("modifier", ""); if (!"".equals(modifierGroupKey)) { User modifierUser = getUserFromUserGroupKey(modifierGroupKey); parameters.put("modifier.uid", modifierUser.getName()); parameters.put("modifier.fullName", modifierUser.getDisplayName()); parameters.put("modifier.qualifiedName", modifierUser.getQualifiedName()); addUserKeyToFormItems(formItems, "modifier.key", modifierUser); } String assignee = formItems.getString("_assignee", ""); if (!"".equals(assignee)) { User assigneeUser = getUserFromUserKey(assignee); if (assigneeUser == null) { assigneeUser = getUserFromUserGroupKey(assignee); } parameters.put("assignment.assigneeUserKey", assignee); parameters.put("assignment.assigneeDisplayName", assigneeUser.getDisplayName()); parameters.put("assignment.assigneeQualifiedName", assigneeUser.getQualifiedName().toString()); } String assigner = formItems.getString("_assigner", ""); if (!"".equals(assigner)) { User assignerUser = getUserFromUserKey(assigner); if (assignerUser == null) { assignerUser = getUserFromUserGroupKey(assigner); } parameters.put("assignment.assignerUserKey", assigner); parameters.put("assignment.assignerDisplayName", assignerUser.getDisplayName()); parameters.put("assignment.assignerQualifiedName", assignerUser.getQualifiedName().toString()); } String assignmentDueDate = formItems.getString("date_assignmentDueDate", ""); if (!"".equals(assignmentDueDate)) { DateTimeFormatter norwegianDateFormatter = DateTimeFormat.forPattern("dd.MM.yyyy"); DateMidnight assignmentDueDateAsDateTime = norwegianDateFormatter .parseDateTime(assignmentDueDate).toDateMidnight(); DateTimeFormatter isoDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd"); String assignmentDueDateAsStringIsoFormatted = isoDateFormatter .print(assignmentDueDateAsDateTime); parameters.put("assignment.dueDate", assignmentDueDateAsStringIsoFormatted); parameters.put("assignment.dueDate.op", formItems.getString("_assignmentDueDate.op", "")); } xmlContent = new SearchUtility(userDao, groupDao, securityService, contentService) .advancedSearch(oldUser, formItems, contentTypes, orderBy.toString(), index, count); parameters.put("asearchtext", formItems.getString("asearchtext", "")); parameters.put("ascope", formItems.getString("ascope")); parameters.put("subcategories", formItems.getString("subcategories")); parameters.put("state", formItems.getString("state", "")); parameters.put("owner", ownerGroupKey); parameters.put("modifier", modifierGroupKey); parameters.put("created.op", formItems.getString("created.op", "")); parameters.put("created", formItems.getString("datecreated", "")); parameters.put("modified.op", formItems.getString("modified.op", "")); parameters.put("modified", formItems.getString("datemodified", "")); parameters.put("acontentkey", formItems.getString("acontentkey", "")); parameters.put("filter", formItems.getString("filter", "")); parameters.put("selectedtabpage", formItems.getString("selectedtabpage", "")); parameters.put("duedate", assignmentDueDate); } parameters.put("searchtype", searchType); } else if (hasAdminReadOnCategory) { xmlContent = admin.getContent(oldUser, categoryKey, false, orderBy.toString(), index, count, 0, 0, 0); } if (xmlContent != null) { Document contentDoc = xmlContent.getAsDOMDocument(); XMLTool.mergeDocuments(verticalDoc, contentDoc, true); // Find all content types and categories in this list Element[] contentElems = XMLTool.getElements(contentDoc.getDocumentElement(), "content"); Set<Integer> contentTypeKeys = new HashSet<Integer>(); Set<Integer> categoryKeys = new HashSet<Integer>(); for (Element contentElem : contentElems) { contentTypeKeys.add(Integer.parseInt(contentElem.getAttribute("contenttypekey"))); Element categoryElem = XMLTool.getElement(contentElem, "categoryname"); categoryKeys.add(Integer.parseInt(categoryElem.getAttribute("key"))); } if (contentTypeKeys.size() == 0 && searchType == null) { // This is a normal listing of an empty category contentTypeKeys.add(contentTypeKey); } if (contentTypeKeys.size() > 0) { Integer[] keyArray = new Integer[contentTypeKeys.size()]; int[] primitiveArray = ArrayUtils.toPrimitive(contentTypeKeys.toArray(keyArray)); XMLDocument ctyDoc = admin.getContentTypes(primitiveArray, true); XMLTool.mergeDocuments(verticalDoc, ctyDoc.getAsDOMDocument(), true); } // Get content types for this site XMLDocument siteContentTypesDoc = admin.getContentTypes(false); final Document siteContentTypesDocument = siteContentTypesDoc.getAsDOMDocument(); XMLTool.renameElement(siteContentTypesDocument.getDocumentElement(), "sitecontenttypes"); XMLTool.mergeDocuments(verticalDoc, siteContentTypesDocument, true); // Get all categories if (categoryKeys.size() > 0) { Integer[] keyArray = new Integer[categoryKeys.size()]; keyArray = categoryKeys.toArray(keyArray); CategoryCriteria categoryCriteria = new CategoryCriteria(); categoryCriteria.addCategoryKeys(Arrays.asList(keyArray)); Document categoriesDoc = admin.getMenu(oldUser, Types.CATEGORY, categoryCriteria, false) .getAsDOMDocument(); XMLTool.mergeDocuments(verticalDoc, categoriesDoc, false); } } Document headerDoc = XMLTool.domparse(admin.getCategoryPathXML(categoryKey, contentTypes)); XMLTool.mergeDocuments(verticalDoc, headerDoc, true); // Default browse config Document defaultBrowseConfig = XMLTool.domparse(AdminStore.getXML(session, "defaultbrowseconfig.xml")); XMLTool.mergeDocuments(verticalDoc, defaultBrowseConfig, true); // Feedback if (formItems.containsKey("feedback")) { addFeedback(verticalDoc, formItems.getInt("feedback")); } // Category header if (categoryKey != null) { // Category // Small hack: we put the current category on /data/category, all categories // used are also present in /data/categories/category, but without contentcount and accessrights Document categoryDoc = XMLTool.domparse(admin.getCategory(oldUser, categoryKey.toInt())); XMLTool.mergeDocuments(verticalDoc, categoryDoc, false); int superCategoryKey = admin.getSuperCategoryKey(categoryKey.toInt()); if (superCategoryKey != -1) { CategoryAccessRight supercar = admin.getCategoryAccessRight(oldUser, superCategoryKey); parameters.put("parentcategoryadministrate", supercar.getAdministrate()); } // Trenger indexparametre for vite hvilke felt det kan sorteres p.. list.xsl Document indexingDoc = XMLTool.domparse(admin.getIndexingParametersXML(contentTypeKey)); XMLTool.mergeDocuments(verticalDoc, indexingDoc, true); parameters.put("cat", categoryKey.toString()); parameters.put("contenttypekey", Integer.toString(contentTypeKey)); parameters.put("selectedunitkey", Integer.toString(admin.getUnitKey(categoryKey.toInt()))); } else { parameters.putInt("cat", -1); parameters.putInt("selectedunitkey", -1); } if (categoryDisabled_which_means_user_do_not_have_read_access) { parameters.put("searchonly", "true"); } parameters.put("index", index); parameters.put("count", count); parameters.put("op", op); parameters.put("subop", subop); parameters.put("hasAdminBrowse", hasAdminReadOnCategory); parameters.put("hasCategoryRead", hasCategoryRead); parameters.put("hasCategoryCreate", hasCategoryCreate); parameters.put("hasCategoryPublish", hasCategoryPublish); parameters.put("hasCategoryAdministrate", hasCategoryAdministrate); parameters.put("fieldname", formItems.getString("fieldname", "")); parameters.put("fieldrow", formItems.getString("fieldrow", "")); parameters.put("contenttypestring", contentTypesString.toString()); parameters.put("sortby", sortBy); parameters.put("sortby-direction", sortByDirection); parameters.put("contenthandler", contenthandler); parameters.put("minoccurrence", formItems.getString("minoccurrence", "")); parameters.put("maxoccurrence", formItems.getString("maxoccurrence", "")); if (formItems.containsKey("reload")) { parameters.put("reload", formItems.getString("reload")); } transformXML(request, response, verticalDoc, "content_list.xsl", parameters); }
From source file:com.vmware.identity.idm.server.config.directory.DirectoryConfigStore.java
@Override public void setAuthnTypes(String tenantName, boolean password, boolean windows, boolean certificate, boolean rsaSecureID) throws Exception { // Set AuthnTypes HashSet<Integer> authnTypes = new HashSet<Integer>(); if (password) authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_PASSWORD); if (windows)//from w w w.j ava 2 s . com authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_WINDOWS); if (certificate) authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_TLS_CERTIFICATE); if (rsaSecureID) authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_RSA_SECUREID); if (authnTypes.size() == 0) // This is to distinguish the case that // none of the AuthnTypes is set and // the case of migrating from old schema // where AuthnTypes is not there. authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_NONE); int[] authnTypesArray = ArrayUtils.toPrimitive(authnTypes.toArray(new Integer[authnTypes.size()])); this.setTenantProperty(tenantName, TenantLdapObject.PROPERTY_AUTHN_TYPES, ServerUtils.getLdapValue(authnTypesArray)); }
From source file:net.ymate.platform.persistence.jdbc.impl.DefaultSession.java
public <T extends IEntity> int[] delete(Class<T> entityClass, ShardingList<Serializable> ids) throws Exception { List<Integer> _results = new ArrayList<Integer>(); for (ShardingList.ShardingElement<Serializable> _element : ids) { _results.add(this.delete(entityClass, _element.getElement(), _element)); }//from ww w.j av a2 s . c om return ArrayUtils.toPrimitive(_results.toArray(new Integer[0])); }
From source file:opennlp.tools.similarity.apps.solr.IterativeSearchRequestHandler.java
public DocList filterResultsBySyntMatchReduceDocSet(DocList docList, SolrQueryRequest req, SolrParams params) { //if (!docList.hasScores()) // return docList; int len = docList.size(); if (len < 1) // do nothing return docList; ParserChunker2MatcherProcessor pos = ParserChunker2MatcherProcessor.getInstance(); DocIterator iter = docList.iterator(); float[] syntMatchScoreArr = new float[len]; String requestExpression = req.getParamString(); String[] exprParts = requestExpression.split("&"); for (String part : exprParts) { if (part.startsWith("q=")) requestExpression = part;// w w w . ja v a 2 s . co m } String fieldNameQuery = StringUtils.substringBetween(requestExpression, "=", ":"); // extract phrase query (in double-quotes) String[] queryParts = requestExpression.split("\""); if (queryParts.length >= 2 && queryParts[1].length() > 5) requestExpression = queryParts[1].replace('+', ' '); else if (requestExpression.indexOf(":") > -1) {// still field-based expression requestExpression = requestExpression.replaceAll(fieldNameQuery + ":", "").replace('+', ' ') .replaceAll(" ", " ").replace("q=", ""); } if (fieldNameQuery == null) return docList; if (requestExpression == null || requestExpression.length() < 5 || requestExpression.split(" ").length < 3) return docList; int[] docIDsHits = new int[len]; IndexReader indexReader = req.getSearcher().getIndexReader(); List<Integer> bestMatchesDocIds = new ArrayList<Integer>(); List<Float> bestMatchesScore = new ArrayList<Float>(); List<Pair<Integer, Float>> docIdsScores = new ArrayList<Pair<Integer, Float>>(); try { for (int i = 0; i < docList.size(); ++i) { int docId = iter.nextDoc(); docIDsHits[i] = docId; Document doc = indexReader.document(docId); // get text for event String answerText = doc.get(fieldNameQuery); if (answerText == null) continue; SentencePairMatchResult matchResult = pos.assessRelevance(requestExpression, answerText); float syntMatchScore = new Double( parseTreeChunkListScorer.getParseTreeChunkListScore(matchResult.getMatchResult())) .floatValue(); bestMatchesDocIds.add(docId); bestMatchesScore.add(syntMatchScore); syntMatchScoreArr[i] = (float) syntMatchScore; //*iter.score(); System.out.println(" Matched query = '" + requestExpression + "' with answer = '" + answerText + "' | doc_id = '" + docId); System.out.println(" Match result = '" + matchResult.getMatchResult() + "' with score = '" + syntMatchScore + "';"); docIdsScores.add(new Pair(docId, syntMatchScore)); } } catch (CorruptIndexException e1) { // TODO Auto-generated catch block e1.printStackTrace(); //log.severe("Corrupt index"+e1); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); //log.severe("File read IO / index"+e1); } Collections.sort(docIdsScores, new PairComparable()); for (int i = 0; i < docIdsScores.size(); i++) { bestMatchesDocIds.set(i, docIdsScores.get(i).getFirst()); bestMatchesScore.set(i, docIdsScores.get(i).getSecond()); } System.out.println(bestMatchesScore); float maxScore = docList.maxScore(); // do not change int limit = docIdsScores.size(); int start = 0; DocSlice ds = null; ds = new DocSlice(start, limit, ArrayUtils.toPrimitive(bestMatchesDocIds.toArray(new Integer[0])), ArrayUtils.toPrimitive(bestMatchesScore.toArray(new Float[0])), bestMatchesDocIds.size(), maxScore); return ds; }