Example usage for java.math MathContext DECIMAL128

List of usage examples for java.math MathContext DECIMAL128

Introduction

In this page you can find the example usage for java.math MathContext DECIMAL128.

Prototype

MathContext DECIMAL128

To view the source code for java.math MathContext DECIMAL128.

Click Source Link

Document

A MathContext object with a precision setting matching the IEEE 754R Decimal128 format, 34 digits, and a rounding mode of RoundingMode#HALF_EVEN HALF_EVEN , the IEEE 754R default.

Usage

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatImportHelper.java

private Object convertStringTypes(Object val, HCatFieldSchema hfs) {
    HCatFieldSchema.Type hfsType = hfs.getType();
    if (hfsType == HCatFieldSchema.Type.STRING || hfsType == HCatFieldSchema.Type.VARCHAR
            || hfsType == HCatFieldSchema.Type.CHAR) {
        String str = val.toString();
        if (doHiveDelimsReplacement) {
            str = FieldFormatter.hiveStringReplaceDelims(str, hiveDelimsReplacement, hiveDelimiters);
        }//from w  w w. j  a  v a2s .co  m
        if (hfsType == HCatFieldSchema.Type.STRING) {
            return str;
        } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
            HiveVarchar hvc = new HiveVarchar(str, vti.getLength());
            return hvc;
        } else if (hfsType == HCatFieldSchema.Type.CHAR) {
            CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
            HiveChar hc = new HiveChar(val.toString(), cti.getLength());
            return hc;
        }
    } else if (hfsType == HCatFieldSchema.Type.DECIMAL) {
        BigDecimal bd = new BigDecimal(val.toString(), MathContext.DECIMAL128);
        HiveDecimal hd = HiveDecimal.create(bd);
        return hd;
    }
    return null;
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatImportHelper.java

private Object convertNumberTypes(Object val, HCatFieldSchema hfs) {
    HCatFieldSchema.Type hfsType = hfs.getType();

    if (!(val instanceof Number)) {
        return null;
    }//from  ww  w. j  a  va2s.  com
    if (val instanceof BigDecimal && hfsType == HCatFieldSchema.Type.STRING
            || hfsType == HCatFieldSchema.Type.VARCHAR || hfsType == HCatFieldSchema.Type.CHAR) {
        BigDecimal bd = (BigDecimal) val;
        String bdStr = null;
        if (bigDecimalFormatString) {
            bdStr = bd.toPlainString();
        } else {
            bdStr = bd.toString();
        }
        if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
            HiveVarchar hvc = new HiveVarchar(bdStr, vti.getLength());
            return hvc;
        } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
            HiveChar hChar = new HiveChar(bdStr, cti.getLength());
            return hChar;
        } else {
            return bdStr;
        }
    }
    Number n = (Number) val;
    if (hfsType == HCatFieldSchema.Type.TINYINT) {
        return n.byteValue();
    } else if (hfsType == HCatFieldSchema.Type.SMALLINT) {
        return n.shortValue();
    } else if (hfsType == HCatFieldSchema.Type.INT) {
        return n.intValue();
    } else if (hfsType == HCatFieldSchema.Type.BIGINT) {
        return n.longValue();
    } else if (hfsType == HCatFieldSchema.Type.FLOAT) {
        return n.floatValue();
    } else if (hfsType == HCatFieldSchema.Type.DOUBLE) {
        return n.doubleValue();
    } else if (hfsType == HCatFieldSchema.Type.BOOLEAN) {
        return n.byteValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
    } else if (hfsType == HCatFieldSchema.Type.STRING) {
        return n.toString();
    } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
        VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
        HiveVarchar hvc = new HiveVarchar(val.toString(), vti.getLength());
        return hvc;
    } else if (hfsType == HCatFieldSchema.Type.CHAR) {
        CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
        HiveChar hChar = new HiveChar(val.toString(), cti.getLength());
        return hChar;
    } else if (hfsType == HCatFieldSchema.Type.DECIMAL) {
        BigDecimal bd = new BigDecimal(n.doubleValue(), MathContext.DECIMAL128);
        return HiveDecimal.create(bd);
    }
    return null;
}

From source file:org.ballerinalang.bre.bvm.BVM.java

/**
 * This is to be used to continue the execution of a strand when a non blocking call continues.
 *
 * @param strand to be executed//from  ww  w  .j  a v  a  2 s  .c o m
 */
