Example usage for java.lang Boolean Boolean

List of usage examples for java.lang Boolean Boolean

Introduction

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

Prototype

@Deprecated(since = "9")
public Boolean(String s) 

Source Link

Document

Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true" .

Usage

From source file:org.systemsbiology.mzxmlviewer.utilities.SpectrumComponent.java

public void setScan(Scan s) {
    if (chart == null) {
        data = new MyDataSet(s.getMassIntensityList());
        chart = ChartFactory.createXYBarChart("Spectrum @ " + s.getRetentionTime() + " s", "m/z", false,
                "intensity", data, PlotOrientation.VERTICAL, false, false, false);

        //chart.getXYPlot().setDomainAxis(new NumberAxis());
        //chart.getXYPlot().setRangeAxis(new NumberAxis());
        XYBarRenderer renderer = new XYBarRenderer();
        renderer.setSeriesItemLabelsVisible(0, new Boolean(true));
        chart.getXYPlot().setRenderer(renderer);
        removeAll();//from w  w w  .  j  a v  a  2s . c  o m
        add(new ChartPanel(chart));
        validate();
        repaint();
    }

    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(1);
    chart.setTitle("Spectrum @ " + format.format(s.getDoubleRetentionTime()) + " s");
    chart.getXYPlot().clearDomainMarkers();
    if (s.getMsLevel() == 2)
        chart.getXYPlot().addDomainMarker(new ValueMarker(s.getPrecursorMz()));
    data.setData(s.getMassIntensityList());
}

From source file:de.vandermeer.skb.interfaces.transformers.Object_To_Target.java

