Example usage for com.google.gson.stream JsonReader setLenient

List of usage examples for com.google.gson.stream JsonReader setLenient

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader setLenient.

Prototype

public final void setLenient(boolean lenient) 

Source Link

Document

Configure this parser to be liberal in what it accepts.

Usage

From source file:abtlibrary.utils.as24ApiClient.JSON.java

License:Apache License

/**
 * Deserialize the given JSON string to Java object.
 *
 * @param <T> Type/*from  w ww  .  j av  a2  s  .  c  om*/
 * @param body The JSON string
 * @param returnType The type to deserialize inot
 * @return The deserialized Java object
 */
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
    try {
        if (apiClient.isLenientOnJson()) {
            JsonReader jsonReader = new JsonReader(new StringReader(body));
            // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
            jsonReader.setLenient(true);
            return gson.fromJson(jsonReader, returnType);
        } else {
            return gson.fromJson(body, returnType);
        }
    } catch (JsonParseException e) {
        // Fallback processing when failed to parse JSON form response body:
        //   return the response body string directly for the String return type;
        //   parse response body into date or datetime for the Date return type.
        if (returnType.equals(String.class))
            return (T) body;
        else if (returnType.equals(Date.class))
            return (T) apiClient.parseDateOrDatetime(body);
        else
            throw (e);
    }
}

From source file:cern.c2mon.shared.client.request.ClientRequestImpl.java

License:Open Source License

/**
 * @param json Json string representation of a <code>TransferTagRequestImpl</code> class
 * @return The deserialized Json message
 * @throws JsonSyntaxException This exception is raised when Gson attempts to read
 *                             (or write) a malformed JSON element.
 *///from w  ww.  java2 s . c  o  m
public static final ClientRequest fromJson(final String json) {
    JsonReader jsonReader = new JsonReader(new StringReader(json));
    jsonReader.setLenient(true);
    return getGson().fromJson(jsonReader, ClientRequestImpl.class);
}

From source file:cern.c2mon.shared.client.request.ClientRequestImpl.java

License:Open Source License

@Override
public final Collection<T> fromJsonResponse(final String jsonString) throws JsonSyntaxException {
    Type collectionType;/*from   w w w  .  j  av  a2 s. co  m*/
    TypeReference jacksonCollectionType;
    JsonReader jsonReader = new JsonReader(new StringReader(jsonString));
    jsonReader.setLenient(true);

    try {
        switch (resultType) {
        case TRANSFER_TAG_LIST:
            jacksonCollectionType = new TypeReference<Collection<TransferTagImpl>>() {
            };
            return TransferTagSerializer.fromCollectionJson(jsonString, jacksonCollectionType);
        case TRANSFER_TAG_VALUE_LIST:
            jacksonCollectionType = new TypeReference<Collection<TransferTagValueImpl>>() {
            };
            return TransferTagSerializer.fromCollectionJson(jsonString, jacksonCollectionType);
        case SUPERVISION_EVENT_LIST:
            collectionType = new TypeToken<Collection<SupervisionEventImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_DAQ_XML:
            collectionType = new TypeToken<Collection<ProcessXmlResponseImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_TAG_CONFIGURATION_LIST:
            collectionType = new TypeToken<Collection<TagConfigImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_CONFIGURATION_REPORT_HEADER:
            collectionType = new TypeToken<Collection<ConfigurationReportHeader>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_CONFIGURATION_REPORT:
            collectionType = new TypeToken<Collection<ConfigurationReport>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_ACTIVE_ALARM_LIST:
            collectionType = new TypeToken<Collection<AlarmValueImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_ALARM_LIST:
            collectionType = new TypeToken<Collection<AlarmValueImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_COMMAND_HANDLES_LIST:
            collectionType = new TypeToken<Collection<CommandTagHandleImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_COMMAND_REPORT:
            collectionType = new TypeToken<Collection<CommandReportImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_PROCESS_NAMES:
            collectionType = new TypeToken<Collection<ProcessNameResponseImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_DEVICE_CLASS_NAMES:
            collectionType = new TypeToken<Collection<DeviceClassNameResponseImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_DEVICE_LIST:
            collectionType = new TypeToken<Collection<TransferDeviceImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        case TRANSFER_TAG_STATISTICS:
            collectionType = new TypeToken<Collection<TagStatisticsResponseImpl>>() {
            }.getType();
            return getGson().fromJson(jsonReader, collectionType);
        default:
            throw new JsonSyntaxException("Unknown result type specified");
        }
    } finally {
        try {
            jsonReader.close();
        } catch (IOException e) {
        }
    }
}