static void execute(Strand strand) {
    int i, j, k, l;
    int cpIndex;
    FunctionCallCPEntry funcCallCPEntry;
    FunctionRefCPEntry funcRefCPEntry;
    TypeRefCPEntry typeRefCPEntry;
    FunctionInfo functionInfo;
    InstructionCALL callIns;

    boolean debugEnabled = strand.programFile.getDebugger().isDebugEnabled();

    int callersRetRegIndex;

    StackFrame sf = strand.currentFrame;

    while (sf.ip >= 0) {
        if (strand.aborted) {
            handleFutureTermination(strand);
            return;
        }
        if (debugEnabled && debug(strand)) {
            return;
        }

        Instruction instruction = sf.code[sf.ip];
        int opcode = instruction.getOpcode();
        int[] operands = instruction.getOperands();
        sf.ip++;

        switch (opcode) {
        case InstructionCodes.ICONST:
            cpIndex = operands[0];
            i = operands[1];
            sf.longRegs[i] = ((IntegerCPEntry) sf.constPool[cpIndex]).getValue();
            break;
        case InstructionCodes.FCONST:
            cpIndex = operands[0];
            i = operands[1];
            sf.doubleRegs[i] = ((FloatCPEntry) sf.constPool[cpIndex]).getValue();
            break;
        case InstructionCodes.DCONST:
            cpIndex = operands[0];
            i = operands[1];
            String decimalVal = ((UTF8CPEntry) sf.constPool[cpIndex]).getValue();
            sf.refRegs[i] = new BDecimal(new BigDecimal(decimalVal, MathContext.DECIMAL128));
            break;
        case InstructionCodes.SCONST:
            cpIndex = operands[0];
            i = operands[1];
            sf.stringRegs[i] = ((StringCPEntry) sf.constPool[cpIndex]).getValue();
            break;
        case InstructionCodes.ICONST_0:
            i = operands[0];
            sf.longRegs[i] = 0;
            break;
        case InstructionCodes.ICONST_1:
            i = operands[0];
            sf.longRegs[i] = 1;
            break;
        case InstructionCodes.ICONST_2:
            i = operands[0];
            sf.longRegs[i] = 2;
            break;
        case InstructionCodes.ICONST_3:
            i = operands[0];
            sf.longRegs[i] = 3;
            break;
        case InstructionCodes.ICONST_4:
            i = operands[0];
            sf.longRegs[i] = 4;
            break;
        case InstructionCodes.ICONST_5:
            i = operands[0];
            sf.longRegs[i] = 5;
            break;
        case InstructionCodes.FCONST_0:
            i = operands[0];
            sf.doubleRegs[i] = 0;
            break;
        case InstructionCodes.FCONST_1:
            i = operands[0];
            sf.doubleRegs[i] = 1;
            break;
        case InstructionCodes.FCONST_2:
            i = operands[0];
            sf.doubleRegs[i] = 2;
            break;
        case InstructionCodes.FCONST_3:
            i = operands[0];
            sf.doubleRegs[i] = 3;
            break;
        case InstructionCodes.FCONST_4:
            i = operands[0];
            sf.doubleRegs[i] = 4;
            break;
        case InstructionCodes.FCONST_5:
            i = operands[0];
            sf.doubleRegs[i] = 5;
            break;
        case InstructionCodes.BCONST_0:
            i = operands[0];
            sf.intRegs[i] = 0;
            break;
        case InstructionCodes.BCONST_1:
            i = operands[0];
            sf.intRegs[i] = 1;
            break;
        case InstructionCodes.RCONST_NULL:
            i = operands[0];
            sf.refRegs[i] = null;
            break;
        case InstructionCodes.BACONST:
            cpIndex = operands[0];
            i = operands[1];
            sf.refRegs[i] = new BValueArray(((BlobCPEntry) sf.constPool[cpIndex]).getValue());
            break;

        case InstructionCodes.IMOVE:
        case InstructionCodes.FMOVE:
        case InstructionCodes.SMOVE:
        case InstructionCodes.BMOVE:
        case InstructionCodes.RMOVE:
        case InstructionCodes.IALOAD:
        case InstructionCodes.BIALOAD:
        case InstructionCodes.FALOAD:
        case InstructionCodes.SALOAD:
        case InstructionCodes.BALOAD:
        case InstructionCodes.RALOAD:
        case InstructionCodes.JSONALOAD:
        case InstructionCodes.IGLOAD:
        case InstructionCodes.FGLOAD:
        case InstructionCodes.SGLOAD:
        case InstructionCodes.BGLOAD:
        case InstructionCodes.RGLOAD:
        case InstructionCodes.MAPLOAD:
        case InstructionCodes.JSONLOAD:
            execLoadOpcodes(strand, sf, opcode, operands);
            break;

        case InstructionCodes.IASTORE:
        case InstructionCodes.BIASTORE:
        case InstructionCodes.FASTORE:
        case InstructionCodes.SASTORE:
        case InstructionCodes.BASTORE:
        case InstructionCodes.RASTORE:
        case InstructionCodes.JSONASTORE:
        case InstructionCodes.IGSTORE:
        case InstructionCodes.FGSTORE:
        case InstructionCodes.SGSTORE:
        case InstructionCodes.BGSTORE:
        case InstructionCodes.RGSTORE:
        case InstructionCodes.MAPSTORE:
        case InstructionCodes.JSONSTORE:
            execStoreOpcodes(strand, sf, opcode, operands);
            break;

        case InstructionCodes.IADD:
        case InstructionCodes.FADD:
        case InstructionCodes.SADD:
        case InstructionCodes.DADD:
        case InstructionCodes.XMLADD:
        case InstructionCodes.ISUB:
        case InstructionCodes.FSUB:
        case InstructionCodes.DSUB:
        case InstructionCodes.IMUL:
        case InstructionCodes.FMUL:
        case InstructionCodes.DMUL:
        case InstructionCodes.IDIV:
        case InstructionCodes.FDIV:
        case InstructionCodes.DDIV:
        case InstructionCodes.IMOD:
        case InstructionCodes.FMOD:
        case InstructionCodes.DMOD:
        case InstructionCodes.INEG:
        case InstructionCodes.FNEG:
        case InstructionCodes.DNEG:
        case InstructionCodes.BNOT:
        case InstructionCodes.IEQ:
        case InstructionCodes.FEQ:
        case InstructionCodes.SEQ:
        case InstructionCodes.BEQ:
        case InstructionCodes.DEQ:
        case InstructionCodes.REQ:
        case InstructionCodes.REF_EQ:
        case InstructionCodes.TEQ:
        case InstructionCodes.INE:
        case InstructionCodes.FNE:
        case InstructionCodes.SNE:
        case InstructionCodes.BNE:
        case InstructionCodes.DNE:
        case InstructionCodes.RNE:
        case InstructionCodes.REF_NEQ:
        case InstructionCodes.TNE:
        case InstructionCodes.IAND:
        case InstructionCodes.IOR:
        case InstructionCodes.IXOR:
        case InstructionCodes.BILSHIFT:
        case InstructionCodes.BIRSHIFT:
        case InstructionCodes.IRSHIFT:
        case InstructionCodes.ILSHIFT:
        case InstructionCodes.IURSHIFT:
        case InstructionCodes.TYPE_TEST:
        case InstructionCodes.IS_LIKE:
            execBinaryOpCodes(strand, sf, opcode, operands);
            break;
        case InstructionCodes.TYPELOAD:
            cpIndex = operands[0];
            j = operands[1];
            TypeRefCPEntry typeEntry = (TypeRefCPEntry) sf.constPool[cpIndex];
            sf.refRegs[j] = new BTypeDescValue(typeEntry.getType());
            break;
        case InstructionCodes.HALT:
            if (strand.fp > 0) {
                // Stop the observation context before popping the stack frame
                ObserveUtils.stopCallableObservation(strand);
                strand.popFrame();
                break;
            }
            sf.ip = -1;
            strand.respCallback.signal();
            break;
        case InstructionCodes.IGT:
        case InstructionCodes.FGT:
        case InstructionCodes.DGT:
        case InstructionCodes.IGE:
        case InstructionCodes.FGE:
        case InstructionCodes.DGE:
        case InstructionCodes.ILT:
        case InstructionCodes.FLT:
        case InstructionCodes.DLT:
        case InstructionCodes.ILE:
        case InstructionCodes.FLE:
        case InstructionCodes.DLE:
        case InstructionCodes.REQ_NULL:
        case InstructionCodes.RNE_NULL:
        case InstructionCodes.BR_TRUE:
        case InstructionCodes.BR_FALSE:
        case InstructionCodes.GOTO:
            execCmpAndBranchOpcodes(strand, sf, opcode, operands);
            break;
        case InstructionCodes.INT_RANGE:
            execIntegerRangeOpcodes(sf, operands);
            break;
        case InstructionCodes.TR_RETRY:
            InstructionTrRetry trRetry = (InstructionTrRetry) instruction;
            retryTransaction(strand, trRetry.blockId, trRetry.abortEndIp, trRetry.trStatusReg);
            break;
        case InstructionCodes.CALL:
            callIns = (InstructionCALL) instruction;
            strand = invokeCallable(strand, callIns.functionInfo, callIns.argRegs, callIns.retRegs[0],
                    callIns.flags);
            if (strand == null) {
                return;
            }
            break;
        case InstructionCodes.VCALL:
            InstructionVCALL vcallIns = (InstructionVCALL) instruction;
            strand = invokeVirtualFunction(strand, sf, vcallIns.receiverRegIndex, vcallIns.functionInfo,
                    vcallIns.argRegs, vcallIns.retRegs[0], vcallIns.flags);
            if (strand == null) {
                return;
            }
            break;
        case InstructionCodes.TR_BEGIN:
            InstructionTrBegin trBegin = (InstructionTrBegin) instruction;
            beginTransaction(strand, trBegin.transactionType, trBegin.blockId, trBegin.retryCountReg,
                    trBegin.committedFuncIndex, trBegin.abortedFuncIndex);
            break;
        case InstructionCodes.TR_END:
            InstructionTrEnd trEnd = (InstructionTrEnd) instruction;
            endTransaction(strand, trEnd.blockId, trEnd.endType, trEnd.statusRegIndex, trEnd.errorRegIndex);
            break;
        case InstructionCodes.WRKSEND:
            InstructionWRKSendReceive wrkSendIns = (InstructionWRKSendReceive) instruction;
            handleWorkerSend(strand, wrkSendIns.dataChannelInfo, wrkSendIns.type, wrkSendIns.reg,
                    wrkSendIns.channelInSameStrand);
            break;
        case InstructionCodes.WRKRECEIVE:
            InstructionWRKSendReceive wrkReceiveIns = (InstructionWRKSendReceive) instruction;
            if (!handleWorkerReceive(strand, wrkReceiveIns.dataChannelInfo, wrkReceiveIns.type,
                    wrkReceiveIns.reg, wrkReceiveIns.channelInSameStrand)) {
                return;
            }
            break;
        case InstructionCodes.CHNRECEIVE:
            Instruction.InstructionCHNReceive chnReceiveIns = (Instruction.InstructionCHNReceive) instruction;
            if (!handleCHNReceive(strand, chnReceiveIns.channelName, chnReceiveIns.receiverType,
                    chnReceiveIns.receiverReg, chnReceiveIns.keyType, chnReceiveIns.keyReg)) {
                return;
            }
            break;
        case InstructionCodes.CHNSEND:
            Instruction.InstructionCHNSend chnSendIns = (Instruction.InstructionCHNSend) instruction;
            handleCHNSend(strand, chnSendIns.channelName, chnSendIns.dataType, chnSendIns.dataReg,
                    chnSendIns.keyType, chnSendIns.keyReg);
            break;
        case InstructionCodes.FLUSH:
            Instruction.InstructionFlush flushIns = (Instruction.InstructionFlush) instruction;
            if (!WaitCallbackHandler.handleFlush(strand, flushIns.retReg, flushIns.channels)) {
                return;
            }
            break;
        case InstructionCodes.WORKERSYNCSEND:
            Instruction.InstructionWRKSyncSend syncSendIns = (Instruction.InstructionWRKSyncSend) instruction;
            if (!handleWorkerSyncSend(strand, syncSendIns.dataChannelInfo, syncSendIns.type, syncSendIns.reg,
                    syncSendIns.retReg, syncSendIns.isSameStrand)) {
                return;
            }
            //worker data channel will resume this upon data retrieval or error
            break;
        case InstructionCodes.PANIC:
            i = operands[0];
            if (i >= 0) {
                BError error = (BError) sf.refRegs[i];
                if (error == null) {
                    //TODO do we need this null check?
                    handleNullRefError(strand);
                    break;
                }
                strand.setError(error);
            }
            handleError(strand);
            break;
        case InstructionCodes.ERROR:
            createNewError(operands, strand, sf);
            break;
        case InstructionCodes.FPCALL:
            i = operands[0];
            if (sf.refRegs[i] == null) {
                handleNullRefError(strand);
                break;
            }
            cpIndex = operands[1];
            funcCallCPEntry = (FunctionCallCPEntry) sf.constPool[cpIndex];
            functionInfo = ((BFunctionPointer) sf.refRegs[i]).value();
            strand = invokeCallable(strand, (BFunctionPointer) sf.refRegs[i], funcCallCPEntry, functionInfo, sf,
                    funcCallCPEntry.getFlags());
            if (strand == null) {
                return;
            }
            break;
        case InstructionCodes.FPLOAD:
            i = operands[0];
            j = operands[1];
            k = operands[2];
            funcRefCPEntry = (FunctionRefCPEntry) sf.constPool[i];
            typeEntry = (TypeRefCPEntry) sf.constPool[k];
            BFunctionPointer functionPointer = new BFunctionPointer(funcRefCPEntry.getFunctionInfo(),
                    typeEntry.getType());
            sf.refRegs[j] = functionPointer;
            findAndAddAdditionalVarRegIndexes(sf, operands, functionPointer);
            break;
        case InstructionCodes.VFPLOAD:
            i = operands[0];
            j = operands[1];
            k = operands[2];
            int m = operands[5];
            funcRefCPEntry = (FunctionRefCPEntry) sf.constPool[i];
            typeEntry = (TypeRefCPEntry) sf.constPool[k];

            BMap<String, BValue> structVal = (BMap<String, BValue>) sf.refRegs[m];
            if (structVal == null) {
                handleNullRefError(strand);
                break;
            }

            StructureTypeInfo structInfo = (ObjectTypeInfo) ((BStructureType) structVal.getType())
                    .getTypeInfo();
            FunctionInfo attachedFuncInfo = structInfo.funcInfoEntries
                    .get(funcRefCPEntry.getFunctionInfo().getName());

            BFunctionPointer fPointer = new BFunctionPointer(attachedFuncInfo, typeEntry.getType());
            sf.refRegs[j] = fPointer;
            findAndAddAdditionalVarRegIndexes(sf, operands, fPointer);
            break;

        case InstructionCodes.I2ANY:
        case InstructionCodes.BI2ANY:
        case InstructionCodes.F2ANY:
        case InstructionCodes.S2ANY:
        case InstructionCodes.B2ANY:
        case InstructionCodes.ANY2I:
        case InstructionCodes.ANY2BI:
        case InstructionCodes.ANY2F:
        case InstructionCodes.ANY2S:
        case InstructionCodes.ANY2B:
        case InstructionCodes.ANY2D:
        case InstructionCodes.ARRAY2JSON:
        case InstructionCodes.JSON2ARRAY:
        case InstructionCodes.ANY2JSON:
        case InstructionCodes.ANY2XML:
        case InstructionCodes.ANY2MAP:
        case InstructionCodes.ANY2TYPE:
        case InstructionCodes.ANY2E:
        case InstructionCodes.ANY2T:
        case InstructionCodes.ANY2C:
        case InstructionCodes.ANY2DT:
        case InstructionCodes.CHECKCAST:
        case InstructionCodes.IS_ASSIGNABLE:
        case InstructionCodes.O2JSON:
        case InstructionCodes.TYPE_CAST:
            execTypeCastOpcodes(strand, sf, opcode, operands);
            break;

        case InstructionCodes.I2F:
        case InstructionCodes.I2S:
        case InstructionCodes.I2B:
        case InstructionCodes.I2D:
        case InstructionCodes.I2BI:
        case InstructionCodes.F2BI:
        case InstructionCodes.D2BI:
        case InstructionCodes.F2I:
        case InstructionCodes.F2S:
        case InstructionCodes.F2B:
        case InstructionCodes.F2D:
        case InstructionCodes.S2I:
        case InstructionCodes.S2F:
        case InstructionCodes.S2B:
        case InstructionCodes.S2D:
        case InstructionCodes.B2I:
        case InstructionCodes.B2F:
        case InstructionCodes.B2S:
        case InstructionCodes.B2D:
        case InstructionCodes.D2I:
        case InstructionCodes.D2F:
        case InstructionCodes.D2S:
        case InstructionCodes.D2B:
        case InstructionCodes.DT2XML:
        case InstructionCodes.DT2JSON:
        case InstructionCodes.T2MAP:
        case InstructionCodes.T2JSON:
        case InstructionCodes.MAP2JSON:
        case InstructionCodes.JSON2MAP:
        case InstructionCodes.MAP2T:
        case InstructionCodes.JSON2T:
        case InstructionCodes.XMLATTRS2MAP:
        case InstructionCodes.XML2S:
        case InstructionCodes.ANY2SCONV:
            execTypeConversionOpcodes(strand, sf, opcode, operands);
            break;

        case InstructionCodes.INEWARRAY:
            i = operands[0];
            j = operands[2];
            sf.refRegs[i] = new BValueArray(BTypes.typeInt, (int) sf.longRegs[j]);
            break;
        case InstructionCodes.BINEWARRAY:
            i = operands[0];
            j = operands[2];
            sf.refRegs[i] = new BValueArray(BTypes.typeByte, (int) sf.longRegs[j]);
            break;
        case InstructionCodes.FNEWARRAY:
            i = operands[0];
            j = operands[2];
            sf.refRegs[i] = new BValueArray(BTypes.typeFloat, (int) sf.longRegs[j]);
            break;
        case InstructionCodes.SNEWARRAY:
            i = operands[0];
            j = operands[2];
            sf.refRegs[i] = new BValueArray(BTypes.typeString, (int) sf.longRegs[j]);
            break;
        case InstructionCodes.BNEWARRAY:
            i = operands[0];
            j = operands[2];
            sf.refRegs[i] = new BValueArray(BTypes.typeBoolean, (int) sf.longRegs[j]);
            break;
        case InstructionCodes.RNEWARRAY:
            i = operands[0];
            cpIndex = operands[1];
            typeRefCPEntry = (TypeRefCPEntry) sf.constPool[cpIndex];
            sf.refRegs[i] = new BValueArray(typeRefCPEntry.getType());
            break;
        case InstructionCodes.NEWSTRUCT:
            createNewStruct(operands, sf);
            break;
        case InstructionCodes.NEWMAP:
            i = operands[0];
            cpIndex = operands[1];
            typeRefCPEntry = (TypeRefCPEntry) sf.constPool[cpIndex];
            sf.refRegs[i] = new BMap<String, BRefType>(typeRefCPEntry.getType());
            break;
        case InstructionCodes.NEWTABLE:
            i = operands[0];
            cpIndex = operands[1];
            j = operands[2];
            k = operands[3];
            l = operands[4];
            typeRefCPEntry = (TypeRefCPEntry) sf.constPool[cpIndex];
            BValueArray indexColumns = (BValueArray) sf.refRegs[j];
            BValueArray keyColumns = (BValueArray) sf.refRegs[k];
            BValueArray dataRows = (BValueArray) sf.refRegs[l];
            try {
                sf.refRegs[i] = new BTable(typeRefCPEntry.getType(), indexColumns, keyColumns, dataRows);
            } catch (BallerinaException e) {
                strand.setError(BLangVMErrors.createError(strand, e.getMessage()));
                handleError(strand);
            }
            break;
        case InstructionCodes.NEWSTREAM:
            i = operands[0];
            cpIndex = operands[1];
            typeRefCPEntry = (TypeRefCPEntry) sf.constPool[cpIndex];
            StringCPEntry name = (StringCPEntry) sf.constPool[operands[2]];
            BStream stream = new BStream(typeRefCPEntry.getType(), name.getValue());
            sf.refRegs[i] = stream;
            break;
        case InstructionCodes.IRET:
            j = operands[0];
            if (strand.fp > 0) {
                StackFrame pf = strand.peekFrame(1);
                callersRetRegIndex = sf.retReg;
                pf.longRegs[callersRetRegIndex] = sf.longRegs[j];
            } else {
                strand.respCallback.setIntReturn(sf.longRegs[j]);
            }
            break;
        case InstructionCodes.FRET:
            j = operands[0];
            if (strand.fp > 0) {
                StackFrame pf = strand.peekFrame(1);
                callersRetRegIndex = sf.retReg;
                pf.doubleRegs[callersRetRegIndex] = sf.doubleRegs[j];
            } else {
                strand.respCallback.setFloatReturn(sf.doubleRegs[j]);
            }
            break;
        case InstructionCodes.SRET:
            j = operands[0];
            if (strand.fp > 0) {
                StackFrame pf = strand.peekFrame(1);
                callersRetRegIndex = sf.retReg;
                pf.stringRegs[callersRetRegIndex] = sf.stringRegs[j];
            } else {
                strand.respCallback.setStringReturn(sf.stringRegs[j]);
            }
            break;
        case InstructionCodes.BRET:
            j = operands[0];
            if (strand.fp > 0) {
                StackFrame pf = strand.peekFrame(1);
                callersRetRegIndex = sf.retReg;
                pf.intRegs[callersRetRegIndex] = sf.intRegs[j];
            } else {
                strand.respCallback.setBooleanReturn(sf.intRegs[j]);
            }
            break;
        case InstructionCodes.DRET:
        case InstructionCodes.RRET:
            j = operands[0];
            if (strand.fp > 0) {
                StackFrame pf = strand.peekFrame(1);
                callersRetRegIndex = sf.retReg;
                pf.refRegs[callersRetRegIndex] = sf.refRegs[j];
            } else {
                strand.respCallback.setRefReturn(sf.refRegs[j]);
            }
            if (checkIsType(sf.refRegs[j], BTypes.typeError)) {
                sf.errorRetReg = j;
            }
            break;
        case InstructionCodes.RET:
            if (strand.fp > 0) {
                // Stop the observation context before popping the stack frame
                ObserveUtils.stopCallableObservation(strand);
                if (sf.errorRetReg > -1) {
                    //notifying waiting workers
                    sf.handleChannelError(sf.refRegs[sf.errorRetReg], strand.peekFrame(1).wdChannels);
                }
                strand.popFrame();
                break;
            }
            if (sf.errorRetReg > -1) {
                //notifying waiting workers
                sf.handleChannelError(sf.refRegs[sf.errorRetReg], strand.respCallback.parentChannels);
            }
            sf.ip = -1;
            strand.respCallback.signal();
            return;
        case InstructionCodes.XMLATTRSTORE:
        case InstructionCodes.XMLATTRLOAD:
        case InstructionCodes.XML2XMLATTRS:
        case InstructionCodes.S2QNAME:
        case InstructionCodes.NEWQNAME:
        case InstructionCodes.NEWXMLELEMENT:
        case InstructionCodes.NEWXMLCOMMENT:
        case InstructionCodes.NEWXMLTEXT:
        case InstructionCodes.NEWXMLPI:
        case InstructionCodes.XMLSEQSTORE:
        case InstructionCodes.XMLSEQLOAD:
        case InstructionCodes.XMLLOAD:
        case InstructionCodes.XMLLOADALL:
        case InstructionCodes.NEWXMLSEQ:
            execXMLOpcodes(strand, sf, opcode, operands);
            break;
        case InstructionCodes.ITR_NEXT:
            execIteratorOperation(strand, sf, instruction);
            break;
        case InstructionCodes.LOCK:
            InstructionLock instructionLock = (InstructionLock) instruction;
            if (!handleVariableLock(strand, instructionLock.types, instructionLock.pkgRefs,
                    instructionLock.varRegs, instructionLock.fieldRegs, instructionLock.varCount,
                    instructionLock.uuid)) {
                return;
            }
            break;
        case InstructionCodes.UNLOCK:
            InstructionUnLock instructionUnLock = (InstructionUnLock) instruction;
            handleVariableUnlock(strand, instructionUnLock.types, instructionUnLock.pkgRefs,
                    instructionUnLock.varRegs, instructionUnLock.varCount, instructionUnLock.uuid,
                    instructionUnLock.hasFieldVar);
            break;
        case InstructionCodes.WAIT:
            if (!execWait(strand, operands)) {
                return;
            }
            break;
        case InstructionCodes.WAITALL:
            if (!execWaitForAll(strand, operands)) {
                return;
            }
            break;
        default:
            throw new UnsupportedOperationException();
        }
        sf = strand.currentFrame;
    }
}

