List of usage examples for java.util UUID fromString
public static UUID fromString(String name)
From source file:com.github.fedorchuck.webstore.dao.impl.postgresql.JdbcUserRepositoryTest.java
private User getNewUser() { return new User("testUserName", "testPassword", "testUserFirstName", "testUserLastName", "testUser@email", 0, UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d")); }
From source file:edu.stanford.junction.provider.bluetooth.Junction.java
public Junction(URI uri, ActivityScript script, final JunctionActor actor, BluetoothSwitchboardConfig config) throws JunctionException { mConfig = config;/*from www .j av a 2s . c o m*/ mActivityScript = script; mUri = uri; mSwitchboard = uri.getAuthority(); setActor(actor); if (DBG) Log.d(TAG, "doing bluetooth"); if (mSwitchboard.equals(mBtAdapter.getAddress())) { Log.d(TAG, "starting new junction hub"); mIsHub = true; mSession = mConfig.getUuid().toString(); mConnections = new HashSet<ConnectedThread>(); mRemoveConnections = new HashSet<ConnectedThread>(); mAcceptThread = new AcceptThread(); mAcceptThread.start(); } else { Log.d(TAG, "connecting to junction hub: " + mSwitchboard); mIsHub = false; mSession = uri.getPath().substring(1); BluetoothDevice hub = mBtAdapter.getRemoteDevice(mSwitchboard); mConnectThread = new ConnectThread(hub, UUID.fromString(mSession)); mConnectThread.start(); } if (mIsHub) { triggerActorJoin(mIsHub); } else { synchronized (mJoinLock) { if (!mJoinComplete) { try { mJoinLock.wait(12000); } catch (InterruptedException e) { // Ignored } } if (mJoinComplete) { triggerActorJoin(mIsActivityCreator); } else { throw new JunctionException("Failed to join session, handshake not complete."); } } } }
From source file:at.alladin.rmbt.controlServer.ResultResource.java
@Post("json") public String request(final String entity) { final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY"); addAllowOrigin();//from w ww .j a v a 2 s .com JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); System.out.println(MessageFormat.format(labels.getString("NEW_RESULT"), getIP())); if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); System.out.println(request); final String lang = request.optString("client_language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } // System.out.println(request.toString(4)); if (conn != null) { conn.setAutoCommit(false); final Test test = new Test(conn); if (request.optString("test_token").length() > 0) { final String[] token = request.getString("test_token").split("_"); try { // Check if UUID final UUID testUuid = UUID.fromString(token[0]); final String data = token[0] + "_" + token[1]; final String hmac = Helperfunctions.calculateHMAC(secret, data); if (hmac.length() == 0) errorList.addError("ERROR_TEST_TOKEN"); if (token[2].length() > 0 && hmac.equals(token[2])) { final List<String> clientNames = Arrays .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*")); final List<String> clientVersions = Arrays .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*")); if (test.getTestByUuid(testUuid) > 0) if (clientNames.contains(request.optString("client_name")) && clientVersions.contains(request.optString("client_version"))) { test.setFields(request); final String networkOperator = request .optString("telephony_network_operator"); if (MCC_MNC_PATTERN.matcher(networkOperator).matches()) test.getField("network_operator").setString(networkOperator); else test.getField("network_operator").setString(null); final String networkSimOperator = request .optString("telephony_network_sim_operator"); if (MCC_MNC_PATTERN.matcher(networkSimOperator).matches()) test.getField("network_sim_operator").setString(networkSimOperator); else test.getField("network_sim_operator").setString(null); // RMBTClient Info final String ipLocalRaw = request.optString("test_ip_local", null); if (ipLocalRaw != null) { final InetAddress ipLocalAddress = InetAddresses.forString(ipLocalRaw); // original address (not filtered) test.getField("client_ip_local") .setString(InetAddresses.toAddrString(ipLocalAddress)); // anonymized local address final String ipLocalAnonymized = Helperfunctions .anonymizeIp(ipLocalAddress); test.getField("client_ip_local_anonymized") .setString(ipLocalAnonymized); // type of local ip test.getField("client_ip_local_type") .setString(Helperfunctions.IpType(ipLocalAddress)); // public ip final InetAddress ipPublicAddress = InetAddresses .forString(test.getField("client_public_ip").toString()); test.getField("nat_type").setString( Helperfunctions.getNatType(ipLocalAddress, ipPublicAddress)); } final String ipServer = request.optString("test_ip_server", null); if (ipServer != null) { final InetAddress testServerInetAddress = InetAddresses .forString(ipServer); test.getField("server_ip") .setString(InetAddresses.toAddrString(testServerInetAddress)); } //log IP address final String ipSource = getIP(); test.getField("source_ip").setString(ipSource); //log anonymized address try { final InetAddress ipSourceIP = InetAddress.getByName(ipSource); final String ipSourceAnonymized = Helperfunctions .anonymizeIp(ipSourceIP); test.getField("source_ip_anonymized").setString(ipSourceAnonymized); } catch (UnknownHostException e) { System.out.println("Exception thrown:" + e); } // Additional Info ////////////////////////////////////////////////// // extended test stats: ////////////////////////////////////////////////// final TestStat extendedTestStat = TestStat .checkForSubmittedTestStats(request, test.getUid()); if (extendedTestStat != null) { final TestStatDao testStatDao = new TestStatDao(conn); testStatDao.save(extendedTestStat); } ////////////////////////////////////////////////// JSONArray speedData = request.optJSONArray("speed_detail"); if (speedData != null && !test.hasError()) { final PreparedStatement psSpeed = conn.prepareStatement( "INSERT INTO test_speed (test_id, upload, thread, time, bytes) VALUES (?,?,?,?,?)"); psSpeed.setLong(1, test.getUid()); for (int i = 0; i < speedData.length(); i++) { final JSONObject item = speedData.getJSONObject(i); final String direction = item.optString("direction"); if (direction != null && (direction.equals("download") || direction.equals("upload"))) { psSpeed.setBoolean(2, direction.equals("upload")); psSpeed.setInt(3, item.optInt("thread")); psSpeed.setLong(4, item.optLong("time")); psSpeed.setLong(5, item.optLong("bytes")); psSpeed.executeUpdate(); } } } final JSONArray pingData = request.optJSONArray("pings"); if (pingData != null && !test.hasError()) { final PreparedStatement psPing = conn.prepareStatement( "INSERT INTO ping (test_id, value, value_server, time_ns) " + "VALUES(?,?,?,?)"); psPing.setLong(1, test.getUid()); for (int i = 0; i < pingData.length(); i++) { final JSONObject pingDataItem = pingData.getJSONObject(i); long valueClient = pingDataItem.optLong("value", -1); if (valueClient >= 0) psPing.setLong(2, valueClient); else psPing.setNull(2, Types.BIGINT); long valueServer = pingDataItem.optLong("value_server", -1); if (valueServer >= 0) psPing.setLong(3, valueServer); else psPing.setNull(3, Types.BIGINT); long timeNs = pingDataItem.optLong("time_ns", -1); if (timeNs >= 0) psPing.setLong(4, timeNs); else psPing.setNull(4, Types.BIGINT); psPing.executeUpdate(); } } final JSONArray geoData = request.optJSONArray("geoLocations"); if (geoData != null && !test.hasError()) for (int i = 0; i < geoData.length(); i++) { final JSONObject geoDataItem = geoData.getJSONObject(i); if (geoDataItem.optLong("tstamp", 0) != 0 && geoDataItem.optDouble("geo_lat", 0) != 0 && geoDataItem.optDouble("geo_long", 0) != 0) { final GeoLocation geoloc = new GeoLocation(conn); geoloc.setTest_id(test.getUid()); final long clientTime = geoDataItem.optLong("tstamp"); final Timestamp tstamp = java.sql.Timestamp .valueOf(new Timestamp(clientTime).toString()); geoloc.setTime(tstamp, test.getField("timezone").toString()); geoloc.setAccuracy( (float) geoDataItem.optDouble("accuracy", 0)); geoloc.setAltitude(geoDataItem.optDouble("altitude", 0)); geoloc.setBearing((float) geoDataItem.optDouble("bearing", 0)); geoloc.setSpeed((float) geoDataItem.optDouble("speed", 0)); geoloc.setProvider(geoDataItem.optString("provider", "")); geoloc.setGeo_lat(geoDataItem.optDouble("geo_lat", 0)); geoloc.setGeo_long(geoDataItem.optDouble("geo_long", 0)); geoloc.setTime_ns(geoDataItem.optLong("time_ns", 0)); geoloc.storeLocation(); // Store Last Geolocation as // Testlocation if (i == geoData.length() - 1) { if (geoDataItem.has("geo_lat")) test.getField("geo_lat").setField(geoDataItem); if (geoDataItem.has("geo_long")) test.getField("geo_long").setField(geoDataItem); if (geoDataItem.has("accuracy")) test.getField("geo_accuracy").setField(geoDataItem); if (geoDataItem.has("provider")) test.getField("geo_provider").setField(geoDataItem); } if (geoloc.hasError()) { errorList.addError(geoloc.getError()); break; } } } final JSONArray cellData = request.optJSONArray("cellLocations"); if (cellData != null && !test.hasError()) for (int i = 0; i < cellData.length(); i++) { final JSONObject cellDataItem = cellData.getJSONObject(i); final Cell_location cellloc = new Cell_location(conn); cellloc.setTest_id(test.getUid()); final long clientTime = cellDataItem.optLong("time"); final Timestamp tstamp = java.sql.Timestamp .valueOf(new Timestamp(clientTime).toString()); cellloc.setTime(tstamp, test.getField("timezone").toString()); cellloc.setTime_ns(cellDataItem.optLong("time_ns", 0)); cellloc.setLocation_id(cellDataItem.optInt("location_id", 0)); cellloc.setArea_code(cellDataItem.optInt("area_code", 0)); cellloc.setPrimary_scrambling_code( cellDataItem.optInt("primary_scrambling_code", 0)); cellloc.storeLocation(); if (cellloc.hasError()) { errorList.addError(cellloc.getError()); break; } } int signalStrength = Integer.MAX_VALUE; //measured as RSSI (GSM,UMTS,Wifi) int lteRsrp = Integer.MAX_VALUE; // signal strength measured as RSRP int lteRsrq = Integer.MAX_VALUE; // signal quality of LTE measured as RSRQ int linkSpeed = UNKNOWN; final int networkType = test.getField("network_type").intValue(); final JSONArray signalData = request.optJSONArray("signals"); if (signalData != null && !test.hasError()) { for (int i = 0; i < signalData.length(); i++) { final JSONObject signalDataItem = signalData.getJSONObject(i); final Signal signal = new Signal(conn); signal.setTest_id(test.getUid()); final long clientTime = signalDataItem.optLong("time"); final Timestamp tstamp = java.sql.Timestamp .valueOf(new Timestamp(clientTime).toString()); signal.setTime(tstamp, test.getField("timezone").toString()); final int thisNetworkType = signalDataItem.optInt("network_type_id", 0); signal.setNetwork_type_id(thisNetworkType); final int thisSignalStrength = signalDataItem .optInt("signal_strength", UNKNOWN); if (thisSignalStrength != UNKNOWN) signal.setSignal_strength(thisSignalStrength); signal.setGsm_bit_error_rate( signalDataItem.optInt("gsm_bit_error_rate", 0)); final int thisLinkSpeed = signalDataItem.optInt("wifi_link_speed", 0); signal.setWifi_link_speed(thisLinkSpeed); final int rssi = signalDataItem.optInt("wifi_rssi", UNKNOWN); if (rssi != UNKNOWN) signal.setWifi_rssi(rssi); lteRsrp = signalDataItem.optInt("lte_rsrp", UNKNOWN); lteRsrq = signalDataItem.optInt("lte_rsrq", UNKNOWN); final int lteRssnr = signalDataItem.optInt("lte_rssnr", UNKNOWN); final int lteCqi = signalDataItem.optInt("lte_cqi", UNKNOWN); final long timeNs = signalDataItem.optLong("time_ns", UNKNOWN); signal.setLte_rsrp(lteRsrp); signal.setLte_rsrq(lteRsrq); signal.setLte_rssnr(lteRssnr); signal.setLte_cqi(lteCqi); signal.setTime_ns(timeNs); signal.storeSignal(); if (networkType == 99) // wlan { if (rssi < signalStrength && rssi != UNKNOWN) signalStrength = rssi; } else if (thisSignalStrength < signalStrength && thisSignalStrength != UNKNOWN) signalStrength = thisSignalStrength; if (thisLinkSpeed != 0 && (linkSpeed == UNKNOWN || thisLinkSpeed < linkSpeed)) linkSpeed = thisLinkSpeed; if (signal.hasError()) { errorList.addError(signal.getError()); break; } } // set rssi value (typically GSM,UMTS, but also old LTE-phones) if (signalStrength != Integer.MAX_VALUE && signalStrength != UNKNOWN && signalStrength != 0) // 0 dBm is out of range ((IntField) test.getField("signal_strength")) .setValue(signalStrength); // set rsrp value (typically LTE) if (lteRsrp != Integer.MAX_VALUE && lteRsrp != UNKNOWN && lteRsrp != 0) // 0 dBm is out of range ((IntField) test.getField("lte_rsrp")).setValue(lteRsrp); // set rsrq value (LTE) if (lteRsrq != Integer.MAX_VALUE && lteRsrq != UNKNOWN) ((IntField) test.getField("lte_rsrq")).setValue(lteRsrq); if (linkSpeed != Integer.MAX_VALUE && linkSpeed != UNKNOWN) ((IntField) test.getField("wifi_link_speed")).setValue(linkSpeed); } // use max network type final String sqlMaxNetworkType = "SELECT nt.uid" + " FROM signal s" + " JOIN network_type nt" + " ON s.network_type_id=nt.uid" + " WHERE test_id=?" + " ORDER BY nt.technology_order DESC" + " LIMIT 1"; final PreparedStatement psMaxNetworkType = conn .prepareStatement(sqlMaxNetworkType); psMaxNetworkType.setLong(1, test.getUid()); if (psMaxNetworkType.execute()) { final ResultSet rs = psMaxNetworkType.getResultSet(); if (rs.next()) { final int maxNetworkType = rs.getInt("uid"); if (maxNetworkType != 0) ((IntField) test.getField("network_type")) .setValue(maxNetworkType); } } /* * check for different types (e.g. * 2G/3G) */ final String sqlAggSignal = "WITH agg AS" + " (SELECT array_agg(DISTINCT nt.group_name ORDER BY nt.group_name) agg" + " FROM signal s" + " JOIN network_type nt ON s.network_type_id=nt.uid WHERE test_id=?)" + " SELECT uid FROM agg JOIN network_type nt ON nt.aggregate=agg"; final PreparedStatement psAgg = conn.prepareStatement(sqlAggSignal); psAgg.setLong(1, test.getUid()); if (psAgg.execute()) { final ResultSet rs = psAgg.getResultSet(); if (rs.next()) { final int newNetworkType = rs.getInt("uid"); if (newNetworkType != 0) ((IntField) test.getField("network_type")) .setValue(newNetworkType); } } if (test.getField("network_type").intValue() <= 0) errorList.addError("ERROR_NETWORK_TYPE"); final IntField downloadField = (IntField) test.getField("speed_download"); if (downloadField.isNull() || downloadField.intValue() <= 0 || downloadField.intValue() > 10000000) // 10 gbit/s limit errorList.addError("ERROR_DOWNLOAD_INSANE"); final IntField upField = (IntField) test.getField("speed_upload"); if (upField.isNull() || upField.intValue() <= 0 || upField.intValue() > 10000000) // 10 gbit/s limit errorList.addError("ERROR_UPLOAD_INSANE"); //clients still report eg: "test_ping_shortest":9195040 (note the 'test_' prefix there!) final LongField pingField = (LongField) test.getField("ping_shortest"); if (pingField.isNull() || pingField.longValue() <= 0 || pingField.longValue() > 60000000000L) // 1 min limit errorList.addError("ERROR_PING_INSANE"); if (errorList.isEmpty()) test.getField("status").setString("FINISHED"); else test.getField("status").setString("ERROR"); test.storeTestResults(false); if (test.hasError()) errorList.addError(test.getError()); } else errorList.addError("ERROR_CLIENT_VERSION"); } else errorList.addError("ERROR_TEST_TOKEN_MALFORMED"); } catch (final IllegalArgumentException e) { e.printStackTrace(); errorList.addError("ERROR_TEST_TOKEN_MALFORMED"); } } else errorList.addError("ERROR_TEST_TOKEN_MISSING"); conn.commit(); } else errorList.addError("ERROR_DB_CONNECTION"); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSDON Data " + e.toString()); e.printStackTrace(); } catch (final SQLException e) { System.out.println("Error while storing data " + e.toString()); e.printStackTrace(); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } return answer.toString(); }
From source file:net.sourceforge.msscodefactory.cfcrm.v2_0.CFCrmXMsgRspnHandler.CFCrmXMsgRspnLoggedOutHandler.java
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { try {// www . j av a 2 s . c om // Common XML Attributes String attrId = null; // Response Attributes String attrSecSessionId = null; // Attribute Extraction String attrLocalName; int numAttrs; int idxAttr; final String S_ProcName = "startElement"; final String S_LocalName = "LocalName"; assert qName.equals("RspnLoggedOut"); CFCrmXMsgRspnHandler xmsgRspnHandler = (CFCrmXMsgRspnHandler) getParser(); if (xmsgRspnHandler == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser()"); } ICFCrmSchemaObj schemaObj = xmsgRspnHandler.getSchemaObj(); if (schemaObj == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser().getSchemaObj()"); } // Extract Attributes numAttrs = attrs.getLength(); for (idxAttr = 0; idxAttr < numAttrs; idxAttr++) { attrLocalName = attrs.getLocalName(idxAttr); if (attrLocalName.equals("Id")) { if (attrId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("SecSessionId")) { if (attrSecSessionId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrSecSessionId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("schemaLocation")) { // ignored } else { throw CFLib.getDefaultExceptionFactory().newUnrecognizedAttributeException(getClass(), S_ProcName, getParser().getLocationInfo(), attrLocalName); } } // Ensure that required attributes have values if ((attrSecSessionId == null) || (attrSecSessionId.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "SecSessionId"); } // Convert string attributes to native Java types UUID natSecSessionId = UUID.fromString(attrSecSessionId); if (natSecSessionId == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "conversionOfSecSessionIdToUUID"); } // Clean up after the logout schemaObj.setAuthorization(null); } catch (RuntimeException e) { throw new RuntimeException("Near " + getParser().getLocationInfo() + ": Caught and rethrew " + e.getClass().getName() + " - " + e.getMessage(), e); } catch (Error e) { throw new Error("Near " + getParser().getLocationInfo() + ": Caught and rethrew " + e.getClass().getName() + " - " + e.getMessage(), e); } }
From source file:de.huberlin.cuneiform.dag.JsonReportEntry.java
public JsonReportEntry(String raw) throws JSONException { JSONObject obj, valueObj;/* ww w . jav a2 s . com*/ String valueString; try { obj = new JSONObject(raw); setTimestamp(obj.getLong(ATT_TIMESTAMP)); setRunId(UUID.fromString(obj.getString(ATT_RUNID))); if (obj.has(ATT_TASKID)) if (!obj.isNull(ATT_TASKID)) setTaskId(obj.getLong(ATT_TASKID)); if (obj.has(ATT_TASKNAME)) if (!obj.isNull(ATT_TASKNAME)) setTaskname(obj.getString(ATT_TASKNAME)); if (obj.has(ATT_LANG)) if (!obj.isNull(ATT_LANG)) setLang(obj.getString(ATT_LANG)); if (obj.has(ATT_INVOCID)) if (!obj.isNull(ATT_INVOCID)) setInvocId(obj.getLong(ATT_INVOCID)); setKey(obj.getString(ATT_KEY)); try { valueObj = obj.getJSONObject(ATT_VALUE); setValueFromJsonObj(valueObj); } catch (JSONException e) { valueString = obj.getString(ATT_VALUE); setValueFromRawString(valueString); } } catch (JSONException e) { System.err.println("[raw]"); System.err.println(raw); throw e; } }
From source file:net.sf.mpaxs.spi.server.HostRegister.java
/** * Shutdown the host register./* ww w .ja v a2 s . c o m*/ * * @param timeout maximum time to wait before hard shutdown * @param timeUnit time unit for timeout * @throws InterruptedException */ public void shutdown(long timeout, TimeUnit timeUnit) throws InterruptedException { HashMap<UUID, Host> hosts = getHosts(); try { for (Iterator<UUID> i = hosts.keySet().iterator(); i.hasNext();) { Host host = hosts.get(i.next()); IComputeHost remRef; try { remRef = (IComputeHost) Naming .lookup("//" + host.getIP() + ":" + settings.getLocalPort() + "/" + host.getName()); remRef.masterServerShuttingDown( UUID.fromString(settings.getString(ConfigurationKeys.KEY_AUTH_TOKEN))); } catch (NotBoundException ex) { EventLogger.getInstance().getLogger().log(Level.SEVERE, "Not Bound Exception!", ex); } catch (MalformedURLException ex) { EventLogger.getInstance().getLogger().log(Level.SEVERE, "MalformedURLException!", ex); } catch (RemoteException ex) { EventLogger.getInstance().getLogger().log(Level.SEVERE, "RemoteException!", ex); } } } catch (Exception e) { EventLogger.getInstance().getLogger().log(Level.SEVERE, "Exception while shutting down hosts!", e); throw new RuntimeException(e); } finally { //we need to shut down the executor and event service //we can not throw the interrupted exceptions however, since //that would try { EventLogger.getInstance().getLogger().log(Level.INFO, "Shutting down host register executor service"); executorService.shutdown(); if (!executorService.awaitTermination(timeout, timeUnit)) { executorService.shutdownNow(); } } catch (InterruptedException ie) { executorService.shutdownNow(); Thread.currentThread().interrupt(); } finally { try { EventLogger.getInstance().getLogger().log(Level.INFO, "Shutting down host register event service"); eventService.shutdown(); if (!eventService.awaitTermination(timeout, timeUnit)) { eventService.shutdownNow(); } } catch (InterruptedException ie) { eventService.shutdownNow(); Thread.currentThread().interrupt(); } } } }
From source file:com.claresco.tinman.servlet.XapiServletUtility.java
protected static UUID validateUUID(String theUUIDString) throws XapiBadParamException { try {//w w w . j a va 2 s. c o m if (theUUIDString != null && !theUUIDString.isEmpty()) { return UUID.fromString(theUUIDString); } else { throw new XapiBadParamException("Bad UUID"); } } catch (IllegalArgumentException e) { throw new XapiBadParamException("Bad UUID"); } }
From source file:net.sourceforge.msscodefactory.cfcrm.v2_1.CFCrmXMsgRqstHandler.CFCrmXMsgRqstSecSessionDeleteBySecProxyIdxHandler.java
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { try {//from w w w . j a v a2 s . co m // Common XML Attributes String attrId = null; String attrSecProxyId = null; // Attribute Extraction String attrLocalName; int numAttrs; int idxAttr; final String S_ProcName = "startElement"; final String S_LocalName = "LocalName"; assert qName.equals("RqstSecSessionDeleteBySecProxyIdx"); CFCrmXMsgRqstHandler xmsgRqstHandler = (CFCrmXMsgRqstHandler) getParser(); if (xmsgRqstHandler == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser()"); } ICFCrmSchemaObj schemaObj = xmsgRqstHandler.getSchemaObj(); if (schemaObj == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser().getSchemaObj()"); } // Extract Attributes numAttrs = attrs.getLength(); for (idxAttr = 0; idxAttr < numAttrs; idxAttr++) { attrLocalName = attrs.getLocalName(idxAttr); if (attrLocalName.equals("Id")) { if (attrId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("SecProxyId")) { if (attrSecProxyId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrSecProxyId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("schemaLocation")) { // ignored } else { throw CFLib.getDefaultExceptionFactory().newUnrecognizedAttributeException(getClass(), S_ProcName, getParser().getLocationInfo(), attrLocalName); } } // Ensure that required attributes have values // Save named attributes to context CFLibXmlCoreContext curContext = getParser().getCurContext(); // Convert string attributes to native Java types UUID natSecProxyId; natSecProxyId = UUID.fromString(attrSecProxyId); // Delete the objects schemaObj.getSecSessionTableObj().deleteSecSessionBySecProxyIdx(natSecProxyId); String response = CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFCrmXMsgSecSessionMessageFormatter.formatSecSessionRspnDeleted() + "\n" + CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); ((CFCrmXMsgRqstHandler) getParser()).appendResponse(response); } catch (RuntimeException e) { String response = CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFCrmXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFCrmXMsgRqstHandler xmsgRqstHandler = ((CFCrmXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (Error e) { String response = CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFCrmXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFCrmXMsgRqstHandler xmsgRqstHandler = ((CFCrmXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } }
From source file:com.n1t3slay3r.empirecraft.main.Update.java
/** * Query the API to find the latest approved file's details. *//* ww w.j a va 2 s.c o m*/ public void query() { URL url; try { // Create the URL to query using the project's ID url = new URL(API_HOST + API_QUERY + projectID); } catch (MalformedURLException e) { return; } try { // Open a connection and query the project URLConnection conn = url.openConnection(); if (apiKey != null) { // Add the API key to the request if present conn.addRequestProperty("X-API-Key", apiKey); } // Add the user-agent to identify the program conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)"); // Read the response of the query // The response will be in a JSON format, so only reading one line is necessary. final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); // Parse the array of files from the query's response JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() > 0) { // Get the newest file's details JSONObject latest = (JSONObject) array.get(array.size() - 1); // Get the version's title String versionName = (String) latest.get(API_NAME_VALUE); // Get the version's link String versionLink = (String) latest.get(API_LINK_VALUE); // Get the version's release type String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE); // Get the version's file name String versionFileName = (String) latest.get(API_FILE_NAME_VALUE); // Get the version's game version String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE); if (playername != null) { Bukkit.getPlayer(UUID.fromString(playername)) .sendMessage(ChatColor.YELLOW + "The latest version of " + ChatColor.GOLD + versionFileName + ChatColor.YELLOW + " is " + ChatColor.GOLD + versionName + ChatColor.YELLOW + ", a " + ChatColor.GOLD + versionType.toUpperCase() + ChatColor.YELLOW + " for " + ChatColor.GOLD + versionGameVersion + ChatColor.YELLOW + ", available at: " + ChatColor.GOLD + versionLink); } else { System.out.println("The latest version of " + versionFileName + " is " + versionName + ", a " + versionType.toUpperCase() + " for " + versionGameVersion + ", available at: " + versionLink); } } } catch (IOException e) { } }
From source file:net.sourceforge.msscodefactory.cfcrm.v2_0.CFCrmXMsgRqstHandler.CFCrmXMsgRqstSecSessionDeleteByIdIdxHandler.java
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { try {//from w ww.ja v a 2 s. c o m // Common XML Attributes String attrId = null; String attrSecSessionId = null; // Attribute Extraction String attrLocalName; int numAttrs; int idxAttr; final String S_ProcName = "startElement"; final String S_LocalName = "LocalName"; assert qName.equals("RqstSecSessionDeleteByIdIdx"); CFCrmXMsgRqstHandler xmsgRqstHandler = (CFCrmXMsgRqstHandler) getParser(); if (xmsgRqstHandler == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser()"); } ICFCrmSchemaObj schemaObj = xmsgRqstHandler.getSchemaObj(); if (schemaObj == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "getParser().getSchemaObj()"); } // Extract Attributes numAttrs = attrs.getLength(); for (idxAttr = 0; idxAttr < numAttrs; idxAttr++) { attrLocalName = attrs.getLocalName(idxAttr); if (attrLocalName.equals("Id")) { if (attrId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("SecSessionId")) { if (attrSecSessionId != null) { throw CFLib.getDefaultExceptionFactory().newUniqueIndexViolationException(getClass(), S_ProcName, S_LocalName, attrLocalName); } attrSecSessionId = attrs.getValue(idxAttr); } else if (attrLocalName.equals("schemaLocation")) { // ignored } else { throw CFLib.getDefaultExceptionFactory().newUnrecognizedAttributeException(getClass(), S_ProcName, getParser().getLocationInfo(), attrLocalName); } } // Ensure that required attributes have values$implRqstTableDeleteByHandlerCheckReqKeyAttrs$ // Save named attributes to context CFLibXmlCoreContext curContext = getParser().getCurContext(); // Convert string attributes to native Java types UUID natSecSessionId; natSecSessionId = UUID.fromString(attrSecSessionId); // Delete the objects schemaObj.getSecSessionTableObj().deleteSecSessionByIdIdx(natSecSessionId); String response = CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFCrmXMsgSecSessionMessageFormatter.formatSecSessionRspnDeleted() + "\n" + CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); ((CFCrmXMsgRqstHandler) getParser()).appendResponse(response); } catch (RuntimeException e) { String response = CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFCrmXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFCrmXMsgRqstHandler xmsgRqstHandler = ((CFCrmXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } catch (Error e) { String response = CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPreamble() + "\n" + "\t" + CFCrmXMsgSchemaMessageFormatter.formatRspnException("\n\t\t\t", e) + "\n" + CFCrmXMsgSchemaMessageFormatter.formatRspnXmlPostamble(); CFCrmXMsgRqstHandler xmsgRqstHandler = ((CFCrmXMsgRqstHandler) getParser()); xmsgRqstHandler.resetResponse(); xmsgRqstHandler.appendResponse(response); xmsgRqstHandler.setCaughtException(true); } }