From source file:cognition.common.helper.JsonHelper.java

License:Apache License

public List<T> loadFromReader(Reader reader) {
    Gson gson = new Gson();

    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(reader);
    JsonReader jsonReader = new JsonReader(bufferedReader);
    jsonReader.setLenient(true);
    if (!clazz.isArray()) {
        Object data = gson.fromJson(jsonReader, clazz);
        T object = (T) data;//  w ww  . ja  va2 s .c  o m
        return Arrays.asList(object);
    }

    Object[] data = gson.fromJson(jsonReader, clazz);
    return Arrays.asList((T[]) data);
}

From source file:com.avatarproject.core.storage.Serializer.java

License:Open Source License

/**
 * Gets the object from file/*w ww . j ava 2  s. com*/
 * @param caller Class<?> of the object being deserialized
 * @param file File containing the object
 * @return Deserialized Object
 */
public static Object get(Class<?> caller, File file) {
    try {
        if (!file.exists()) {
            return null;
        }
        if (file.length() == 0) {
            return null;
        }
        JsonReader reader = new JsonReader(
                new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")));
        Gson gson = new Gson();
        reader.setLenient(true);
        Object object = gson.fromJson(reader, caller);
        reader.close();
        if (object != null && object instanceof Serializer) {
            ((Serializer) object).setFile(file);
        }
        return object;
    } catch (Exception e) {
        log.warning("Error loading GSON Object '" + caller.getSimpleName() + "' for '" + file.toString() + "'");
        e.printStackTrace();
        return null;
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.isservice.index.service.impl.IndexMetaServiceImpl.java

License:Open Source License

@Override
public List<IndexMeta> loadIndexMetasLocalImage(String idxBaseDir, String currNodeKey, String clusterName) {
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "loadIndexMetasLocalImage",
            "[idxBaseDir:" + idxBaseDir + "][currNodeKey:" + currNodeKey + "][clusterName:" + clusterName
                    + "]"));
    List<IndexMeta> result = new ArrayList<IndexMeta>();
    if (!StringUtils.isEmpty(idxBaseDir) && !StringUtils.isEmpty(currNodeKey)) {
        File idxBaseDirFile = new File(idxBaseDir);
        if (FileUtils.isEmptyDir(idxBaseDirFile)) {
            return null;
        } else if (FileUtils.isExistGivingFileSuffix(idxBaseDirFile,
                IndexFileSystemConstants.INDEX_META_IMAGE_FILE_SAVED)) {

            String[] fileNames = idxBaseDirFile.list(new FileUtils.LocalImageFilenameFilter(
                    IndexFileSystemConstants.INDEX_META_IMAGE_FILE_SAVED));
            for (String filePath : fileNames) {
                byte[] fileByte = FileUtils.readFile(idxBaseDir + File.separator + filePath);

                String fileStr = new String(fileByte);
                StringReader sr = new StringReader(fileStr);
                JsonReader jr = new JsonReader(sr);
                jr.setLenient(true);
                IndexMeta currMeta = AnswerCoreConstant.GSON.fromJson(jr, new TypeToken<IndexMeta>() {
                }.getType());//from   ww  w  .  ja  v a2  s  .c  o m

                //currNodeKey
                for (IndexShard idxShard : currMeta.getIdxShardList()) {
                    idxShard.setNodeKey(currNodeKey);
                    idxShard.setClusterName(clusterName);
                    idxShard.getReplicaNodeKeyList().clear();
                }
                currMeta.setClusterName(clusterName);

                result.add(currMeta);
            }
        } else {
            for (String currDsDir : idxBaseDirFile.list()) {
                //??????
                List<IndexMeta> tmpResult = loadIndexMetasLocalImage(idxBaseDir + File.separator + currDsDir,
                        currNodeKey, clusterName);
                if (CollectionUtils.isNotEmpty(tmpResult)) {
                    result.addAll(tmpResult);
                }
            }
        }
    }
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "loadIndexMetasLocalImage",
            "[idxBaseDir:" + idxBaseDir + "][currNodeKey:" + currNodeKey + "][clusterName:" + clusterName
                    + "][result.size:" + result.size() + "]"));
    return result;
}