From source file:org.ballerinalang.bre.bvm.BVM.java

private static void execTypeConversionOpcodes(Strand ctx, StackFrame sf, int opcode, int[] operands) {
    int i;/* w w w.ja  v  a2s .c  o  m*/
    int j;
    BRefType bRefType;
    String str;

    switch (opcode) {
    case InstructionCodes.I2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = sf.longRegs[i];
        break;
    case InstructionCodes.I2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = Long.toString(sf.longRegs[i]);
        break;
    case InstructionCodes.I2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = sf.longRegs[i] != 0 ? 1 : 0;
        break;
    case InstructionCodes.I2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = new BDecimal((new BigDecimal(sf.longRegs[i], MathContext.DECIMAL128)).setScale(1,
                BigDecimal.ROUND_HALF_EVEN));
        break;
    case InstructionCodes.I2BI:
        i = operands[0];
        j = operands[1];
        if (!isByteLiteral(sf.longRegs[i])) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.INT_TNAME + "' value '" + sf.longRegs[i] + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = sf.longRegs[i];
        break;
    case InstructionCodes.F2BI:
        i = operands[0];
        j = operands[1];
        double floatVal = sf.doubleRegs[i];
        if (Double.isNaN(floatVal) || Double.isInfinite(floatVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + floatVal + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }

        long floatAsIntVal = Math.round(floatVal);
        if (!isByteLiteral(floatAsIntVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + floatVal + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = floatAsIntVal;
        break;
    case InstructionCodes.D2BI:
        i = operands[0];
        j = operands[1];

        DecimalValueKind valueKind = ((BDecimal) sf.refRegs[i]).valueKind;
        if (valueKind == DecimalValueKind.NOT_A_NUMBER || valueKind == DecimalValueKind.NEGATIVE_INFINITY
                || valueKind == DecimalValueKind.POSITIVE_INFINITY) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }

        long doubleAsIntVal = Math.round(((BDecimal) sf.refRegs[i]).floatValue());
        if (!isByteLiteral(doubleAsIntVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = doubleAsIntVal;
        break;
    case InstructionCodes.F2I:
        i = operands[0];
        j = operands[1];
        double valueToConvert = sf.doubleRegs[i];
        if (Double.isNaN(valueToConvert) || Double.isInfinite(valueToConvert)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + valueToConvert
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        if (!isFloatWithinIntRange(valueToConvert)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "out " + "of range '" + TypeConstants.FLOAT_TNAME + "' value '" + valueToConvert
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        sf.longRegs[j] = Math.round(valueToConvert);
        break;
    case InstructionCodes.F2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = Double.toString(sf.doubleRegs[i]);
        break;
    case InstructionCodes.F2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = sf.doubleRegs[i] != 0.0 ? 1 : 0;
        break;
    case InstructionCodes.F2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = new BDecimal(new BigDecimal(sf.doubleRegs[i], MathContext.DECIMAL128));
        break;
    case InstructionCodes.S2I:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BInteger(Long.parseLong(str));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.INT_TNAME);
        }
        break;
    case InstructionCodes.S2F:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BFloat(Double.parseDouble(str));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.FLOAT_TNAME);
        }
        break;
    case InstructionCodes.S2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = Boolean.parseBoolean(sf.stringRegs[i]) ? 1 : 0;
        break;
    case InstructionCodes.S2D:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BDecimal(new BigDecimal(str, MathContext.DECIMAL128));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.DECIMAL_TNAME);
        }
        break;
    case InstructionCodes.B2I:
        i = operands[0];
        j = operands[1];
        sf.longRegs[j] = sf.intRegs[i];
        break;
    case InstructionCodes.B2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = sf.intRegs[i];
        break;
    case InstructionCodes.B2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.intRegs[i] == 1 ? "true" : "false";
        break;
    case InstructionCodes.B2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = sf.intRegs[i] == 1
                ? new BDecimal(BigDecimal.ONE.setScale(1, BigDecimal.ROUND_HALF_EVEN))
                : new BDecimal(BigDecimal.ZERO.setScale(1, BigDecimal.ROUND_HALF_EVEN));
        break;
    case InstructionCodes.D2I:
        i = operands[0];
        j = operands[1];
        BDecimal decimal = (BDecimal) sf.refRegs[i];
        DecimalValueKind decValueKind = decimal.valueKind;
        if (decValueKind == DecimalValueKind.NOT_A_NUMBER || decValueKind == DecimalValueKind.NEGATIVE_INFINITY
                || decValueKind == DecimalValueKind.POSITIVE_INFINITY) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        if (!isDecimalWithinIntRange((decimal.decimalValue()))) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "out of range '" + TypeConstants.DECIMAL_TNAME + "' value '" + decimal
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = Math.round(((BDecimal) sf.refRegs[i]).decimalValue().doubleValue());
        break;
    case InstructionCodes.D2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = ((BDecimal) sf.refRegs[i]).floatValue();
        break;
    case InstructionCodes.D2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.refRegs[i].stringValue();
        break;
    case InstructionCodes.D2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = ((BDecimal) sf.refRegs[i]).decimalValue().compareTo(BigDecimal.ZERO) != 0 ? 1 : 0;
        break;
    case InstructionCodes.DT2XML:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            handleTypeConversionError(ctx, sf, j, BTypes.typeNull, BTypes.typeXML);
            break;
        }

        try {
            sf.refRegs[j] = XMLUtils.tableToXML((BTable) bRefType);
        } catch (Exception e) {
            sf.refRegs[j] = null;
            handleTypeConversionError(ctx, sf, j, TypeConstants.TABLE_TNAME, TypeConstants.XML_TNAME);
        }
        break;
    case InstructionCodes.DT2JSON:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            handleNullRefError(ctx);
            break;
        }

        try {
            sf.refRegs[j] = JSONUtils.toJSON((BTable) bRefType);
        } catch (Exception e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.TABLE_TNAME, TypeConstants.XML_TNAME);
        }
        break;
    case InstructionCodes.T2MAP:
        convertStructToMap(ctx, operands, sf);
        break;
    case InstructionCodes.T2JSON:
        convertStructToJSON(ctx, operands, sf);
        break;
    case InstructionCodes.MAP2JSON:
        convertMapToJSON(ctx, operands, sf);
        break;
    case InstructionCodes.JSON2MAP:
        convertJSONToMap(ctx, operands, sf);
        break;
    case InstructionCodes.MAP2T:
        convertMapToStruct(ctx, operands, sf);
        break;
    case InstructionCodes.JSON2T:
        convertJSONToStruct(ctx, operands, sf);
        break;
    case InstructionCodes.XMLATTRS2MAP:
        i = operands[0];
        j = operands[1];
        bRefType = sf.refRegs[i];
        sf.refRegs[j] = ((BXMLAttributes) sf.refRegs[i]).value();
        break;
    case InstructionCodes.XML2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.refRegs[i].stringValue();
        break;
    case InstructionCodes.ANY2SCONV:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            sf.stringRegs[j] = STRING_NULL_VALUE;
        } else {
            sf.stringRegs[j] = bRefType.stringValue();
        }
        break;
    default:
        throw new UnsupportedOperationException();
    }
}

