code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public static ApiUser getUserAgent(User sfsUser) { Object userAgent = sfsUser.getProperty(APIKey.USER); if(userAgent == null) throw new RuntimeException("Can not get user agent"); return (ApiUser)userAgent; }
Get user agent object mapped to smartfox user object @param sfsUser smartfox user object @return user agent object
public static ApiRoom getRoomAgent(Room sfsRoom) { Object roomAgent = sfsRoom.getProperty(APIKey.ROOM); if(roomAgent == null) throw new RuntimeException("Can not get user agent"); return (ApiRoom)roomAgent; }
Get room agent object mapped to smartfox room object @param sfsRoom smartfox room object @return room agent object
public boolean verify(byte[] message, byte[] signature) { try { // this way signatureInstance should be thread safe final Signature signatureInstance = ((provider == null) || (provider.length() == 0)) ? Signature .getInstance(algorithm) : Signature.getInstance(algorithm, provider); signatureInstance.initVerify(publicKey); signatureInstance.update(message); return signatureInstance.verify(signature); } catch (java.security.SignatureException e) { return false; } catch (Exception e) { throw new SignatureException("error verifying signature", e); } }
Verifies the authenticity of a message using a digital signature. @param message the original message to verify @param signature the digital signature @return true if the original message is verified by the digital signature
public static <X> List<X> mostVotedFor(Map<X, Double> votes) { // Choose the label with the greatest number of votes // If there is a tie, choose the one with the least index double maxTalley = Double.NEGATIVE_INFINITY; List<X> maxTickets = new ArrayList<X>(); for(Entry<X,Double> entry : votes.entrySet()) { X ticket = entry.getKey(); double talley = entry.getValue(); if (talley > maxTalley) { maxTickets = new ArrayList<X>(); maxTickets.add(ticket); maxTalley = talley; } else if (talley == maxTalley) { maxTickets.add(ticket); } } return maxTickets; }
Choose the <X> with the greatest number of votes. @param <X> The type of the thing being voted for. @param votes Maps <X> to a Double representing the number of votes it received. @return The <X> that received the most votes.
public static <X,Y> Map<X,Y> zip(List<X> keys, List<Y> values) { if (keys.size() != values.size()) { throw new IllegalArgumentException("Lengths are not equal"); } Map<X,Y> map = new HashMap<>(keys.size()); for (int i=0; i<keys.size(); i++) { map.put(keys.get(i), values.get(i)); } return map; }
Like Python's zip, this creates a map by zipping together the key and values lists.
public String sign(KeyStoreChooser keyStoreChooser, PrivateKeyChooserByAlias privateKeyChooserByAlias, String message) { Base64EncodedSigner signer = cache.get(cacheKey(keyStoreChooser, privateKeyChooserByAlias)); if (signer != null) { return signer.sign(message); } Base64EncodedSignerImpl signerImpl = new Base64EncodedSignerImpl(); signerImpl.setAlgorithm(algorithm); signerImpl.setCharsetName(charsetName); signerImpl.setProvider(provider); PrivateKey privateKey = privateKeyRegistryByAlias.get(keyStoreChooser, privateKeyChooserByAlias); if (privateKey == null) { throw new SignatureException("private key not found: keyStoreName=" + keyStoreChooser.getKeyStoreName() + ", alias=" + privateKeyChooserByAlias.getAlias()); } signerImpl.setPrivateKey(privateKey); cache.put(cacheKey(keyStoreChooser, privateKeyChooserByAlias), signerImpl); return signerImpl.sign(message); }
Signs a message. @param keyStoreChooser the keystore chooser @param privateKeyChooserByAlias the private key chooser @param message the message to sign @return the base64 encoded signature
@SuppressWarnings("unchecked") @Override public Boolean execute() { try { api.playerToSpectator(CommandUtil.getSfsUser(user, api), CommandUtil.getSfsRoom(targetRoom, extension), fireClientEvent, fireServerEvent); } catch (SFSRoomException e) { throw new IllegalStateException(e); } return Boolean.TRUE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
public void init(FgExampleList data) { if (data == null && prm.featCountCutoff > 0) { throw new IllegalArgumentException("Data can only be null if there is no feature count cutoff."); } // Ensure the FactorTemplateList is initialized, and maybe count features along the way. if (templates.isGrowing() && data != null) { log.info("Growing feature template list by iterating over examples"); extractAllFeats(data, templates); templates.stopGrowth(); feAlphabet.stopGrowth(); } numTemplates = templates.size(); // Apply a feature count cutoff. this.included = new boolean[numTemplates][][]; for (int t=0; t<numTemplates; t++) { FactorTemplate template = templates.get(t); int numConfigs = template.getNumConfigs(); int numFeats = template.getAlphabet().size(); included[t] = new boolean[numConfigs][numFeats]; } BoolArrays.fill(included, true); if (prm.featCountCutoff >= 1) { log.info("Applying feature count cutoff: " + prm.featCountCutoff); IntIntDenseVector[][] counts = countFeatures(data, templates); excludeByFeatCount(counts); } // Always include the bias features. for (int t=0; t<included.length; t++) { FactorTemplate template = templates.get(t); FeatureNames alphabet = template.getAlphabet(); for (int k = 0; k < alphabet.size(); k++) { if (alphabet.isBiasFeature(k)) { for (int c = 0; c < included[t].length; c++) { included[t][c][k] = true; } } } } // Set the indices to track only the included parameters. // All other entries are set to -1. // Also: Count the number of parameters, accounting for excluded params. numParams = feAlphabet.size(); this.indices = new int[numTemplates][][]; for (int t=0; t<indices.length; t++) { FactorTemplate template = templates.get(t); int numConfigs = template.getNumConfigs(); int numFeats = template.getAlphabet().size(); indices[t] = new int[numConfigs][numFeats]; for (int c = 0; c < indices[t].length; c++) { for (int k = 0; k < indices[t][c].length; k++) { indices[t][c][k] = included[t][c][k] ? numParams++ : -1; } } } reservedOffset = numParams; numParams += reservedMax; if (reservedMax > 0) { log.debug("Reserved {} parameters starting at {}", reservedMax, reservedOffset); } if (fcmAlphabet.size() > 0) { log.debug("FCM is using {} features", fcmAlphabet.size()); } fcmAlphabet.stopGrowth(); // If we are using the feature hashing trick, we may want to further increase // the number of model parameters. numParams = Math.max(numParams, featureHashModMax); initialized = true; }
The case of data == null should only be allowed in testing.
private void extractAllFeats(FgExampleList data, FactorTemplateList templates) { // Create a "no-op" counter. IFgModel counts = new IFgModel() { @Override public void addAfterScaling(FeatureVector fv, double multiplier) { } @Override public void add(int feat, double addend) { } }; // Loop over all factors in the dataset. for (int i=0; i<data.size(); i++) { if (i % 1000 == 0) { log.debug("Processing example: " + i); } LFgExample ex = data.get(i); FactorGraph fgLat = MarginalLogLikelihood.getFgLat(ex.getFactorGraph(), ex.getGoldConfig()); // Create a "no-op" inferencer, which returns arbitrary marginals. NoOpInferencer inferencer = new NoOpInferencer(ex.getFactorGraph()); for (int a=0; a<ex.getFactorGraph().getNumFactors(); a++) { Factor f = fgLat.getFactor(a); if (f instanceof ObsFeatureCarrier && f instanceof TemplateFactor) { // For each observation function extractor. int t = templates.getTemplateId((TemplateFactor) f); if (t != -1) { ((ObsFeatureCarrier) f).getObsFeatures(); } } else { // For each standard factor. f = ex.getFactorGraph().getFactor(a); if (f instanceof GlobalFactor) { ((GlobalFactor) f).addExpectedPartials(counts, 0, inferencer, a); } else { VarTensor marg = inferencer.getMarginalsForFactorId(a); f.addExpectedPartials(counts, marg, 0); } } } } }
Loops through all examples to create the features, thereby ensuring that the FTS are initialized.
private IntIntDenseVector[][] countFeatures(FgExampleList data, FactorTemplateList templates) { IntIntDenseVector[][] counts = new IntIntDenseVector[numTemplates][]; for (int t=0; t<numTemplates; t++) { FactorTemplate template = templates.get(t); int numConfigs = template.getNumConfigs(); int numFeats = template.getAlphabet().size(); counts[t] = new IntIntDenseVector[numConfigs]; for (int c=0; c<numConfigs; c++) { counts[t][c] = new IntIntDenseVector(numFeats); } } for (int i=0; i<data.size(); i++) { LFgExample ex = data.get(i); FactorGraph fg = ex.getFactorGraph(); for (int a=0; a<ex.getFactorGraph().getNumFactors(); a++) { Factor f = fg.getFactor(a); if (f instanceof ObsFeatureCarrier && f instanceof TemplateFactor) { int t = templates.getTemplateId((TemplateFactor) f); if (t != -1) { FeatureVector fv = ((ObsFeatureCarrier) f).getObsFeatures(); // We must clamp the predicted variables and loop over the latent ones. VarConfig predVc = ex.getGoldConfigPred(a); IntIter iter = IndexForVc.getConfigIter(ex.getFactorGraph().getFactor(a).getVars(), predVc); while (iter.hasNext()) { // The configuration of all the latent/predicted variables, // where the predicted variables have been clamped. int config = iter.next(); for (IntDoubleEntry entry : fv) { counts[t][config].add(entry.index(), 1); } } } } } } return counts; }
Counts the number of times each feature appears in the gold training data.
private void excludeByFeatCount(IntIntDenseVector[][] counts) { for (int t=0; t<included.length; t++) { for (int c = 0; c < included[t].length; c++) { for (int k = 0; k < included[t][c].length; k++) { boolean exclude = (counts[t][c].get(k) < prm.featCountCutoff); if (exclude) { included[t][c][k] = false; } } } } }
Exclude those features which do not pass the feature count cutoff threshold (bias features will be kept separately).
@Override public void handleServerEvent(ISFSEvent event) throws SFSException { Zone sfsZone = (Zone) event.getParameter(SFSEventParam.ZONE); ApiBuddyImpl buddy = (ApiBuddyImpl) event.getParameter(SFSBuddyEventParam.BUDDY); notifyToHandlers((ApiZone) sfsZone.getProperty(APIKey.ZONE), buddy); }
/* (non-Javadoc) @see com.smartfoxserver.v2.extensions.IServerEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent)
protected void notifyToHandlers(ApiZone zone, ApiBuddyImpl buddy) { for(ServerHandlerClass handler : handlers) { notifyToHandler(handler, zone, buddy); } }
Notify event to handlers (listeners) @param zone api zone reference @param buddy api buddy reference
protected void notifyToHandler(ServerHandlerClass handler, ApiZone zone, ApiBuddyImpl buddy) { ReflectMethodUtil.invokeHandleMethod( handler.getHandleMethod(), handler.newInstance(), context, zone, buddy); }
Notify event to handler @param handler structure of handler class @param zone api zone reference @param buddy api buddy reference
public double get(int... indices) { checkIndices(indices); int c = getConfigIdx(indices); return values.get(c); }
Gets the value of the entry corresponding to the given indices. @param indices The indices of the multi-dimensional array. @return The current value.
public double getFast(int i0, int i1, int i2) { int c = offset; c += strides[0] * i0; c += strides[1] * i1; c += strides[2] * i2; return values.get(c); }
Gets the value of the entry corresponding to the given indices. @param indices The indices of the multi-dimensional array. @return The current value.
public double set(int[] indices, double val) { checkIndices(indices); int c = getConfigIdx(indices); return values.set(c, val); }
Sets the value of the entry corresponding to the given indices. @param indices The indices of the multi-dimensional array. @param val The value to set. @return The previous value.
public double add(int[] indices, double val) { checkIndices(indices); int c = getConfigIdx(indices); return values.set(c, s.plus(values.get(c), val)); }
Adds the value to the entry corresponding to the given indices. @param indices The indices of the multi-dimensional array. @param val The value to add. @return The previous value.
public double subtract(int[] indices, double val) { checkIndices(indices); int c = getConfigIdx(indices); return values.set(c, s.minus(values.get(c), val)); }
Subtracts the value to the entry corresponding to the given indices. @param indices The indices of the multi-dimensional array. @param val The value to subtract. @return The previous value.
private static int[] getStrides(int[] dims) { int rightmost = dims.length - 1; int[] strides = new int[dims.length]; if (dims.length > 0) { strides[rightmost] = 1; for (int i=rightmost-1; i >= 0; i--) { strides[i] = dims[i+1]*strides[i+1]; } } return strides; }
Gets the strides for the given dimensions. The stride for dimension i (stride[i]) denotes the step forward in values array necessary to increase the index for that dimension by 1.
private void checkIndices(int... indices) { if (indices.length != dims.length) { throw new IllegalArgumentException(String.format( "Indices array is not the correct length. expected=%d actual=%d", indices.length, dims.length)); } for (int i=0; i<indices.length; i++) { if (indices[i] < 0 || dims[i] <= indices[i]) { throw new IllegalArgumentException(String.format( "Indices array contains an index that is out of bounds: i=%d index=%d", i, indices[i])); } } }
Checks that the indices are valid.
public void addValue(int idx, double val) { int c = get1dConfigIdx(idx); values.set(c, s.plus(values.get(c), val)); }
Adds the value to the idx'th entry.
public void subtractValue(int idx, double val) { int c = get1dConfigIdx(idx); values.set(c, s.minus(values.get(c), val)); }
Subtracts the value from the idx'th entry.
public void multiplyValue(int idx, double val) { int c = get1dConfigIdx(idx); values.set(c, s.times(values.get(c), val)); }
Multiplies the value with the idx'th entry.
public void divideValue(int idx, double val) { int c = get1dConfigIdx(idx); values.set(c, s.divide(values.get(c), val)); }
Divides the value from the idx'th entry.
public void elemAdd(VTensor other) { checkEqualSize(this, other); for (int c = 0; c < this.size(); c++) { addValue(c, other.getValue(c)); } }
Adds a factor elementwise to this one. @param other The addend. @throws IllegalArgumentException If the two tensors have different sizes.
@Override public void elemAdd(MVec addend) { if (addend instanceof VTensor) { elemAdd((VTensor)addend); } else { throw new IllegalArgumentException("Addend must be of type " + this.getClass()); } }
Implements {@link MVec#elemAdd(MVec)}.
public void elemSubtract(VTensor other) { checkEqualSize(this, other); for (int c = 0; c < this.size(); c++) { subtractValue(c, other.getValue(c)); } }
Subtracts a factor elementwise from this one. @param other The subtrahend. @throws IllegalArgumentException If the two tensors have different sizes.
public void elemMultiply(VTensor other) { checkEqualSize(this, other); for (int c = 0; c < this.size(); c++) { multiplyValue(c, other.getValue(c)); } }
Multiply a factor elementwise with this one. @param other The multiplier. @throws IllegalArgumentException If the two tensors have different sizes.
public void elemDivide(VTensor other) { checkEqualSize(this, other); for (int c = 0; c < this.size(); c++) { divideValue(c, other.getValue(c)); } }
Divide a factor elementwise from this one. @param other The divisor. @throws IllegalArgumentException If the two tensors have different sizes.
public void elemApply(Lambda.FnIntDoubleToDouble fn) { for (int c=0; c<this.size; c++) { this.setValue(c, fn.call(c, this.getValue(c))); } }
Adds a factor elementwise to this one. @param other The addend. @throws IllegalArgumentException If the two tensors have different sizes.
public void exp() { for (int c=0; c<this.size(); c++) { this.setValue(c, s.exp(this.getValue(c))); } }
Take the exp of each entry.
public void log() { for (int c=0; c<this.size(); c++) { this.setValue(c, s.log(this.getValue(c))); } }
Take the log of each entry.
public double normalize() { double propSum = this.getSum(); if (propSum == s.zero()) { this.fill(s.divide(s.one(), s.fromReal(this.size()))); } else if (propSum == s.posInf()) { int count = count(s.posInf()); if (count == 0) { throw new RuntimeException("Unable to normalize since sum is infinite but contains no infinities: " + this.toString()); } double constant = s.divide(s.one(), s.fromReal(count)); for (int d=0; d<this.size(); d++) { if (this.getValue(d) == s.posInf()) { this.setValue(d, constant); } else { this.setValue(d, s.zero()); } } } else { this.divide(propSum); assert !this.containsNaN(); } return propSum; }
Normalizes the values so that they sum to 1
public double getSum() { double sum = s.zero(); for (int c = 0; c < this.size(); c++) { sum = s.plus(sum, getValue(c)); } return sum; }
Gets the sum of all the entries in this tensor.
public double getProd() { double prod = s.one(); for (int c = 0; c < this.size(); c++) { prod = s.times(prod, getValue(c)); } return prod; }
Gets the product of all the entries in this tensor.
public double getMax() { double max = s.minValue(); for (int c = 0; c < this.size(); c++) { double val = getValue(c); if (s.gte(val, max)) { max = val; } } return max; }
Gets the max value in the tensor.
public int getArgmaxConfigId() { int argmax = -1; double max = s.minValue(); for (int c = 0; c < this.size(); c++) { double val = getValue(c); if (s.gte(val, max)) { max = val; argmax = c; } } return argmax; }
Gets the ID of the configuration with the maximum value.
public double getInfNorm() { double max = s.negInf(); for (int c = 0; c < this.size(); c++) { double abs = s.abs(getValue(c)); if (s.gte(abs, max)) { max = abs; } } return max; }
Gets the infinity norm of this tensor. Defined as the maximum absolute value of the entries.
public int count(double val) { int count = 0; for (int i=0; i<this.size(); i++) { if (this.getValue(i) == val) { count++; } } return count; }
Gets the number of times a given value occurs in the Tensor (exact match).
public double getDotProduct(VTensor other) { checkEqualSize(this, other); double dot = s.zero(); for (int c = 0; c < this.size(); c++) { dot = s.plus(dot, s.times(this.getValue(c), other.getValue(c))); } return dot; }
Computes the sum of the entries of the pointwise product of two tensors with identical domains.
public void set(VTensor other) { checkEqualSize(this, other); this.dims = IntArrays.copyOf(other.dims); for (int c = 0; c < this.size(); c++) { this.setValue(c, other.getValue(c)); } }
Sets the dimensions and values to be the same as the given tensor. Assumes that the size of the two vectors are equal.
public double[] getValuesAsNativeArray() { double[] vs = new double[this.size()]; for (int c = 0; c < vs.length; c++) { vs[c] = getValue(c); } return vs; }
Gets a copy of the internal values as a native array.
public boolean containsNaN() { for (int c = 0; c < this.size(); c++) { if (s.isNaN(this.getValue(c))) { return true; } } return false; }
Returns true if this tensor contains any NaNs.
public static VTensor combine(VTensor t1, VTensor t2) { checkSameDims(t1, t2); checkSameAlgebra(t1, t2); int[] dims3 = IntArrays.insertEntry(t1.getDims(), 0, 2); VTensor y = new VTensor(t1.s, dims3); y.addTensor(t1, 0, 0); y.addTensor(t2, 0, 1); return y; }
Combines two identically sized tensors by adding an initial dimension of size 2. @param t1 The first tensor to add. @param t2 The second tensor to add. @return The combined tensor.
static int guessNumWords(Beliefs b) { int n = -1; for (int v=0; v<b.varBeliefs.length; v++) { Var var = b.varBeliefs[v].getVars().get(0); if (var instanceof LinkVar) { LinkVar link = (LinkVar) var; int p = link.getParent(); int c = link.getChild(); n = Math.max(n, Math.max(p, c)); } } return n+1; }
Gets the maximum index of a parent or child in a LinkVar, plus one.
public void addEx(double weight, int x, int y, FeatureVector[] fvs) { if (numYs == -1) { numYs = fvs.length; } if (yAlphabet.size() > numYs) { throw new IllegalStateException("Y alphabet has grown larger than the number of Ys"); } if (y >= numYs) { throw new IllegalArgumentException("Invalid y: " + y); } else if (fvs.length != numYs) { throw new IllegalArgumentException("Features must be given for all labels y"); } LogLinearExample ex = new LogLinearExample(weight, x, y, fvs); exList.add(ex); }
Adds a new log-linear model instance. @param weight The weight of this example. @param x The observation, x. @param y The prediction, y. @param fvs The binary features on the observations, x, for all possible labels, y'. Indexed by y'.
public void addExStrFeats(double weight, Object xObj, Object yObj, List<String>[] fvStrs) { FeatureVector[] fvs = new FeatureVector[fvStrs.length]; for (int i=0; i<fvs.length; i++) { fvs[i] = new FeatureVector(); for (String featName : fvStrs[i]) { fvs[i].add(featAlphabet.lookupIndex(featName), 1); } } addEx(weight, xObj, yObj, fvs); }
Adds a new log-linear model instance. @param weight The weight of this example. @param x The observation, x. @param y The prediction, y. @param fvs The binary features on the observations, x, for all possible labels, y'. Indexed by y'.
public void addEx(double weight, Object xObj, Object yObj, FeatureVector[] fvs) { int x = xAlphabet.lookupIndex(xObj); int y = yAlphabet.lookupIndex(yObj); addEx(weight, x, y, fvs); }
Adds a new log-linear model instance. @param weight The weight of this example. @param x The observation, x. @param y The prediction, y. @param fvs The binary features on the observations, x, for all possible labels, y'. Indexed by y'.
public Map getModelEntryMap(Map requestParamMap,String tableName,String modelName,String dbName) throws Exception{ return getModelEntryMap( requestParamMap, tableName, modelName, dbName,""); }
��ȡ���ģ�� @param requestParamMap �ύ������� @param tableName ����� @param modelName ģ����� @return @throws Exception
public String createWhereInStr(Map requestParamMap0,Map modelEntryMap){ if(modelEntryMap==null){ return null; } //add 201902 ning Map requestParamMap=new CaseInsensitiveKeyMap(); if(requestParamMap0!=null){ requestParamMap.putAll(requestParamMap0); } Cobj cobjValues=Cutil.createCobj(" and "); String tempDbType=calcuDbType(); Iterator it=modelEntryMap.keySet().iterator(); while(it.hasNext()){ String key=(String) it.next(); MicroDbModelEntry modelEntry=(MicroDbModelEntry) modelEntryMap.get(key); Object value= requestParamMap.get(key); String whereValue=""; if(CheckModelTypeUtil.isNumber(modelEntry)){ whereValue=Cutil.rep("<REPLACE>",(String) value); }else if(CheckModelTypeUtil.isDate(modelEntry) ){ //20171103 for oracle String temp="str_to_date('<REPLACE>','%Y-%m-%d %H:%i:%s')"; if(tempDbType!=null && "oracle".equals(tempDbType)){ temp="to_date('<REPLACE>','"+ORCL_DATE_FORMAT+"')"; } whereValue=Cutil.rep(temp,(String) value); }else{ whereValue=Cutil.rep("'<REPLACE>'",(String) value); } if(CheckModelTypeUtil.isRealCol(modelEntry)==false){ String metaName=modelEntry.getMetaContentId(); String realKey=CheckModelTypeUtil.getRealColName(key); cobjValues.append(Cutil.rep(metaName+"->>'$.<REPLACE>'=", realKey)+whereValue,value!=null); }else if(CheckModelTypeUtil.isRealCol(modelEntry)){ //add 20171115 by ninghao if(value instanceof MicroColObj){ String colInfoStr=((MicroColObj)value).getColInfo(); List colData=((MicroColObj)value).getColData(); cobjValues.append(key+" "+colInfoStr); }else{ //end cobjValues.append(Cutil.rep("<REPLACE>=", key)+whereValue,value!=null); } } } return cobjValues.getStr(); }
���ģ�ͺ��ύ����where�ַ� @param requestParamMap �ύ���� @param modelEntryMap ���ģ�� @return @throws Exception
public String createUpdateInStr(Map dbColMap0,Map modelEntryMap){ if(dbColMap0==null){ return null; } //add 201902 ning Map dbColMap=new CaseInsensitiveKeyMap(); if(dbColMap0!=null){ dbColMap.putAll(dbColMap0); } List realValueList=new ArrayList(); List extValueList=new ArrayList(); Boolean metaFlag=false; Map<String,Cobj> metaFlagMap=new LinkedHashMap(); Cobj crealValues=Cutil.createCobj(); String tempDbType=calcuDbType(); Iterator it=modelEntryMap.keySet().iterator(); while(it.hasNext()){ String key=(String) it.next(); MicroDbModelEntry modelEntry=(MicroDbModelEntry) modelEntryMap.get(key); if(CheckModelTypeUtil.isDynamicCol(modelEntry)){ String value=(String) dbColMap.get(key); String metaName=modelEntry.getMetaContentId(); Cobj cobjValues=metaFlagMap.get(metaName); if(cobjValues==null){ cobjValues=Cutil.createCobj(); metaFlagMap.put(metaName,cobjValues); } String realKey=CheckModelTypeUtil.getRealColName(key); cobjValues.append(Cutil.rep("'$.<REPLACE>'", realKey),value!=null); if(CheckModelTypeUtil.isNumber(modelEntry)){ cobjValues.append(Cutil.rep("<REPLACE>",value),value!=null); }else if(CheckModelTypeUtil.isDate(modelEntry) ){ if(value!=null ){ if(value.toLowerCase().equals("now()")){ //for oracle String tmpValue="now()"; if(tempDbType!=null && "oracle".equals(tempDbType)){ tmpValue="SYSDATE"; } cobjValues.append(Cutil.rep("<REPLACE>",tmpValue),value!=null); }else{ cobjValues.append(Cutil.rep("'<REPLACE>'",value),value!=null); } } }else if(realKey.endsWith("_json")){ cobjValues.append(Cutil.rep("<REPLACE>",value),value!=null && !"".equals(value)); }else{ cobjValues.append(Cutil.rep("'<REPLACE>'",value),value!=null); } if(value!=null){ extValueList.add(value); } }else if(CheckModelTypeUtil.isRealCol(modelEntry)){ //add 20170830 by ninghao Object vobj=dbColMap.get(key); if(vobj instanceof MicroColObj){ String colInfoStr=((MicroColObj)vobj).getColInfo(); crealValues.append(key+"="+colInfoStr); continue; } //end String value=(String) dbColMap.get(key); String whereValue=""; //add 201807 ning if(value!=null && MICRO_DB_NULL.equals(value)){ if(tempDbType!=null && "oracle".equals(tempDbType)){ whereValue="NULL"; }else{ whereValue="null"; }//end }else if(CheckModelTypeUtil.isNumber(modelEntry)){ whereValue=Cutil.rep("<REPLACE>",value); }else if(CheckModelTypeUtil.isDate(modelEntry)){ if(value!=null ){ if(value.toLowerCase().equals("now()")){ //for oracle String tmpValue="now()"; if(tempDbType!=null && "oracle".equals(tempDbType)){ tmpValue="SYSDATE"; } whereValue=tmpValue; }else{ //for oracle String temp="str_to_date('<REPLACE>','%Y-%m-%d %H:%i:%s')"; if(tempDbType!=null && "oracle".equals(tempDbType)){ temp="to_date('<REPLACE>','"+ORCL_DATE_FORMAT+"')"; } whereValue=Cutil.rep(temp,value); } } }else{ whereValue=Cutil.rep("'<REPLACE>'",value); } if(value!=null ){ crealValues.append(Cutil.rep("<REPLACE>=", key)+whereValue,value!=null); } } } Set<String> metaKeySet=metaFlagMap.keySet(); for(String key:metaKeySet){ Cobj cobj=metaFlagMap.get(key); String dynamic=cobj.getStr(); crealValues.append(Cutil.rep(key+"=JSON_SET(ifnull("+key+",'{}'),<REPLACE>)",dynamic),dynamic!=null ); } return crealValues.getStr(); }
���ģ�ͺ��ύ����update-set�ַ� @param dbColMap �ύ���� @param modelEntryMap ���ģ�� @param placeList ռλ���滻ֵ @return @throws Exception
public String createInsertBeforeStr4ModelEntry(Map dbColMap0,Map<String,MicroDbModelEntry> modelEntryMap){ if(dbColMap0==null){ return null; } //add 201902 ning Map dbColMap=new CaseInsensitiveKeyMap(); if(dbColMap0!=null){ dbColMap.putAll(dbColMap0); } Cobj crealValues=Cutil.createCobj(); Map metaMap=new HashMap(); Iterator it=dbColMap.keySet().iterator(); Set<String> metaFlagSet=new TreeSet(); while(it.hasNext()){ String key=(String) it.next(); String value=(String) dbColMap.get(key); MicroDbModelEntry modelEntry=modelEntryMap.get(key); if(modelEntry==null){ continue; } if(CheckModelTypeUtil.isRealCol(modelEntry)==false){ if(value!=null){ String metaName=modelEntry.getMetaContentId(); metaFlagSet.add(metaName); } }else { crealValues.append(key,value!=null); } } for(String metaName:metaFlagSet){ crealValues.append(metaName); } return crealValues.getStr(); }
��װ�������ַ� @param dbColMap �ύ��� @param modelEntryMap ���ģ�� @return @throws Exception
public String createInsertValueStr4ModelEntry(Map dbColMap0,Map<String,MicroDbModelEntry> modelEntryMap){ if(dbColMap0==null){ return null; } //add 201902 ning Map dbColMap=new CaseInsensitiveKeyMap(); if(dbColMap0!=null){ dbColMap.putAll(dbColMap0); } Cobj crealValues=Cutil.createCobj(); Map metaFlagMap=new TreeMap(); String tempDbType=calcuDbType(); Iterator it=dbColMap.keySet().iterator(); while(it.hasNext()){ String key=(String) it.next(); MicroDbModelEntry modelEntry=modelEntryMap.get(key); if(modelEntry==null){ continue; } if(CheckModelTypeUtil.isRealCol(modelEntry)==false){ String value=(String) dbColMap.get(key); String metaName=modelEntry.getMetaContentId(); Map metaMap=(Map) metaFlagMap.get(metaName); String realKey=CheckModelTypeUtil.getRealColName(key); if(metaMap==null){ metaMap=new HashMap(); metaFlagMap.put(metaName, metaMap); } if(CheckModelTypeUtil.isNumber(modelEntry)){ if(value.contains(".")){ metaMap.put(realKey, new BigDecimal(value)); }else{ metaMap.put(realKey, Long.valueOf(value)); } }else if(CheckModelTypeUtil.isDate(modelEntry)){ metaMap.put(realKey, value); }else{ metaMap.put(realKey, value); } }else{ //add 20170830 by ninghao Object vobj=dbColMap.get(key); if(vobj instanceof MicroColObj){ String colInfoStr=((MicroColObj)vobj).getColInfo(); crealValues.append(key+"="+colInfoStr); continue; } //end String value=(String) dbColMap.get(key); String whereValue=""; //add 201807 ning if(value!=null && MICRO_DB_NULL.equals(value)){ if(tempDbType!=null && "oracle".equals(tempDbType)){ whereValue="NULL"; }else{ whereValue="null"; }//end }else if(CheckModelTypeUtil.isNumber(modelEntry)){ whereValue=Cutil.rep("<REPLACE>",value); }else if(CheckModelTypeUtil.isDate(modelEntry)){ //add for oracle String temp="str_to_date('<REPLACE>','%Y-%m-%d %H:%i:%s')"; if(tempDbType!=null && "oracle".equals(tempDbType)){ temp="to_date('<REPLACE>','"+ORCL_DATE_FORMAT+"')"; } whereValue=Cutil.rep(temp,value); }else{ whereValue=Cutil.rep("'<REPLACE>'",value); } crealValues.append(whereValue,value!=null); } } String dynamic=null; Iterator iter = metaFlagMap.keySet().iterator(); while(iter.hasNext()){ String key=(String) iter.next(); Map metaMap=(Map) metaFlagMap.get(key); Gson gson=new Gson(); dynamic=gson.toJson(metaMap); crealValues.append(Cutil.rep("'<REPLACE>'",dynamic,dynamic!=null )); } return crealValues.getStr(); }
��װ����value�ַ� @param dbColMap �ύ��� @param modelEntryMap ���ģ�� @return @throws Exception
public String createWhere4Join(Map requestParamMap0,String joinName,String colsStr) throws Exception{ //add 201902 ning Map requestParamMap=new CaseInsensitiveKeyMap(); if(requestParamMap0!=null){ requestParamMap.putAll(requestParamMap0); } String[] colsArray=colsStr.split(","); Map<String,String> colsMap=new HashMap(); for(String colName:colsArray){ String[] asArray=colName.split(" as "); String diffName=asArray[0]; String keyName=diffName; int index=keyName.indexOf("."); keyName=keyName.substring(index); if(asArray.length>1){ keyName=asArray[1]; } colsMap.put(keyName, diffName); } Map modelEntryMap=getModelEntryMap(requestParamMap,joinName,null,dbName,colsStr); Map requestParamMapEx=new HashMap(); Map modelEntryMapEx=new HashMap(); Set<String> keySet=colsMap.keySet(); for(String colKey:keySet){ String diffName=colsMap.get(colKey); requestParamMapEx.put(diffName, requestParamMap.get(colKey)); modelEntryMapEx.put(diffName, modelEntryMap.get(colKey)); } String retStr= createWhereInStr(requestParamMapEx, modelEntryMapEx); return retStr; }
����joinʱ��ǰ׺��where����
private Map getInfoList4PageServiceInnerEx(Map requestParamMap0,String tableName,Map pageMap,String cusWhere,String cusSelect,String modelName,List cusPlaceList) throws Exception{ //add 201807 ning //Map requestParamMap=changeCase4Param(requestParamMap0); //add 201902 ning Map requestParamMap=new CaseInsensitiveKeyMap(); if(requestParamMap0!=null){ requestParamMap.putAll(requestParamMap0); } String page=(String) pageMap.get("page"); String rows=(String) pageMap.get("rows"); String sort=(String) pageMap.get("sort"); String order=(String) pageMap.get("order"); String cusSort=(String) pageMap.get("cusSort"); String tempDbType=calcuDbType(); Integer pageNum=Integer.valueOf(page); Integer rowsNum=Integer.valueOf(rows); if(modelName==null || "".equals(modelName)){ modelName=tableName; } String tempKeyId=calcuIdKey(); String id=(String) requestParamMap.get(tempKeyId); String where=""; if(cusWhere !=null && !"".equals(cusWhere)){ where="where "+cusWhere; } String whereCols=""; Map whereColsMap=requestParamMap; if(whereColsMap!=null && !whereColsMap.isEmpty()){ StringBuilder sb=new StringBuilder(""); Set<String> keySet=whereColsMap.keySet(); int i=0; for(String key:keySet){ if(!key.contains(".")){ continue; } if(key.contains("dbcol_")){ continue; } String colName=key; String realColName=colName.replace(".", CheckModelTypeUtil.DUMMY_SPLIT); String colsStr=colName+" as "+realColName; if(i==0){ sb.append(colsStr); }else{ sb.append(",").append(colsStr); } i++; } whereCols=sb.toString(); } Map modelEntryMap=getModelEntryMap(requestParamMap,tableName,modelName,dbName,whereCols); List placeList=new ArrayList(); String whereInStr=createWhereInStr(requestParamMap,modelEntryMap,placeList); if(whereInStr!=null && !"".equals(whereInStr)){ if(!where.equals("")){ where=where+" and "+whereInStr; }else{ where="where "+whereInStr; } } List realPlaceList=new ArrayList(); //realPlaceList.addAll(placeList); if(cusPlaceList==null){ cusPlaceList=new ArrayList(); } realPlaceList.addAll(cusPlaceList); //add 20170927 realPlaceList.addAll(placeList); String selectCount="select count(1) from "+tableName+" "+where; Integer total=getInnerDao().queryObjJoinCountByCondition(selectCount,realPlaceList.toArray()); String select=""; if(cusSelect!=null && !"".equals(cusSelect)){ select="select "+cusSelect+" from "+tableName+" "+where; }else{ select="select * from "+tableName+" "+where; } String orderSql=""; if(cusSort!=null && !"".equals(cusSort)){ orderSql="order by "+cusSort; }else if(sort!=null && !sort.equals("")){ orderSql="order by "+sort+" "+order; } String sql=select+" "+orderSql; int startNum=getInnerDao().calcuStartIndex(pageNum-1, rowsNum); int endNum=startNum+rowsNum; List infoList=getInnerDao().queryObjJoinDataByPageCondition(sql, startNum, endNum,realPlaceList.toArray()); if(infoList==null){ infoList=new ArrayList(); } CheckModelTypeUtil.addMetaCols(infoList); CheckModelTypeUtil.changeNoStrCols(infoList); Map retMap=new HashMap(); retMap.put("rows", infoList); retMap.put("total", total); return retMap; }
��ҳ��ѯ @param requestParamMap �ύ���� @param tableName ����� @param pageMap ��ҳ���� @param cusWhere ����where�ַ� @param cusSelect ����select�ַ� @param modelName ģ����� @return @throws Exception
public Map getInfoList4PageServiceBySql(String countSql,String sql,Map pageMap) throws Exception{ return getInfoList4PageServiceInnerExBySql(countSql, null, sql, null, pageMap); }
sql
public Map getInfoList4PageServiceByRep(String countSql,String sql, Map paramMap, Map pageMap) throws Exception{ List countPlaceList=new ArrayList(); List placeList=new ArrayList(); String realCountSql=sqlTemplateService(countSql, paramMap, countPlaceList); String realSql=sqlTemplateService(sql, paramMap, placeList); return getInfoList4PageServiceInnerExBySql(realCountSql,countPlaceList,realSql,placeList,pageMap); }
add by ning 20190430
public Map getInfoList4PageServiceByMySqlRep(String sql,Map paramMap, Map pageMap) throws Exception{ List placeList=new ArrayList(); String realSql=sqlTemplateService(sql, paramMap, placeList); return getInfoList4PageServiceInnerExByMySql(realSql, placeList, pageMap); }
add by ning 20190430
public Map getInfoList4PageServiceInner(Map requestParamMap,String tableName,Map pageMap,String cusWhere,String cusSelect,String modelName,List cusPlaceList) throws Exception{ return getInfoList4PageServiceInnerEx(requestParamMap,tableName,pageMap,cusWhere,cusSelect,modelName,cusPlaceList); }
inner
public Integer createInfoServiceInner(Map requestParamMap0,String tableName,String cusCol,String cusValue,String modelName) throws Exception{ //add 201902 ning Map requestParamMap=new CaseInsensitiveKeyMap(); if(requestParamMap0!=null){ requestParamMap.putAll(requestParamMap0); } //add 20170829 ninghao Integer filterViewRet=filterView(tableName,requestParamMap,"","",TYPE_INSERT); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } String tempDbType=calcuDbType(); //add 20170627 ninghao filterParam(tableName,requestParamMap); //add 201807 ning //Map requestParamMap=changeCase4Param(requestParamMap0); boolean autoFlag=false; if(modelName==null || "".equals(modelName)){ modelName=tableName; } String tempKeyId=calcuIdKey(); Map modelEntryMap=getModelEntryMap(requestParamMap,tableName,modelName,dbName); MicroDbModelEntry idEntry=(MicroDbModelEntry) modelEntryMap.get(tempKeyId); String id=(String) requestParamMap.get(tempKeyId); if(id==null || "".equals(id)){ requestParamMap.put(tempKeyId, null); if(idEntry!=null && idEntry.colType.equals(String.class)){ id=UUID.randomUUID().toString(); requestParamMap.put(tempKeyId, id); }else if(idEntry==null){//add 201805 ning support nonid autoFlag=false; }else{ autoFlag=true; } } String cols=createInsertBeforeStr4ModelEntry(requestParamMap,modelEntryMap); List placeList=new ArrayList(); String values=createInsertValueStr4ModelEntry(requestParamMap,modelEntryMap,placeList); String ncols=Cutil.jn(",", cols,cusCol); String nvalues=Cutil.jn(",", values,cusValue); Integer retStatus=0; if(autoFlag==false){ retStatus=getInnerDao().insertObj(tableName, ncols, nvalues,placeList.toArray()); }else{ KeyHolder keyHolder=new GeneratedKeyHolder(); retStatus=getInnerDao().insertObj(tableName, ncols, nvalues,placeList.toArray(),keyHolder,tempKeyId); if(keyHolder!=null){ /* List keyList=keyHolder.getKeyList(); if(keyList!=null && keyList.size()>0){ Map keyMap=(Map) keyList.get(0); Object retId=keyMap.get(defaultId); if(retId!=null){ requestParamMap.put(defaultId, retId.toString()); } }*/ requestParamMap0.put(tempKeyId, keyHolder.getKey().toString()); } } //add 201807 //requestParamMap0.put(calcuDbOutCaseId(), requestParamMap.get(tempKeyId)); return retStatus; }
������ݼ�¼ @param requestParamMap �ύ���� @param tableName ����� @param cusCol �����ֶ��ַ� @param cusValue ����value�ַ� @param modelName ģ����� @return @throws Exception
public Integer updateInfoServiceInner(String id,Map requestParamMap,String tableName,String cusCondition,String cusSetStr,String modelName) throws Exception{ String tempKeyId=calcuIdKey(); //add 20170829 ninghao Integer filterViewRet=filterView(tableName,requestParamMap,id,tempKeyId,TYPE_UPDATE_ID); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } String tempDbType=calcuDbType(); //add 20170627 ninghao filterParam(tableName,requestParamMap); //String id=(String) requestParamMap.get(defaultId); String condition=tempKeyId+"=?"; if(modelName==null || "".equals(modelName)){ modelName=tableName; } Map modelEntryMap=getModelEntryMap(requestParamMap,tableName,modelName,dbName); List placeList=new ArrayList(); //add 201807 ning //Map requestParamMap=changeCase4Param(requestParamMap0); String setStr=createUpdateInStr(requestParamMap,modelEntryMap,placeList); String nCondition=cusCondition; String nSetStr=setStr; //add 201806 ninghao if(condition!=null && !"".equals(condition)){ nCondition=Cutil.jn(" and ", condition,cusCondition); } if(cusSetStr!=null && !"".equals(cusSetStr)){ nSetStr=Cutil.jn(",", setStr,cusSetStr); } placeList.add(id); Integer retStatus=getInnerDao().updateObjByCondition(tableName, nCondition, nSetStr,placeList.toArray()); return retStatus; }
������ݼ�¼ @param requestParamMap �ύ���� @param tableName ����� @param cusCondition ���������ַ� @param cusSetStr ����set�ַ� @param modelName ģ����� @return @throws Exception
private Integer updateInfoServiceInnerBySql(String sql,List placeList) throws Exception{ if(placeList==null){ placeList=new ArrayList(); } String tempDbType=calcuDbType(); Integer retStatus=getInnerDao().updateObjByCondition(sql,placeList.toArray()); return retStatus; }
sql
public Integer updateInfoServiceByRep(String sql,Map paramMap) throws Exception{ List placeList=new ArrayList(); String realSql=sqlTemplateService(sql, paramMap, placeList); return updateInfoServiceInnerBySql(realSql, placeList); }
add by ning 20190430
public Integer updateInfoByIdService(String id,Map requestParamMap,String tableName,String cusCondition,String cusSetStr) throws Exception{ return updateInfoServiceInner(id,requestParamMap,tableName,cusCondition,cusSetStr,null); }
���id������ݼ�¼ @param id �������� @param requestParamMap �ύ���� @param tableName ����� @param cusCondition ���������ַ� @param cusSetStr ����set�ַ� @param modelName ģ����� @return @throws Exception
public Integer updateInfoByBizIdServiceInner(String bizId,String tableName,String bizCol,Map requestParamMap,String cusCondition,String cusSetStr,String modelName) throws Exception{ //add 20170829 ninghao Integer filterViewRet=filterView(tableName,requestParamMap,bizId,bizCol,TYPE_UPDATE_BIZID); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } //add 20170627 ninghao filterParam(tableName,requestParamMap); String tempDbType=calcuDbType(); String condition=Cutil.rep(bizCol+"=?",bizId); if(modelName==null || "".equals(modelName)){ modelName=tableName; } //add 201807 ning //Map requestParamMap=changeCase4Param(requestParamMap0); Map modelEntryMap=getModelEntryMap(requestParamMap,tableName,modelName,dbName); List placeList=new ArrayList(); String setStr=createUpdateInStr(requestParamMap,modelEntryMap,placeList); String nCondition=Cutil.jn(" and ", cusCondition,condition); String nSetStr=Cutil.jn(",", setStr,cusSetStr); placeList.add(bizId); Integer retStatus=getInnerDao().updateObjByCondition(tableName, nCondition, nSetStr,placeList.toArray()); return retStatus; }
���ҵ��id������ݼ�¼ @param bizid ҵ������ @param tableName ����� @param bizCol ҵ������� @param requestParamMap �ύ���� @param cusCondition ���������ַ� @param cusSetStr ����set�ַ� @param modelName ģ����� @return @throws Exception
public Integer delInfoService(Map requestParamMap,String tableName){ String tempKeyId=calcuIdKey(); String id=(String) requestParamMap.get(tempKeyId); //add 20170829 ninghao Integer filterViewRet=filterView(tableName,requestParamMap,id,tempKeyId,TYPE_DEL_ID); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } String tempDbType=calcuDbType(); Integer retStatus=getInnerDao().delObjByBizId(tableName, id, tempKeyId); return retStatus; }
ɾ����ݼ�¼ @param requestParamMap �ύ���� @param tableName ����� @return @throws Exception
public Integer delInfoByIdListService(List<String> idList,String tableName){ int status=0; String tempDbType=calcuDbType(); String tempKeyId=calcuIdKey(); for(String id:idList){ int retStatus=getInnerDao().delObjByBizId(tableName, id, tempKeyId); status=status+retStatus; } return status; }
���id�б�����ɾ��
public Integer delInfoByBizIdService(String bizId,String tableName,String bizCol){ Integer filterViewRet=filterView(tableName,new HashMap(),bizId,bizCol,TYPE_DEL_BIZID); if(filterViewRet!=null && filterViewRet>0){ return filterViewRet; } Integer retStatus=getInnerDao().delObjByBizId(tableName,bizId,bizCol); return retStatus; }
���ҵ��idɾ����ݼ�¼ @param requestParamMap �ύ���� @param tableName ����� @return @throws Exception
public Integer delInfoByBizIdListService(List<String> bizIdList,String tableName,String bizCol){ int status=0; for(String bizId:bizIdList){ int retStatus=getInnerDao().delObjByBizId(tableName,bizId,bizCol); status=status+retStatus; } return status; }
���ҵ��id�б�����ɾ��
public Map getInfoByIdService(Map requestParamMap,String tableName){ String tempKeyId=calcuIdKey(); String id=(String) requestParamMap.get(tempKeyId); //add 20170831 ninghao Map filterViewRet=filterView4Select(tableName,requestParamMap,id,tempKeyId,TYPE_SELECT_ID); if(filterViewRet!=null ){ return filterViewRet; } Map retMap=getInnerDao().queryObjJoinByBizId(tableName, id, tempKeyId); if(retMap==null){ return null; } CheckModelTypeUtil.addMetaCols(retMap); CheckModelTypeUtil.changeNoStrCols(retMap); return retMap; }
���id��ȡ��ݼ�¼ @param requestParamMap �ύ���� @param tableName ����� @return @throws Exception
public Map getInfoByBizIdService(String bizId,String tableName,String bizCol){ //add 20170831 ninghao Map filterViewRet=filterView4Select(tableName,new HashMap(),bizId,bizCol,TYPE_SELECT_BIZID); if(filterViewRet!=null ){ return filterViewRet; } Map retMap=getInnerDao().queryObjJoinByBizId(tableName, bizId,bizCol); if(retMap==null){ return null; } CheckModelTypeUtil.addMetaCols(retMap); CheckModelTypeUtil.changeNoStrCols(retMap); return retMap; }
���ҵ��id��ȡ��ݼ�¼ @param bizId ҵ��id @param tableName ����� @param bizCol ҵ������� @return @throws Exception
private List getInfoListAllServiceInnerEx(Map requestParamMap,String tableName,Map sortMap,String cusWhere,String cusSelect,String modelName,int limit,List cusPlaceList) throws Exception{ String tempKeyId=calcuIdKey(); String sort=(String) sortMap.get("sort"); String order=(String) sortMap.get("order"); String cusSort=(String) sortMap.get("cusSort"); if(modelName==null || "".equals(modelName)){ modelName=tableName; } //add 201807 ning //Map requestParamMap=changeCase4Param(requestParamMap0); String id=(String) requestParamMap.get(tempKeyId); String where=""; if(cusWhere !=null && !"".equals(cusWhere)){ where="where "+cusWhere; } if(modelName==null || "".equals(modelName)){ modelName=tableName; } String whereCols=""; Map whereColsMap=requestParamMap; if(whereColsMap!=null && !whereColsMap.isEmpty()){ StringBuilder sb=new StringBuilder(""); Set<String> keySet=whereColsMap.keySet(); int i=0; for(String key:keySet){ if(!key.contains(".")){ continue; } if(key.contains("dbcol_")){ continue; } String colName=key; String realColName=colName.replace(".", CheckModelTypeUtil.DUMMY_SPLIT); String colsStr=colName+" as "+realColName; if(i==0){ sb.append(colsStr); }else{ sb.append(",").append(colsStr); } i++; } whereCols=sb.toString(); } Map modelEntryMap=getModelEntryMap(requestParamMap,tableName,modelName,dbName,whereCols); List placeList=new ArrayList(); String whereInStr=createWhereInStr(requestParamMap,modelEntryMap,placeList); if(cusPlaceList==null){ cusPlaceList=new ArrayList(); } List realPlaceList=new ArrayList(); realPlaceList.addAll(placeList); realPlaceList.addAll(cusPlaceList); if(whereInStr!=null && !"".equals(whereInStr)){ if(!where.equals("")){ where=where+" and "+whereInStr; }else{ where="where "+whereInStr; } } String select=""; if(cusSelect!=null && !"".equals(cusSelect)){ select="select "+cusSelect+" from "+tableName+" "+where; }else{ select="select * from "+tableName+" "+where; } //String orderSql="order by "; String orderSql=""; if(cusSort!=null && !"".equals(cusSort)){ orderSql="order by "+cusSort; }else if(sort!=null && !sort.equals("")){ orderSql="order by "+sort+" "+order; } /* String orderSql=""; if(sort!=null && !sort.equals("")){ orderSql="order by "+sort+" "+order; }*/ /* else{ orderSql=orderSql+"id desc"; }*/ List infoList=null; String sql=select+" "+orderSql; if(limit>=0){ infoList=getInnerDao().queryLimitObjJoinByCondition(sql,realPlaceList.toArray(),limit); }else{ infoList=getInnerDao().queryObjJoinByCondition(sql,realPlaceList.toArray()); } if(infoList==null){ return null; } CheckModelTypeUtil.addMetaCols(infoList); //CheckModelTypeUtil.changeDateCols(infoList); CheckModelTypeUtil.changeNoStrCols(infoList); return infoList; }
��ȡ�Ƿ�ҳ��ݼ�¼ @param bizId ҵ��id @param tableName ����� @param bizCol ҵ������� @return @throws Exception
public List getInfoListAllServiceByReq(String sql,Map paramMap) throws Exception{ List placeList=new ArrayList(); String realSql=sqlTemplateService(sql,paramMap,placeList); return getInfoListAllServiceInnerExBySql(realSql, placeList); }
add by ning 20190430
public Map getSingleInfoService(Map requestParamMap,String tableName,Map sortMap) throws Exception{ List retList= getInfoListAllServiceInner(requestParamMap,tableName,sortMap,"","","",1); if(retList==null || retList.size()<=0){ return null; } return (Map) retList.get(0); }
single
public Map getSingleInfoServiceByRep(String sql,Map requestParamMap) throws Exception{ List placeList=new ArrayList(); sqlTemplateService(sql,requestParamMap,placeList); String realSql=sqlTemplateService(sql,requestParamMap,placeList);; Map retMap= getInnerDao().querySingleObjJoinByCondition(realSql,placeList.toArray()); CheckModelTypeUtil.addMetaCols(retMap); CheckModelTypeUtil.changeNoStrCols(retMap); return retMap; }
add 20190430 by ning
public Map getSingleInfoService(String sql) throws Exception{ /* String realSql=sql+" limit 1"; List retList= getInfoListAllServiceInnerExBySql(realSql, null); if(retList==null || retList.size()<=0){ return null; } return (Map) retList.get(0);*/ //for oracle String realSql=sql; Map retMap= getInnerDao().querySingleObjJoinByCondition(realSql); CheckModelTypeUtil.addMetaCols(retMap); CheckModelTypeUtil.changeNoStrCols(retMap); return retMap; }
sql
public Integer getSeqByMysql(String seqKey){ PlatformTransactionManager transactionManager=MicroTranManagerHolder.getTransactionManager(dbName); DefaultTransactionDefinition def =new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus status=transactionManager.getTransaction(def); try { String sql="select get_micro_seq('"+seqKey+"') as seq"; List retList=getInnerDao().queryObjJoinByCondition(sql); if(retList==null){ transactionManager.commit(status); return null; } Map retMap=(Map) retList.get(0); Integer seq=(Integer) retMap.get("seq"); transactionManager.commit(status); return seq; } catch(Exception ex) { transactionManager.rollback(status); throw new RuntimeException("getseq error",ex); } }
/* public void dbTranNestRollbackAndReStart() throws Exception{ PlatformTransactionManager transactionManager=MicroTranManagerHolder.getTransactionManager(dbName); DefaultTransactionDefinition def =new DefaultTransactionDefinition(); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status=transactionManager.getTransaction(def); transactionManager.rollback(status); ((AbstractPlatformTransactionManager) transactionManager).setFailEarlyOnGlobalRollbackOnly(false); }
public String getNodeData(String nodePath,String formId,String tableName,String dataColName,String idColName){ MicroMetaDao microDao=getInnerDao(); String select=dataColName+"->>'$."+dianNode(nodePath)+"' as dyna_data"; String sql="select "+select+" from "+tableName+" where "+idColName+"=?"; Object[] paramArray=new Object[1]; paramArray[0]=formId; Map retMap=microDao.querySingleObjJoinByCondition(sql,paramArray); //返回的一定是个map if(retMap!=null){ return (String) retMap.get("dyna_data"); } return null; }
页面获取指定节点数据(data)
public void putNodeData(String paramData,String nodePath,String formId,String tableName,String dataColName,String idColName,String dataType){ checkAndCreateNodePathService(nodePath,formId,tableName,dataColName,idColName); String sql="update "+tableName+" set "+dataColName+"=JSON_SET("+dataColName+",?,"; String filter="$."+dianNode(nodePath); List placeList=new ArrayList(); placeList.add(filter); if(dataType==null || "".equals(dataType) || "string".equalsIgnoreCase(dataType)){ sql=sql+"?) where "+idColName+"=?"; placeList.add(paramData); placeList.add(formId); }else if("json".equals(dataType)){ sql=sql+"convert(?,JSON)) where "+idColName+"=?"; placeList.add(paramData); placeList.add(formId); }else{ sql=sql+paramData+") where "+idColName+"=?"; placeList.add(formId); } MicroMetaDao microDao=getInnerDao(); microDao.updateObjByCondition(sql, placeList.toArray()); return ; }
设置指定位置数据(data)
public Map getMapByIdService4text(String id, String tableName, String colName){ Map data=getInfoByIdService(id,tableName); if(data==null){ return null; } String dataStr=(String) data.get(colName); if(dataStr==null || "".equals(dataStr)){ dataStr="{}"; } Gson gson = new Gson(); Map dataMap=gson.fromJson(dataStr,Map.class); return dataMap; }
20180605 ning
public static Object getCurDataByFull4text(Map dataMap,String dept_fullpath){ String[] paths=dept_fullpath.split("/"); int size=paths.length; String dept_id=""; if(size>0){ dept_id=paths[size-1]; } String dept_path=""; int dept_id_size=dept_id.length(); dept_path=(String) dept_fullpath.subSequence(0, dept_fullpath.length()-dept_id_size); Object deptData=null; Map parentMap=(Map) getParentObjByPath4text(dataMap,dept_path); if(parentMap!=null){ int haveIndex=dept_id.indexOf("["); if(haveIndex<=0){ deptData=parentMap.get(dept_id); }else{ String real_id=dept_id.substring(0,haveIndex); int lastIndex=dept_id.indexOf("]"); String real_index=dept_id.substring(haveIndex+1,lastIndex); Integer index_i=Integer.valueOf(real_index); List tempList=(List) parentMap.get(real_id); deptData=tempList.get(index_i); } } return deptData; }
根据fullpath获取指定位置数据(data)
private static Object getParentObjByPath4text(Map dataMap,String dept_path){ String[] pathNode=dept_path.split("/"); int size=pathNode.length; if(size<0){ return dataMap; } Object subObj=null; Map rowObj=dataMap; if(dept_path.equals("")){ return dataMap; } for(int i=0;i<size;i++){ String key=pathNode[i]; if(key.contains("[")){ int start=key.indexOf("["); int end=key.indexOf("]"); String realKey=key.substring(0,start); String temp=key.substring(start+1, end); int index=0; if(temp!=null && !"".equals(temp)){ index=Integer.valueOf(temp); } List tempList=(List) rowObj.get(realKey); if(tempList==null){ tempList=new ArrayList(); rowObj.put(realKey, tempList); } int lsize=tempList.size(); while(lsize<index+1){ tempList.add(new HashMap()); lsize=tempList.size(); } subObj=tempList.get(index); }else{ subObj=rowObj.get(key); if(subObj==null){ subObj=new HashMap(); rowObj.put(key, subObj); } } if(i+1<size){ rowObj=(Map) subObj; } } return subObj; }
根据path获取指定位置数据(data)
public static int setCurDataByFull4text(Map dataMap,String dept_fullpath,Object paramObj){ String[] paths=dept_fullpath.split("/"); int size=paths.length; String dept_id=""; if(size>0){ dept_id=paths[size-1]; } String dept_path=""; int dept_id_size=dept_id.length(); dept_path=(String) dept_fullpath.subSequence(0, dept_fullpath.length()-dept_id_size); Map pMap=(Map) getParentObjByPath4text(dataMap,dept_path); int index=getDeptIdIndex(dept_id); if(index<0){ pMap.put(dept_id,paramObj); }else{ String realDeptId=getRealDeptId(dept_id); List tempList=(List) pMap.get(realDeptId); Map tempMap=(Map) getDataFromList(tempList,index); tempList.set(index, paramObj); } return 1; }
根据fullpath设置指定位置数据(data)
public static int appendParentMap4text(String dept_fullpath,Map dataMap,Map paramObj){ String[] paths=dept_fullpath.split("/"); int size=paths.length; String dept_id=""; if(size>0){ dept_id=paths[size-1]; } String dept_path=""; int dept_id_size=dept_id.length(); dept_path=(String) dept_fullpath.subSequence(0, dept_fullpath.length()-dept_id_size); Map pMap=(Map) getParentObjByPath4text(dataMap,dept_path); List targetList=(List) pMap.get(dept_id); if(targetList==null){ targetList=new ArrayList(); pMap.put(dept_id, targetList); } targetList.add(paramObj); return 1; }
设置指定位置数据(data)
private static Object getDataFromList(List dataList,int index){ int size=dataList.size(); while(size<index+1){ dataList.add(new HashMap()); size=dataList.size(); } Object retObj=dataList.get(index); return retObj; }
获取index值时自动填充之前值
private static String getRealDeptId(String deptId){ int start=deptId.indexOf("["); String realKey=deptId; if(start>0){ realKey=deptId.substring(0,start); } return realKey; }
获取非index的路径
private static int getDeptIdIndex(String deptId){ int start=deptId.indexOf("["); if(start<=0){ return -1; } int end=deptId.indexOf("]"); String temp=deptId.substring(start+1, end); int index=0; if(temp!=null && !"".equals(temp)){ index=Integer.valueOf(temp); } return index; }
获取最后的index
@SuppressWarnings("unchecked") @Override public Boolean execute() { try { SmartFoxServer.getInstance() .getAPIManager() .getBuddyApi() .initBuddyList(CommandUtil.getSfsUser(username, api), fireServerEvent); } catch (IOException e) { throw new IllegalStateException(e); } return Boolean.TRUE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
@Override public void backward() { Tensor x = modInX.getOutput(); Tensor w = modInW.getOutput(); { Tensor tmp = new Tensor(yAdj); // copy tmp.elemDivide(w); correctForZeros(tmp); modInX.getOutputAdj().elemAdd(tmp); } { Tensor tmp = new Tensor(w); // copy tmp.fill(s.one()); tmp.elemDivide(w); tmp.elemDivide(w); tmp.multiply(s.fromReal(-1)); tmp.elemMultiply(yAdj); tmp.elemMultiply(x); correctForZeros(tmp); modInW.getOutputAdj().elemAdd(tmp); } }
Backward pass: dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i / w_i dG/dw_i += dG/dy_i dy_i/dw_i = dG/dy_i * x_i / (- w_i^2)
@Override public List<ApiZone> all() { List<ApiZone> answer = new ArrayList<>(); for(Zone zone : SmartFoxServer.getInstance() .getZoneManager().getZoneList()) { answer.add((ApiZone) zone.getProperty(APIKey.ZONE)); } return answer; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.FindZone#all()
@Override public ApiZone find(int id) { Zone zone = SmartFoxServer.getInstance() .getZoneManager() .getZoneById(id); if(zone != null && zone.containsProperty(APIKey.ZONE)) return (ApiZone) zone.getProperty(APIKey.ZONE); return null; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.FindZone#find(int)
@Override public ApiZone find(String name) { Zone zone = SmartFoxServer.getInstance() .getZoneManager() .getZoneByName(name); if(zone != null && zone.containsProperty(APIKey.ZONE)) return (ApiZone) zone.getProperty(APIKey.ZONE); return null; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.FindZone#find(java.lang.String)
private void getLogOddsRatios(VarTensor[] inMsgs, double[][] spanWeights) { Algebra s = inMsgs[0].getAlgebra(); // Compute the odds ratios of the messages for each edge in the tree. DoubleArrays.fill(spanWeights, Double.NEGATIVE_INFINITY); for (VarTensor inMsg : inMsgs) { SpanVar span = (SpanVar) inMsg.getVars().get(0); double oddsRatio = s.toLogProb(inMsg.getValue(SpanVar.TRUE)) - s.toLogProb(inMsg.getValue(SpanVar.FALSE)); spanWeights[span.getStart()][span.getEnd()] = oddsRatio; } checkSpanWeights(spanWeights); }
Computes the log odds ratio for each edge. w_{ij} = \mu_{ij}(1) / \mu_{ij}(0)
private double getProductOfAllFalseMessages(VarTensor[] inMsgs) { // Precompute the product of all the "false" messages. // pi = \prod_i \mu_i(0) // Here we store log pi. Algebra s = inMsgs[0].getAlgebra(); double logPi = 0.0; for (VarTensor inMsg : inMsgs) { logPi += s.toLogProb(inMsg.getValue(SpanVar.FALSE)); } return logPi; }
Computes pi = \prod_i \mu_i(0).
private void setOutMsgs(VarTensor outMsg, SpanVar span, double outMsgTrue, double outMsgFalse) { // Set the outgoing messages. Algebra s = outMsg.getAlgebra(); outMsg.setValue(SpanVar.FALSE, s.fromLogProb(outMsgFalse)); outMsg.setValue(SpanVar.TRUE, s.fromLogProb(outMsgTrue)); if (log.isTraceEnabled()) { log.trace(String.format("outMsgTrue: %s = %.2f", span.getName(), outMsg.getValue(LinkVar.TRUE))); log.trace(String.format("outMsgFalse: %s = %.2f", span.getName(), outMsg.getValue(LinkVar.FALSE))); } assert !outMsg.containsBadValues() : "message = " + outMsg; }
Sets the outgoing messages.
private static boolean[][] getChart(int n, VarConfig vc) { boolean[][] chart = new boolean[n][n+1]; int count = 0; for (Var v : vc.getVars()) { SpanVar span = (SpanVar) v; chart[span.getStart()][span.getEnd()] = (vc.getState(span) == SpanVar.TRUE); count++; } if (count != (n*(n+1)/2)) { // We didn't see a span variable for every chart cell. return null; } return chart; }
Creates a boolean chart representing the set of spans which are "on", or null if the number of span variables in the assignment is invalid.
private static boolean isTree(int n, boolean[][] chart) { if (!chart[0][n]) { // Root must be a span. return false; } for (int width = 1; width <= n; width++) { for (int start = 0; start <= n - width; start++) { int end = start + width; if (width == 1) { if (!chart[start][end]) { // All width 1 spans must be set. return false; } } else { if (chart[start][end]) { // Count the number of pairs of child spans which could have been combined to form this span. int childPairCount = 0; for (int mid = start + 1; mid <= end - 1; mid++) { if (chart[start][mid] && chart[mid][end]) { childPairCount++; } } if (childPairCount != 1) { // This span should have been built from exactly one pair of child spans. return false; } } } } } return true; }
Returns true if the boolean chart represents a set of spans that form a valid constituency tree, false otherwise.
public static int murmurhash3_x86_32(CharSequence data, int offset, int len, int seed) { final int c1 = 0xcc9e2d51; final int c2 = 0x1b873593; int h1 = seed; int pos = offset; int end = offset + len; int k1 = 0; int k2 = 0; int shift = 0; int bits = 0; int nBytes = 0; // length in UTF8 bytes while (pos < end) { int code = data.charAt(pos++); if (code < 0x80) { k2 = code; bits = 8; /*** // optimized ascii implementation (currently slower!!! code size?) if (shift == 24) { k1 = k1 | (code << 24); k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13); h1 = h1*5+0xe6546b64; shift = 0; nBytes += 4; k1 = 0; } else { k1 |= code << shift; shift += 8; } continue; ***/ } else if (code < 0x800) { k2 = (0xC0 | (code >> 6)) | ((0x80 | (code & 0x3F)) << 8); bits = 16; } else if (code < 0xD800 || code > 0xDFFF || pos>=end) { // we check for pos>=end to encode an unpaired surrogate as 3 bytes. k2 = (0xE0 | (code >> 12)) | ((0x80 | ((code >> 6) & 0x3F)) << 8) | ((0x80 | (code & 0x3F)) << 16); bits = 24; } else { // surrogate pair // int utf32 = pos < end ? (int) data.charAt(pos++) : 0; int utf32 = (int) data.charAt(pos++); utf32 = ((code - 0xD7C0) << 10) + (utf32 & 0x3FF); k2 = (0xff & (0xF0 | (utf32 >> 18))) | ((0x80 | ((utf32 >> 12) & 0x3F))) << 8 | ((0x80 | ((utf32 >> 6) & 0x3F))) << 16 | (0x80 | (utf32 & 0x3F)) << 24; bits = 32; } k1 |= k2 << shift; // int used_bits = 32 - shift; // how many bits of k2 were used in k1. // int unused_bits = bits - used_bits; // (bits-(32-shift)) == bits+shift-32 == bits-newshift shift += bits; if (shift >= 32) { // mix after we have a complete word k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); // ROTL32(h1,13); h1 = h1*5+0xe6546b64; shift -= 32; // unfortunately, java won't let you shift 32 bits off, so we need to check for 0 if (shift != 0) { k1 = k2 >>> (bits-shift); // bits used == bits - newshift } else { k1 = 0; } nBytes += 4; } } // inner // handle tail if (shift > 0) { nBytes += shift >> 3; k1 *= c1; k1 = (k1 << 15) | (k1 >>> 17); // ROTL32(k1,15); k1 *= c2; h1 ^= k1; } // finalization h1 ^= nBytes; // fmix(h1); h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return h1; }
Returns the MurmurHash3_x86_32 hash of the UTF-8 bytes of the String without actually encoding the string to a temporary buffer. This is more than 2x faster than hashing the result of String.getBytes().
public MicroMetaBean getMetaBeanById(String tableName, String id) { /* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder .getDbSource(dbName);*/ JdbcTemplate jdbcTemplate = getMicroJdbcTemplate(); String sql = "select * from " + tableName + " where id=?"; logger.debug(sql); logger.debug("["+id+"]"); Map retMap = jdbcTemplate.queryForMap(sql, id); MicroMetaBean metaBean = new MicroMetaBean(); metaBean.setId((String) retMap.get("id")); metaBean.setMeta_content((String) retMap.get("meta_content")); metaBean.setMeta_key((String) retMap.get("meta_key")); metaBean.setMeta_name((String) retMap.get("meta_name")); metaBean.setMeta_type((String) retMap.get("meta_type")); metaBean.setRemark((String) retMap.get("remark")); metaBean.setCreate_time((Date) retMap.get("create_time")); metaBean.setUpdate_time((Date) retMap.get("update_time")); return metaBean; }
/* 锟斤拷锟絠d锟斤拷询锟斤拷准锟斤拷锟絙ean