static JsObjectImpl create( JsParserResult parserResult, ObjectNode objectNode, List<Identifier> fqName, ModelBuilder modelBuilder, boolean belongsToParent) { JsObjectImpl scope = modelBuilder.getCurrentObject(); JsObject parent = scope; JsObject result = null; Identifier name = fqName.get(fqName.size() - 1); JsObjectImpl newObject; if (!belongsToParent) { List<Identifier> objectName = fqName.size() > 1 ? fqName.subList(0, fqName.size() - 1) : fqName; parent = ModelUtils.getJsObject(modelBuilder, objectName); } result = parent.getProperty(name.getName()); newObject = new JsObjectImpl( parent, name, ModelUtils.documentOffsetRange( parserResult, objectNode.getStart(), objectNode.getFinish())); newObject.setDeclared(true); if (result != null) { // the object already exist due a definition of a property => needs to be copied for (String propertyName : result.getProperties().keySet()) { newObject.addProperty(propertyName, result.getProperty(propertyName)); } } JsDocumentationHolder docHolder = parserResult.getDocumentationHolder(); newObject.setDocumentation(docHolder.getDocumentation(objectNode)); parent.addProperty(name.getName(), newObject); return (JsObjectImpl) newObject; }
/** * @param dataMapping * @return */ private boolean isReadOnly(DataMapping dataMapping) { if (ModelUtils.isSystemDefinedReadOnlyData(dataMapping)) { return true; } else if (ModelUtils.isDMSReadOnlyData(getModel(), dataMapping)) { return true; } return Direction.IN == dataMapping.getDirection(); }
static JsFunctionImpl create( JsParserResult parserResult, FunctionNode functionNode, List<Identifier> fqName, ModelBuilder modelBuilder, boolean isAnnonymous) { JsObjectImpl inObject = modelBuilder.getCurrentObject(); JsObject globalObject = modelBuilder.getGlobal(); JsObject parentObject = isAnnonymous ? globalObject : inObject; int start = Token.descPosition(functionNode.getFirstToken()); int end = Token.descPosition(functionNode.getLastToken()) + Token.descLength(functionNode.getLastToken()); List<Identifier> parameters = new ArrayList(functionNode.getParameters().size()); for (IdentNode node : functionNode.getParameters()) { parameters.add(create(parserResult, node)); } JsFunctionImpl result; if (fqName.size() > 1) { List<Identifier> objectName = fqName.subList(0, fqName.size() - 1); parentObject = isAnnonymous ? globalObject : ModelUtils.getJsObject(modelBuilder, objectName); result = new JsFunctionImpl( modelBuilder.getCurrentDeclarationScope(), parentObject, fqName.get(fqName.size() - 1), parameters, ModelUtils.documentOffsetRange(parserResult, start, end)); if (parentObject instanceof JsFunction && !"prototype".equals(parentObject.getName())) { result.addModifier(Modifier.STATIC); } } else { result = new JsFunctionImpl( modelBuilder.getCurrentDeclarationScope(), inObject, fqName.get(fqName.size() - 1), parameters, ModelUtils.documentOffsetRange(parserResult, start, end)); } String propertyName = result.getDeclarationName().getName(); JsObject property = parentObject.getProperty(propertyName); // the already existing property parentObject.addProperty(result.getDeclarationName().getName(), result); if (property != null) { result.addOccurrence(property.getDeclarationName().getOffsetRange()); for (Occurrence occurrence : property.getOccurrences()) { result.addOccurrence(occurrence.getOffsetRange()); } } JsDocumentationHolder docHolder = parserResult.getDocumentationHolder(); result.setDocumentation(docHolder.getDocumentation(functionNode)); result.setAnonymous(isAnnonymous); return result; }
@Test public void testCreateUser() throws BiobankCheckException, Exception { String name = "createUser" + r.nextInt(); String password = "******"; UserWrapper user = UserHelper.addUser(name, password, true); // check biobank user User dbUser = ModelUtils.getObjectWithId(appService, User.class, user.getId()); Assert.assertNotNull(dbUser); Assert.assertEquals(name, dbUser.getLogin()); Assert.assertNotNull(dbUser.getCsmUserId()); // check csm user UserProvisioningManager upm = SecurityServiceProvider.getUserProvisioningManager( BiobankCSMSecurityUtil.APPLICATION_CONTEXT_NAME); gov.nih.nci.security.authorization.domainobjects.User csmUser = upm.getUser(name); Assert.assertNotNull(csmUser); Assert.assertNotNull(csmUser.getPassword()); Assert.assertFalse(csmUser.getPassword().isEmpty()); // check user can connect BiobankApplicationService newUserAppService = AllTestsSuite.connect(name, password); // check user can access a biobank object using the new appService try { newUserAppService.search(Site.class, new Site()); } catch (AccessDeniedException ade) { Assert.fail("User should be able to access any object"); } }
public static RegressorFeatureTransformer deserialize(byte[] data) { List<Model> models = ModelUtils.deserializeModels(data); return new RegressorFeatureTransformer( checkType(models.get(0), Regressor.class, "model 0"), checkType(models.get(1), FeatureTransformation.class, "model 1")); }
private String[] generatePlaceholderNames(int columnCount) { String[] placeholders = new String[columnCount]; for (int i = 0; i < columnCount; i++) { placeholders[i] = ModelUtils.generatePlaceholderName(i); } return placeholders; }
public static Set<Entity> getSingletons(Resource res) { Set<Entity> singletons = new HashSet<Entity>(); for (Entity entidad : ModelUtils.<Entity>getVisibleNodes(LedPackage.Literals.ENTITY, res)) { if (LedEntidadUtils.esSingleton(entidad)) singletons.add(entidad); } return singletons; }
@Override public float[] getNormals() { if (normals == null) { normals = ModelUtils.calculateNormals(getFaces()); } return normals; }
/** Initializes the non-standard library package along with its content. */ public AcceleoNonStandardLibrary() { final ResourceSet resourceSet = new ResourceSetImpl(); /* * Crude workaround : We try not to reload the std lib for no reason, but that means the OCL standard * lib used for our references must be the sole instance used by OCL. FIXME : For now, use internals * ... try and find a way to use it without restricted access. */ resourceSet.getResources().add(OCLStandardLibraryImpl.INSTANCE.getString().eResource()); try { if (nonStdLibPackage == null) { nonStdLibPackage = (EPackage) ModelUtils.load(URI.createURI(NS_URI), resourceSet); collectionType = (EClass) nonStdLibPackage.getEClassifier(TYPE_COLLECTION_NAME); eObjectType = (EClass) nonStdLibPackage.getEClassifier(TYPE_EOBJECT_NAME); oclAnyType = (EClass) nonStdLibPackage.getEClassifier(TYPE_OCLANY_NAME); orderedSetType = (EClass) nonStdLibPackage.getEClassifier(TYPE_ORDEREDSET_NAME); sequenceType = (EClass) nonStdLibPackage.getEClassifier(TYPE_SEQUENCE_NAME); stringType = (EClass) nonStdLibPackage.getEClassifier(PRIMITIVE_STRING_NAME); } } catch (IOException e) { AcceleoCommonPlugin.log( AcceleoCommonMessages.getString("AcceleoNonStandardLibrary.LoadFailure"), false); //$NON-NLS-1$ } }
/** * Sets the underlying data being managed by this instance. * * @param data This Object will be converted into a {@link DataModel}. * @see ModelUtils#toDataModel */ @Override public void setWrappedData(Object data) { _baseIndicesList = null; _model = ModelUtils.toDataModel(data); _sortCriterion = null; _sortedIndicesList = null; _wrappedData = data; }
@Test public void testDeleteUser() throws BiobankCheckException, Exception { String name = "deleteUser" + r.nextInt(); UserWrapper user = UserHelper.addUser(name, null, false); User dbUser = ModelUtils.getObjectWithId(appService, User.class, user.getId()); Assert.assertNotNull(dbUser); UserProvisioningManager upm = SecurityServiceProvider.getUserProvisioningManager( BiobankCSMSecurityUtil.APPLICATION_CONTEXT_NAME); gov.nih.nci.security.authorization.domainobjects.User csmUser = upm.getUser(name); Assert.assertNotNull(csmUser); Integer idUser = user.getId(); user.delete(); Assert.assertNull(ModelUtils.getObjectWithId(appService, User.class, idUser)); csmUser = upm.getUser(name); Assert.assertNull(csmUser); }
/** * @param dataMapping * @param maPath * @return */ private Path createStructureDataMapping(DataMapping dataMapping, ManualActivityPath maPath) { Set<TypedXPath> xpaths = ModelUtils.getXPaths(getModel(), dataMapping); for (TypedXPath path : xpaths) { if (path.getParentXPath() == null) { return new XsdPath( maPath, path, dataMapping.getId(), Direction.IN == dataMapping.getDirection()); } } return null; }
@Override protected float[] score0(double data[], float preds[]) { float[] p = super.score0(data, preds); int ntrees = ntrees(); if (p.length == 1) { if (ntrees > 0) div(p, ntrees); } // regression - compute avg over all trees else { // classification float s = sum(p); if (s > 0) div(p, s); // unify over all classes p[0] = ModelUtils.getPrediction(p, data); } return p; }
static JsObjectImpl createAnonymousObject( JsParserResult parserResult, ObjectNode objectNode, ModelBuilder modelBuilder) { String name = modelBuilder.getUnigueNameForAnonymObject(); JsObjectImpl result = new AnonymousObject( modelBuilder.getGlobal(), name, ModelUtils.documentOffsetRange( parserResult, objectNode.getStart(), objectNode.getFinish())); modelBuilder.getGlobal().addProperty(name, result); JsDocumentationHolder docHolder = parserResult.getDocumentationHolder(); result.setDocumentation(docHolder.getDocumentation(objectNode)); return result; }
@Override public Block evaluateFinal() { Dataset dataset = new Dataset(labels, rows); Model model; if (regression) { model = new RegressorFeatureTransformer( new SvmRegressor(params), new FeatureUnitNormalizer()); } else { model = new ClassifierFeatureTransformer( new SvmClassifier(params), new FeatureUnitNormalizer()); } model.train(dataset); BlockBuilder builder = getFinalType().createBlockBuilder(new BlockBuilderStatus()); getFinalType().writeSlice(builder, ModelUtils.serialize(model)); return builder.build(); }
@Test public void testRemoveMembershipWithRole() throws Exception { String name = "removeMembershipWithRole" + r.nextInt(); UserWrapper user = UserHelper.addUser(name, null, true); RoleWrapper role = RoleHelper.addRole(name, true); MembershipWrapper mwr = MembershipHelper.newMembership(user, null, null); mwr.addToRoleCollection(Arrays.asList(role)); user.persist(); user.reload(); Assert.assertEquals(1, user.getMembershipCollection(false).size()); mwr = user.getMembershipCollection(false).get(0); Integer mwrId = mwr.getId(); user.removeFromMembershipCollection(Arrays.asList(mwr)); user.persist(); user.reload(); Assert.assertEquals(0, user.getMembershipCollection(false).size()); Membership msDB = ModelUtils.getObjectWithId(appService, Membership.class, mwrId); Assert.assertNull(msDB); }
@Override public void addInput(Page page) { Block block = page.getBlock(labelChannel); for (int position = 0; position < block.getPositionCount(); position++) { if (labelIsLong) { labels.add((double) BIGINT.getLong(block, position)); } else { labels.add(DOUBLE.getDouble(block, position)); } } block = page.getBlock(featuresChannel); for (int position = 0; position < block.getPositionCount(); position++) { FeatureVector featureVector = ModelUtils.jsonToFeatures(VARCHAR.getSlice(block, position)); rowsSize += featureVector.getEstimatedSize(); rows.add(featureVector); } if (params == null) { block = page.getBlock(paramsChannel); params = LibSvmUtils.parseParameters(VARCHAR.getSlice(block, 0).toStringUtf8()); } }
/** * Reads the DatabaseMetaData for the details of this table including primary keys and indexes. * * @param metaData the database meta data */ void read(DatabaseMetaData metaData) throws SQLException { ResultSet rs = null; // primary keys try { rs = metaData.getPrimaryKeys(null, schema, table); while (rs.next()) { String c = rs.getString("COLUMN_NAME"); primaryKeys.add(c); } closeSilently(rs); // indexes rs = metaData.getIndexInfo(null, schema, table, false, true); indexes = Utils.newHashMap(); while (rs.next()) { IndexInspector info = new IndexInspector(rs); if (info.type.equals(IndexType.UNIQUE)) { String name = info.name.toLowerCase(); if (name.startsWith("primary") || name.startsWith("sys_idx_sys_pk") || name.startsWith("sql") || name.endsWith("_pkey")) { // skip primary key indexes continue; } } if (indexes.containsKey(info.name)) { indexes.get(info.name).addColumn(rs); } else { indexes.put(info.name, info); } } closeSilently(rs); // columns rs = metaData.getColumns(null, schema, table, null); columns = Utils.newHashMap(); while (rs.next()) { ColumnInspector col = new ColumnInspector(); col.name = rs.getString("COLUMN_NAME"); col.type = rs.getString("TYPE_NAME"); col.clazz = ModelUtils.getClassForSqlType(col.type, dateTimeClass); col.size = rs.getInt("COLUMN_SIZE"); col.nullable = rs.getInt("NULLABLE") == DatabaseMetaData.columnNullable; try { Object autoIncrement = rs.getObject("IS_AUTOINCREMENT"); if (autoIncrement instanceof Boolean) { col.isAutoIncrement = (Boolean) autoIncrement; } else if (autoIncrement instanceof String) { String val = autoIncrement.toString().toLowerCase(); col.isAutoIncrement = val.equals("true") | val.equals("yes"); } else if (autoIncrement instanceof Number) { Number n = (Number) autoIncrement; col.isAutoIncrement = n.intValue() > 0; } } catch (SQLException s) { // throw s; } if (primaryKeys.size() == 1) { if (col.name.equalsIgnoreCase(primaryKeys.get(0))) { col.isPrimaryKey = true; } } if (!col.isAutoIncrement) { col.defaultValue = rs.getString("COLUMN_DEF"); } columns.put(col.name.toLowerCase(), col); } } finally { closeSilently(rs); } }
/** * Validates a column against the model's field definition. Checks for existence, supported type, * type mapping, default value, defined lengths, primary key, autoincrement. */ private void validate( List<ValidationRemark> remarks, FieldDefinition fieldDef, boolean throwError) { // unknown field if (!columns.containsKey(fieldDef.columnName.toLowerCase())) { // unknown column mapping remarks.add(error(table, fieldDef, "Does not exist in database!").throwError(throwError)); return; } ColumnInspector col = columns.get(fieldDef.columnName.toLowerCase()); Class<?> fieldClass = fieldDef.field.getType(); Class<?> jdbcClass = ModelUtils.getClassForSqlType(col.type, dateTimeClass); // supported type check // iciql maps to VARCHAR for unsupported types. if (fieldDef.dataType.equals("VARCHAR") && (fieldClass != String.class)) { remarks.add( error( table, fieldDef, "iciql does not currently implement support for " + fieldClass.getName()) .throwError(throwError)); } // number types if (!fieldClass.equals(jdbcClass)) { if (Number.class.isAssignableFrom(fieldClass)) { remarks.add( warn( table, col, format( "Precision mismatch: ModelObject={0}, ColumnObject={1}", fieldClass.getSimpleName(), jdbcClass.getSimpleName()))); } else { if (!Date.class.isAssignableFrom(jdbcClass)) { remarks.add( warn( table, col, format( "Object Mismatch: ModelObject={0}, ColumnObject={1}", fieldClass.getSimpleName(), jdbcClass.getSimpleName()))); } } } // string types if (fieldClass == String.class) { if ((fieldDef.length != col.size) && (col.size < Integer.MAX_VALUE)) { remarks.add( warn( table, col, format( "{0}.length={1}, ColumnMaxLength={2}", IQColumn.class.getSimpleName(), fieldDef.length, col.size))); } if (fieldDef.length > 0 && !fieldDef.trim) { remarks.add( consider( table, col, format( "{0}.trim=true will prevent IciqlExceptions on" + " INSERT or UPDATE, but will clip data!", IQColumn.class.getSimpleName()))); } } // numeric autoIncrement if (fieldDef.isAutoIncrement != col.isAutoIncrement) { remarks.add( warn( table, col, format( "{0}.autoIncrement={1}" + " while Column autoIncrement={2}", IQColumn.class.getSimpleName(), fieldDef.isAutoIncrement, col.isAutoIncrement))); } // default value if (!col.isAutoIncrement && !col.isPrimaryKey) { String defaultValue = null; if (fieldDef.defaultValue != null && fieldDef.defaultValue instanceof String) { defaultValue = fieldDef.defaultValue.toString(); } // check Model.defaultValue format if (!ModelUtils.isProperlyFormattedDefaultValue(defaultValue)) { remarks.add( error( table, col, format( "{0}.defaultValue=\"{1}\"" + " is improperly formatted!", IQColumn.class.getSimpleName(), defaultValue)) .throwError(throwError)); // next field return; } // compare Model.defaultValue to Column.defaultValue if (isNullOrEmpty(defaultValue) && !isNullOrEmpty(col.defaultValue)) { // Model.defaultValue is NULL, Column.defaultValue is NOT NULL remarks.add( warn( table, col, format( "{0}.defaultValue=\"\"" + " while column default=\"{1}\"", IQColumn.class.getSimpleName(), col.defaultValue))); } else if (!isNullOrEmpty(defaultValue) && isNullOrEmpty(col.defaultValue)) { // Column.defaultValue is NULL, Model.defaultValue is NOT NULL remarks.add( warn( table, col, format( "{0}.defaultValue=\"{1}\"" + " while column default=\"\"", IQColumn.class.getSimpleName(), defaultValue))); } else if (!isNullOrEmpty(defaultValue) && !isNullOrEmpty(col.defaultValue)) { if (!defaultValue.equals(col.defaultValue)) { // Model.defaultValue != Column.defaultValue remarks.add( warn( table, col, format( "{0}.defaultValue=\"{1}\"" + " while column default=\"{2}\"", IQColumn.class.getSimpleName(), defaultValue, col.defaultValue))); } } // sanity check Model.defaultValue literal value if (!ModelUtils.isValidDefaultValue(fieldDef.field.getType(), defaultValue)) { remarks.add( error( table, col, format( "{0}.defaultValue=\"{1}\" is invalid!", IQColumn.class.getSimpleName(), defaultValue))); } } }
private StatementBuilder generateColumn( Set<String> imports, ColumnInspector col, boolean trimStrings) { StatementBuilder sb = new StatementBuilder(); Class<?> clazz = col.clazz; String column = ModelUtils.convertColumnToFieldName(col.name.toLowerCase()); sb.append('\t'); if (clazz == null) { // unsupported type clazz = Object.class; sb.append("// unsupported type " + col.type); } else { // Imports // don't import primitives, java.lang classes, or byte [] if (clazz.getPackage() == null) { } else if (clazz.getPackage().getName().equals("java.lang")) { } else if (clazz.equals(byte[].class)) { } else { imports.add(clazz.getCanonicalName()); } // @IQColumn sb.append('@').append(IQColumn.class.getSimpleName()); // IQColumn annotation parameters AnnotationBuilder ap = new AnnotationBuilder(); // IQColumn.name if (!col.name.equalsIgnoreCase(column)) { ap.addParameter("name", col.name); } // IQColumn.primaryKey // composite primary keys are annotated on the table if (col.isPrimaryKey && primaryKeys.size() == 1) { ap.addParameter("primaryKey=true"); } // IQColumn.length if ((clazz == String.class) && (col.size > 0) && (col.size < Integer.MAX_VALUE)) { ap.addParameter("length", col.size); // IQColumn.trim if (trimStrings) { ap.addParameter("trim=true"); } } else { // IQColumn.AutoIncrement if (col.isAutoIncrement) { ap.addParameter("autoIncrement=true"); } } // IQColumn.nullable if (!col.nullable) { ap.addParameter("nullable=false"); } // IQColumn.defaultValue if (!isNullOrEmpty(col.defaultValue)) { ap.addParameter("defaultValue=\"" + col.defaultValue + "\""); } // add leading and trailing () if (ap.length() > 0) { ap.insert(0, '('); ap.append(')'); } sb.append(ap); } sb.append(eol); // variable declaration sb.append("\t" + "public "); sb.append(clazz.getSimpleName()); sb.append(' '); sb.append(column); sb.append(';'); sb.append(eol).append(eol); return sb; }
/** * Generates a model (class definition) from this table. The model includes indexes, primary keys, * default values, lengths, and nullables. information. * * <p>The caller may optionally set a destination package name, whether or not to include the * schema name (setting schema can be a problem when using the model between databases), and if to * automatically trim strings for those that have a maximum length. * * <p> * * @param packageName * @param annotateSchema * @param trimStrings * @return a complete model (class definition) for this table as a string */ String generateModel(String packageName, boolean annotateSchema, boolean trimStrings) { // import statements Set<String> imports = Utils.newHashSet(); imports.add(Serializable.class.getCanonicalName()); imports.add(IQSchema.class.getCanonicalName()); imports.add(IQTable.class.getCanonicalName()); imports.add(IQIndexes.class.getCanonicalName()); imports.add(IQIndex.class.getCanonicalName()); imports.add(IQColumn.class.getCanonicalName()); imports.add(IndexType.class.getCanonicalName()); // fields StringBuilder fields = new StringBuilder(); List<ColumnInspector> sortedColumns = Utils.newArrayList(columns.values()); Collections.sort(sortedColumns); for (ColumnInspector col : sortedColumns) { fields.append(generateColumn(imports, col, trimStrings)); } // build complete class definition StringBuilder model = new StringBuilder(); if (!isNullOrEmpty(packageName)) { // package model.append("package " + packageName + ";"); model.append(eol).append(eol); } // imports List<String> sortedImports = new ArrayList<String>(imports); Collections.sort(sortedImports); for (String imp : sortedImports) { model.append("import ").append(imp).append(';').append(eol); } model.append(eol); // @IQSchema if (annotateSchema && !isNullOrEmpty(schema)) { model.append('@').append(IQSchema.class.getSimpleName()); model.append('('); AnnotationBuilder ap = new AnnotationBuilder(); ap.addParameter(null, schema); model.append(ap); model.append(')').append(eol); } // @IQTable model.append('@').append(IQTable.class.getSimpleName()); model.append('('); // IQTable annotation parameters AnnotationBuilder ap = new AnnotationBuilder(); ap.addParameter("name", table); if (primaryKeys.size() > 1) { ap.addParameter("primaryKey", primaryKeys); } // finish @IQTable annotation model.append(ap); model.append(')').append(eol); // @IQIndexes // @IQIndex String indexAnnotations = generateIndexAnnotations(); if (!StringUtils.isNullOrEmpty(indexAnnotations)) { model.append(indexAnnotations); } // class declaration String clazzName = ModelUtils.convertTableToClassName(table); model.append(format("public class {0} implements Serializable '{'", clazzName)).append(eol); model.append(eol); model.append("\tprivate static final long serialVersionUID = 1L;").append(eol); model.append(eol); // field declarations model.append(fields); // default constructor model.append("\t" + "public ").append(clazzName).append("() {").append(eol); model.append("\t}").append(eol); // end of class body model.append('}'); model.trimToSize(); return model.toString(); }
@Override public byte[] getSerializedData() { return ModelUtils.serializeModels(regressor, transformation); }
TableDefinition<T> createTableIfRequired(Db db) { if (!createTableIfRequired) { // skip table and index creation // but still check for upgrades db.upgradeTable(this); return this; } SQLDialect dialect = db.getDialect(); SQLStatement stat = new SQLStatement(db); StatementBuilder buff; if (memoryTable && dialect.supportsMemoryTables()) { buff = new StatementBuilder("CREATE MEMORY TABLE IF NOT EXISTS "); } else { buff = new StatementBuilder("CREATE TABLE IF NOT EXISTS "); } buff.append(dialect.getTableName(schemaName, tableName)).append('('); for (FieldDefinition field : fields) { buff.appendExceptFirst(", "); buff.append(field.columnName).append(' ').append(field.dataType); if (field.maxLength > 0) { buff.append('(').append(field.maxLength).append(')'); } if (field.isAutoIncrement) { buff.append(" AUTO_INCREMENT"); } if (!field.allowNull) { buff.append(" NOT NULL"); } // default values if (!field.isAutoIncrement && !field.isPrimaryKey) { String dv = field.defaultValue; if (!StringUtils.isNullOrEmpty(dv)) { if (ModelUtils.isProperlyFormattedDefaultValue(dv) && ModelUtils.isValidDefaultValue(field.field.getType(), dv)) { buff.append(" DEFAULT " + dv); } } } } // primary key if (primaryKeyColumnNames != null && primaryKeyColumnNames.size() > 0) { buff.append(", PRIMARY KEY("); buff.resetCount(); for (String n : primaryKeyColumnNames) { buff.appendExceptFirst(", "); buff.append(n); } buff.append(')'); } buff.append(')'); stat.setSQL(buff.toString()); StatementLogger.create(stat.getSQL()); stat.executeUpdate(); // create indexes for (IndexDefinition index : indexes) { String sql = db.getDialect().getCreateIndex(schemaName, tableName, index); stat.setSQL(sql); StatementLogger.create(stat.getSQL()); stat.executeUpdate(); } // tables are created using IF NOT EXISTS // but we may still need to upgrade db.upgradeTable(this); return this; }
static IdentifierImpl create(JsParserResult parserResult, LiteralNode node) { return new IdentifierImpl( node.getString(), ModelUtils.documentOffsetRange(parserResult, node.getStart(), node.getFinish())); }
public String getPvtDateTrimDate() { return ModelUtils.trimDate(pvtDate); }
/** * 性別説明を返す。 * * @return 性別説明 */ public String getGenderDesc() { return genderDesc != null ? genderDesc : ModelUtils.getGenderDesc(gender); }
/** * 年齢と生年月日を返す。 * * @return age(yyyy-MM-dd) */ public String getAgeBirthday() { return ModelUtils.getAgeBirthday(birthday); }
protected String normStr(String s) { return ModelUtils.encodeString(s); }
/** * CLAIM送信を行う。 * * @param sendModel 送信するDocuentModel * @throws Exception */ public void send(DiagnosisSendWrapper wrapper) throws Exception { // s.oh^ 2013/12/10 傷病名のCLAIM送信する/しない Properties config = new Properties(); StringBuilder sbPath = new StringBuilder(); sbPath.append(System.getProperty("jboss.home.dir")); sbPath.append(File.separator); sbPath.append("custom.properties"); File f = new File(sbPath.toString()); FileInputStream fin = new FileInputStream(f); InputStreamReader isr = new InputStreamReader(fin, "JISAutoDetect"); config.load(isr); isr.close(); String claimSend = config.getProperty("diagnosis.claim.send"); if (claimSend != null && claimSend.equals("false")) { return; } // s.oh$ // 新規病名 List<RegisteredDiagnosisModel> addedDiagnosis = wrapper.getAddedDiagnosis(); // 更新病名 List<RegisteredDiagnosisModel> updatedDiagnosis = wrapper.getUpdatedDiagnosis(); // minagawa^ LSC 1.4 傷病名の削除 2013/06/24 // 削除病名 List<RegisteredDiagnosisModel> deletedDiagnosis = wrapper.getDeletedDiagnosis(); // minagawa$ // 実際にCLAIM送信する病名 List<RegisteredDiagnosisModel> actualList = new ArrayList<RegisteredDiagnosisModel>(); // 新規病名を送信する if (addedDiagnosis != null && addedDiagnosis.size() > 0) { for (RegisteredDiagnosisModel rdm : addedDiagnosis) { if (isDorcaUpdatedDisease(rdm) || isPureDisease(rdm)) { actualList.add(rdm); } } if (!actualList.isEmpty()) { if (DEBUG) { debug("-------- Send Diagnosis List to add ----------------"); for (RegisteredDiagnosisModel r : actualList) { debug(r.getDiagnosis()); } } } } // 更新された病名を CLAIM 送信する // detuched object のみ if (updatedDiagnosis != null && updatedDiagnosis.size() > 0) { if (DEBUG) { debug("-------- Send Diagnosis List to update ----------------"); for (RegisteredDiagnosisModel r : updatedDiagnosis) { debug(r.getDiagnosis()); } } actualList.addAll(updatedDiagnosis); } // minagawa^ LSC 1.4 傷病名の削除 2013/06/24 if (deletedDiagnosis != null && deletedDiagnosis.size() > 0) { if (DEBUG) { debug("-------- Send Diagnosis List to delete ----------------"); for (RegisteredDiagnosisModel r : updatedDiagnosis) { debug(r.getDiagnosis()); } } actualList.addAll(deletedDiagnosis); } if (actualList.isEmpty()) { return; } // minagawa$ // DocInfo & RD をカプセル化したアイテムを生成する ArrayList<DiagnosisModuleItem> moduleItems = new ArrayList<DiagnosisModuleItem>(); for (RegisteredDiagnosisModel rd : actualList) { DocInfoModel docInfo = new DocInfoModel(); docInfo.setDocId(GUIDGenerator.generate(docInfo)); docInfo.setTitle(IInfoModel.DEFAULT_DIAGNOSIS_TITLE); docInfo.setPurpose(IInfoModel.PURPOSE_RECORD); docInfo.setFirstConfirmDate(ModelUtils.getDateTimeAsObject(rd.getConfirmDate())); docInfo.setConfirmDate(ModelUtils.getDateTimeAsObject(rd.getFirstConfirmDate())); // s.oh^ 2013/05/10 傷病名対応 rd.setDiagnosisCode(HAND_CODE); // ORCAから取り込んだ場合、コードに0000999を設定する // s.oh$ DiagnosisModuleItem mItem = new DiagnosisModuleItem(); mItem.setDocInfo(docInfo); mItem.setRegisteredDiagnosisModule(rd); moduleItems.add(mItem); } // ヘルパー用の値を生成する String confirmDate = wrapper.getConfirmDate(); // ヘルパークラスを生成する DiseaseHelper dhl = new DiseaseHelper(); dhl.setPatientId(wrapper.getPatientId()); // 患者ID dhl.setConfirmDate(confirmDate); // 確定日 dhl.setDiagnosisModuleItems(moduleItems); // RD+DocInfo dhl.setGroupId(GUIDGenerator.generate(dhl)); // GroupId dhl.setDepartment(wrapper.getDepartment()); // 診療科コード dhl.setDepartmentDesc(wrapper.getDepartmentDesc()); // 診療科名 dhl.setCreatorName(wrapper.getCreatorName()); // 担当医名 dhl.setCreatorId(wrapper.getCreatorLicense()); // 担当医コード dhl.setJmariCode(wrapper.getJamariCode()); // JMARI code dhl.setCreatorLicense(wrapper.getCreatorLicense()); // 医療資格 dhl.setFacilityName(wrapper.getFacilityName()); // 施設名 if (DEBUG) { debug("患者ID=" + dhl.getPatientId()); debug("確定日=" + dhl.getConfirmDate()); debug("GroupId=" + dhl.getGroupId()); debug("診療科コード=" + dhl.getDepartment()); debug("診療科名=" + dhl.getDepartmentDesc()); debug("担当医名=" + dhl.getCreatorName()); debug("担当医コード=" + dhl.getCreatorId()); debug("JMARI code=" + dhl.getJmariCode()); debug("医療資格=" + dhl.getCreatorLicense()); debug("施設名=" + dhl.getFacilityName()); } // ログのために基本情報を生成する StringBuilder sb = new StringBuilder(); sb.append(confirmDate).append(" "); sb.append(wrapper.getPatientId()).append(" "); sb.append(wrapper.getPatientName()).append(" "); sb.append(wrapper.getPatientGender()); String baseInfo = sb.toString(); // -------------------------------------------------------- // CLIAM message を生成する // -------------------------------------------------------- VelocityContext context = VelocityHelper.getContext(); context.put(OBJECT_NAME, dhl); StringWriter sw = new StringWriter(); BufferedWriter bw = new BufferedWriter(sw); Velocity.mergeTemplate(TEMPLATE_NAME, TEMPLATE_ENC, context, bw); bw.flush(); bw.close(); String claimMessage = sw.toString(); // minagawa^ CLAIM Log log(claimMessage); // if (DEBUG) { // debug(claimMessage); // } // minagawa$ // -------------------------------------------------------- // ORCAへ接続する Socket socket = new Socket(host, port); OutputStream out = socket.getOutputStream(); DataOutputStream dout = new DataOutputStream(out); BufferedOutputStream writer = new BufferedOutputStream(dout); InputStream in = socket.getInputStream(); DataInputStream din = new DataInputStream(in); BufferedInputStream reader = new BufferedInputStream(din); // Writes UTF8 data writer.write(claimMessage.getBytes(enc)); writer.write(EOT); writer.flush(); // Reads result int c = reader.read(); if (c == ACK) { sb = new StringBuilder(); sb.append(ACK_STR).append(baseInfo); log(sb.toString()); } else if (c == NAK) { sb = new StringBuilder(); sb.append(NAK_STR).append(baseInfo); log(sb.toString()); } writer.close(); reader.close(); socket.close(); }
void mapFields() { boolean byAnnotationsOnly = false; boolean inheritColumns = false; boolean strictTypeMapping = false; if (clazz.isAnnotationPresent(JQTable.class)) { JQTable tableAnnotation = clazz.getAnnotation(JQTable.class); byAnnotationsOnly = tableAnnotation.annotationsOnly(); inheritColumns = tableAnnotation.inheritColumns(); strictTypeMapping = tableAnnotation.strictTypeMapping(); } List<Field> classFields = New.arrayList(); classFields.addAll(Arrays.asList(clazz.getDeclaredFields())); if (inheritColumns) { Class<?> superClass = clazz.getSuperclass(); classFields.addAll(Arrays.asList(superClass.getDeclaredFields())); } for (Field f : classFields) { // default to field name String columnName = f.getName(); boolean isAutoIncrement = false; boolean isPrimaryKey = false; int maxLength = 0; boolean trimString = false; boolean allowNull = true; String defaultValue = ""; boolean hasAnnotation = f.isAnnotationPresent(JQColumn.class); if (hasAnnotation) { JQColumn col = f.getAnnotation(JQColumn.class); if (!StringUtils.isNullOrEmpty(col.name())) { columnName = col.name(); } isAutoIncrement = col.autoIncrement(); isPrimaryKey = col.primaryKey(); maxLength = col.maxLength(); trimString = col.trimString(); allowNull = col.allowNull(); defaultValue = col.defaultValue(); } boolean isPublic = Modifier.isPublic(f.getModifiers()); boolean reflectiveMatch = isPublic && !byAnnotationsOnly; if (reflectiveMatch || hasAnnotation) { FieldDefinition fieldDef = new FieldDefinition(); fieldDef.field = f; fieldDef.columnName = columnName; fieldDef.isAutoIncrement = isAutoIncrement; fieldDef.isPrimaryKey = isPrimaryKey; fieldDef.maxLength = maxLength; fieldDef.trimString = trimString; fieldDef.allowNull = allowNull; fieldDef.defaultValue = defaultValue; fieldDef.dataType = ModelUtils.getDataType(fieldDef, strictTypeMapping); fields.add(fieldDef); } } List<String> primaryKey = New.arrayList(); for (FieldDefinition fieldDef : fields) { if (fieldDef.isPrimaryKey) { primaryKey.add(fieldDef.columnName); } } if (primaryKey.size() > 0) { setPrimaryKey(primaryKey); } }