From source file:org.cirdles.calamari.algorithms.TukeyBiweight.java

public static ValueModel calculateTukeyBiweightMean(String name, double tuningConstant, double[] values) {
    // guarantee termination
    BigDecimal epsilon = BigDecimal.ONE.movePointLeft(10);
    int iterationMax = 100;
    int iterationCounter = 0;

    int n = values.length;
    // initial mean is median
    BigDecimal mean = new BigDecimal(calculateMedian(values));

    // initial sigma is median absolute deviation from mean = median (MAD)
    double deviations[] = new double[n];
    for (int i = 0; i < values.length; i++) {
        deviations[i] = StrictMath.abs(values[i] - mean.doubleValue());
    }//from w w  w . j  av a2s .c  o  m
    BigDecimal sigma = new BigDecimal(calculateMedian(deviations)).max(BigDecimal.valueOf(SQUID_TINY_VALUE));

    BigDecimal previousMean;
    BigDecimal previousSigma;

    do {
        iterationCounter++;
        previousMean = mean;
        previousSigma = sigma;

        // init to zeroes
        BigDecimal[] deltas = new BigDecimal[n];
        BigDecimal[] u = new BigDecimal[n];
        BigDecimal sa = BigDecimal.ZERO;
        BigDecimal sb = BigDecimal.ZERO;
        BigDecimal sc = BigDecimal.ZERO;

        BigDecimal tee = new BigDecimal(tuningConstant).multiply(sigma);

        for (int i = 0; i < n; i++) {
            deltas[i] = new BigDecimal(values[i]).subtract(mean);
            if (tee.compareTo(deltas[i].abs()) > 0) {
                deltas[i] = new BigDecimal(values[i]).subtract(mean);
                u[i] = deltas[i].divide(tee, MathContext.DECIMAL128);
                BigDecimal uSquared = u[i].multiply(u[i]);
                sa = sa.add(deltas[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)).pow(2));
                sb = sb.add(BigDecimal.ONE.subtract(uSquared)
                        .multiply(BigDecimal.ONE.subtract(new BigDecimal(5.0).multiply(uSquared))));
                sc = sc.add(u[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)));
            }
        }

        sigma = bigDecimalSqrtBabylonian(sa.multiply(new BigDecimal(n))).divide(sb.abs(),
                MathContext.DECIMAL128);
        sigma = sigma.max(BigDecimal.valueOf(SQUID_TINY_VALUE));
        mean = previousMean.add(tee.multiply(sc).divide(sb, MathContext.DECIMAL128));

    } // both tests against epsilon must pass OR iterations top out
      // april 2016 Simon B discovered we need 101 iterations possible, hence the "<=" below
    while (((sigma.subtract(previousSigma).abs().divide(sigma, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            || mean.subtract(previousMean).abs().divide(mean, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            && (iterationCounter <= iterationMax));

    return new ValueModel(name, mean, "ABS", sigma);
}

From source file:org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement.java

private BigDecimal getAvancement(SQLRowAccessor r) {
    Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("ECHEANCE_CLIENT"));
    long totalEch = 0;

    for (SQLRowAccessor row : rows) {
        if (!row.getBoolean("REGLE") && !row.getBoolean("REG_COMPTA")) {
            totalEch += row.getLong("MONTANT");
        }// w w  w.  ja va  2s . co m
    }

    SQLRowAccessor avoir = r.getForeign("ID_AVOIR_CLIENT");
    BigDecimal avoirTTC = BigDecimal.ZERO;
    if (avoir != null && !avoir.isUndefined()) {
        avoirTTC = new BigDecimal(avoir.getLong("MONTANT_TTC"));
    }

    final BigDecimal totalAregler = new BigDecimal(r.getLong("T_TTC")).subtract(avoirTTC);
    if (totalAregler.signum() > 0 && totalEch > 0) {
        return totalAregler.subtract(new BigDecimal(totalEch)).divide(totalAregler, MathContext.DECIMAL128)
                .movePointRight(2).setScale(2, RoundingMode.HALF_UP);
    } else {
        return BigDecimal.ONE.movePointRight(2);
    }
}

From source file:org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement.java

/**
 * Transfert en commande fournisseur/*from www . j a v a 2 s .  c om*/
 * */
public void transfertCommande(final int idFacture) {
    ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {

        @Override
        public void run() {
            SQLElement elt = Configuration.getInstance().getDirectory()
                    .getElement("SAISIE_VENTE_FACTURE_ELEMENT");
            SQLTable tableCmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT")
                    .getTable();
            SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("ARTICLE");
            List<SQLRow> rows = getTable().getRow(idFacture).getReferentRows(elt.getTable());
            final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
            SQLRow rowDeviseF = null;
            for (SQLRow sqlRow : rows) {
                // on rcupre l'article qui lui correspond
                SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
                for (SQLField field : eltArticle.getTable().getFields()) {
                    if (sqlRow.getTable().getFieldsName().contains(field.getName())) {
                        rowArticle.put(field.getName(), sqlRow.getObject(field.getName()));
                    }
                }

                int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
                SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
                SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
                SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
                rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
                rowValsElt.put("QTE", sqlRow.getObject("QTE"));
                rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));

                // gestion de la devise
                rowDeviseF = sqlRow.getForeignRow("ID_DEVISE");
                SQLRow rowDeviseHA = rowArticleFind.getForeignRow("ID_DEVISE_HA");
                BigDecimal qte = new BigDecimal(rowValsElt.getInt("QTE"));
                if (rowDeviseF != null && !rowDeviseF.isUndefined()) {
                    if (rowDeviseF.getID() == rowDeviseHA.getID()) {
                        rowValsElt.put("PA_DEVISE", rowArticleFind.getObject("PA_DEVISE"));
                        rowValsElt.put("PA_DEVISE_T", ((BigDecimal) rowArticleFind.getObject("PA_DEVISE"))
                                .multiply(qte, MathContext.DECIMAL128));
                        rowValsElt.put("ID_DEVISE", rowDeviseF.getID());
                    } else {
                        BigDecimal taux = (BigDecimal) rowDeviseF.getObject("TAUX");
                        rowValsElt.put("PA_DEVISE", taux.multiply((BigDecimal) rowValsElt.getObject("PA_HT")));
                        rowValsElt.put("PA_DEVISE_T", ((BigDecimal) rowValsElt.getObject("PA_DEVISE"))
                                .multiply(qte, MathContext.DECIMAL128));
                        rowValsElt.put("ID_DEVISE", rowDeviseF.getID());
                    }
                }

                BigDecimal prixHA = (BigDecimal) rowValsElt.getObject("PA_HT");
                rowValsElt.put("T_PA_HT", prixHA.multiply(qte, MathContext.DECIMAL128));

                rowValsElt.put("T_PA_HT", prixHA.multiply(qte, MathContext.DECIMAL128));
                rowValsElt.put("T_PA_TTC",
                        ((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(
                                new BigDecimal(rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0),
                                MathContext.DECIMAL128));

                map.add(rowArticleFind.getForeignRow("ID_FOURNISSEUR"), rowValsElt);

            }
            MouvementStockSQLElement.createCommandeF(map, rowDeviseF);

        }

    });

}

From source file:org.openconcerto.erp.core.sales.order.element.CommandeClientSQLElement.java

/**
 * Transfert d'une commande en commande fournisseur
 * //from   ww w . j a v  a 2 s.  co m
 * @param commandeID
 */
public void transfertCommande(int commandeID) {

    SQLElement elt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
    SQLTable tableCmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT").getTable();
    SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("ARTICLE");
    SQLRow rowCmd = getTable().getRow(commandeID);
    List<SQLRow> rows = rowCmd.getReferentRows(elt.getTable());
    final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
    for (SQLRow sqlRow : rows) {
        // on rcupre l'article qui lui correspond
        SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
        for (SQLField field : eltArticle.getTable().getFields()) {
            if (sqlRow.getTable().getFieldsName().contains(field.getName())) {
                rowArticle.put(field.getName(), sqlRow.getObject(field.getName()));
            }
        }

        int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
        SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
        SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
        SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
        rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
        rowValsElt.put("QTE", sqlRow.getObject("QTE"));
        rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
        rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT"))
                .multiply(new BigDecimal(rowValsElt.getInt("QTE")), MathContext.DECIMAL128));
        rowValsElt.put("T_PA_TTC",
                ((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(
                        new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)),
                        MathContext.DECIMAL128));

        map.add(rowArticleFind.getForeignRow("ID_FOURNISSEUR"), rowValsElt);

    }
    MouvementStockSQLElement.createCommandeF(map, rowCmd.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"),
            rowCmd.getString("NUMERO") + " - " + rowCmd.getString("NOM"));
}