From source file:com.cdancy.artifactory.rest.fallbacks.ArtifactoryFallbacks.java

License:Apache License

public static RequestStatus createPromoteBuildFromError(String message) {
    List<Message> messages = new ArrayList<>();
    List<Error> errors = new ArrayList<>();

    JsonReader reader = new JsonReader(new StringReader(message));
    reader.setLenient(true);

    JsonElement possibleMessages = parser.parse(reader).getAsJsonObject().get("messages");
    if (possibleMessages != null) {
        JsonArray jsonArray = possibleMessages.getAsJsonArray();
        Iterator<JsonElement> iter = jsonArray.iterator();
        while (iter.hasNext()) {
            JsonElement jsonElement = iter.next();
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            Message mess = Message.create(jsonObject.get("level").getAsString(),
                    jsonObject.get("message").getAsString());
            messages.add(mess);/*from   w w w . jav a  2 s.  c  om*/
        }
    }

    JsonElement possibleErrors = parser.parse(message).getAsJsonObject().get("errors");
    if (possibleErrors != null) {
        JsonArray jsonArray = possibleErrors.getAsJsonArray();
        Iterator<JsonElement> iter = jsonArray.iterator();
        while (iter.hasNext()) {
            JsonElement jsonElement = iter.next();
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            Error error = Error.create(jsonObject.get("status").getAsInt(),
                    jsonObject.get("message").getAsString());
            errors.add(error);
        }
    }

    return RequestStatus.create(messages, errors);
}

From source file:com.cloud.agent.manager.SimulatorManagerImpl.java

License:Apache License