/**
 * Type safe transformation from Object to target class, with optional special processing for `Object[]` and `Collection`.
 * The conversion is done in the following sequence:
 * /*from  w  w w.  j  a v a2s  . co  m*/
 *     * If value is `null`, the `nullValue` will be returned.
 *     * If the requested class is an object array ({@link #getClazzT()}==Object[]),
 *       then the return is `value` (if value is an `Object[]`)
 *       or `Collection.toArray()` (if value is a `Collection)`.
 *       In all other cases the process proceeds
 *     * If `collFist` is set to `true` and value is a `Collection`, the first value of this collection will be used for the further process
 *     * Now another `null` test returning `nullValue` if value is `null`
 *     * Next test if the {@link #getClazzT()} is an instance of `value.class`. If true, `value` will be returned
 *     * Next try for some standard type conversions for `value`, namely
 *       ** If {@link #getClazzT()} is an instance of `Boolean` and value is `true` or `on` (case insensitive), then return `Boolean(true)`
 *       ** If {@link #getClazzT()} is an instance of `Boolean` and value is `false` or `off` (case insensitive), then return `Boolean(false)`
 *       ** If {@link #getClazzT()} is an instance of `Integer` then try to return `Integer.valueOf(value.toString)`
 *       ** If {@link #getClazzT()} is an instance of `Double` then try to return `Double.valueOf(value.toString)`
 *       ** If {@link #getClazzT()} is an instance of `Long` then try to return `Long.valueOf(value.toString)`
 *     * The last option is to return `valueFalse` to indicate that no test was successful
 * 
 * This method does suppress warnings for "`unchecked`" castings, because a casting from any concrete return type to `T` is unsafe.
 * Because all actual castings follow an explicit type check, this suppression should have not negative impact (i.e. there are no {@link ClassCastException}).
 * 
 * @param obj input object for conversion
 * @return a value of type `T` if a conversion was successful, `nullValue` if `null` was tested successfully, `falseValue` in all other cases
 */
@SuppressWarnings("unchecked")
@Override
default T transform(Object obj) {
    if (obj == null) {
        return this.getNullValue();
    }

    //next check for Object[], because here we want collections unchanged
    if (this.getClazzT().isInstance(new Object[] {})) {
        if (obj instanceof Object[]) {
            return (T) obj;
        } else if (obj instanceof Collection) {
            return (T) ((Collection<?>) obj).toArray();
        }
    }

    //now, if collection use the first value
    if (this.getCollFirstFlag() == true && ClassUtils.isAssignable(obj.getClass(), Collection.class)) {
        Collection_To_FirstElement<Object> tr = Collection_To_FirstElement.create();
        obj = tr.transform((Collection<Object>) obj);
    }

    //check value again, this maybe the one from the collection
    if (obj == null) {
        return this.getNullValue();
    }

    //if value is T, return caste to T
    if (this.getClazzT().isInstance(obj)) {
        return (T) obj;
    }

    if (this.getClazzT().isInstance(new Boolean(true))) {
        Object ret = String_To_Boolean.create().transform(obj.toString());
        if (ret != null) {
            return (T) ret;
        }
    }
    if (this.getClazzT().isInstance(new Integer(0))) {
        try {
            return (T) Integer.valueOf(obj.toString());
        } catch (Exception ignore) {
        }
    }
    if (this.getClazzT().isInstance(new Double(0))) {
        try {
            return (T) Double.valueOf(obj.toString());
        } catch (Exception ignore) {
        }
    }
    if (this.getClazzT().isInstance(new Long(0))) {
        try {
            return (T) Long.valueOf(obj.toString());
        } catch (Exception ignore) {
        }
    }

    //no other option, return falseValue
    return this.getFalseValue();
}

From source file:werecloud.api.bean.VMWareMacCache.java

private PropertyFilterSpec createEventFilterSpec() {
    // Set up a PropertySpec to use the latestPage attribute
    // of the EventHistoryCollector

    PropertySpec propSpec = new PropertySpec();
    propSpec.setAll(new Boolean(false));
    propSpec.setPathSet(new String[] { "latestPage" });
    propSpec.setType(_eventHistoryCollector.getMOR().getType());

    // PropertySpecs are wrapped in a PropertySpec array
    PropertySpec[] propSpecAry = new PropertySpec[] { propSpec };

    // Set up an ObjectSpec with the above PropertySpec for the
    // EventHistoryCollector we just created
    // as the Root or Starting Object to get Attributes for.
    ObjectSpec objSpec = new ObjectSpec();
    objSpec.setObj(_eventHistoryCollector.getMOR());
    objSpec.setSkip(new Boolean(false));

    // Get Event objects in "latestPage" from "EventHistoryCollector"
    // and no "traversl" further, so, no SelectionSpec is specified
    objSpec.setSelectSet(new SelectionSpec[] {});

    // ObjectSpecs are wrapped in an ObjectSpec array
    ObjectSpec[] objSpecAry = new ObjectSpec[] { objSpec };

    PropertyFilterSpec spec = new PropertyFilterSpec();
    spec.setPropSet(propSpecAry);//from w ww.  jav a  2s.  c  o m
    spec.setObjectSet(objSpecAry);
    return spec;
}

From source file:jp.terasoluna.fw.web.taglib.IfAuthorizedBlockTag.java

/**
 * ^O{fB?I?\bh?B/*from   w  ww . j  a  v a2 s  .c o  m*/
 *
 * @return ???w
 * @throws JspException JSPO
 */
@Override
public int doAfterBody() throws JspException {

    // u?bN?
    Boolean blockInfo = null;
    try {
        // pageContext u?bN?
        blockInfo = (Boolean) pageContext.getAttribute(this.blockId);
    } catch (ClassCastException e) {
        if (log.isWarnEnabled()) {
            log.warn("Class cast error.", e);
        }
    }

    // {fB?o
    boolean outputBody = false;
    if (blockInfo != null && blockInfo.booleanValue()) {
        //blockInfonulltrue??
        outputBody = true;
    }

    // ?eu?bN?
    if (this.parentBlockId != null) {
        // ANZX`FbN
        pageContext.setAttribute(this.parentBlockId, new Boolean(outputBody));
    }

    // {fB?o
    if (outputBody) {
        try {
            bodyContent.writeOut(bodyContent.getEnclosingWriter());
        } catch (IOException e) {
            log.error("Output error.");
            throw new JspException(e);
        }
    }

    // {fB?]
    return SKIP_BODY;
}

From source file:com.atolcd.web.scripts.ZipContents.java

public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {

    String nodes = req.getParameter("nodes");
    if (nodes == null || nodes.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "nodes");
    }/*  w  w w  .  ja v  a2 s. c  om*/

    List<String> nodeIds = new ArrayList<String>();
    StringTokenizer tokenizer = new StringTokenizer(nodes, ",");
    if (tokenizer.hasMoreTokens()) {
        while (tokenizer.hasMoreTokens()) {
            nodeIds.add(tokenizer.nextToken());
        }
    }

    String filename = req.getParameter("filename");
    if (filename == null || filename.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "filename");
    }

    String noaccentStr = req.getParameter("noaccent");
    if (noaccentStr == null || noaccentStr.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "noaccent");
    }

    try {
        res.setContentType(MIMETYPE_ZIP);
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition",
                "attachment;filename=\"" + unAccent(filename) + ZIP_EXTENSION + "\"");

        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        res.setHeader("Expires", "0");

        createZipFile(nodeIds, res.getOutputStream(), new Boolean(noaccentStr));
    } catch (RuntimeException e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                "Erreur lors de la gnration de l'archive.");
    }
}

From source file:es.pode.gestorFlujo.presentacion.objetosPendientes.Publicar.PublicarControllerImpl.java

/**
 * @see es.pode.gestorFlujo.presentacion.objetosPendientes.Publicar.PublicarController#publicarODE(org.apache.struts.action.ActionMapping,
 *      es.pode.gestorFlujo.presentacion.objetosPendientes.Publicar.PublicarODEForm,
 *      javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * //from  w ww.j  a v  a 2s.c om
 * publica un ode, ya sea despublicado o propuesto.
 */

public final void publicarODE(ActionMapping mapping,
        es.pode.gestorFlujo.presentacion.objetosPendientes.Publicar.PublicarODEForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    ResultadoOperacionVO resultadoPublicacion;
    PublicarSession publiSes = this.getPublicarSession(request);
    logger.info("Publicando ODE: " + publiSes.getTitulo() + " Despublicado?: "
            + publiSes.getEsDespublicado().booleanValue() + " IdODE: " + publiSes.getIdODE());

    boolean comentarioValidado = false;//El comentario es obligatorio en el caso de los despublicados, pero no en el caso de la primera publicaion
    if (publiSes.getEsDespublicado().booleanValue()) {
        if (logger.isDebugEnabled())
            logger.debug("Es un ODE despublicado");
        if (form.getComentarios() != null) {
            if ((form.getComentarios().trim().length() > 0) && (form.getComentarios().length() < 2500)) {
                if (logger.isDebugEnabled())
                    logger.debug("Comentarios correctos publicando ODE :" + publiSes.getIdODE() + " de titulo: "
                            + publiSes.getTitulo() + " Comentarios: " + form.getComentarios()
                            + " tipoLicencia: " + publiSes.getTipoLicencia() + " Comunidades: "
                            + publiSes.getComunidades() + ";");
                comentarioValidado = true;
                publiSes.setEsDespublicado(new Boolean(true));
            } else {
                logger.warn("Longitud de comentario no vlida al publicar el ODE con IdODE["
                        + publiSes.getIdODE() + "] usuario[" + LdapUserDetailsUtils.getUsuario()
                        + "]comentarios[" + form.getComentarios() + "] y titulo[" + publiSes.getTitulo()
                        + "]; longitud: " + form.getComentarios().length());
                throw new ValidatorException("{gestorFlujo.comentario.longitud}");
            }
        } else {
            logger.warn("Longitud de comentario no vlida al publicar el ODE con IdODE[" + publiSes.getIdODE()
                    + "] usuario[" + LdapUserDetailsUtils.getUsuario() + "]comentarios[" + form.getComentarios()
                    + "] y titulo[" + publiSes.getTitulo() + "]; longitud: " + form.getComentarios().length());
            throw new ValidatorException("{gestorFlujo.comentario.longitud}");
        }
    } else if (!publiSes.getEsDespublicado().booleanValue()) {
        if (form.getComentarios().length() < 2500) {
            if (logger.isDebugEnabled())
                logger.debug("Comentarios correctos publicando ODE :" + publiSes.getIdODE() + " de titulo: "
                        + publiSes.getTitulo() + " Comentarios: " + form.getComentarios() + " tipoLicencia: "
                        + publiSes.getTipoLicencia() + " Comunidades: " + publiSes.getComunidades() + ";");
            comentarioValidado = true;
            publiSes.setEsDespublicado(new Boolean(false));
        } else {
            logger.warn("Longitud de comentario no vlida al publicar el ODE con IdODE[" + publiSes.getIdODE()
                    + "] usuario[" + LdapUserDetailsUtils.getUsuario() + "]comentarios[" + form.getComentarios()
                    + "] y titulo[" + publiSes.getTitulo() + "]; longitud: " + form.getComentarios().length());
            throw new ValidatorException("{gestorFlujo.comentario.longitud}");
        }
    } else {
        logger.warn("No se han introducido comentarios al publicar el ODE con IdODE[" + publiSes.getIdODE()
                + "] usuario[" + LdapUserDetailsUtils.getUsuario() + "]comentarios[" + form.getComentarios()
                + "] y titulo[" + publiSes.getTitulo() + "]");
        throw new ValidatorException("{gestorFlujo.comentario.obligatorio}");
    }
    if (logger.isDebugEnabled())
        logger.debug("Comentarios correctos publicando ODE :" + publiSes.getIdODE() + " de titulo: "
                + publiSes.getTitulo() + " Comentarios: " + form.getComentarios() + " tipoLicencia: "
                + publiSes.getTipoLicencia() + " Comunidades: " + publiSes.getComunidades() + ";");

    if (publiSes.getTipoLicencia() != null && publiSes.getTipoLicencia().length() > 0) {
        // Ahora comprobamos que existan las comunidades

        String[] nodosValidos = interseccionNodos(publiSes.getComunidades());
        if ((nodosValidos != null) && nodosValidos.length > 0) {
            String nodosValidosString = "";
            for (int i = 0; i < nodosValidos.length; i++) {//Para que slo haya nodos vlidos en la publicacion y tambien el nodo local
                nodosValidosString = nodosValidosString + nodosValidos[i] + ",";
            }
            nodosValidosString = nodosValidosString.substring(0, nodosValidosString.length() - 1);
            publiSes.setComunidades(nodosValidosString);

            //Si tienes todos los nodos ser universal

            SrvNodoService nodosPlataforma = this.getSrvNodoService();

            String[] nodosListados = obtenNodosLocalesIds(nodosPlataforma);
            if (nodosValidos.length == nodosListados.length) {
                publiSes.setUniversal(getPropertyValue("licencia.acceso.universal"));
            }

            try {
                TerminoYPadreVO[] typ = this.getSrvVocabulariosControladosService()
                        .crearTraduccionAIngles(new String[] { publiSes.getTipoLicencia() });

                publiSes.setTipoLicencia(typ[0].getNomTermino());

                if (publiSes.getEsDespublicado().booleanValue()) {
                    resultadoPublicacion = this.getSrvPublicacionService().publicarDespublicado(
                            publiSes.getIdODE(), LdapUserDetailsUtils.getUsuario(), form.getComentarios(),
                            publiSes.getTitulo(), publiSes.getComunidades(), publiSes.getTipoLicencia(),
                            publiSes.getUniversal());
                    publiSes.setEsDespublicado(true);
                    if (logger.isDebugEnabled())
                        logger.debug("Publicando ODE despublicado: en nodos " + publiSes.getComunidades()
                                + "idODE:" + publiSes.getIdODE() + "idioma usuario:"
                                + LdapUserDetailsUtils.getUsuario() + "comentarios:" + form.getComentarios()
                                + "titulo:" + publiSes.getTitulo() + "comunidades:" + publiSes.getComunidades()
                                + "tipoLicencia:" + publiSes.getTipoLicencia() + "universa?"
                                + publiSes.getUniversal());
                } else {
                    resultadoPublicacion = this.getSrvPublicacionService().publicar(publiSes.getIdODE(),
                            LdapUserDetailsUtils.getUsuario(), form.getComentarios(), publiSes.getTitulo(),
                            publiSes.getComunidades(), publiSes.getTipoLicencia(), publiSes.getUniversal());
                    publiSes.setEsDespublicado(false);
                    if (logger.isDebugEnabled())
                        logger.debug("Publicando ODE publicado: en nodos " + publiSes.getComunidades()
                                + "idODE:" + publiSes.getIdODE() + "idioma usuario:"
                                + LdapUserDetailsUtils.getUsuario() + "comentarios:" + form.getComentarios()
                                + "comunidades:" + publiSes.getComunidades() + "tipoLicencia:"
                                + publiSes.getTipoLicencia() + "universa?" + publiSes.getUniversal());

                }
                // limpiamos la sesin una vez que hemos publicado
                publiSes.setComunidades("");
                publiSes.setIdODE("");
                publiSes.setTipoLicencia("");
                publiSes.setUniversal("");

            } catch (Exception ex) {
                logger.error("ERROR (excepcin) publicando el ODE con IdODE[" + publiSes.getIdODE()
                        + "] usuario[" + LdapUserDetailsUtils.getUsuario() + "]comentarios["
                        + form.getComentarios() + "] y titulo[" + publiSes.getTitulo() + "]" + "\n", ex);
                throw new ValidatorException("{gestorFlujo.excepcion.publicar.publicar}");
            }

            if (!resultadoPublicacion.getIdResultado().equals("0.0")) {
                logger.error("Error publicando el ODE con IdODE[" + publiSes.getIdODE() + "] usuario["
                        + LdapUserDetailsUtils.getUsuario() + "]comentarios[" + form.getComentarios()
                        + "] y titulo[" + publiSes.getTitulo() + "] : "
                        + resultadoPublicacion.getDescripcion());

                // throw new
                // ValidatorException(resultadoPublicacion.getDescripcion());
                // saveErrorMessage(request,
                // "gestorFlujo.error.publicar", new String[] {
                // publiSes.getTitulo(),
                // resultadoPublicacion.getDescripcion() });
                form.setMensajes(resultadoPublicacion.getDescripcion()
                        .substring(0, resultadoPublicacion.getDescripcion().length() - 1).split(SPLITTER_VAL));

            } else {
                logger.info("Publicado correctamente: ODE con IdODE[" + publiSes.getIdODE() + "] usuario["
                        + LdapUserDetailsUtils.getUsuario() + "]comentarios[" + form.getComentarios()
                        + "] y titulo[" + publiSes.getTitulo() + "]");
            }
        } else {
            logger.warn("No se puede publicar pq la licencia no tiene asociadas comunidades["
                    + publiSes.getIdODE() + "] usuario[" + LdapUserDetailsUtils.getUsuario() + "]comentarios["
                    + form.getComentarios() + "] y titulo[" + publiSes.getTitulo() + "]; longitud: "
                    + form.getComentarios().length());
            throw new ValidatorException("{gestorFlujo.publicar.comunidadObligatoria}");
        }
    } else {
        logger.warn("No se puede publicar pq no hay un tipo de licencia asociada[" + publiSes.getIdODE()
                + "] usuario[" + LdapUserDetailsUtils.getUsuario() + "]comentarios[" + form.getComentarios()
                + "] y titulo[" + publiSes.getTitulo() + "]; longitud: " + form.getComentarios().length());
        throw new ValidatorException("{gestorFlujo.publicar.tipoLicenciaObligatoria}");
    }

}

From source file:es.pode.catalogadorWeb.presentacion.importar.ImportarControllerImpl.java

public String submit(ActionMapping mapping, SubmitForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String resultado = "";
    String action = form.getAccion();

    //String idiomaLocale=((Locale)request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE)).getLanguage();
    ResourceBundle i18n = I18n.getInstance().getResource("application-resources",
            (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE));

    if (action != null) {
        if (action.equals(i18n.getString("catalogadorAvanzado.importar.aceptar"))) {
            resultado = "Aceptar";
            if (form.getFichero() == null || form.getFichero().getFileName().equals("")
                    || form.getFichero().getFileSize() == 0)
                throw new ValidatorException("{catalogadorAvanzado.importar.error.ficherovacio}");

            //crear el datahandler
            InternetHeaders ih = new InternetHeaders();
            MimeBodyPart mbp = null;/*from   www  .j a va 2  s.c om*/
            DataSource source = null;
            DataHandler dh = null;
            try {
                FormFile ff = (FormFile) form.getFichero();
                mbp = new MimeBodyPart(ih, ff.getFileData());
                source = new MimePartDataSource(mbp);
                dh = new DataHandler(source);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("error al crear el datahandler");
                }
                throw new ValidatorException("{catalogadorAvanzado.importar.error}");
            }

            //validar el fichero
            Boolean valido = new Boolean(false);
            try {
                valido = this.getSrvValidadorService().obtenerValidacionLomes(dh);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("error al llamar al servicio de validacin");
                }
                throw new ValidatorException("{catalogadorAvanzado.importar.error.novalido}");
            }

            if (!valido.booleanValue())
                throw new ValidatorException("{catalogadorAvanzado.importar.error.novalido}");

            //agregar el datahandler a sesion
            this.getCatalogadorAvSession(request).setLomesImportado(dh);

        } else if (action.equals(i18n.getString("catalogadorAvanzado.importar.cancelar")))
            resultado = "Cancelar";
    }
    return resultado;
}

From source file:info.archinnov.achilles.it.TestEntityWithComplexTypes.java

@Test
public void should_insert() throws Exception {
    //Given/*  w  w  w  .  j  av  a2 s .  co  m*/
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final TestUDT udt = new TestUDT();
    udt.setList(asList("list"));
    udt.setName("name");
    udt.setMap(ImmutableMap.of(1, "1"));
    UUID timeuuid = UUIDs.timeBased();
    java.time.Instant jdkInstant = Instant.now();
    java.time.LocalDate jdkLocalDate = java.time.LocalDate.now();
    java.time.LocalTime jdkLocalTime = java.time.LocalTime.now();
    java.time.ZonedDateTime jdkZonedDateTime = java.time.ZonedDateTime.now();

    final EntityWithComplexTypes entity = new EntityWithComplexTypes();
    entity.setId(id);
    entity.setCodecOnClass(new ClassAnnotatedByCodec());
    entity.setComplexNestingMap(
            ImmutableMap.of(udt, ImmutableMap.of(1, Tuple3.of(1, 2, ConsistencyLevel.ALL))));
    entity.setConsistencyLevel(ConsistencyLevel.EACH_QUORUM);
    entity.setInteger(123);
    entity.setJsonMap(ImmutableMap.of(1, asList(1, 2, 3)));
    entity.setListNesting(asList(ImmutableMap.of(1, "one")));
    entity.setListUdt(asList(udt));
    entity.setMapUdt(ImmutableMap.of(1, udt));
    entity.setMapWithNestedJson(ImmutableMap.of(1, asList(ImmutableMap.of(1, "one"))));
    entity.setObjectBoolean(new Boolean(true));
    entity.setObjectByte(new Byte("5"));
    entity.setObjectByteArray(new Byte[] { 7 });
    entity.setOkSet(Sets.newHashSet(ConsistencyLevel.LOCAL_ONE, ConsistencyLevel.LOCAL_QUORUM));
    entity.setPrimitiveBoolean(true);
    entity.setPrimitiveByte((byte) 3);
    entity.setPrimitiveByteArray(new byte[] { 4 });
    entity.setSimpleUdt(udt);
    entity.setTime(buildDate());
    entity.setTimeuuid(timeuuid);
    entity.setTuple1(Tuple1.of(ConsistencyLevel.THREE));
    entity.setTuple2(Tuple2.of(ConsistencyLevel.TWO, 2));
    entity.setTupleNesting(Tuple2.of(1, asList("1")));
    entity.setValue("val");
    entity.setWriteTime(1000L);
    entity.setWriteTimeWithCodec("2000");
    entity.setIntWrapper(new IntWrapper(123));
    entity.setProtocolVersion(ProtocolVersion.V4);
    entity.setEncoding(Enumerated.Encoding.ORDINAL);
    entity.setDoubleArray(new double[] { 1.0, 2.0 });
    entity.setFloatArray(new float[] { 3.0f, 4.0f });
    entity.setIntArray(new int[] { 5, 6 });
    entity.setLongArray(new long[] { 7L, 8L });
    entity.setListOfLongArray(Arrays.asList(new long[] { 9L, 10L }));
    entity.setJdkInstant(jdkInstant);
    entity.setJdkLocalDate(jdkLocalDate);
    entity.setJdkLocalTime(jdkLocalTime);
    entity.setJdkZonedDateTime(jdkZonedDateTime);
    entity.setProtocolVersionAsOrdinal(ProtocolVersion.V2);
    entity.setOptionalString(Optional.empty());
    entity.setOptionalProtocolVersion(Optional.of(ProtocolVersion.V3));
    entity.setOptionalEncodingAsOrdinal(Optional.of(ProtocolVersion.V2));
    entity.setListOfOptional(Arrays.asList(Optional.of("1"), Optional.of("2")));

    //When
    manager.crud().insert(entity).execute();

    //Then
    final Metadata metadata = session.getCluster().getMetadata();
    final TupleValue tupleValue = metadata.newTupleType(text(), cint(), cint()).newValue("1", 2, 5);

    final TupleValue nestedTuple2Value = metadata.newTupleType(cint(), list(text())).newValue(1, asList("1"));

    final Row actual = session.execute("SELECT * FROM entity_complex_types WHERE id = " + id).one();

    assertThat(actual).isNotNull();
    assertThat(actual.getString("codec_on_class")).isEqualTo("ClassAnnotatedByCodec{}");
    final Map<String, Map<Integer, TupleValue>> complexMapNesting = actual.getMap("complex_nesting_map",
            new TypeToken<String>() {
            }, new TypeToken<Map<Integer, TupleValue>>() {
            });
    assertThat(complexMapNesting).containsEntry("{\"list\":[\"list\"],\"map\":{\"1\":\"1\"},\"name\":\"name\"}",
            ImmutableMap.of(1, tupleValue));
    assertThat(actual.getString("consistencylevel")).isEqualTo("EACH_QUORUM");
    assertThat(actual.getString("integer")).isEqualTo("123");
    assertThat(actual.getString("json_map")).isEqualTo("{\"1\":[1,2,3]}");
    assertThat(actual.getList("list_nesting", new TypeToken<Map<Integer, String>>() {
    })).containsExactly(ImmutableMap.of(1, "one"));
    final UDTValue foundUDT = actual.getUDTValue("simple_udt");
    assertThat(foundUDT.getString("name")).isEqualTo("name");
    assertThat(foundUDT.getList("list", String.class)).containsExactly("list");
    assertThat(foundUDT.getMap("map", String.class, String.class)).containsEntry("1", "1");
    assertThat(actual.getList("list_udt", UDTValue.class)).containsExactly(foundUDT);
    assertThat(actual.getMap("map_udt", Integer.class, UDTValue.class)).containsEntry(1, foundUDT);
    assertThat(actual.getMap("map_with_nested_json", Integer.class, String.class)).containsEntry(1,
            "[{\"1\":\"one\"}]");
    assertThat(actual.getBool("object_bool")).isTrue();
    assertThat(actual.getByte("object_byte")).isEqualTo((byte) 5);
    assertThat(actual.getBytes("object_byte_array")).isEqualTo(ByteBuffer.wrap(new byte[] { (byte) 7 }));
    assertThat(actual.getSet("ok_set", Integer.class)).containsExactly(6, 10);
    assertThat(actual.getBool("primitive_bool")).isTrue();
    assertThat(actual.getByte("primitive_byte")).isEqualTo((byte) 3);
    assertThat(actual.getBytes("primitive_byte_array")).isEqualTo(ByteBuffer.wrap(new byte[] { (byte) 4 }));
    assertThat(actual.getString("time")).isEqualTo(buildDate().getTime() + "");
    assertThat(actual.getUUID("timeuuid")).isEqualTo(timeuuid);
    assertThat(actual.getTupleValue("tuple1").get(0, String.class)).isEqualTo("\"THREE\"");
    assertThat(actual.getTupleValue("tuple2").get(0, String.class)).isEqualTo("\"TWO\"");
    assertThat(actual.getTupleValue("tuple2").get(1, String.class)).isEqualTo("2");
    assertThat(actual.getTupleValue("tuple_nesting")).isEqualTo(nestedTuple2Value);
    assertThat(actual.getString("value")).isEqualTo("val");
    assertThat(actual.getInt("intwrapper")).isEqualTo(123);
    assertThat(actual.getString("protocolversion")).isEqualTo("V4");
    assertThat(actual.getInt("encoding")).isEqualTo(1);
    assertThat(actual.get("doublearray", double[].class)).isEqualTo(new double[] { 1.0, 2.0 });
    assertThat(actual.get("floatarray", float[].class)).isEqualTo(new float[] { 3.0f, 4.0f });
    assertThat(actual.get("intarray", int[].class)).isEqualTo(new int[] { 5, 6 });
    assertThat(actual.get("longarray", long[].class)).isEqualTo(new long[] { 7L, 8L });
    assertThat(actual.getList("listoflongarray", long[].class)).containsExactly(new long[] { 9L, 10L });
    assertThat(actual.get("jdkinstant", java.time.Instant.class)).isNotNull();
    assertThat(actual.get("jdklocaldate", java.time.LocalDate.class)).isNotNull();
    assertThat(actual.get("jdklocaltime", java.time.LocalTime.class)).isNotNull();
    assertThat(actual.get("jdkzoneddatetime", java.time.ZonedDateTime.class)).isNotNull();
    assertThat(actual.getInt("protocolversionasordinal")).isEqualTo(1);
    assertThat(actual.isNull("optionalstring")).isTrue();
    assertThat(actual.getString("optionalprotocolversion")).isEqualTo("V3");
    assertThat(actual.getInt("optionalencodingasordinal")).isEqualTo(1);
    assertThat(actual.getList("listofoptional", String.class)).containsExactly("1", "2");
}

From source file:com.github.biconou.subsonic.service.CMusJukeboxService.java

/**
 * /*from  w w  w .j  a va 2 s  .c  o m*/
 * @param file
 * @param offset
 */
private synchronized void play(MediaFile file, int offset) {
    InputStream in = null;
    try {

        if (LOG.isDebugEnabled()) {
            LOG.debug("Begin of play : file = {}", file != null ? file.getName() : "null");
        }

        // Resume if possible.
        boolean sameFile = file != null && file.equals(currentPlayingFile);
        if (LOG.isDebugEnabled()) {
            LOG.debug("sameFile={} (file={} and currentPlayingFile={})", new Object[] { new Boolean(sameFile),
                    file.getName(), currentPlayingFile == null ? "null" : currentPlayingFile.getName() });
        }

        boolean paused = getCMusController().isPaused();
        if (LOG.isDebugEnabled()) {
            LOG.debug("CMUS paused ? {} ", paused);
        }

        if (sameFile && paused && offset == 0) {
            getCMusController().play();
        } else {
            this.offset = offset;
            getCMusController().stop();

            cmusPlayingFile = null;

            if (currentPlayingFile != null) {
                onSongEnd(currentPlayingFile);
            }

            if (file != null) {
                //int duration = file.getDurationSeconds() == null ? 0 : file.getDurationSeconds() - offset;
                //TranscodingService.Parameters parameters = new TranscodingService.Parameters(file, new VideoTranscodingSettings(0, 0, offset, duration, false));
                //String command = settingsService.getJukeboxCommand();
                //parameters.setTranscoding(new Transcoding(null, null, null, null, command, null, null, false));
                //in = transcodingService.getTranscodedInputStream(parameters);
                //audioPlayer = new AudioPlayer(in, this);

                getCMusController().initPlayQueue(file.getFile().getAbsolutePath());

                getCMusController().setGain(gain);
                getCMusController().play();

                onSongStart(file);
            }
        }

        currentPlayingFile = file;

    } catch (Exception x) {
        LOG.error("Error in jukebox: " + x, x);
        IOUtils.closeQuietly(in);
    }
}

From source file:com.bibisco.manager.ConfigManager.java

private Boolean getBooleanMandatoryAttribute(HierarchicalConfiguration pHierarchicalConfiguration,
        String pStrPosition, String pStrAbsolutePosition4Log, String pStrAttributeName)
        throws BibiscoException {

    String lStrMandatoryAttributeValue;
    Boolean lBlnMandatoryAttributeValue;

    lStrMandatoryAttributeValue = getMandatoryAttribute(pHierarchicalConfiguration, pStrPosition,
            pStrAbsolutePosition4Log, pStrAttributeName);
    if (lStrMandatoryAttributeValue.equalsIgnoreCase(String.valueOf(Boolean.TRUE))
            || lStrMandatoryAttributeValue.equalsIgnoreCase(String.valueOf(Boolean.FALSE))) {
        lBlnMandatoryAttributeValue = new Boolean(lStrMandatoryAttributeValue);
    } else {/* w  w w  .  j av a2s. com*/
        mLog.error("Error while reading configuration " + CONFIG_FILENAME + " at position "
                + pStrAbsolutePosition4Log + ": attribute " + pStrAttributeName + " must be a boolean.");
        throw new BibiscoException("bibiscoException.configManager.getBooleanMandatoryAttribute",
                CONFIG_FILENAME, pStrAbsolutePosition4Log, pStrAttributeName);
    }

    return lBlnMandatoryAttributeValue;
}