From source file:org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement.java

private static BigDecimal getValuePiece(SQLRowValues rowVals, int value) {
    if (rowVals.getObject("ID_MODE_VENTE_ARTICLE") == null) {
        throw new IllegalArgumentException("La SQLRowValues ne contient pas ID_MODE_VENTE_ARTICLE");
    }/*from  w w w . ja v  a 2 s .c  o  m*/
    int mode = rowVals.getInt("ID_MODE_VENTE_ARTICLE");
    if (mode == 1) {
        mode = A_LA_PIECE;
    }
    // prix HA
    BigDecimal metrique1HA = rowVals.getObject("PRIX_METRIQUE_HA_1") == null ? BigDecimal.ZERO
            : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_HA_1"));

    // Prix VT
    BigDecimal metrique1VT = rowVals.getObject("PRIX_METRIQUE_VT_1") == null ? BigDecimal.ZERO
            : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_VT_1"));

    // Valeur
    float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F
            : rowVals.getFloat("VALEUR_METRIQUE_1");
    float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F
            : rowVals.getFloat("VALEUR_METRIQUE_2");
    float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F
            : rowVals.getFloat("VALEUR_METRIQUE_3");

    // Mode de vente  la piece
    if (mode == A_LA_PIECE) {
        if (value == PRIX_HA) {
            if (rowVals.getObject("PA_HT") != null) {
                return (BigDecimal) rowVals.getObject("PA_HT");

            }
            return BigDecimal.ZERO;

        }
        if (rowVals.getObject("PV_HT") != null) {
            return (BigDecimal) rowVals.getObject("PV_HT");
        }
        return BigDecimal.ZERO;

    }
    // Mode de vente au metre carr
    if (mode == AU_METRE_CARRE) {
        float surface = valMetrique1 * valMetrique2;
        if (value == PRIX_HA) {
            return metrique1HA.multiply(BigDecimal.valueOf(surface), MathContext.DECIMAL128);
        }
        return metrique1VT.multiply(BigDecimal.valueOf(surface), MathContext.DECIMAL128);
    }
    // Mode de vente au metre, largeur
    if (mode == AU_METRE_LARGEUR) {
        if (value == PRIX_HA) {
            return metrique1HA.multiply(BigDecimal.valueOf(valMetrique2), MathContext.DECIMAL128);
        }
        return metrique1VT.multiply(BigDecimal.valueOf(valMetrique2), MathContext.DECIMAL128);
    }
    // Mode de vente au metre, longueur
    if (mode == AU_METRE_LONGUEUR) {
        if (value == PRIX_HA) {
            return metrique1HA.multiply(BigDecimal.valueOf(valMetrique1), MathContext.DECIMAL128);
        }
        return metrique1VT.multiply(BigDecimal.valueOf(valMetrique1), MathContext.DECIMAL128);
    }
    // Mode de vente au poids / m2
    if (mode == AU_POID_METRECARRE) {
        float surface = valMetrique1 * valMetrique2;
        float p = surface * valMetrique3;
        if (value == PRIX_HA) {
            return metrique1HA.multiply(BigDecimal.valueOf(p), MathContext.DECIMAL128);
        }
        return metrique1VT.multiply(BigDecimal.valueOf(p), MathContext.DECIMAL128);
    }
    throw new IllegalStateException("Unknown mode:" + mode);

}