@DB
@Override//w  w w.  j ava 2  s .  com
public Answer simulate(final Command cmd, final String hostGuid) {
    Answer answer = null;
    Exception exception = null;
    TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
    try {
        final MockHost host = _mockHost.findByGuid(hostGuid);
        String cmdName = cmd.toString();
        final int index = cmdName.lastIndexOf(".");
        if (index != -1) {
            cmdName = cmdName.substring(index + 1);
        }

        final SimulatorInfo info = new SimulatorInfo();
        info.setHostUuid(hostGuid);

        final MockConfigurationVO config = _mockConfigDao.findByNameBottomUP(host.getDataCenterId(),
                host.getPodId(), host.getClusterId(), host.getId(), cmdName);
        if (config != null && (config.getCount() == null || config.getCount().intValue() > 0)) {
            final Map<String, String> configParameters = config.getParameters();
            for (final Map.Entry<String, String> entry : configParameters.entrySet()) {
                if (entry.getKey().equalsIgnoreCase("enabled")) {
                    info.setEnabled(Boolean.parseBoolean(entry.getValue()));
                } else if (entry.getKey().equalsIgnoreCase("timeout")) {
                    try {
                        info.setTimeout(Integer.valueOf(entry.getValue()));
                    } catch (final NumberFormatException e) {
                        s_logger.debug("invalid timeout parameter: " + e.toString());
                    }
                }

                if (entry.getKey().equalsIgnoreCase("wait")) {
                    try {
                        final int wait = Integer.valueOf(entry.getValue());
                        Thread.sleep(wait);
                    } catch (final NumberFormatException e) {
                        s_logger.debug("invalid wait parameter: " + e.toString());
                    } catch (final InterruptedException e) {
                        s_logger.debug("thread is interrupted: " + e.toString());
                    }
                }

                if (entry.getKey().equalsIgnoreCase("result")) {
                    final String value = entry.getValue();
                    if (value.equalsIgnoreCase("fail")) {
                        answer = new Answer(cmd, false, "Simulated failure");
                    } else if (value.equalsIgnoreCase("fault")) {
                        exception = new Exception("Simulated fault");
                    }
                }
            }

            if (exception != null) {
                throw exception;
            }

            if (answer == null) {
                final String message = config.getJsonResponse();
                if (message != null) {
                    // json response looks like {"<Type>":....}
                    final String objectType = message.split(":")[0].substring(2).replace("\"", "");
                    final String objectData = message.substring(message.indexOf(':') + 1, message.length() - 1);
                    if (objectType != null) {
                        Class<?> clz = null;
                        try {
                            clz = Class.forName(objectType);
                        } catch (final ClassNotFoundException e) {
                        }
                        if (clz != null) {
                            final StringReader reader = new StringReader(objectData);
                            final JsonReader jsonReader = new JsonReader(reader);
                            jsonReader.setLenient(true);
                            answer = (Answer) s_gson.fromJson(jsonReader, clz);
                        }
                    }
                }
            }
        }

        if (answer == null) {
            if (cmd instanceof GetHostStatsCommand) {
                answer = _mockAgentMgr.getHostStatistic((GetHostStatsCommand) cmd);
            } else if (cmd instanceof CheckHealthCommand) {
                answer = _mockAgentMgr.checkHealth((CheckHealthCommand) cmd);
            } else if (cmd instanceof PingTestCommand) {
                answer = _mockAgentMgr.pingTest((PingTestCommand) cmd);
            } else if (cmd instanceof PrepareForMigrationCommand) {
                answer = _mockVmMgr.prepareForMigrate((PrepareForMigrationCommand) cmd);
            } else if (cmd instanceof MigrateCommand) {
                answer = _mockVmMgr.migrate((MigrateCommand) cmd, info);
            } else if (cmd instanceof StartCommand) {
                answer = _mockVmMgr.startVM((StartCommand) cmd, info);
            } else if (cmd instanceof CheckSshCommand) {
                answer = _mockVmMgr.checkSshCommand((CheckSshCommand) cmd);
            } else if (cmd instanceof CheckVirtualMachineCommand) {
                answer = _mockVmMgr.checkVmState((CheckVirtualMachineCommand) cmd);
            } else if (cmd instanceof SetStaticNatRulesCommand) {
                answer = _mockNetworkMgr.SetStaticNatRules((SetStaticNatRulesCommand) cmd);
            } else if (cmd instanceof SetFirewallRulesCommand) {
                answer = _mockNetworkMgr.SetFirewallRules((SetFirewallRulesCommand) cmd);
            } else if (cmd instanceof SetPortForwardingRulesCommand) {
                answer = _mockNetworkMgr.SetPortForwardingRules((SetPortForwardingRulesCommand) cmd);
            } else if (cmd instanceof NetworkUsageCommand) {
                answer = _mockNetworkMgr.getNetworkUsage((NetworkUsageCommand) cmd);
            } else if (cmd instanceof IpAssocCommand) {
                answer = _mockNetworkMgr.IpAssoc((IpAssocCommand) cmd);
            } else if (cmd instanceof LoadBalancerConfigCommand) {
                answer = _mockNetworkMgr.LoadBalancerConfig((LoadBalancerConfigCommand) cmd);
            } else if (cmd instanceof DhcpEntryCommand) {
                answer = _mockNetworkMgr.AddDhcpEntry((DhcpEntryCommand) cmd);
            } else if (cmd instanceof VmDataCommand) {
                answer = _mockVmMgr.setVmData((VmDataCommand) cmd);
            } else if (cmd instanceof CleanupNetworkRulesCmd) {
                answer = _mockVmMgr.cleanupNetworkRules((CleanupNetworkRulesCmd) cmd, info);
            } else if (cmd instanceof CheckNetworkCommand) {
                answer = _mockAgentMgr.checkNetworkCommand((CheckNetworkCommand) cmd);
            } else if (cmd instanceof StopCommand) {
                answer = _mockVmMgr.stopVM((StopCommand) cmd);
            } else if (cmd instanceof RebootCommand) {
                answer = _mockVmMgr.rebootVM((RebootCommand) cmd);
            } else if (cmd instanceof GetVncPortCommand) {
                answer = _mockVmMgr.getVncPort((GetVncPortCommand) cmd);
            } else if (cmd instanceof CheckConsoleProxyLoadCommand) {
                answer = _mockVmMgr.checkConsoleProxyLoad((CheckConsoleProxyLoadCommand) cmd);
            } else if (cmd instanceof WatchConsoleProxyLoadCommand) {
                answer = _mockVmMgr.watchConsoleProxyLoad((WatchConsoleProxyLoadCommand) cmd);
            } else if (cmd instanceof SecurityGroupRulesCmd) {
                answer = _mockVmMgr.addSecurityGroupRules((SecurityGroupRulesCmd) cmd, info);
            } else if (cmd instanceof SavePasswordCommand) {
                answer = _mockVmMgr.savePassword((SavePasswordCommand) cmd);
            } else if (cmd instanceof PrimaryStorageDownloadCommand) {
                answer = _mockStorageMgr.primaryStorageDownload((PrimaryStorageDownloadCommand) cmd);
            } else if (cmd instanceof CreateCommand) {
                answer = _mockStorageMgr.createVolume((CreateCommand) cmd);
            } else if (cmd instanceof AttachIsoCommand) {
                answer = _mockStorageMgr.AttachIso((AttachIsoCommand) cmd);
            } else if (cmd instanceof DeleteStoragePoolCommand) {
                answer = _mockStorageMgr.DeleteStoragePool((DeleteStoragePoolCommand) cmd);
            } else if (cmd instanceof ModifyStoragePoolCommand) {
                answer = _mockStorageMgr.ModifyStoragePool((ModifyStoragePoolCommand) cmd);
            } else if (cmd instanceof CreateStoragePoolCommand) {
                answer = _mockStorageMgr.CreateStoragePool((CreateStoragePoolCommand) cmd);
            } else if (cmd instanceof SecStorageSetupCommand) {
                answer = _mockStorageMgr.SecStorageSetup((SecStorageSetupCommand) cmd);
            } else if (cmd instanceof ListTemplateCommand) {
                answer = _mockStorageMgr.ListTemplates((ListTemplateCommand) cmd);
            } else if (cmd instanceof ListVolumeCommand) {
                answer = _mockStorageMgr.ListVolumes((ListVolumeCommand) cmd);
            } else if (cmd instanceof DestroyCommand) {
                answer = _mockStorageMgr.Destroy((DestroyCommand) cmd);
            } else if (cmd instanceof DownloadProgressCommand) {
                answer = _mockStorageMgr.DownloadProcess((DownloadProgressCommand) cmd);
            } else if (cmd instanceof DownloadCommand) {
                answer = _mockStorageMgr.Download((DownloadCommand) cmd);
            } else if (cmd instanceof GetStorageStatsCommand) {
                answer = _mockStorageMgr.GetStorageStats((GetStorageStatsCommand) cmd);
            } else if (cmd instanceof ManageSnapshotCommand) {
                answer = _mockStorageMgr.ManageSnapshot((ManageSnapshotCommand) cmd);
            } else if (cmd instanceof BackupSnapshotCommand) {
                answer = _mockStorageMgr.BackupSnapshot((BackupSnapshotCommand) cmd, info);
            } else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
                answer = _mockStorageMgr.CreateVolumeFromSnapshot((CreateVolumeFromSnapshotCommand) cmd);
            } else if (cmd instanceof DeleteCommand) {
                answer = _mockStorageMgr.Delete((DeleteCommand) cmd);
            } else if (cmd instanceof SecStorageVMSetupCommand) {
                answer = _mockStorageMgr.SecStorageVMSetup((SecStorageVMSetupCommand) cmd);
            } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
                answer = _mockStorageMgr
                        .CreatePrivateTemplateFromSnapshot((CreatePrivateTemplateFromSnapshotCommand) cmd);
            } else if (cmd instanceof ComputeChecksumCommand) {
                answer = _mockStorageMgr.ComputeChecksum((ComputeChecksumCommand) cmd);
            } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
                answer = _mockStorageMgr
                        .CreatePrivateTemplateFromVolume((CreatePrivateTemplateFromVolumeCommand) cmd);
            } else if (cmd instanceof UploadStatusCommand) {
                answer = _mockStorageMgr.getUploadStatus((UploadStatusCommand) cmd);
            } else if (cmd instanceof MaintainCommand) {
                answer = _mockAgentMgr.maintain((MaintainCommand) cmd);
            } else if (cmd instanceof GetVmStatsCommand) {
                answer = _mockVmMgr.getVmStats((GetVmStatsCommand) cmd);
            } else if (cmd instanceof CheckRouterCommand) {
                answer = _mockVmMgr.checkRouter((CheckRouterCommand) cmd);
            } else if (cmd instanceof GetDomRVersionCmd) {
                answer = _mockVmMgr.getDomRVersion((GetDomRVersionCmd) cmd);
            } else if (cmd instanceof CopyVolumeCommand) {
                answer = _mockStorageMgr.CopyVolume((CopyVolumeCommand) cmd);
            } else if (cmd instanceof PlugNicCommand) {
                answer = _mockNetworkMgr.plugNic((PlugNicCommand) cmd);
            } else if (cmd instanceof UnPlugNicCommand) {
                answer = _mockNetworkMgr.unplugNic((UnPlugNicCommand) cmd);
            } else if (cmd instanceof IpAssocVpcCommand) {
                answer = _mockNetworkMgr.ipAssoc((IpAssocVpcCommand) cmd);
            } else if (cmd instanceof SetSourceNatCommand) {
                answer = _mockNetworkMgr.setSourceNat((SetSourceNatCommand) cmd);
            } else if (cmd instanceof SetNetworkACLCommand) {
                answer = _mockNetworkMgr.setNetworkAcl((SetNetworkACLCommand) cmd);
            } else if (cmd instanceof SetupGuestNetworkCommand) {
                answer = _mockNetworkMgr.setUpGuestNetwork((SetupGuestNetworkCommand) cmd);
            } else if (cmd instanceof SetPortForwardingRulesVpcCommand) {
                answer = _mockNetworkMgr.setVpcPortForwards((SetPortForwardingRulesVpcCommand) cmd);
            } else if (cmd instanceof SetStaticNatRulesCommand) {
                answer = _mockNetworkMgr.setVPCStaticNatRules((SetStaticNatRulesCommand) cmd);
            } else if (cmd instanceof SetStaticRouteCommand) {
                answer = _mockNetworkMgr.setStaticRoute((SetStaticRouteCommand) cmd);
            } else if (cmd instanceof Site2SiteVpnCfgCommand) {
                answer = _mockNetworkMgr.siteToSiteVpn((Site2SiteVpnCfgCommand) cmd);
            } else if (cmd instanceof CheckS2SVpnConnectionsCommand) {
                answer = _mockNetworkMgr.checkSiteToSiteVpnConnection((CheckS2SVpnConnectionsCommand) cmd);
            } else if (cmd instanceof CreateVMSnapshotCommand) {
                answer = _mockVmMgr.createVmSnapshot((CreateVMSnapshotCommand) cmd);
            } else if (cmd instanceof DeleteVMSnapshotCommand) {
                answer = _mockVmMgr.deleteVmSnapshot((DeleteVMSnapshotCommand) cmd);
            } else if (cmd instanceof RevertToVMSnapshotCommand) {
                answer = _mockVmMgr.revertVmSnapshot((RevertToVMSnapshotCommand) cmd);
            } else if (cmd instanceof NetworkRulesVmSecondaryIpCommand) {
                answer = _mockVmMgr.plugSecondaryIp((NetworkRulesVmSecondaryIpCommand) cmd);
            } else if (cmd instanceof ScaleVmCommand) {
                answer = _mockVmMgr.scaleVm((ScaleVmCommand) cmd);
            } else if (cmd instanceof PvlanSetupCommand) {
                answer = _mockNetworkMgr.setupPVLAN((PvlanSetupCommand) cmd);
            } else if (cmd instanceof StorageSubSystemCommand) {
                answer = storageHandler.handleStorageCommands((StorageSubSystemCommand) cmd);
            } else if (cmd instanceof FenceCommand) {
                answer = _mockVmMgr.fence((FenceCommand) cmd);
            } else if (cmd instanceof GetRouterAlertsCommand || cmd instanceof VpnUsersCfgCommand
                    || cmd instanceof RemoteAccessVpnCfgCommand || cmd instanceof SetMonitorServiceCommand
                    || cmd instanceof AggregationControlCommand
                    || cmd instanceof SecStorageFirewallCfgCommand) {
                answer = new Answer(cmd);
            } else {
                s_logger.error("Simulator does not implement command of type " + cmd.toString());
                answer = Answer.createUnsupportedCommandAnswer(cmd);
            }
        }

        if (config != null && config.getCount() != null && config.getCount().intValue() > 0) {
            if (answer != null) {
                config.setCount(config.getCount().intValue() - 1);
                _mockConfigDao.update(config.getId(), config);
            }
        }

        return answer;
    } catch (final Exception e) {
        s_logger.error("Failed execute cmd: ", e);
        txn.rollback();
        return new Answer(cmd, false, e.toString());
    } finally {
        txn.close();
        txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
        txn.close();
    }
}

