List of usage examples for java.lang Enum valueOf
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
From source file:com.alliander.osgp.acceptancetests.devicemonitoring.GetPowerUsageHistorySteps.java
@DomainStep("a get power usage history response message with correlationId (.*), deviceId (.*), qresult (.*), qdescription (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) is found in the queue (.*)") public void givenAGetPowerUsageHistoryResponseMessageIsFoundInQueue(final String correlationId, final String deviceId, final String qresult, final String qdescription, final String fromDate, final String untilDate, final String recordTime, final String meterType, final String totalConsumedEnergy, final String actualConsumedPower, final String psldDataTotalLightHours, final String actualCurrent1, final String actualCurrent2, final String actualCurrent3, final String actualPower1, final String actualPower2, final String actualPower3, final String averagePowerFactor1, final String averagePowerFactor2, final String averagePowerFactor3, final String relayData1Index, final String relayData1LightingMinutes, final String relayData2Index, final String relayData2LightingMinutes, final Boolean isFound) throws ParseException { LOGGER.info(// w w w. j a va 2 s . c o m "GIVEN: \"a get power usage history response message with correlationId {}, deviceId {}, qresult {} and qdescription {} is found {}\".", correlationId, deviceId, qresult, qdescription, isFound); if (isFound) { final ObjectMessage messageMock = mock(ObjectMessage.class); try { when(messageMock.getJMSCorrelationID()).thenReturn(correlationId); when(messageMock.getStringProperty("OrganisationIdentification")).thenReturn(ORGANISATION_ID); when(messageMock.getStringProperty("DeviceIdentification")).thenReturn(deviceId); final MeterType metertype = StringUtils.isBlank(meterType) ? null : Enum.valueOf(MeterType.class, meterType); DateTime dateTime = null; if (!recordTime.equals("")) { final Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(recordTime); dateTime = new DateTime(date); } final com.alliander.osgp.domain.core.valueobjects.PowerUsageData powerUsageData = new com.alliander.osgp.domain.core.valueobjects.PowerUsageData( dateTime, metertype, Long.parseLong(totalConsumedEnergy), Long.parseLong(actualConsumedPower)); final List<com.alliander.osgp.domain.core.valueobjects.RelayData> list = new ArrayList<>(); list.add(new com.alliander.osgp.domain.core.valueobjects.RelayData(Integer.valueOf(relayData1Index), Integer.valueOf(relayData1LightingMinutes))); list.add(new com.alliander.osgp.domain.core.valueobjects.RelayData(Integer.valueOf(relayData2Index), Integer.valueOf(relayData2LightingMinutes))); final com.alliander.osgp.domain.core.valueobjects.SsldData ssldData = new com.alliander.osgp.domain.core.valueobjects.SsldData( Integer.valueOf(actualCurrent1), Integer.valueOf(actualCurrent2), Integer.valueOf(actualCurrent3), Integer.valueOf(actualPower1), Integer.valueOf(actualPower2), Integer.valueOf(actualPower3), Integer.valueOf(averagePowerFactor1), Integer.valueOf(averagePowerFactor2), Integer.valueOf(averagePowerFactor3), list); powerUsageData.setSsldData(ssldData); final List<com.alliander.osgp.domain.core.valueobjects.PowerUsageData> powerUsageDatas = new ArrayList<com.alliander.osgp.domain.core.valueobjects.PowerUsageData>(); powerUsageDatas.add(powerUsageData); final com.alliander.osgp.domain.core.valueobjects.PowerUsageHistoryResponse powerUsageHistoryResponse = new com.alliander.osgp.domain.core.valueobjects.PowerUsageHistoryResponse( powerUsageDatas); final ResponseMessage message = new ResponseMessage(correlationId, ORGANISATION_ID, deviceId, ResponseMessageResultType.valueOf(qresult), null, powerUsageHistoryResponse); when(messageMock.getObject()).thenReturn(message); } catch (final JMSException e) { LOGGER.error("JMSException", e); } when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))) .thenReturn(messageMock); } else { when(this.publicLightingResponsesJmsTemplate.receiveSelected(any(String.class))).thenReturn(null); } }
From source file:com.dngames.mobilewebcam.PhotoSettings.java
@Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key == "cam_refresh") { int new_refresh = getEditInt(mContext, prefs, "cam_refresh", 60); String msg = "Camera refresh set to " + new_refresh + " seconds!"; if (MobileWebCam.gIsRunning) { if (!mNoToasts && new_refresh != mRefreshDuration) { try { Toast.makeText(mContext.getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } catch (RuntimeException e) { e.printStackTrace(); }//www.ja v a 2 s.c o m } } else if (new_refresh != mRefreshDuration) { MobileWebCam.LogI(msg); } } // get all preferences for (Field f : getClass().getFields()) { { BooleanPref bp = f.getAnnotation(BooleanPref.class); if (bp != null) { try { f.setBoolean(this, prefs.getBoolean(bp.key(), bp.val())); } catch (Exception e) { Log.e("MobileWebCam", "Exception: " + bp.key() + " <- " + bp.val()); e.printStackTrace(); } } } { EditIntPref ip = f.getAnnotation(EditIntPref.class); if (ip != null) { try { int eval = getEditInt(mContext, prefs, ip.key(), ip.val()) * ip.factor(); if (ip.max() != Integer.MAX_VALUE) eval = Math.min(eval, ip.max()); if (ip.min() != Integer.MIN_VALUE) eval = Math.max(eval, ip.min()); f.setInt(this, eval); } catch (Exception e) { e.printStackTrace(); } } } { IntPref ip = f.getAnnotation(IntPref.class); if (ip != null) { try { int eval = prefs.getInt(ip.key(), ip.val()) * ip.factor(); if (ip.max() != Integer.MAX_VALUE) eval = Math.min(eval, ip.max()); if (ip.min() != Integer.MIN_VALUE) eval = Math.max(eval, ip.min()); f.setInt(this, eval); } catch (Exception e) { // handle wrong set class e.printStackTrace(); Editor edit = prefs.edit(); edit.remove(ip.key()); edit.putInt(ip.key(), ip.val()); edit.commit(); try { f.setInt(this, ip.val()); } catch (IllegalArgumentException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } } } } { EditFloatPref fp = f.getAnnotation(EditFloatPref.class); if (fp != null) { try { float eval = getEditFloat(mContext, prefs, fp.key(), fp.val()); if (fp.max() != Float.MAX_VALUE) eval = Math.min(eval, fp.max()); if (fp.min() != Float.MIN_VALUE) eval = Math.max(eval, fp.min()); f.setFloat(this, eval); } catch (Exception e) { e.printStackTrace(); } } } { StringPref sp = f.getAnnotation(StringPref.class); if (sp != null) { try { f.set(this, prefs.getString(sp.key(), getDefaultString(mContext, sp))); } catch (Exception e) { e.printStackTrace(); } } } } mCustomImageScale = Enum.valueOf(ImageScaleMode.class, prefs.getString("custompicscale", "CROP")); mAutoStart = prefs.getBoolean("autostart", false); mCameraStartupEnabled = prefs.getBoolean("cam_autostart", true); mShutterSound = prefs.getBoolean("shutter", true); mDateTimeColor = GetPrefColor(prefs, "datetime_color", "#FFFFFFFF", Color.WHITE); mDateTimeShadowColor = GetPrefColor(prefs, "datetime_shadowcolor", "#FF000000", Color.BLACK); mDateTimeBackgroundColor = GetPrefColor(prefs, "datetime_backcolor", "#80FF0000", Color.argb(0x80, 0xFF, 0x00, 0x00)); mDateTimeBackgroundLine = prefs.getBoolean("datetime_fillline", true); mDateTimeX = prefs.getInt("datetime_x", 98); mDateTimeY = prefs.getInt("datetime_y", 98); mDateTimeAlign = Paint.Align.valueOf(prefs.getString("datetime_imprintalign", "RIGHT")); mDateTimeFontScale = (float) prefs.getInt("datetime_fontsize", 6); mTextColor = GetPrefColor(prefs, "text_color", "#FFFFFFFF", Color.WHITE); mTextShadowColor = GetPrefColor(prefs, "text_shadowcolor", "#FF000000", Color.BLACK); mTextBackgroundColor = GetPrefColor(prefs, "text_backcolor", "#80FF0000", Color.argb(0x80, 0xFF, 0x00, 0x00)); mTextBackgroundLine = prefs.getBoolean("text_fillline", true); mTextX = prefs.getInt("text_x", 2); mTextY = prefs.getInt("text_y", 2); mTextAlign = Paint.Align.valueOf(prefs.getString("text_imprintalign", "LEFT")); mTextFontScale = (float) prefs.getInt("infotext_fontsize", 6); mTextFontname = prefs.getString("infotext_fonttypeface", ""); mStatusInfoColor = GetPrefColor(prefs, "statusinfo_color", "#FFFFFFFF", Color.WHITE); mStatusInfoShadowColor = GetPrefColor(prefs, "statusinfo_shadowcolor", "#FF000000", Color.BLACK); mStatusInfoX = prefs.getInt("statusinfo_x", 2); mStatusInfoY = prefs.getInt("statusinfo_y", 98); mStatusInfoAlign = Paint.Align.valueOf(prefs.getString("statusinfo_imprintalign", "LEFT")); mStatusInfoBackgroundColor = GetPrefColor(prefs, "statusinfo_backcolor", "#00000000", Color.TRANSPARENT); mStatusInfoFontScale = (float) prefs.getInt("statusinfo_fontsize", 6); mStatusInfoBackgroundLine = prefs.getBoolean("statusinfo_fillline", false); mGPSColor = GetPrefColor(prefs, "gps_color", "#FFFFFFFF", Color.WHITE); mGPSShadowColor = GetPrefColor(prefs, "gps_shadowcolor", "#FF000000", Color.BLACK); mGPSX = prefs.getInt("gps_x", 98); mGPSY = prefs.getInt("gps_y", 2); mGPSAlign = Paint.Align.valueOf(prefs.getString("gps_imprintalign", "RIGHT")); mGPSBackgroundColor = GetPrefColor(prefs, "gps_backcolor", "#00000000", Color.TRANSPARENT); mGPSFontScale = (float) prefs.getInt("gps_fontsize", 6); mGPSBackgroundLine = prefs.getBoolean("gps_fillline", false); mImprintPictureX = prefs.getInt("imprint_picture_x", 0); mImprintPictureY = prefs.getInt("imprint_picture_y", 0); mNightAutoConfigEnabled = prefs.getBoolean("night_auto_enabled", false); mSetNightConfiguration = prefs.getBoolean("cam_nightconfiguration", false); // override night camera parameters (read again with postfix) getCurrentNightSettings(); mFilterPicture = false; //***prefs.getBoolean("filter_picture", false); mFilterType = getEditInt(mContext, prefs, "filter_sel", 0); if (mImprintPicture) { if (mImprintPictureURL.length() == 0) { // sdcard image File path = new File(Environment.getExternalStorageDirectory() + "/MobileWebCam/"); if (path.exists()) { synchronized (gImprintBitmapLock) { if (gImprintBitmap != null) gImprintBitmap.recycle(); gImprintBitmap = null; File file = new File(path, "imprint.png"); try { FileInputStream in = new FileInputStream(file); gImprintBitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e) { Toast.makeText(mContext, "Error: unable to read imprint bitmap " + file.getName() + "!", Toast.LENGTH_SHORT).show(); gImprintBitmap = null; } catch (OutOfMemoryError e) { Toast.makeText(mContext, "Error: imprint bitmap " + file.getName() + " too large!", Toast.LENGTH_LONG).show(); gImprintBitmap = null; } } } } else { DownloadImprintBitmap(); } synchronized (gImprintBitmapLock) { if (gImprintBitmap == null) { // last resort: resource default try { gImprintBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.imprint); } catch (OutOfMemoryError e) { Toast.makeText(mContext, "Error: default imprint bitmap too large!", Toast.LENGTH_LONG) .show(); gImprintBitmap = null; } } } } mNoToasts = prefs.getBoolean("no_messages", false); mFullWakeLock = prefs.getBoolean("full_wakelock", true); switch (getEditInt(mContext, prefs, "camera_mode", 1)) { case 0: mMode = Mode.MANUAL; break; case 2: mMode = Mode.HIDDEN; break; case 3: mMode = Mode.BACKGROUND; break; case 1: default: mMode = Mode.NORMAL; break; } }
From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java
/** * Read a {@link Writable}, {@link String}, primitive type, or an array of * the preceding.//from w ww . jav a 2 s . c om * @param in * @param objectWritable * @param conf * @return the object * @throws IOException */ @SuppressWarnings("unchecked") static Object readObject(DataInput in, HbaseObjectWritableFor96Migration objectWritable, Configuration conf) throws IOException { Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in)); Object instance; if (declaredClass.isPrimitive()) { // primitive types if (declaredClass == Boolean.TYPE) { // boolean instance = Boolean.valueOf(in.readBoolean()); } else if (declaredClass == Character.TYPE) { // char instance = Character.valueOf(in.readChar()); } else if (declaredClass == Byte.TYPE) { // byte instance = Byte.valueOf(in.readByte()); } else if (declaredClass == Short.TYPE) { // short instance = Short.valueOf(in.readShort()); } else if (declaredClass == Integer.TYPE) { // int instance = Integer.valueOf(in.readInt()); } else if (declaredClass == Long.TYPE) { // long instance = Long.valueOf(in.readLong()); } else if (declaredClass == Float.TYPE) { // float instance = Float.valueOf(in.readFloat()); } else if (declaredClass == Double.TYPE) { // double instance = Double.valueOf(in.readDouble()); } else if (declaredClass == Void.TYPE) { // void instance = null; } else { throw new IllegalArgumentException("Not a primitive: " + declaredClass); } } else if (declaredClass.isArray()) { // array if (declaredClass.equals(byte[].class)) { instance = Bytes.readByteArray(in); } else { int length = in.readInt(); instance = Array.newInstance(declaredClass.getComponentType(), length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE Class<?> componentType = readClass(conf, in); int length = in.readInt(); instance = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } else if (List.class.isAssignableFrom(declaredClass)) { // List int length = in.readInt(); instance = new ArrayList(length); for (int i = 0; i < length; i++) { ((ArrayList) instance).add(readObject(in, conf)); } } else if (declaredClass == String.class) { // String instance = Text.readString(in); } else if (declaredClass.isEnum()) { // enum instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in)); } else if (declaredClass == Message.class) { String className = Text.readString(in); try { declaredClass = getClassByName(conf, className); instance = tryInstantiateProtobuf(declaredClass, in); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else if (Scan.class.isAssignableFrom(declaredClass)) { int length = in.readInt(); byte[] scanBytes = new byte[length]; in.readFully(scanBytes); ClientProtos.Scan.Builder scanProto = ClientProtos.Scan.newBuilder(); instance = ProtobufUtil.toScan(scanProto.mergeFrom(scanBytes).build()); } else { // Writable or Serializable Class instanceClass = null; int b = (byte) WritableUtils.readVInt(in); if (b == NOT_ENCODED) { String className = Text.readString(in); try { instanceClass = getClassByName(conf, className); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else { instanceClass = CODE_TO_CLASS.get(b); } if (Writable.class.isAssignableFrom(instanceClass)) { Writable writable = WritableFactories.newInstance(instanceClass, conf); try { writable.readFields(in); } catch (Exception e) { LOG.error("Error in readFields", e); throw new IOException("Error in readFields", e); } instance = writable; if (instanceClass == NullInstance.class) { // null declaredClass = ((NullInstance) instance).declaredClass; instance = null; } } else { int length = in.readInt(); byte[] objectBytes = new byte[length]; in.readFully(objectBytes); ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(objectBytes); ois = new ObjectInputStream(bis); instance = ois.readObject(); } catch (ClassNotFoundException e) { LOG.error("Class not found when attempting to deserialize object", e); throw new IOException("Class not found when attempting to " + "deserialize object", e); } finally { if (bis != null) bis.close(); if (ois != null) ois.close(); } } } if (objectWritable != null) { // store values objectWritable.declaredClass = declaredClass; objectWritable.instance = instance; } return instance; }
From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java
/** * Read a {@link Writable}, {@link String}, primitive type, or an array of * the preceding.//from w w w . ja va 2 s . co m * @param in * @param objectWritable * @param conf * @return the object * @throws IOException */ @SuppressWarnings("unchecked") public static Object readObject(DataInput in, HbaseObjectWritable objectWritable, Configuration conf) throws IOException { Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in)); Object instance; if (declaredClass.isPrimitive()) { // primitive types if (declaredClass == Boolean.TYPE) { // boolean instance = Boolean.valueOf(in.readBoolean()); } else if (declaredClass == Character.TYPE) { // char instance = Character.valueOf(in.readChar()); } else if (declaredClass == Byte.TYPE) { // byte instance = Byte.valueOf(in.readByte()); } else if (declaredClass == Short.TYPE) { // short instance = Short.valueOf(in.readShort()); } else if (declaredClass == Integer.TYPE) { // int instance = Integer.valueOf(in.readInt()); } else if (declaredClass == Long.TYPE) { // long instance = Long.valueOf(in.readLong()); } else if (declaredClass == Float.TYPE) { // float instance = Float.valueOf(in.readFloat()); } else if (declaredClass == Double.TYPE) { // double instance = Double.valueOf(in.readDouble()); } else if (declaredClass == Void.TYPE) { // void instance = null; } else { throw new IllegalArgumentException("Not a primitive: " + declaredClass); } } else if (declaredClass.isArray()) { // array if (declaredClass.equals(byte[].class)) { instance = Bytes.readByteArray(in); } else if (declaredClass.equals(Result[].class)) { instance = Result.readArray(in); } else { int length = in.readInt(); instance = Array.newInstance(declaredClass.getComponentType(), length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE Class<?> componentType = readClass(conf, in); int length = in.readInt(); instance = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } else if (List.class.isAssignableFrom(declaredClass)) { // List int length = in.readInt(); instance = new ArrayList(length); for (int i = 0; i < length; i++) { ((ArrayList) instance).add(readObject(in, conf)); } } else if (declaredClass == String.class) { // String instance = Text.readString(in); } else if (declaredClass.isEnum()) { // enum instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in)); } else if (declaredClass == Message.class) { String className = Text.readString(in); try { declaredClass = getClassByName(conf, className); instance = tryInstantiateProtobuf(declaredClass, in); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else { // Writable or Serializable Class instanceClass = null; int b = (byte) WritableUtils.readVInt(in); if (b == NOT_ENCODED) { String className = Text.readString(in); try { instanceClass = getClassByName(conf, className); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else { instanceClass = CODE_TO_CLASS.get(b); } if (Writable.class.isAssignableFrom(instanceClass)) { Writable writable = WritableFactories.newInstance(instanceClass, conf); try { writable.readFields(in); } catch (Exception e) { LOG.error("Error in readFields", e); throw new IOException("Error in readFields", e); } instance = writable; if (instanceClass == NullInstance.class) { // null declaredClass = ((NullInstance) instance).declaredClass; instance = null; } } else { int length = in.readInt(); byte[] objectBytes = new byte[length]; in.readFully(objectBytes); ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(objectBytes); ois = new ObjectInputStream(bis); instance = ois.readObject(); } catch (ClassNotFoundException e) { LOG.error("Class not found when attempting to deserialize object", e); throw new IOException("Class not found when attempting to " + "deserialize object", e); } finally { if (bis != null) bis.close(); if (ois != null) ois.close(); } } } if (objectWritable != null) { // store values objectWritable.declaredClass = declaredClass; objectWritable.instance = instance; } return instance; }
From source file:com.mtbs3d.minecrift.settings.VRSettings.java
public void loadOptions(JSONObject theProfiles) { // Load Minecrift options try {/*from www .j a va2 s .co m*/ ProfileReader optionsVRReader = new ProfileReader(ProfileManager.PROFILE_SET_VR, theProfiles); String var2 = ""; while ((var2 = optionsVRReader.readLine()) != null) { try { String[] optionTokens = var2.split(":"); if (optionTokens[0].equals("version")) { this.version = Integer.parseInt(optionTokens[1]); } // if (optionTokens[0].equals("firstLoad")) // { // this.firstLoad = optionTokens[1].equals("true"); // } if (optionTokens[0].equals("stereoProviderPluginID")) { this.stereoProviderPluginID = optionTokens[1]; } if (optionTokens[0].equals("badStereoProviderPluginID")) { if (optionTokens.length > 1) { // Trap if no entry this.badStereoProviderPluginID = optionTokens[1]; } } if (optionTokens[0].equals("hudOpacity")) { this.hudOpacity = this.parseFloat(optionTokens[1]); if (hudOpacity < 0.15f) hudOpacity = 1.0f; } if (optionTokens[0].equals("menuBackground")) { this.menuBackground = optionTokens[1].equals("true"); } if (optionTokens[0].equals("renderFullFirstPersonModelMode")) { this.renderFullFirstPersonModelMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("shaderIndex")) { this.shaderIndex = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("walkUpBlocks")) { this.walkUpBlocks = optionTokens[1].equals("true"); } if (optionTokens[0].equals("displayMirrorMode")) { this.displayMirrorMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("mixedRealityKeyColor")) { String[] split = optionTokens[1].split(","); this.mixedRealityKeyColor = new Color(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])); } if (optionTokens[0].equals("mixedRealityRenderHands")) { this.mixedRealityRenderHands = optionTokens[1].equals("true"); } if (optionTokens[0].equals("mixedRealityUnityLike")) { this.mixedRealityUnityLike = optionTokens[1].equals("true"); } if (optionTokens[0].equals("mixedRealityUndistorted")) { this.mixedRealityMRPlusUndistorted = optionTokens[1].equals("true"); } if (optionTokens[0].equals("mixedRealityAlphaMask")) { this.mixedRealityAlphaMask = optionTokens[1].equals("true"); } if (optionTokens[0].equals("mixedRealityFov")) { this.mixedRealityFov = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("insideBlockSolidColor")) { this.insideBlockSolidColor = optionTokens[1].equals("true"); } if (optionTokens[0].equals("hudScale")) { this.hudScale = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("renderScaleFactor")) { this.renderScaleFactor = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrHudLockMode")) { this.vrHudLockMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("hudDistance")) { this.hudDistance = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("hudPitchOffset")) { this.hudPitchOffset = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("hudYawOffset")) { this.hudYawOffset = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("useFsaa")) { this.useFsaa = optionTokens[1].equals("true"); } if (optionTokens[0].equals("movementSpeedMultiplier")) { this.movementSpeedMultiplier = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("renderInGameCrosshairMode")) { this.renderInGameCrosshairMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("renderBlockOutlineMode")) { this.renderBlockOutlineMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("crosshairScale")) { this.crosshairScale = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("menuCrosshairScale")) { this.menuCrosshairScale = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("renderInGameCrosshairMode")) { this.renderInGameCrosshairMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("renderBlockOutlineMode")) { this.renderBlockOutlineMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("hudOcclusion")) { this.hudOcclusion = optionTokens[1].equals("true"); } if (optionTokens[0].equals("menuAlwaysFollowFace")) { this.menuAlwaysFollowFace = optionTokens[1].equals("true"); } if (optionTokens[0].equals("useCrosshairOcclusion")) { this.useCrosshairOcclusion = optionTokens[1].equals("true"); } if (optionTokens[0].equals("inertiaFactor")) { this.inertiaFactor = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("smoothRunTickCount")) { this.smoothRunTickCount = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("smoothTick")) { this.smoothTick = optionTokens[1].equals("true"); } if (optionTokens[0].equals("hideGui")) { this.hideGui = optionTokens[1].equals("true"); } // VIVE START - new options if (optionTokens[0].equals("simulateFalling")) { this.simulateFalling = optionTokens[1].equals("true"); } if (optionTokens[0].equals("weaponCollision")) { this.weaponCollision = optionTokens[1].equals("true"); } if (optionTokens[0].equals("animalTouching")) { this.animaltouching = optionTokens[1].equals("true"); } // VIVE END - new options //JRBUDDA if (optionTokens[0].equals("allowCrawling")) { this.vrAllowCrawling = optionTokens[1].equals("true"); } if (optionTokens[0].equals("allowModeSwitch")) { this.vrAllowLocoModeSwotch = optionTokens[1].equals("true"); } if (optionTokens[0].equals("freeMoveDefault")) { this.vrFreeMove = optionTokens[1].equals("true"); } if (optionTokens[0].equals("limitedTeleport")) { this.vrLimitedSurvivalTeleport = optionTokens[1].equals("true"); } if (optionTokens[0].equals("reverseHands")) { this.vrReverseHands = optionTokens[1].equals("true"); } if (optionTokens[0].equals("stencilOn")) { this.vrUseStencil = optionTokens[1].equals("true"); } if (optionTokens[0].equals("bcbOn")) { this.vrShowBlueCircleBuddy = optionTokens[1].equals("true"); } if (optionTokens[0].equals("worldScale")) { this.vrWorldScale = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("worldRotation")) { this.vrWorldRotation = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrWorldRotationIncrement")) { this.vrWorldRotationIncrement = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrFixedCamposX")) { this.vrFixedCamposX = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrFixedCamposY")) { this.vrFixedCamposY = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrFixedCamposZ")) { this.vrFixedCamposZ = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrFixedCamrotPitch")) { this.vrFixedCamrotPitch = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrFixedCamrotYaw")) { this.vrFixedCamrotYaw = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrFixedCamrotRoll")) { this.vrFixedCamrotRoll = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("mrMovingCamOffsetX")) { this.mrMovingCamOffsetX = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("mrMovingCamOffsetY")) { this.mrMovingCamOffsetY = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("mrMovingCamOffsetZ")) { this.mrMovingCamOffsetZ = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("mrMovingCamOffsetPitch")) { this.mrMovingCamOffsetPitch = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("mrMovingCamOffsetYaw")) { this.mrMovingCamOffsetYaw = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("mrMovingCamOffsetRoll")) { this.mrMovingCamOffsetRoll = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrTouchHotbar")) { this.vrTouchHotbar = optionTokens[1].equals("true"); } if (optionTokens[0].equals("seated")) { this.seated = optionTokens[1].equals("true"); } if (optionTokens[0].equals("jumpThreshold")) { this.jumpThreshold = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("sneakThreshold")) { this.sneakThreshold = this.parseFloat(optionTokens[1]); } if (optionTokens[0].equals("realisticSneakEnabled")) { this.realisticSneakEnabled = optionTokens[1].equals("true"); } if (optionTokens[0].equals("seatedhmd")) { this.seatedUseHMD = optionTokens[1].equals("true"); } if (optionTokens[0].equals("realisticJumpEnabled")) { this.realisticJumpEnabled = optionTokens[1].equals("true"); } if (optionTokens[0].equals("realisticClimbEnabled")) { this.realisticClimbEnabled = optionTokens[1].equals("true"); } if (optionTokens[0].equals("realisticSwimEnabled")) { this.realisticSwimEnabled = optionTokens[1].equals("true"); } if (optionTokens[0].equals("realisticRowEnabled")) { this.realisticRowEnabled = optionTokens[1].equals("true"); } if (optionTokens[0].equals("headToHmdLength")) { this.headToHmdLength = parseFloat(optionTokens[1]); } if (optionTokens[0].equals("walkMultiplier")) { this.walkMultiplier = parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vrFreeMoveMode")) { this.vrFreeMoveMode = Integer.parseInt(optionTokens[1]); } if (optionTokens[0].equals("xSensitivity")) { this.xSensitivity = parseFloat(optionTokens[1]); } if (optionTokens[0].equals("ySensitivity")) { this.ySensitivity = parseFloat(optionTokens[1]); } if (optionTokens[0].equals("keyholeX")) { this.keyholeX = parseFloat(optionTokens[1]); } if (optionTokens[0].equals("autoCalibration")) { this.autoCalibration = parseFloat(optionTokens[1]); } if (optionTokens[0].equals("manualCalibration")) { this.manualCalibration = parseFloat(optionTokens[1]); } if (optionTokens[0].equals("vehicleRotation")) { this.vehicleRotation = optionTokens[1].equals("true"); } if (optionTokens[0].equals("fovReduction")) { this.useFOVReduction = optionTokens[1].equals("true"); } if (optionTokens[0].startsWith("BUTTON_") || optionTokens[0].startsWith("OCULUS_")) { VRControllerButtonMapping vb = new VRControllerButtonMapping( Enum.valueOf(ViveButtons.class, optionTokens[0]), ""); String[] pts = optionTokens[1].split("_"); if (pts.length == 1 || !optionTokens[1].startsWith("keyboard")) { vb.FunctionDesc = optionTokens[1]; vb.FunctionExt = 0; } else { vb.FunctionDesc = pts[0]; vb.FunctionExt = (char) pts[1].getBytes()[0]; } this.buttonMappings[vb.Button.ordinal()] = vb; } if (optionTokens[0].startsWith("QUICKCOMMAND_")) { String[] pts = optionTokens[0].split("_"); int i = Integer.parseInt(pts[1]); if (optionTokens.length == 1) vrQuickCommands[i] = ""; else vrQuickCommands[i] = optionTokens[1]; } //END JRBUDDA } catch (Exception var7) { logger.warn("Skipping bad VR option: " + var2); var7.printStackTrace(); } } optionsVRReader.close(); } catch (Exception var8) { logger.warn("Failed to load VR options!"); var8.printStackTrace(); } }
From source file:module.workflow.presentationTier.actions.ProcessManagement.java
public ActionForward viewTypeDescription(final ActionMapping mapping, final ActionForm form, final HttpServletRequest request, final HttpServletResponse response) throws IOException { String classname = request.getParameter("classname"); int indexOfInnerClassInEnum = classname.indexOf("$"); if (indexOfInnerClassInEnum > 0) { classname = classname.substring(0, indexOfInnerClassInEnum); }/*from ww w. j av a2 s . com*/ PresentableProcessState type; try { Class<Enum> stateEnum = (Class<Enum>) Class.forName(classname); type = (PresentableProcessState) Enum.valueOf(stateEnum, request.getParameter("type")); } catch (Exception e) { e.printStackTrace(); return null; } request.setAttribute("name", type.getLocalizedName()); JsonObject reply = new JsonObject(); reply.addProperty("name", type.getLocalizedName()); reply.addProperty("description", type.getDescription()); try (OutputStream outputStream = response.getOutputStream()) { byte[] jsonReply = reply.toString().getBytes(); response.setContentType("text"); response.setContentLength(jsonReply.length); outputStream.write(jsonReply); outputStream.flush(); } return null; }
From source file:org.smf4j.spring.RegistryNodeTemplateDefinitionParser.java
protected Object getFrequency(ParserContext context, Element element, String freq) { Class<Enum> frequencyClass; try {/*from w ww.j a va2s . c o m*/ frequencyClass = (Class<Enum>) Class.forName(FREQUENCY_CLASS); } catch (ClassNotFoundException e) { context.getReaderContext().error("Unable to load Frequency class '" + FREQUENCY_CLASS + "'", context.extractSource(element)); return null; } Object frequency = null; if (StringUtils.hasLength(freq)) { try { frequency = Enum.valueOf(frequencyClass, freq.toUpperCase()); } catch (IllegalArgumentException e) { context.getReaderContext().error("Unknown frequency '" + freq + "'", context.extractSource(element)); return null; } } return frequency; }
From source file:com.github.dozermapper.core.MappingProcessor.java
private <T extends Enum<T>> T mapEnum(Enum<T> srcFieldValue, Class<T> destFieldType) { String name = srcFieldValue.name(); return Enum.valueOf(getSerializableEnumClass(destFieldType), name); }
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from ww w. ja v a 2 s . c o m printRequest(request); sessionId.set(request.getSession().getId()); String dataSource = request.getParameter("_dataSource"); // List grid export if ("export".equals(request.getParameter("_operationType"))) { exportData(dataSource, response); return; } response.setContentType("text/plain;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "-1"); if ("getMenu".equals(dataSource)) { response.getWriter().write(listServices()); } else if ("userInfo".equals(dataSource)) { ServiceContext ctx = ServiceContextStore.get(); PrintWriter out = response.getWriter(); out.print(ctx.getUserId()); for (String role : ctx.getRoles()) { out.print(","); out.print(role); } out.flush(); } else if ("createDataSource".equals(dataSource)) { HashMap<String, String> classToServiceName = new HashMap<String, String>(); for (ServiceDescription serviceDesc : getServiceDescription()) { log.log(Level.INFO, "Service translation from {0} to {1}", new Object[] { serviceDesc.getExpectedClass().getName(), serviceDesc.getName() }); classToServiceName.put(serviceDesc.getExpectedClass().getName(), serviceDesc.getName()); } GuiDataSourceService dataSourceService = getGuiDataSourceService(); dataSourceService.setServiceMapping(ServiceContextStore.get(), classToServiceName); StringBuilder output = new StringBuilder(); output.append("dataSources###"); List<GuiDataSource> allDataSources = dataSourceService.findAll(ServiceContextStore.get()); for (GuiDataSource dataSourceDef : allDataSources) { ds2Ref.put(dataSourceDef.getBaseClass(), dataSourceDef.getTitleField()); dataSourceDef.setBaseClass(null); log.log(Level.INFO, "Entity def for {0}", dataSourceDef.getXxxID()); dataSourceDef.setDataURL(getServiceUrl(request)); output.append("$wnd.isc.RestDataSource.create(") .append(mapObjToOutput(dataSourceDef, 6, new Stack<Object>(), true, false)) .append(");\n"); } ListSettingsService listInstance = (ListSettingsService) findService(LIST_SETTINGS_SERVICE) .getInstance(); List<ListSettings> guiList = listInstance.findUserSettings(ServiceContextStore.get()); for (ListSettings listSettings : guiList) { output.append("\n###").append(listSettings.getListID()).append("###") .append(listSettings.getSettings()); } log.log(Level.INFO, "Create datasource {0}", output.toString()); response.getWriter().append(output); } else if (findService(dataSource) != null) { ServiceDescription serviceDesc = findService(dataSource); String operationType = request.getParameter("_operationType"); String methodName = request.getParameter("_operationId"); if (methodName != null && !methodName.endsWith("_fetch")) { log.log(Level.FINER, "Executing method '" + dataSource + "." + methodName + "'"); MethodDescription methodDescription = serviceDesc.getOtherMethods().get(methodName); if (methodDescription != null) { Object valObj = null; HashMap<String, Object> jsData = unifyRequest(request); Object[] params = prepareMethodParam(jsData, true, methodDescription.parameterNames, methodDescription.method.getParameterTypes()); // Resolve "ids" for iterations int iterate = -1; if (jsData.get("ids") != null) { Class<?>[] paramTypes = methodDescription.method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { if (Long.class.equals(paramTypes[i]) || paramTypes[i].equals(Long.TYPE) && methodDescription.parameterNames[i].equals("id") && params[i] == null) { iterate = i; break; } else if (Collection.class.isAssignableFrom(paramTypes[i]) && methodDescription.parameterNames[i].equals("ids") && params[i] == null) { List<Long> longList = new ArrayList<Long>(); String ids = (String) jsData.get("ids"); String[] idSplit = ids.split(","); for (int k = 0; k < idSplit.length; k++) { if (idSplit[i].length() > 0) { longList.add(Long.parseLong(idSplit[i])); } } params[i] = longList; break; } } } if (iterate != -1) { if (log.isLoggable(Level.FINER)) { for (int j = 0; j < params.length; j++) { log.log(Level.FINER, " Parameter[{0}]={1}", new Object[] { j, params[j] }); } } String ids = (String) jsData.get("ids"); String[] idSplit = ids.split(","); ArrayList<Object> listResult = new ArrayList<Object>(); valObj = listResult; for (int i = 0; i < idSplit.length; i++) { if (idSplit[i].length() > 0) { params[iterate] = Long.parseLong(idSplit[i]); Object subValObj = methodDescription.method.invoke(serviceDesc.getInstance(), params); if (subValObj != null && subValObj instanceof Collection) { listResult.addAll((Collection) subValObj); } else if (subValObj != null) { listResult.add(subValObj); } } } log.info("Return value: " + valObj); } else if (params != null) { if (log.isLoggable(Level.FINER)) { for (int j = 0; j < params.length; j++) { log.log(Level.FINER, " Parameter[{0}]={1}", new Object[] { j, params[j] }); } } valObj = methodDescription.method.invoke(serviceDesc.getInstance(), params); log.info("Return value: " + valObj); } Collection<Object> collResult; PagedResult<?> pagedResult = null; if (valObj == null) { collResult = new ArrayList<Object>(); for (int i = 0; i < params.length; i++) { if (params[i] != null && params[i].getClass().equals(serviceDesc.getExpectedClass())) { collResult.add(params[i]); break; } } } else if (valObj instanceof Collection) { collResult = (Collection) valObj; } else if (valObj instanceof PagedResult) { collResult = null; pagedResult = (PagedResult) valObj; } else { ArrayList<Object> serviceResultArray = new ArrayList<Object>(); serviceResultArray.add(valObj); collResult = serviceResultArray; } if (collResult != null) { sendResponse(response.getWriter(), 0, collResult.size(), collResult); } else if (pagedResult != null) { sendResponse(response.getWriter(), pagedResult); } } else { throw new IllegalArgumentException( "No " + methodName + " operation available on " + dataSource); } } else if (operationType == null) { throw makeApplicationException("Unsupported operation", "ERR9001", "NULL"); } else if (operationType.equals("fetch") && request.getParameter("id") != null) { Long idVal = Long.parseLong(request.getParameter("id")); if (serviceDesc.getFindById() != null) { Object serviceResult = serviceDesc.getFindById().invoke(serviceDesc.getInstance(), ServiceContextStore.get(), idVal); ArrayList<Object> serviceResultArray = new ArrayList<Object>(); serviceResultArray.add(serviceResult); sendResponse(response.getWriter(), 0, 1, serviceResultArray); } else { throw new IllegalArgumentException("No fetch operation available"); } } else if (operationType.equals("fetch")) { List<?> serviceResult; PagedResult<?> pagedServiceResult = null; String sRow = request.getParameter("_startRow"); int startRow = sRow == null ? 0 : Integer.parseInt(sRow); String eRow = request.getParameter("_endRow"); int endRow = eRow == null ? 0 : Integer.parseInt(eRow); ArrayList<String> queryParams = new ArrayList(); Enumeration pNames = request.getParameterNames(); while (pNames.hasMoreElements()) { String paramName = (String) pNames.nextElement(); if (!paramName.startsWith("_")) { queryParams.add(paramName); } else if ("_sortBy".equals(paramName)) { queryParams.add("sortBy"); } } if (queryParams.size() > 0) { Collection<MethodDescription> methods = serviceDesc.getOtherMethods().values(); MethodDescription matchedMethod = null; int matchLength = 1000; for (MethodDescription method : methods) { String[] methodParamNames = method.parameterNames; if (methodParamNames != null && methodParamNames.length >= queryParams.size() && (List.class.isAssignableFrom(method.method.getReturnType()) || PagedResult.class.isAssignableFrom(method.method.getReturnType()))) { boolean matchParam = false; for (String queryParam : queryParams) { matchParam = false; for (String methodParamName : methodParamNames) { if (queryParam.equals(methodParamName)) { matchParam = true; break; } } if (!matchParam) { break; } } if (matchParam && method.parameterNames.length < matchLength) { matchedMethod = method; matchLength = method.parameterNames.length; } } } Object[] params = null; if (matchedMethod != null) { HashMap<String, Object> jsData = unifyRequest(request); params = prepareMethodParam(jsData, true, matchedMethod.parameterNames, matchedMethod.method.getParameterTypes()); } else { List<ConditionalCriteria> conditions = new ArrayList(); for (MethodDescription method : methods) { if (method.getMethodName().equals("findByCondition")) { Class<?>[] parameterTypes = method.method.getParameterTypes(); if (List.class.isAssignableFrom(parameterTypes[0])) { params = new Object[] { conditions }; matchedMethod = method; break; } else if (parameterTypes.length == 3 && ServiceContext.class.isAssignableFrom(parameterTypes[0]) && List.class.isAssignableFrom(parameterTypes[1]) && PagingParameter.class.isAssignableFrom(parameterTypes[2])) { endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow; PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD); params = new Object[] { ServiceContextStore.get(), conditions, pagingParam }; matchedMethod = method; break; } else if (parameterTypes.length == 2 && ServiceContext.class.isAssignableFrom(parameterTypes[0]) && List.class.isAssignableFrom(parameterTypes[1])) { params = new Object[] { ServiceContextStore.get(), conditions }; matchedMethod = method; break; } } } if (matchedMethod != null) { for (String queryParam : queryParams) { LeafProperty<?> queryProp = new LeafProperty(queryParam, ScServlet.class); String matchStyle = request.getParameter("_textMatchStyle"); String queryValue = request.getParameter(queryParam); if (queryParam.equals("sortBy")) { queryValue = normalizeAssoc(serviceDesc, request.getParameter("_sortBy")); if (queryValue.startsWith("+")) { LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1), ScServlet.class); conditions.add(ConditionalCriteria.orderAsc(sortProp)); } else if (queryValue.startsWith("-")) { LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1), ScServlet.class); conditions.add(ConditionalCriteria.orderDesc(sortProp)); } else { LeafProperty<?> sortProp = new LeafProperty(queryValue, ScServlet.class); conditions.add(ConditionalCriteria.orderAsc(sortProp)); } } else if (queryValue.indexOf('%') != -1) { conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp, request.getParameter(queryParam) + "%")); } else { String[] queryParamSplit = queryParam.split("\\."); Class watchClass = serviceDesc.getExpectedClass(); Object otherEqVal = null; boolean isString = false; for (String queryParamPart : queryParamSplit) { try { Method method = watchClass.getMethod( makeGetMethodName(queryParamPart), (Class[]) null); watchClass = method.getReturnType(); if (Collection.class.isAssignableFrom(watchClass)) { // TODO look deeper into class of collection break; } else if (Enum.class.isAssignableFrom(watchClass)) { otherEqVal = Enum.valueOf(watchClass, queryValue); break; } else if (String.class.equals(watchClass)) { isString = true; break; } else if (Long.class.equals(watchClass)) { isString = true; otherEqVal = Long.parseLong(queryValue); break; } else if (Integer.class.equals(watchClass)) { isString = true; otherEqVal = Integer.parseInt(queryValue); break; } else if (Double.class.equals(watchClass)) { isString = true; otherEqVal = Double.parseDouble(queryValue); break; } else if (Date.class.equals(watchClass)) { otherEqVal = dateFormat.parse(queryValue); break; } else if (findServiceByClassName(watchClass.getName()) != null && "null".equals(queryValue)) { otherEqVal = "null"; break; } else if (findServiceByClassName(watchClass.getName()) != null && findServiceByClassName(watchClass.getName()) .getFindById() != null) { ServiceDescription srvc = findServiceByClassName( watchClass.getName()); otherEqVal = srvc.getFindById().invoke(srvc.getInstance(), ServiceContextStore.get(), Long.parseLong(queryValue)); } } catch (NoSuchMethodException nsme) { // Ignore error, isString will stay false break; } } boolean isLike = "substring".equals(matchStyle) || "startsWith".equals(matchStyle); if ("null".equals(otherEqVal)) { conditions.add(ConditionalCriteria.isNull(queryProp)); } else if (otherEqVal instanceof Date) { DateMidnight start = (new DateTime(otherEqVal)).toDateMidnight(); DateMidnight stop = start.plusDays(1); conditions.add(ConditionalCriteria.between(queryProp, start.toDate(), stop.toDate())); } else if (isString && otherEqVal != null && isLike) { conditions.add(ConditionalCriteria.like(queryProp, otherEqVal)); } else if (isString && "substring".equals(matchStyle)) { conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp, "%" + request.getParameter(queryParam) + "%")); } else if (isString && "startsWith".equals(matchStyle)) { conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp, request.getParameter(queryParam) + "%")); } else if (otherEqVal != null) { conditions.add(ConditionalCriteria.equal(queryProp, otherEqVal)); } else { conditions.add(ConditionalCriteria.equal(queryProp, queryValue)); } } } } } if (matchedMethod != null && params != null) { for (int j = 0; j < params.length; j++) { log.log(Level.FINER, " Parameter[{0}]={1}", new Object[] { j, params[j] }); } if (matchedMethod.method.getReturnType().equals(PagedResult.class)) { serviceResult = null; pagedServiceResult = (PagedResult) matchedMethod.method .invoke(serviceDesc.getInstance(), params); } else { serviceResult = (List<?>) matchedMethod.method.invoke(serviceDesc.getInstance(), params); } } else { throw makeApplicationException("You can''t filter with such condition.", "ERR9015", (Serializable[]) null); } } else if (queryParams.size() == 0 && serviceDesc.getFindAll() != null) { Class<?>[] paramTypes = serviceDesc.getFindAll().getParameterTypes(); if (paramTypes.length == 2 && paramTypes[0].equals(ServiceContext.class) && paramTypes[1].equals(PagingParameter.class) && serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) { endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow; PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD); pagedServiceResult = (PagedResult<?>) serviceDesc.getFindAll() .invoke(serviceDesc.getInstance(), ServiceContextStore.get(), pagingParam); serviceResult = null; } else if (paramTypes.length == 1 && paramTypes[0].equals(ServiceContext.class)) { serviceResult = (List<? extends Object>) serviceDesc.getFindAll() .invoke(serviceDesc.getInstance(), ServiceContextStore.get()); } else { serviceResult = null; } } else { throw new ApplicationException("", "No fetch operation available"); } if (pagedServiceResult != null) { sendResponse(response.getWriter(), pagedServiceResult); } else { int resultSize = serviceResult == null ? 0 : serviceResult.size(); endRow = (endRow == 0 ? resultSize : endRow); sendResponse(response.getWriter(), startRow, endRow < resultSize ? endRow : resultSize, serviceResult); } } else if (operationType.equals("update") && request.getParameter("id") != null) { Object val = serviceDesc.getFindById().invoke(serviceDesc.getInstance(), ServiceContextStore.get(), Long.parseLong(request.getParameter("id"))); HashMap<String, Object> reqData = unifyRequest(request); mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val); serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(), ServiceContextStore.get(), val); ArrayList<Object> list = new ArrayList<Object>(); list.add(val); sendResponse(response.getWriter(), 0, 1, list); } else if ((operationType.equals("add") || operationType.equals("update")) && request.getParameter("id") == null) { HashMap<String, Object> reqData = unifyRequest(request); Object val = makeNewInstance(serviceDesc.getExpectedClass(), reqData); if (val != null) { mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val); serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(), ServiceContextStore.get(), val); ArrayList<Object> list = new ArrayList<Object>(); list.add(val); sendResponse(response.getWriter(), 0, 1, list); } else { throw makeApplicationException("Can't create new instance", "ERR9003", serviceDesc.getExpectedClass().getName()); } } else { throw makeApplicationException("Unsupported operation", "ERR9001", operationType); } } else { throw makeApplicationException("Wrong datasource name", "ERR9002", dataSource); } } catch (Throwable ex) { // Find most relevant exception in embedded exceptions ApplicationException appException = null; Throwable relevantException = ex; while (ex != null) { relevantException = ex; if (ex instanceof ApplicationException) { appException = (ApplicationException) ex; break; } if (ex instanceof ValidationException) { break; } ex = ex.getCause(); } // Prepare message String msg = null; if (appException != null) { msg = translate(appException.getMessage()); Serializable[] msgParams = appException.getMessageParameters(); if (msgParams != null) { Object[] params = new Object[msgParams.length]; for (int i = 0; i < msgParams.length; i++) { if (msgParams[i] instanceof Translatable) { params[i] = translate(((Translatable) msgParams[i]).getContent()); } else { params[i] = msgParams[i]; } } msg = MessageFormat.format(msg, params); } } else if (relevantException instanceof ValidationException) { StringBuilder b = new StringBuilder(); for (InvalidValue iv : ((ValidationException) relevantException).getInvalidValues()) { b.append("<b>").append(translate(iv.getPropertyName()) + ":</b> " + iv.getMessage()) .append("<br/>"); } msg = b.toString(); } else { msg = translate("ERR9000"); msg = MessageFormat.format(msg, new Object[] { relevantException.getClass().getName(), relevantException.getMessage() }); } // Print stack trace log.log(Level.WARNING, "Relevant exception", relevantException); if (msg != null) { log.log(Level.WARNING, "SENDING BACK ERROR '" + msg + "'"); response.getWriter() .write("{response:{ status:-1, data:\"" + msg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"") + "\", startRow:0, endRow:0, totalRows:0}}"); } response.flushBuffer(); // response.setStatus(HttpServletResponse.SC_NOT_FOUND); throw new ServletException(msg); } response.flushBuffer(); }
From source file:de.xwic.appkit.core.transport.xml.XmlBeanSerializer.java
/** * @param beanType//from w w w . ja va 2 s.co m * @param element * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Object deserializeEnum(final Class beanType, final Element element) { return Enum.valueOf(beanType, element.elementText(ELM_ENUM)); }