From source file:org.openconcerto.erp.core.supplychain.receipt.component.BonReceptionSQLComponent.java

/**
 * Calcul du prix d'achat pondr pour chacun des articles du bon de reception
 * //from w  w  w  .ja v a 2s  .c o m
 * @param id id du bon de reception
 * @throws SQLException
 */
private void calculPHaPondere(int id) throws SQLException {
    SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete()
            .getTable("ARTICLE");
    SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
    SQLElement eltStock = Configuration.getInstance().getDirectory().getElement("STOCK");
    SQLRow row = getTable().getRow(id);

    // On rcupre les articles qui composent la facture
    SQLTable sqlTableBonElt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete()
            .getTable("BON_RECEPTION_ELEMENT");
    List<SQLRow> elts = row.getReferentRows(sqlTableBonElt);

    for (SQLRow rowEltBon : elts) {

        SQLRowValues rowVals = rowEltBon.createUpdateRow();

        // recupere l'ancien prix d'achat
        int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowVals, false);
        if (idArticle > 1) {
            // Prix d'achat de l'article  l'origine
            SQLRow rowArticle = eltArticle.getTable().getRow(idArticle);
            BigDecimal prixHA = (BigDecimal) rowArticle.getObject("PRIX_METRIQUE_HA_1");

            // Quantit en stock
            int idStock = rowArticle.getInt("ID_STOCK");
            SQLRow rowStock = eltStock.getTable().getRow(idStock);
            BigDecimal qteStock = new BigDecimal(rowStock.getInt("QTE_REEL"));
            if (prixHA != null && qteStock.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal qteRecue = new BigDecimal(rowEltBon.getInt("QTE"));
                BigDecimal prixHACmd = (BigDecimal) rowEltBon.getObject("PRIX_METRIQUE_HA_1");
                if (qteRecue.compareTo(BigDecimal.ZERO) > 0 && prixHACmd != null) {
                    BigDecimal totalHARecue = qteRecue.multiply(prixHACmd, MathContext.DECIMAL128);
                    BigDecimal totalHAStock = qteStock.multiply(prixHA, MathContext.DECIMAL128);
                    BigDecimal totalQte = qteRecue.add(qteStock);
                    BigDecimal prixHaPond = totalHARecue.add(totalHAStock).divide(totalQte,
                            MathContext.DECIMAL128);
                    SQLRowValues rowValsArticle = rowArticle.createEmptyUpdateRow();
                    rowValsArticle.put("PRIX_METRIQUE_HA_1", prixHaPond);
                    rowValsArticle.commit();
                }
            }
        }

    }
}