From source file:com.cloud.agent.transport.Request.java

License:Apache License

public Command[] getCommands() {
    if (_cmds == null) {
        try {/*from  ww w.ja va2  s.  c om*/
            StringReader reader = new StringReader(_content);
            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.setLenient(true);
            _cmds = s_gson.fromJson(jsonReader, (Type) Command[].class);
        } catch (RuntimeException e) {
            s_logger.error("Caught problem with " + _content, e);
            throw e;
        }
    }
    return _cmds;
}

From source file:com.cloud.resource.AgentRoutingResource.java

License:Apache License

@Override
public PingCommand getCurrentStatus(long id) {
    TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.SIMULATOR_DB);
    try {/*from  w  w w  .  j a  v a  2 s.  c  o  m*/
        MockConfigurationVO config = _simMgr.getMockConfigurationDao().findByNameBottomUP(
                agentHost.getDataCenterId(), agentHost.getPodId(), agentHost.getClusterId(), agentHost.getId(),
                "PingCommand");
        if (config != null) {
            Map<String, String> configParameters = config.getParameters();
            for (Map.Entry<String, String> entry : configParameters.entrySet()) {
                if (entry.getKey().equalsIgnoreCase("result")) {
                    String value = entry.getValue();
                    if (value.equalsIgnoreCase("fail")) {
                        return null;
                    }
                }
            }
        }

        config = _simMgr.getMockConfigurationDao().findByNameBottomUP(agentHost.getDataCenterId(),
                agentHost.getPodId(), agentHost.getClusterId(), agentHost.getId(),
                "PingRoutingWithNwGroupsCommand");
        if (config != null) {
            String message = config.getJsonResponse();
            if (message != null) {
                // json response looks like {"<Type>":....}
                String objectType = message.split(":")[0].substring(2).replace("\"", "");
                String objectData = message.substring(message.indexOf(':') + 1, message.length() - 1);
                if (objectType != null) {
                    Class<?> clz = null;
                    try {
                        clz = Class.forName(objectType);
                    } catch (ClassNotFoundException e) {
                        s_logger.info("[ignored] ping returned class", e);
                    }
                    if (clz != null) {
                        StringReader reader = new StringReader(objectData);
                        JsonReader jsonReader = new JsonReader(reader);
                        jsonReader.setLenient(true);
                        return (PingCommand) s_gson.fromJson(jsonReader, clz);
                    }
                }
            }
        }
    } catch (Exception e) {
        txn.rollback();
    } finally {
        txn.close();
        txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
        txn.close();
    }

    if (isStopped()) {
        return null;
    }
    HashMap<String, Pair<Long, Long>> nwGrpStates = _simMgr.syncNetworkGroups(hostGuid);
    return new PingRoutingWithNwGroupsCommand(getType(), id, getHostVmStateReport(), nwGrpStates);
}