List of usage examples for java.lang Float valueOf
@HotSpotIntrinsicCandidate public static Float valueOf(float f)
From source file:magma.tools.benchmark.model.proxy.BenchmarkAgentProxy.java
private Vector3D getForce(String message, String which) { int forceIndex = message.indexOf(which); if (forceIndex >= 0) { int fIndex = message.indexOf("(f", forceIndex); if (fIndex >= 0) { int eIndex = message.indexOf(")", fIndex); String forceString = message.substring(fIndex + 3, eIndex); String[] values = forceString.split(" "); if (values.length == 3) { float x = Float.valueOf(values[0]); float y = Float.valueOf(values[1]); float z = Float.valueOf(values[2]); return new Vector3D(x, y, z); }//from w w w.j ava2s .c o m } System.out.println("Strange force message: " + message.substring(forceIndex, forceIndex + 30)); return null; } return Vector3D.ZERO; }
From source file:Coordinate.java
/** * A private method to caluclate the longitude constant * * @param latitude a latitude coordinate in decimal notation * * @return a double representing the longitude constant *///from www . j a va 2 s. c o m public static double longitudeConstant(float latitude) { //return Math.abs( Math.cos(Math.abs(latitude))); return EARTH_DIAMETER * Math.PI * Math.abs(Math.cos(Math.abs(latitude))) / Float.valueOf("360"); }
From source file:com.act.lcms.LCMSNetCDFParser.java
@Override public Iterator<LCMSSpectrum> getIterator(String inputFile) throws ParserConfigurationException, IOException, XMLStreamException { final NetcdfFile netcdfFile = NetcdfFile.open(inputFile); // Assumption: all referenced Variables will always exist in the NetcdfFfile. // Assumption: these arrays will have the same length. final Array mzValues = netcdfFile.findVariable(MASS_VALUES).read(); final Array intensityValues = netcdfFile.findVariable(INTENSITY_VALUES).read(); assert (mzValues.getSize() == intensityValues.getSize()); // Assumption: the mz/intensity values are always floats. assert (mzValues.getDataType() == DataType.FLOAT && intensityValues.getDataType() == DataType.FLOAT); // Assumption: all of these variables' arrays will have the same lengths. final Array scanTimeArray = netcdfFile.findVariable(SCAN_TIME).read(); final Array scanPointsStartArray = netcdfFile.findVariable(SCAN_POINTS_START).read(); final Array scanPointsCountArray = netcdfFile.findVariable(SCAN_POINTS_COUNT).read(); final Array totalIntensityArray = netcdfFile.findVariable(TOTAL_INTENSITY).read(); assert (scanTimeArray.getSize() == scanPointsStartArray.getSize() && scanPointsStartArray.getSize() == scanPointsCountArray.getSize() && scanPointsCountArray.getSize() == totalIntensityArray.getSize()); // Assumption: the following four columns always have these types. assert (scanTimeArray.getDataType() == DataType.DOUBLE && scanPointsStartArray.getDataType() == DataType.INT && scanPointsCountArray.getDataType() == DataType.INT && totalIntensityArray.getDataType() == DataType.DOUBLE); final long size = scanTimeArray.getSize(); return new Iterator<LCMSSpectrum>() { private int i = 0; @Override/*from w ww . j a v a 2 s. co m*/ public boolean hasNext() { return this.i < size; } @Override public LCMSSpectrum next() { int pointCount = scanPointsCountArray.getInt(i); List<Pair<Double, Double>> mzIntPairs = new ArrayList<>(pointCount); int pointsStart = scanPointsStartArray.getInt(i); int pointsEnd = pointsStart + pointCount; for (int p = pointsStart; p < pointsEnd; p++) { Double mz = Float.valueOf(mzValues.getFloat(p)).doubleValue(); Double intensity = Float.valueOf(intensityValues.getFloat(p)).doubleValue(); mzIntPairs.add(Pair.of(mz, intensity)); } LCMSSpectrum s = new LCMSSpectrum(i, scanTimeArray.getDouble(i), "s", mzIntPairs, null, null, null, i, totalIntensityArray.getDouble(i)); // Don't forget to advance the counter! this.i++; // Close the file if we're done with all the array contents. if (i >= size) { try { netcdfFile.close(); } catch (IOException e) { throw new RuntimeException(e); // TODO: can we do better? } } return s; } }; }
From source file:sundroid.code.SundroidActivity.java
/** Called when the activity is first created. ***/ @Override/*from w ww . ja v a 2s . co m*/ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius); Button cmd_submit = (Button) findViewById(R.id.cmd_submit); cmd_submit.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { try { ///////////////// Code to get weather conditions for entered place /////////////////////////////////////////////////// String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString(); String queryString = "https://www.google.com/ig/api?weather=" + cityParamString; queryString = queryString.replace("#", ""); /* Parsing the xml file*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); GoogleWeatherHandler gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(queryString.replace(" ", "%20")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.d("Sundroid", "parse complete"); WeatherSet ws = gwh.getWeatherSet(); newupdateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition(), " " + cityParamString, ""); ///////////////// Code to get weather conditions for entered place ends /////////////////////////////////////////////////// ///////////////// Code to get latitude and longitude using zipcode starts /////////////////////////////////////////////////// String latlng_querystring = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + cityParamString.replace(" ", "%20") + "&sensor=false"; URL url_latlng = new URL(latlng_querystring); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); xmlhandler_latlong xll = new xmlhandler_latlong(); xr.setContentHandler(xll); xr.parse(new InputSource(url_latlng.openStream())); Latitude_longitude ll = xll.getLatlng_resultset(); double selectedLat = ll.getLat_lng_pair().getLat(); double selectedLng = ll.getLat_lng_pair().getLon(); ///////////////// Code to get latitude and longitude using zipcode ends /////////////////////////////////////////////////// ///////////////// Code to get miles from text box & convert to meters for passing into the api link//////////////////////// EditText edt = (EditText) findViewById(R.id.edit_miles); float miles = Float.valueOf(edt.getText().toString()); float meters = (float) (miles * 1609.344); ///////////////// Code to get miles from text box & convert to meters for passing into the api link ends ///////////////// ///////////////// Code to pass lat,long and radius and get destinations from places api starts////////// ///////////////// URL queryString_1 = new URL("https://maps.googleapis.com/maps/api/place/search/xml?location=" + Double.toString(selectedLat) + "," + Double.toString(selectedLng) + "&radius=" + Float.toString(meters) + "&types=park|types=aquarium|types=point_of_interest|types=establishment|types=museum&sensor=false&key=AIzaSyDmP0SB1SDMkAJ1ebxowsOjpAyeyiwHKQU"); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); xmlhandler_places xhp = new xmlhandler_places(); xr.setContentHandler(xhp); xr.parse(new InputSource(queryString_1.openStream())); int arraysize = xhp.getVicinity_List().size(); String[] place = new String[25]; String[] place_name = new String[25]; Double[] lat_pt = new Double[25]; Double[] lng_pt = new Double[25]; int i; //Getting name and vicinity tags from the xml file// for (i = 0; i < arraysize; i++) { place[i] = xhp.getVicinity_List().get(i); place_name[i] = xhp.getPlacename_List().get(i); lat_pt[i] = xhp.getLatlist().get(i); lng_pt[i] = xhp.getLonglist().get(i); System.out.println("long -" + lng_pt[i]); place[i] = place[i].replace("#", ""); } ///////////////// Code to pass lat,long and radius and get destinations from places api ends////////// ///////////////// //////////////////////while loop for getting top 5 from the array//////////////////////////////////////////////// int count = 0; int while_ctr = 0; String str_weathercondition; str_weathercondition = ""; WeatherCurrentCondition reftemp; //Places to visit if none of places in the given radius are sunny/clear/partly cloudy String[] rainy_place = { "Indoor Mall", "Watch a Movie", "Go to a Restaurant", "Shopping!" }; double theDistance = 0; String str_dist = ""; while (count < 5) { //Checking if xml vicinity value is empty while (place[while_ctr] == null || place[while_ctr].length() < 2) { while_ctr = while_ctr + 1; } //First search for places that are sunny or clear if (while_ctr < i - 1) { queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr]; System.out.println("In while loop - " + queryString); theDistance = (Math.sin(Math.toRadians(selectedLat)) * Math.sin(Math.toRadians(lat_pt[while_ctr])) + Math.cos(Math.toRadians(selectedLat)) * Math.cos(Math.toRadians(lat_pt[while_ctr])) * Math.cos(Math.toRadians(selectedLng - lng_pt[while_ctr]))); str_dist = new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09).intValue() + " miles"; System.out.println(str_dist); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); if (gwh.isIn_error_information()) { System.out.println("Error Info flag set"); } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); // Check if the condition is sunny or partly cloudy if (str_weathercondition.equals("Sunny") || str_weathercondition.equals("Mostly Sunny") || str_weathercondition.equals("Clear")) { System.out.println("Sunny Loop"); // Increment the count ++count; // Disply the place on the widget if (count == 1) { newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr], str_dist); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr], str_dist); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr], str_dist); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr], str_dist); } else if (count == 5) { newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr], str_dist); } else { } } } } // If Five sunny places not found then search for partly cloudy places else if (while_ctr >= i && while_ctr < i * 2) { queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr - i]; queryString = queryString.replace(" ", " "); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); // Use HTTPClient to deal with the URL httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.d(DEBUG_TAG, "parse complete"); if (gwh.isIn_error_information()) { } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); // Check if the condition is sunny or partly cloudy if (str_weathercondition.equals("Partly Cloudy")) { count = count + 1; // Display the place if (count == 1) { newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 5) { newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr - i], str_dist); } else { } } } } //////////////////////////////// Give suggestions for a rainy day else { queryString = "https://www.google.com/ig/api?weather=" + cityParamString; queryString = queryString.replace("#", ""); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); // create a response handler responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); if (gwh.isIn_error_information()) { } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); if (count == 0) { newupdateWeatherInfoView(R.id.weather_1, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], ""); newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 1) { newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], ""); newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[0], ""); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else { } count = 5; } count = 5; } while_ctr++; } /////////////Closing the soft keypad//////////////// InputMethodManager iMethodMgr = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); iMethodMgr.hideSoftInputFromWindow(edt.getWindowToken(), 0); } catch (Exception e) { resetWeatherInfoViews(); Log.e(DEBUG_TAG, "WeatherQueryError", e); } } }); }
From source file:com.neovisionaries.security.DigestTest.java
@Test public void test10() { ByteBuffer byteBuffer = ByteBuffer.allocate(10); byteBuffer.put(new byte[] { 1, 2, 3, 4, 5 }); byteBuffer.flip();/* w w w. j av a2 s . c o m*/ // Ensure there is no infinite loop. Digest.getInstanceSHA256().update("Hello, world.", new String[] { "Hello", "world" }, Boolean.TRUE, new boolean[] { true, false }, new Boolean[] { Boolean.TRUE, Boolean.FALSE }, Byte.valueOf((byte) 0), new byte[] { (byte) 0, (byte) 1 }, new Byte[] { Byte.valueOf((byte) 0), Byte.valueOf((byte) 1) }, byteBuffer, Character.valueOf('b'), new char[] { 'a', 'b' }, new Character[] { Character.valueOf('a'), Character.valueOf('b') }, Double.valueOf(0.0), new double[] { 0.0, 1.0 }, new Double[] { Double.valueOf(0.0), Double.valueOf(1.0) }, Float.valueOf(0.0F), new float[] { 0.0F, 1.0F }, new Float[] { Float.valueOf(0.0F), Float.valueOf(1.0F) }, Integer.valueOf(1), new int[] { 1, 2 }, new Integer[] { Integer.valueOf(0), Integer.valueOf(1) }, Long.valueOf(0L), new long[] { 0L, 1L }, new Long[] { Long.valueOf(0L), Long.valueOf(1L) }, Short.valueOf((short) 0), new short[] { (short) 0, (short) 1 }, new Short[] { Short.valueOf((short) 0), Short.valueOf((short) 1) }, new Object[] { new boolean[] { true, false }, new byte[] { (byte) 0, (byte) 1 } }, new Object[] { new Object[] { new char[] { 'a', 'b' }, new short[] { 10, 20 } }, new Object[] { new float[] { 1.0F, 2.0F }, new double[] { 3.0, 4.0 } } }); assertTrue(true); }
From source file:com.silverpeas.projectManager.model.TaskDetail.java
public void setCharge(String f) { if (f != null && f.length() > 0) { charge = Float.valueOf(f); } else {/* w ww . j av a2 s .com*/ charge = 0; } }
From source file:org.alfresco.serializers.PropertiesTypeConverter.java
@SuppressWarnings("rawtypes") private PropertiesTypeConverter() { ////from ww w. j ava 2s .co m // From string // addConverter(String.class, Class.class, new TypeConverter.Converter<String, Class>() { public Class convert(String source) { try { return Class.forName(source); } catch (ClassNotFoundException e) { throw new TypeConversionException("Failed to convert string to class: " + source, e); } } }); addConverter(String.class, Boolean.class, new TypeConverter.Converter<String, Boolean>() { public Boolean convert(String source) { return Boolean.valueOf(source); } }); addConverter(String.class, Character.class, new TypeConverter.Converter<String, Character>() { public Character convert(String source) { if ((source == null) || (source.length() == 0)) { return null; } return Character.valueOf(source.charAt(0)); } }); addConverter(String.class, Number.class, new TypeConverter.Converter<String, Number>() { public Number convert(String source) { try { return DecimalFormat.getNumberInstance().parse(source); } catch (ParseException e) { throw new TypeConversionException("Failed to parse number " + source, e); } } }); addConverter(String.class, Byte.class, new TypeConverter.Converter<String, Byte>() { public Byte convert(String source) { return Byte.valueOf(source); } }); addConverter(String.class, Short.class, new TypeConverter.Converter<String, Short>() { public Short convert(String source) { return Short.valueOf(source); } }); addConverter(String.class, Integer.class, new TypeConverter.Converter<String, Integer>() { public Integer convert(String source) { return Integer.valueOf(source); } }); addConverter(String.class, Long.class, new TypeConverter.Converter<String, Long>() { public Long convert(String source) { return Long.valueOf(source); } }); addConverter(String.class, Float.class, new TypeConverter.Converter<String, Float>() { public Float convert(String source) { return Float.valueOf(source); } }); addConverter(String.class, Double.class, new TypeConverter.Converter<String, Double>() { public Double convert(String source) { return Double.valueOf(source); } }); addConverter(String.class, BigInteger.class, new TypeConverter.Converter<String, BigInteger>() { public BigInteger convert(String source) { return new BigInteger(source); } }); addConverter(String.class, BigDecimal.class, new TypeConverter.Converter<String, BigDecimal>() { public BigDecimal convert(String source) { return new BigDecimal(source); } }); addConverter(JSON.class, BigDecimal.class, new TypeConverter.Converter<JSON, BigDecimal>() { public BigDecimal convert(JSON source) { String type = (String) source.get("t"); if (type.equals("FIXED_POINT")) { String number = (String) source.get("n"); Integer precision = (Integer) source.get("p"); MathContext ctx = new MathContext(precision); return new BigDecimal(number, ctx); } else { throw new IllegalArgumentException( "Invalid source object for conversion " + source + ", expected a Fixed Decimal object"); } } }); addConverter(String.class, Date.class, new TypeConverter.Converter<String, Date>() { public Date convert(String source) { try { Date date = ISO8601DateFormat.parse(source); return date; } catch (PlatformRuntimeException e) { throw new TypeConversionException("Failed to convert date " + source + " to string", e); } catch (AlfrescoRuntimeException e) { throw new TypeConversionException("Failed to convert date " + source + " to string", e); } } }); addConverter(String.class, Duration.class, new TypeConverter.Converter<String, Duration>() { public Duration convert(String source) { return new Duration(source); } }); addConverter(String.class, QName.class, new TypeConverter.Converter<String, QName>() { public QName convert(String source) { return QName.createQName(source); } }); addConverter(JSON.class, QName.class, new TypeConverter.Converter<JSON, QName>() { public QName convert(JSON source) { String type = (String) source.get("t"); if (type.equals("QNAME")) { String qname = (String) source.get("v"); return QName.createQName(qname); } else { throw new IllegalArgumentException(); } } }); addConverter(String.class, ContentData.class, new TypeConverter.Converter<String, ContentData>() { public ContentData convert(String source) { return ContentData.createContentProperty(source); } }); addConverter(String.class, NodeRef.class, new TypeConverter.Converter<String, NodeRef>() { public NodeRef convert(String source) { return new NodeRef(source); } }); addConverter(JSON.class, NodeRef.class, new TypeConverter.Converter<JSON, NodeRef>() { public NodeRef convert(JSON source) { String type = (String) source.get("t"); if (!type.equals("NODEREF")) { throw new IllegalArgumentException( "Invalid source object for conversion " + source + ", expected a NodeRef object"); } String protocol = (String) source.get("p"); String storeId = (String) source.get("s"); String id = (String) source.get("id"); NodeRef nodeRef = new NodeRef(new StoreRef(protocol, storeId), id); return nodeRef; } }); addConverter(String.class, StoreRef.class, new TypeConverter.Converter<String, StoreRef>() { public StoreRef convert(String source) { return new StoreRef(source); } }); addConverter(JSON.class, StoreRef.class, new TypeConverter.Converter<JSON, StoreRef>() { public StoreRef convert(JSON source) { String type = (String) source.get("t"); if (!type.equals("STOREREF")) { throw new IllegalArgumentException( "Invalid source object for conversion " + source + ", expected a StoreRef object"); } String protocol = (String) source.get("p"); String storeId = (String) source.get("s"); return new StoreRef(protocol, storeId); } }); addConverter(String.class, ChildAssociationRef.class, new TypeConverter.Converter<String, ChildAssociationRef>() { public ChildAssociationRef convert(String source) { return new ChildAssociationRef(source); } }); addConverter(String.class, AssociationRef.class, new TypeConverter.Converter<String, AssociationRef>() { public AssociationRef convert(String source) { return new AssociationRef(source); } }); addConverter(String.class, InputStream.class, new TypeConverter.Converter<String, InputStream>() { public InputStream convert(String source) { try { return new ByteArrayInputStream(source.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new TypeConversionException("Encoding not supported", e); } } }); addConverter(String.class, MLText.class, new TypeConverter.Converter<String, MLText>() { public MLText convert(String source) { return new MLText(source); } }); addConverter(JSON.class, MLText.class, new TypeConverter.Converter<JSON, MLText>() { public MLText convert(JSON source) { String type = (String) source.get("t"); if (!type.equals("MLTEXT")) { throw new IllegalArgumentException( "Invalid source object for conversion " + source + ", expected a NodeRef object"); } MLText mlText = new MLText(); for (String languageTag : source.keySet()) { String text = (String) source.get(languageTag); Locale locale = Locale.forLanguageTag(languageTag); mlText.put(locale, text); } return mlText; } }); // addConverter(JSON.class, ContentDataWithId.class, new TypeConverter.Converter<JSON, ContentDataWithId>() // { // public ContentDataWithId convert(JSON source) // { // String type = (String)source.get("t"); // if(!type.equals("CONTENT_DATA_ID")) // { // throw new IllegalArgumentException("Invalid source object for conversion " // + source // + ", expected a ContentDataWithId object"); // } // String contentUrl = (String)source.get("u"); // String mimeType = (String)source.get("m"); // Long size = (Long)source.get("s"); // String encoding = (String)source.get("e"); // String languageTag = (String)source.get("l"); // Long id = (Long)source.get("id"); // Locale locale = Locale.forLanguageTag(languageTag); // // ContentData contentData = new ContentData(contentUrl, mimeType, size, encoding, locale); // ContentDataWithId contentDataWithId = new ContentDataWithId(contentData, id); // return contentDataWithId; // } // }); addConverter(JSON.class, ContentData.class, new TypeConverter.Converter<JSON, ContentData>() { public ContentData convert(JSON source) { ContentData contentData = null; String type = (String) source.get("t"); if (type.equals("CONTENT")) { String contentUrl = (String) source.get("u"); String mimeType = (String) source.get("m"); Long size = (Long) source.get("s"); String encoding = (String) source.get("e"); String languageTag = (String) source.get("l"); Locale locale = Locale.forLanguageTag(languageTag); contentData = new ContentData(contentUrl, mimeType, size, encoding, locale); } else if (type.equals("CONTENT_DATA_ID")) { String contentUrl = (String) source.get("u"); String mimeType = (String) source.get("m"); Long size = (Long) source.get("s"); String encoding = (String) source.get("e"); String languageTag = (String) source.get("l"); Locale locale = Locale.forLanguageTag(languageTag); contentData = new ContentData(contentUrl, mimeType, size, encoding, locale); } else { throw new IllegalArgumentException( "Invalid source object for conversion " + source + ", expected a ContentData object"); } return contentData; } }); addConverter(JSON.class, String.class, new TypeConverter.Converter<JSON, String>() { public String convert(JSON source) { // TODO distinguish between different BasicDBObject representations e.g. for MLText, ... Set<String> languageTags = source.keySet(); if (languageTags.size() == 0) { throw new IllegalArgumentException("Persisted MLText is invalid " + source); } else if (languageTags.size() > 1) { // TODO logger.warn("Persisted MLText has more than 1 locale " + source); } String languageTag = languageTags.iterator().next(); String text = (String) source.get(languageTag); return text; } }); addConverter(String.class, Locale.class, new TypeConverter.Converter<String, Locale>() { public Locale convert(String source) { return I18NUtil.parseLocale(source); } }); addConverter(String.class, Period.class, new TypeConverter.Converter<String, Period>() { public Period convert(String source) { return new Period(source); } }); addConverter(String.class, VersionNumber.class, new TypeConverter.Converter<String, VersionNumber>() { public VersionNumber convert(String source) { return new VersionNumber(source); } }); // // From Locale // addConverter(Locale.class, String.class, new TypeConverter.Converter<Locale, String>() { public String convert(Locale source) { String localeStr = source.toString(); if (localeStr.length() < 6) { localeStr += "_"; } return localeStr; } }); // // From VersionNumber // addConverter(VersionNumber.class, String.class, new TypeConverter.Converter<VersionNumber, String>() { public String convert(VersionNumber source) { return source.toString(); } }); // // From MLText // addConverter(MLText.class, String.class, new TypeConverter.Converter<MLText, String>() { public String convert(MLText source) { return source.getDefaultValue(); } }); addConverter(MLText.class, JSON.class, new TypeConverter.Converter<MLText, JSON>() { public JSON convert(MLText source) { JSON map = new JSON(); map.put("t", "MLTEXT"); for (Map.Entry<Locale, String> entry : source.entrySet()) { map.put(entry.getKey().toLanguageTag(), entry.getValue()); } return map; } }); // addConverter(ContentDataWithId.class, JSON.class, new TypeConverter.Converter<ContentDataWithId, JSON>() // { // public JSON convert(ContentDataWithId source) // { // JSON map = new JSON(); // // String contentUrl = source.getContentUrl(); // Long id = source.getId(); // String languageTag = source.getLocale().toLanguageTag(); // String encoding = source.getEncoding(); // long size = source.getSize(); // String mimeType = source.getMimetype(); // // map.put("t", "CONTENT_DATA_ID"); // map.put("u", contentUrl); // map.put("m", mimeType); // map.put("s", size); // map.put("e", encoding); // map.put("l", languageTag); // map.put("id", id); // return map; // } // }); addConverter(ContentData.class, JSON.class, new TypeConverter.Converter<ContentData, JSON>() { public JSON convert(ContentData source) { JSON map = new JSON(); String contentUrl = source.getContentUrl(); String languageTag = source.getLocale().toLanguageTag(); String encoding = source.getEncoding(); long size = source.getSize(); String mimeType = source.getMimetype(); map.put("t", "CONTENT_DATA"); map.put("u", contentUrl); map.put("m", mimeType); map.put("s", size); map.put("e", encoding); map.put("l", languageTag); return map; } }); // // From enum // addConverter(Enum.class, String.class, new TypeConverter.Converter<Enum, String>() { public String convert(Enum source) { return source.toString(); } }); // From Period addConverter(Period.class, String.class, new TypeConverter.Converter<Period, String>() { public String convert(Period source) { return source.toString(); } }); // From Class addConverter(Class.class, String.class, new TypeConverter.Converter<Class, String>() { public String convert(Class source) { return source.getName(); } }); // // Number to Subtypes and Date // addConverter(Number.class, Boolean.class, new TypeConverter.Converter<Number, Boolean>() { public Boolean convert(Number source) { return new Boolean(source.longValue() > 0); } }); addConverter(Number.class, Byte.class, new TypeConverter.Converter<Number, Byte>() { public Byte convert(Number source) { return Byte.valueOf(source.byteValue()); } }); addConverter(Number.class, Short.class, new TypeConverter.Converter<Number, Short>() { public Short convert(Number source) { return Short.valueOf(source.shortValue()); } }); addConverter(Number.class, Integer.class, new TypeConverter.Converter<Number, Integer>() { public Integer convert(Number source) { return Integer.valueOf(source.intValue()); } }); addConverter(Number.class, Long.class, new TypeConverter.Converter<Number, Long>() { public Long convert(Number source) { return Long.valueOf(source.longValue()); } }); addConverter(Number.class, Float.class, new TypeConverter.Converter<Number, Float>() { public Float convert(Number source) { return Float.valueOf(source.floatValue()); } }); addConverter(Number.class, Double.class, new TypeConverter.Converter<Number, Double>() { public Double convert(Number source) { return Double.valueOf(source.doubleValue()); } }); addConverter(Number.class, Date.class, new TypeConverter.Converter<Number, Date>() { public Date convert(Number source) { return new Date(source.longValue()); } }); addConverter(Number.class, String.class, new TypeConverter.Converter<Number, String>() { public String convert(Number source) { return source.toString(); } }); addConverter(Number.class, BigInteger.class, new TypeConverter.Converter<Number, BigInteger>() { public BigInteger convert(Number source) { if (source instanceof BigDecimal) { return ((BigDecimal) source).toBigInteger(); } else { return BigInteger.valueOf(source.longValue()); } } }); addConverter(Number.class, BigDecimal.class, new TypeConverter.Converter<Number, BigDecimal>() { public BigDecimal convert(Number source) { if (source instanceof BigInteger) { return new BigDecimal((BigInteger) source); } else if (source instanceof Double) { return BigDecimal.valueOf((Double) source); } else if (source instanceof Float) { Float val = (Float) source; if (val.isInfinite()) { // What else can we do here? this is 3.4 E 38 so is fairly big return new BigDecimal(Float.MAX_VALUE); } return BigDecimal.valueOf((Float) source); } else { return BigDecimal.valueOf(source.longValue()); } } }); addDynamicTwoStageConverter(Number.class, String.class, InputStream.class); // // Date, Timestamp -> // addConverter(Timestamp.class, Date.class, new TypeConverter.Converter<Timestamp, Date>() { public Date convert(Timestamp source) { return new Date(source.getTime()); } }); addConverter(Date.class, Number.class, new TypeConverter.Converter<Date, Number>() { public Number convert(Date source) { return Long.valueOf(source.getTime()); } }); addConverter(Date.class, String.class, new TypeConverter.Converter<Date, String>() { public String convert(Date source) { try { return ISO8601DateFormat.format(source); } catch (PlatformRuntimeException e) { throw new TypeConversionException("Failed to convert date " + source + " to string", e); } } }); addConverter(Date.class, Calendar.class, new TypeConverter.Converter<Date, Calendar>() { public Calendar convert(Date source) { Calendar calendar = Calendar.getInstance(); calendar.setTime(source); return calendar; } }); addConverter(Date.class, GregorianCalendar.class, new TypeConverter.Converter<Date, GregorianCalendar>() { public GregorianCalendar convert(Date source) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(source); return calendar; } }); addDynamicTwoStageConverter(Date.class, String.class, InputStream.class); // // Boolean -> // final Long LONG_FALSE = new Long(0L); final Long LONG_TRUE = new Long(1L); addConverter(Boolean.class, Long.class, new TypeConverter.Converter<Boolean, Long>() { public Long convert(Boolean source) { return source.booleanValue() ? LONG_TRUE : LONG_FALSE; } }); addConverter(Boolean.class, String.class, new TypeConverter.Converter<Boolean, String>() { public String convert(Boolean source) { return source.toString(); } }); addDynamicTwoStageConverter(Boolean.class, String.class, InputStream.class); // // Character -> // addConverter(Character.class, String.class, new TypeConverter.Converter<Character, String>() { public String convert(Character source) { return source.toString(); } }); addDynamicTwoStageConverter(Character.class, String.class, InputStream.class); // // Duration -> // addConverter(Duration.class, String.class, new TypeConverter.Converter<Duration, String>() { public String convert(Duration source) { return source.toString(); } }); addDynamicTwoStageConverter(Duration.class, String.class, InputStream.class); // // Byte // addConverter(Byte.class, String.class, new TypeConverter.Converter<Byte, String>() { public String convert(Byte source) { return source.toString(); } }); addDynamicTwoStageConverter(Byte.class, String.class, InputStream.class); // // Short // addConverter(Short.class, String.class, new TypeConverter.Converter<Short, String>() { public String convert(Short source) { return source.toString(); } }); addDynamicTwoStageConverter(Short.class, String.class, InputStream.class); // // Integer // addConverter(Integer.class, String.class, new TypeConverter.Converter<Integer, String>() { public String convert(Integer source) { return source.toString(); } }); addDynamicTwoStageConverter(Integer.class, String.class, InputStream.class); // // Long // addConverter(Long.class, String.class, new TypeConverter.Converter<Long, String>() { public String convert(Long source) { return source.toString(); } }); addDynamicTwoStageConverter(Long.class, String.class, InputStream.class); // // Float // addConverter(Float.class, String.class, new TypeConverter.Converter<Float, String>() { public String convert(Float source) { return source.toString(); } }); addDynamicTwoStageConverter(Float.class, String.class, InputStream.class); // // Double // addConverter(Double.class, String.class, new TypeConverter.Converter<Double, String>() { public String convert(Double source) { return source.toString(); } }); addDynamicTwoStageConverter(Double.class, String.class, InputStream.class); // // BigInteger // addConverter(BigInteger.class, String.class, new TypeConverter.Converter<BigInteger, String>() { public String convert(BigInteger source) { return source.toString(); } }); addDynamicTwoStageConverter(BigInteger.class, String.class, InputStream.class); // // Calendar // addConverter(Calendar.class, Date.class, new TypeConverter.Converter<Calendar, Date>() { public Date convert(Calendar source) { return source.getTime(); } }); addConverter(Calendar.class, String.class, new TypeConverter.Converter<Calendar, String>() { public String convert(Calendar source) { try { return ISO8601DateFormat.format(source.getTime()); } catch (PlatformRuntimeException e) { throw new TypeConversionException("Failed to convert date " + source + " to string", e); } } }); // // BigDecimal // addConverter(BigDecimal.class, JSON.class, new TypeConverter.Converter<BigDecimal, JSON>() { public JSON convert(BigDecimal source) { String number = source.toPlainString(); int precision = source.precision(); JSON map = new JSON(); map.put("t", "FIXED_POINT"); map.put("n", number); map.put("p", precision); return map; } }); addConverter(BigDecimal.class, String.class, new TypeConverter.Converter<BigDecimal, String>() { public String convert(BigDecimal source) { return source.toString(); } }); addDynamicTwoStageConverter(BigDecimal.class, String.class, InputStream.class); // // QName // addConverter(QName.class, String.class, new TypeConverter.Converter<QName, String>() { public String convert(QName source) { return source.toString(); } }); addDynamicTwoStageConverter(QName.class, String.class, InputStream.class); // // EntityRef (NodeRef, ChildAssociationRef, NodeAssociationRef) // addConverter(EntityRef.class, String.class, new TypeConverter.Converter<EntityRef, String>() { public String convert(EntityRef source) { return source.toString(); } }); addConverter(EntityRef.class, JSON.class, new TypeConverter.Converter<EntityRef, JSON>() { public JSON convert(EntityRef source) { JSON ret = null; if (source instanceof NodeRef) { NodeRef nodeRef = (NodeRef) source; JSON map = new JSON(); map.put("t", "NODEREF"); map.put("p", nodeRef.getStoreRef().getProtocol()); map.put("s", nodeRef.getStoreRef().getIdentifier()); map.put("id", nodeRef.getId()); ret = map; } else if (source instanceof StoreRef) { StoreRef storeRef = (StoreRef) source; JSON map = new JSON(); map.put("t", "STOREREF"); map.put("p", storeRef.getProtocol()); map.put("s", storeRef.getIdentifier()); ret = map; } else { throw new IllegalArgumentException(); } return ret; } }); addDynamicTwoStageConverter(EntityRef.class, String.class, InputStream.class); // // ContentData // addConverter(ContentData.class, String.class, new TypeConverter.Converter<ContentData, String>() { public String convert(ContentData source) { return source.getInfoUrl(); } }); addDynamicTwoStageConverter(ContentData.class, String.class, InputStream.class); // // Path // addConverter(Path.class, String.class, new TypeConverter.Converter<Path, String>() { public String convert(Path source) { return source.toString(); } }); addDynamicTwoStageConverter(Path.class, String.class, InputStream.class); // // Content Reader // addConverter(ContentReader.class, InputStream.class, new TypeConverter.Converter<ContentReader, InputStream>() { public InputStream convert(ContentReader source) { return source.getContentInputStream(); } }); addConverter(ContentReader.class, String.class, new TypeConverter.Converter<ContentReader, String>() { public String convert(ContentReader source) { // Getting the string from the ContentReader binary is meaningless return source.toString(); } }); // // Content Writer // addConverter(ContentWriter.class, String.class, new TypeConverter.Converter<ContentWriter, String>() { public String convert(ContentWriter source) { return source.toString(); } }); // addConverter(Collection.class, BasicDBList.class, new TypeConverter.Converter<Collection, BasicDBList>() // { // public BasicDBList convert(Collection source) // { // BasicDBList ret = new BasicDBList(); // for(Object o : source) // { // ret.add(o); // } // return ret; // } // }); // addConverter(BasicDBList.class, Collection.class, new TypeConverter.Converter<BasicDBList, Collection>() // { // @SuppressWarnings("unchecked") // public Collection convert(BasicDBList source) // { // Collection ret = new LinkedList(); // for(Object o : source) // { // ret.add(o); // } // return ret; // } // }); // // Input Stream // addConverter(InputStream.class, String.class, new TypeConverter.Converter<InputStream, String>() { public String convert(InputStream source) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int read; while ((read = source.read(buffer)) > 0) { out.write(buffer, 0, read); } byte[] data = out.toByteArray(); return new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new TypeConversionException("Cannot convert input stream to String.", e); } catch (IOException e) { throw new TypeConversionException("Conversion from stream to string failed", e); } finally { if (source != null) { try { source.close(); } catch (IOException e) { //NOOP } } } } }); addDynamicTwoStageConverter(InputStream.class, String.class, Date.class); addDynamicTwoStageConverter(InputStream.class, String.class, Double.class); addDynamicTwoStageConverter(InputStream.class, String.class, Long.class); addDynamicTwoStageConverter(InputStream.class, String.class, Boolean.class); addDynamicTwoStageConverter(InputStream.class, String.class, QName.class); addDynamicTwoStageConverter(InputStream.class, String.class, Path.class); addDynamicTwoStageConverter(InputStream.class, String.class, NodeRef.class); }
From source file:org.syncope.core.util.ImportExport.java
private void setParameters(final String tableName, final Attributes atts, final Query query) { Map<String, Integer> colTypes = new HashMap<String, Integer>(); Connection conn = DataSourceUtils.getConnection(dataSource); ResultSet rs = null;// www.j a v a 2 s.c o m Statement stmt = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM " + tableName); for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { colTypes.put(rs.getMetaData().getColumnName(i + 1).toUpperCase(), rs.getMetaData().getColumnType(i + 1)); } } catch (SQLException e) { LOG.error("While", e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { LOG.error("While closing statement", e); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing result set", e); } } DataSourceUtils.releaseConnection(conn, dataSource); } for (int i = 0; i < atts.getLength(); i++) { Integer colType = colTypes.get(atts.getQName(i).toUpperCase()); if (colType == null) { LOG.warn("No column type found for {}", atts.getQName(i).toUpperCase()); colType = Types.VARCHAR; } switch (colType) { case Types.NUMERIC: case Types.REAL: case Types.INTEGER: case Types.TINYINT: try { query.setParameter(i + 1, Integer.valueOf(atts.getValue(i))); } catch (NumberFormatException e) { LOG.error("Unparsable Integer '{}'", atts.getValue(i)); query.setParameter(i + 1, atts.getValue(i)); } break; case Types.DECIMAL: case Types.BIGINT: try { query.setParameter(i + 1, Long.valueOf(atts.getValue(i))); } catch (NumberFormatException e) { LOG.error("Unparsable Long '{}'", atts.getValue(i)); query.setParameter(i + 1, atts.getValue(i)); } break; case Types.DOUBLE: try { query.setParameter(i + 1, Double.valueOf(atts.getValue(i))); } catch (NumberFormatException e) { LOG.error("Unparsable Double '{}'", atts.getValue(i)); query.setParameter(i + 1, atts.getValue(i)); } break; case Types.FLOAT: try { query.setParameter(i + 1, Float.valueOf(atts.getValue(i))); } catch (NumberFormatException e) { LOG.error("Unparsable Float '{}'", atts.getValue(i)); query.setParameter(i + 1, atts.getValue(i)); } break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: try { query.setParameter(i + 1, DateUtils.parseDate(atts.getValue(i), SyncopeConstants.DATE_PATTERNS), TemporalType.TIMESTAMP); } catch (ParseException e) { LOG.error("Unparsable Date '{}'", atts.getValue(i)); query.setParameter(i + 1, atts.getValue(i)); } break; case Types.BIT: case Types.BOOLEAN: query.setParameter(i + 1, "1".equals(atts.getValue(i)) ? Boolean.TRUE : Boolean.FALSE); break; default: query.setParameter(i + 1, atts.getValue(i)); } } }
From source file:com.lyft.hive.serde.DynamoDbSerDe.java
@Override public Object deserialize(Writable blob) throws SerDeException { ArrayList<Object> row = buildRow(); Text rowText = (Text) blob; Map<String, String> values = decomposeRow(rowText.toString()); for (int c = 0; c < numColumns; c++) { try {//from w ww .j a v a2 s . c o m String t = values.get(columnNames.get(c)); TypeInfo typeInfo = columnTypes.get(c); // Convert the column to the correct type when needed and set in row obj PrimitiveTypeInfo pti = (PrimitiveTypeInfo) typeInfo; switch (pti.getPrimitiveCategory()) { case STRING: row.set(c, t); break; case BYTE: Byte b; b = Byte.valueOf(t); row.set(c, b); break; case SHORT: Short s; s = Short.valueOf(t); row.set(c, s); break; case INT: Integer i; i = Integer.valueOf(t); row.set(c, i); break; case LONG: Long l; l = Long.valueOf(t); row.set(c, l); break; case FLOAT: Float f; f = Float.valueOf(t); row.set(c, f); break; case DOUBLE: Double d; d = Double.valueOf(t); row.set(c, d); break; case BOOLEAN: Boolean bool; bool = Boolean.valueOf(t); row.set(c, bool); break; case TIMESTAMP: row.set(c, parseTimestamp(t)); break; case DATE: Date date; date = Date.valueOf(t); row.set(c, date); break; case DECIMAL: HiveDecimal bd = HiveDecimal.create(t); row.set(c, bd); break; case CHAR: HiveChar hc = new HiveChar(t, ((CharTypeInfo) typeInfo).getLength()); row.set(c, hc); break; case VARCHAR: HiveVarchar hv = new HiveVarchar(t, ((VarcharTypeInfo) typeInfo).getLength()); row.set(c, hv); break; default: throw new SerDeException("Unsupported type " + typeInfo); } } catch (RuntimeException e) { row.set(c, null); } } return row; }