List of usage examples for org.apache.hadoop.io DataOutputBuffer DataOutputBuffer
public DataOutputBuffer()
From source file:org.apache.helix.provisioning.yarn.AppLauncher.java
License:Apache License
public boolean launch() throws Exception { LOG.info("Running Client"); yarnClient.start();/* ww w . ja va2 s .c o m*/ // Get a new application id YarnClientApplication app = yarnClient.createApplication(); GetNewApplicationResponse appResponse = app.getNewApplicationResponse(); // TODO get min/max resource capabilities from RM and change memory ask if needed // If we do not have min/max, we may not be able to correctly request // the required resources from the RM for the app master // Memory ask has to be a multiple of min and less than max. // Dump out information about cluster capability as seen by the resource manager int maxMem = appResponse.getMaximumResourceCapability().getMemory(); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); // set the application name ApplicationSubmissionContext appContext = app.getApplicationSubmissionContext(); _appId = appContext.getApplicationId(); _appMasterConfig.setAppId(_appId.getId()); String appName = _applicationSpec.getAppName(); _appMasterConfig.setAppName(appName); _appMasterConfig.setApplicationSpecFactory(_applicationSpecFactory.getClass().getCanonicalName()); appContext.setApplicationName(appName); // Set up the container launch context for the application master ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); LOG.info("Copy Application archive file from local filesystem and add to local environment"); // Copy the application master jar to the filesystem // Create a local resource to point to the destination jar path FileSystem fs = FileSystem.get(_conf); // get packages for each component packages Map<String, URI> packages = new HashMap<String, URI>(); packages.put(AppMasterConfig.AppEnvironment.APP_MASTER_PKG.toString(), appMasterArchive.toURI()); packages.put(AppMasterConfig.AppEnvironment.APP_SPEC_FILE.toString(), _yamlConfigFile.toURI()); for (String serviceName : _applicationSpec.getServices()) { packages.put(serviceName, _applicationSpec.getServicePackage(serviceName)); } Map<String, Path> hdfsDest = new HashMap<String, Path>(); Map<String, String> classpathMap = new HashMap<String, String>(); for (String name : packages.keySet()) { URI uri = packages.get(name); Path dst = copyToHDFS(fs, name, uri); hdfsDest.put(name, dst); String classpath = generateClasspathAfterExtraction(name, new File(uri)); classpathMap.put(name, classpath); _appMasterConfig.setClasspath(name, classpath); String serviceMainClass = _applicationSpec.getServiceMainClass(name); if (serviceMainClass != null) { _appMasterConfig.setMainClass(name, serviceMainClass); } } // Get YAML files describing all workflows to immediately start Map<String, URI> workflowFiles = new HashMap<String, URI>(); List<TaskConfig> taskConfigs = _applicationSpec.getTaskConfigs(); if (taskConfigs != null) { for (TaskConfig taskConfig : taskConfigs) { URI configUri = taskConfig.getYamlURI(); if (taskConfig.name != null && configUri != null) { workflowFiles.put(taskConfig.name, taskConfig.getYamlURI()); } } } // set local resources for the application master // local files or archives as needed // In this scenario, the jar file for the application master is part of the local resources Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); LocalResource appMasterPkg = setupLocalResource(fs, hdfsDest.get(AppMasterConfig.AppEnvironment.APP_MASTER_PKG.toString())); LocalResource appSpecFile = setupLocalResource(fs, hdfsDest.get(AppMasterConfig.AppEnvironment.APP_SPEC_FILE.toString())); localResources.put(AppMasterConfig.AppEnvironment.APP_MASTER_PKG.toString(), appMasterPkg); localResources.put(AppMasterConfig.AppEnvironment.APP_SPEC_FILE.toString(), appSpecFile); for (String name : workflowFiles.keySet()) { URI uri = workflowFiles.get(name); Path dst = copyToHDFS(fs, name, uri); LocalResource taskLocalResource = setupLocalResource(fs, dst); localResources.put(AppMasterConfig.AppEnvironment.TASK_CONFIG_FILE.toString() + "_" + name, taskLocalResource); } // Set local resource info into app master container launch context amContainer.setLocalResources(localResources); // Set the necessary security tokens as needed // amContainer.setContainerTokens(containerToken); // Add AppMaster.jar location to classpath // At some point we should not be required to add // the hadoop specific classpaths to the env. // It should be provided out of the box. // For now setting all required classpaths including // the classpath to "." for the application jar StringBuilder classPathEnv = new StringBuilder(Environment.CLASSPATH.$()).append(File.pathSeparatorChar) .append("./*").append(File.pathSeparatorChar); classPathEnv.append(classpathMap.get(AppMasterConfig.AppEnvironment.APP_MASTER_PKG.toString())); for (String c : _conf.getStrings(YarnConfiguration.YARN_APPLICATION_CLASSPATH, YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH)) { classPathEnv.append(File.pathSeparatorChar); classPathEnv.append(c.trim()); } classPathEnv.append(File.pathSeparatorChar).append("./log4j.properties"); // add the runtime classpath needed for tests to work if (_conf.getBoolean(YarnConfiguration.IS_MINI_YARN_CLUSTER, false)) { classPathEnv.append(':'); classPathEnv.append(System.getProperty("java.class.path")); } LOG.info("\n\n Setting the classpath to launch AppMaster:\n\n"); // Set the env variables to be setup in the env where the application master will be run Map<String, String> env = new HashMap<String, String>(_appMasterConfig.getEnv()); env.put("CLASSPATH", classPathEnv.toString()); amContainer.setEnvironment(env); // Set the necessary command to execute the application master Vector<CharSequence> vargs = new Vector<CharSequence>(30); // Set java executable command LOG.info("Setting up app master launch command"); vargs.add(Environment.JAVA_HOME.$() + "/bin/java"); int amMemory = 4096; // Set Xmx based on am memory size vargs.add("-Xmx" + amMemory + "m"); // Set class name vargs.add(AppMasterLauncher.class.getCanonicalName()); // Set params for Application Master // vargs.add("--num_containers " + String.valueOf(numContainers)); vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stdout"); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stderr"); // Get final commmand StringBuilder command = new StringBuilder(); for (CharSequence str : vargs) { command.append(str).append(" "); } LOG.info("Completed setting up app master command " + command.toString()); List<String> commands = new ArrayList<String>(); commands.add(command.toString()); amContainer.setCommands(commands); // Set up resource type requirements // For now, only memory is supported so we set memory requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory(amMemory); appContext.setResource(capability); // Service data is a binary blob that can be passed to the application // Not needed in this scenario // amContainer.setServiceData(serviceData); // Setup security tokens if (UserGroupInformation.isSecurityEnabled()) { Credentials credentials = new Credentials(); String tokenRenewer = _conf.get(YarnConfiguration.RM_PRINCIPAL); if (tokenRenewer == null || tokenRenewer.length() == 0) { throw new IOException("Can't get Master Kerberos principal for the RM to use as renewer"); } // For now, only getting tokens for the default file-system. final Token<?> tokens[] = fs.addDelegationTokens(tokenRenewer, credentials); if (tokens != null) { for (Token<?> token : tokens) { LOG.info("Got dt for " + fs.getUri() + "; " + token); } } DataOutputBuffer dob = new DataOutputBuffer(); credentials.writeTokenStorageToStream(dob); ByteBuffer fsTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); amContainer.setTokens(fsTokens); } appContext.setAMContainerSpec(amContainer); // Set the priority for the application master Priority pri = Records.newRecord(Priority.class); int amPriority = 0; // TODO - what is the range for priority? how to decide? pri.setPriority(amPriority); appContext.setPriority(pri); String amQueue = "default"; // Set the queue to which this application is to be submitted in the RM appContext.setQueue(amQueue); LOG.info("Submitting application to YARN Resource Manager"); ApplicationId applicationId = yarnClient.submitApplication(appContext); LOG.info("Submitted application with applicationId:" + applicationId); return true; }
From source file:org.apache.helix.provisioning.yarn.GenericApplicationMaster.java
License:Apache License
/** * Parse command line options/* w w w. j a v a2 s . com*/ * @param args Command line args * @return Whether init successful and run should be invoked * @throws ParseException * @throws IOException * @throws YarnException */ public boolean start() throws ParseException, IOException, YarnException { if (Boolean.getBoolean(System.getenv("debug"))) { dumpOutDebugInfo(); } Map<String, String> envs = System.getenv(); if (!envs.containsKey(ApplicationConstants.APP_SUBMIT_TIME_ENV)) { throw new RuntimeException(ApplicationConstants.APP_SUBMIT_TIME_ENV + " not set in the environment"); } if (!envs.containsKey(Environment.NM_HOST.name())) { throw new RuntimeException(Environment.NM_HOST.name() + " not set in the environment"); } if (!envs.containsKey(Environment.NM_HTTP_PORT.name())) { throw new RuntimeException(Environment.NM_HTTP_PORT + " not set in the environment"); } if (!envs.containsKey(Environment.NM_PORT.name())) { throw new RuntimeException(Environment.NM_PORT.name() + " not set in the environment"); } LOG.info("Application master for app" + ", appId=" + appAttemptID.getApplicationId().getId() + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId=" + appAttemptID.getAttemptId()); LOG.info("Starting ApplicationMaster"); Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials(); LOG.info("Credentials: " + credentials); DataOutputBuffer dob = new DataOutputBuffer(); credentials.writeTokenStorageToStream(dob); // Now remove the AM->RM token so that containers cannot access it. Iterator<Token<?>> iter = credentials.getAllTokens().iterator(); while (iter.hasNext()) { Token<?> token = iter.next(); LOG.info("Processing token: " + token); if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) { iter.remove(); } } allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); AMRMClientAsync.CallbackHandler allocListener = new RMCallbackHandler(this); amRMClient = AMRMClientAsync.createAMRMClientAsync(1000, allocListener); amRMClient.init(conf); amRMClient.start(); containerListener = createNMCallbackHandler(); nmClientAsync = new NMClientAsyncImpl(containerListener); nmClientAsync.init(conf); nmClientAsync.start(); // Setup local RPC Server to accept status requests directly from clients // TODO need to setup a protocol for client to be able to communicate to // the RPC server // TODO use the rpc port info to register with the RM for the client to // send requests to this app master // Register self with ResourceManager // This will start heartbeating to the RM appMasterHostname = NetUtils.getHostname(); RegisterApplicationMasterResponse response = amRMClient.registerApplicationMaster(appMasterHostname, appMasterRpcPort, appMasterTrackingUrl); // Dump out information about cluster capability as seen by the // resource manager int maxMem = response.getMaximumResourceCapability().getMemory(); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); return true; }
From source file:org.apache.hoya.core.launch.AbstractLauncher.java
License:Apache License
/** * Complete the launch context (copy in env vars, etc). * @return the container to launch// w w w .ja va 2 s. c o m */ public ContainerLaunchContext completeContainerLaunch() throws IOException { dumpLocalResources(); String cmdStr = HoyaUtils.join(commands, " "); log.debug("Completed setting up container command {}", cmdStr); containerLaunchContext.setCommands(commands); //fix the env variables containerLaunchContext.setEnvironment(env); //service data containerLaunchContext.setServiceData(serviceData); containerLaunchContext.setLocalResources(localResources); DataOutputBuffer dob = new DataOutputBuffer(); credentials.writeTokenStorageToStream(dob); ByteBuffer tokenBuffer = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); containerLaunchContext.setTokens(tokenBuffer); return containerLaunchContext; }
From source file:org.apache.hoya.yarn.appmaster.HoyaAppMaster.java
License:Apache License
/** * Create and run the cluster./*from www .ja va 2s. c o m*/ * @return exit code * @throws Throwable on a failure */ private int createAndRunCluster(String clustername) throws Throwable { HoyaVersionInfo.loadAndPrintVersionInfo(log); //load the cluster description from the cd argument String hoyaClusterDir = serviceArgs.getHoyaClusterURI(); URI hoyaClusterURI = new URI(hoyaClusterDir); Path clusterDirPath = new Path(hoyaClusterURI); HoyaFileSystem fs = getClusterFS(); // build up information about the running application -this // will be passed down to the cluster status MapOperations appInformation = new MapOperations(); AggregateConf instanceDefinition = InstanceIO.loadInstanceDefinitionUnresolved(fs, clusterDirPath); log.info("Deploying cluster {}:", instanceDefinition); //REVISIT: why is this done? appState.updateInstanceDefinition(instanceDefinition); File confDir = getLocalConfDir(); if (!confDir.exists() || !confDir.isDirectory()) { log.error("Bad conf dir {}", confDir); File parentFile = confDir.getParentFile(); log.error("Parent dir {}:\n{}", parentFile, HoyaUtils.listDir(parentFile)); throw new BadCommandArgumentsException("Configuration directory %s doesn't exist", confDir); } Configuration serviceConf = getConfig(); // Try to get the proper filtering of static resources through the yarn proxy working serviceConf.set("hadoop.http.filter.initializers", "org.apache.hadoop.yarn.server.webproxy.amfilter.AmFilterInitializer"); conf = new YarnConfiguration(serviceConf); //get our provider MapOperations globalOptions = instanceDefinition.getInternalOperations().getGlobalOptions(); String providerType = globalOptions.getMandatoryOption(OptionKeys.INTERNAL_PROVIDER_NAME); log.info("Cluster provider type is {}", providerType); HoyaProviderFactory factory = HoyaProviderFactory.createHoyaProviderFactory(providerType); providerService = factory.createServerProvider(); // init the provider BUT DO NOT START IT YET providerService.init(getConfig()); addService(providerService); InetSocketAddress address = HoyaUtils.getRmSchedulerAddress(conf); log.info("RM is at {}", address); yarnRPC = YarnRPC.create(conf); /* * Extract the container ID. This is then * turned into an (incompete) container */ appMasterContainerID = ConverterUtils.toContainerId( HoyaUtils.mandatoryEnvVariable(ApplicationConstants.Environment.CONTAINER_ID.name())); appAttemptID = appMasterContainerID.getApplicationAttemptId(); ApplicationId appid = appAttemptID.getApplicationId(); log.info("Hoya AM for ID {}", appid.getId()); appInformation.put(StatusKeys.INFO_AM_CONTAINER_ID, appMasterContainerID.toString()); appInformation.put(StatusKeys.INFO_AM_APP_ID, appid.toString()); appInformation.put(StatusKeys.INFO_AM_ATTEMPT_ID, appAttemptID.toString()); UserGroupInformation currentUser = UserGroupInformation.getCurrentUser(); Credentials credentials = currentUser.getCredentials(); DataOutputBuffer dob = new DataOutputBuffer(); credentials.writeTokenStorageToStream(dob); dob.close(); // Now remove the AM->RM token so that containers cannot access it. Iterator<Token<?>> iter = credentials.getAllTokens().iterator(); while (iter.hasNext()) { Token<?> token = iter.next(); log.info("Token {}", token.getKind()); if (token.getKind().equals(AMRMTokenIdentifier.KIND_NAME)) { iter.remove(); } } allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); // set up secret manager secretManager = new ClientToAMTokenSecretManager(appAttemptID, null); // if not a secure cluster, extract the username -it will be // propagated to workers if (!UserGroupInformation.isSecurityEnabled()) { hoyaUsername = System.getenv(HADOOP_USER_NAME); log.info(HADOOP_USER_NAME + "='{}'", hoyaUsername); } Map<String, String> envVars; /** * It is critical this section is synchronized, to stop async AM events * arriving while registering a restarting AM. */ synchronized (appState) { int heartbeatInterval = HEARTBEAT_INTERVAL; //add the RM client -this brings the callbacks in asyncRMClient = AMRMClientAsync.createAMRMClientAsync(heartbeatInterval, this); addService(asyncRMClient); //wrap it for the app state model rmOperationHandler = new AsyncRMOperationHandler(asyncRMClient); //now bring it up runChildService(asyncRMClient); //nmclient relays callbacks back to this class nmClientAsync = new NMClientAsyncImpl("nmclient", this); runChildService(nmClientAsync); //bring up the Hoya RPC service startHoyaRPCServer(); InetSocketAddress rpcServiceAddr = rpcService.getConnectAddress(); appMasterHostname = rpcServiceAddr.getHostName(); appMasterRpcPort = rpcServiceAddr.getPort(); appMasterTrackingUrl = null; log.info("AM Server is listening at {}:{}", appMasterHostname, appMasterRpcPort); appInformation.put(StatusKeys.INFO_AM_HOSTNAME, appMasterHostname); appInformation.set(StatusKeys.INFO_AM_RPC_PORT, appMasterRpcPort); //build the role map List<ProviderRole> providerRoles = new ArrayList<ProviderRole>(providerService.getRoles()); providerRoles.addAll(HoyaAMClientProvider.ROLES); // Start up the WebApp and track the URL for it webApp = new HoyaAMWebApp(); WebApps.$for("hoyaam", WebAppApi.class, new WebAppApiImpl(this, appState, providerService), "ws") .with(serviceConf).start(webApp); appMasterTrackingUrl = "http://" + appMasterHostname + ":" + webApp.port(); WebAppService<HoyaAMWebApp> webAppService = new WebAppService<HoyaAMWebApp>("hoya", webApp); webAppService.init(conf); webAppService.start(); addService(webAppService); appInformation.put(StatusKeys.INFO_AM_WEB_URL, appMasterTrackingUrl + "/"); appInformation.set(StatusKeys.INFO_AM_WEB_PORT, webApp.port()); // Register self with ResourceManager // This will start heartbeating to the RM // address = HoyaUtils.getRmSchedulerAddress(asyncRMClient.getConfig()); log.info("Connecting to RM at {},address tracking URL={}", appMasterRpcPort, appMasterTrackingUrl); RegisterApplicationMasterResponse response = asyncRMClient.registerApplicationMaster(appMasterHostname, appMasterRpcPort, appMasterTrackingUrl); Resource maxResources = response.getMaximumResourceCapability(); containerMaxMemory = maxResources.getMemory(); containerMaxCores = maxResources.getVirtualCores(); appState.setContainerLimits(maxResources.getMemory(), maxResources.getVirtualCores()); // set the RM-defined maximum cluster values appInformation.put(ResourceKeys.YARN_CORES, Integer.toString(containerMaxCores)); appInformation.put(ResourceKeys.YARN_MEMORY, Integer.toString(containerMaxMemory)); boolean securityEnabled = UserGroupInformation.isSecurityEnabled(); if (securityEnabled) { secretManager.setMasterKey(response.getClientToAMTokenMasterKey().array()); applicationACLs = response.getApplicationACLs(); //tell the server what the ACLs are rpcService.getServer().refreshServiceAcl(conf, new HoyaAMPolicyProvider()); } // extract container list List<Container> liveContainers = AMRestartSupport.retrieveContainersFromPreviousAttempt(response); String amRestartSupported = Boolean.toString(liveContainers != null); appInformation.put(StatusKeys.INFO_AM_RESTART_SUPPORTED, amRestartSupported); //now validate the installation Configuration providerConf = providerService.loadProviderConfigurationInformation(confDir); providerService.validateApplicationConfiguration(instanceDefinition, confDir, securityEnabled); //determine the location for the role history data Path historyDir = new Path(clusterDirPath, HISTORY_DIR_NAME); //build the instance appState.buildInstance(instanceDefinition, providerConf, providerRoles, fs.getFileSystem(), historyDir, liveContainers, appInformation); // add the AM to the list of nodes in the cluster appState.buildAppMasterNode(appMasterContainerID, appMasterHostname, webApp.port(), appMasterHostname + ":" + webApp.port()); // build up environment variables that the AM wants set in every container // irrespective of provider and role. envVars = new HashMap<String, String>(); if (hoyaUsername != null) { envVars.put(HADOOP_USER_NAME, hoyaUsername); } } String rolesTmpSubdir = appMasterContainerID.toString() + "/roles"; String amTmpDir = globalOptions.getMandatoryOption(OptionKeys.INTERNAL_AM_TMP_DIR); Path tmpDirPath = new Path(amTmpDir); Path launcherTmpDirPath = new Path(tmpDirPath, rolesTmpSubdir); fs.getFileSystem().mkdirs(launcherTmpDirPath); //launcher service launchService = new RoleLaunchService(this, providerService, fs, new Path(getGeneratedConfDir()), envVars, launcherTmpDirPath); runChildService(launchService); appState.noteAMLaunched(); //Give the provider restricted access to the state providerService.bind(appState); // launch the provider; this is expected to trigger a callback that // brings up the service launchProviderService(instanceDefinition, confDir); try { //now block waiting to be told to exit the process waitForAMCompletionSignal(); //shutdown time } finally { finish(); } return amExitCode; }
From source file:org.apache.ignite.yarn.utils.IgniteYarnUtils.java
License:Apache License
/** * Creates a ByteBuffer with serialized {@link Credentials}. * * @param creds The credentials./*from www . j ava2s. co m*/ * @return The ByteBuffer with the credentials. * @throws IOException */ public static ByteBuffer createTokenBuffer(Credentials creds) throws IOException { DataOutputBuffer dob = new DataOutputBuffer(); creds.writeTokenStorageToStream(dob); return ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); }
From source file:org.apache.mahout.clustering.dirichlet.TestMapReduce.java
License:Apache License
public void testNormalModelWritableSerialization() throws Exception { double[] m = { 1.1, 2.2, 3.3 }; Model<?> model = new NormalModel(5, new DenseVector(m), 3.3); DataOutputBuffer out = new DataOutputBuffer(); model.write(out);/*from w ww . j a v a 2 s . c o m*/ Model<?> model2 = new NormalModel(); DataInputBuffer in = new DataInputBuffer(); in.reset(out.getData(), out.getLength()); model2.readFields(in); assertEquals("models", model.toString(), model2.toString()); }
From source file:org.apache.mahout.clustering.dirichlet.TestMapReduce.java
License:Apache License
public void testSampledNormalModelWritableSerialization() throws Exception { double[] m = { 1.1, 2.2, 3.3 }; Model<?> model = new SampledNormalModel(5, new DenseVector(m), 3.3); DataOutputBuffer out = new DataOutputBuffer(); model.write(out);/* w w w. j a va2s .c o m*/ Model<?> model2 = new SampledNormalModel(); DataInputBuffer in = new DataInputBuffer(); in.reset(out.getData(), out.getLength()); model2.readFields(in); assertEquals("models", model.toString(), model2.toString()); }
From source file:org.apache.mahout.clustering.dirichlet.TestMapReduce.java
License:Apache License
public void testAsymmetricSampledNormalModelWritableSerialization() throws Exception { double[] m = { 1.1, 2.2, 3.3 }; double[] s = { 3.3, 4.4, 5.5 }; Model<?> model = new AsymmetricSampledNormalModel(5, new DenseVector(m), new DenseVector(s)); DataOutputBuffer out = new DataOutputBuffer(); model.write(out);/*from w ww . ja v a 2 s . c om*/ Model<?> model2 = new AsymmetricSampledNormalModel(); DataInputBuffer in = new DataInputBuffer(); in.reset(out.getData(), out.getLength()); model2.readFields(in); assertEquals("models", model.toString(), model2.toString()); }
From source file:org.apache.mahout.clustering.dirichlet.TestMapReduce.java
License:Apache License
public void testClusterWritableSerialization() throws Exception { double[] m = { 1.1, 2.2, 3.3 }; DirichletCluster cluster = new DirichletCluster(new NormalModel(5, new DenseVector(m), 4), 10); DataOutputBuffer out = new DataOutputBuffer(); cluster.write(out);// w w w .ja v a 2 s. co m DirichletCluster cluster2 = new DirichletCluster(); DataInputBuffer in = new DataInputBuffer(); in.reset(out.getData(), out.getLength()); cluster2.readFields(in); assertEquals("count", cluster.getTotalCount(), cluster2.getTotalCount()); assertNotNull("model null", cluster2.getModel()); assertEquals("model", cluster.getModel().toString(), cluster2.getModel().toString()); }
From source file:org.apache.mahout.hadoop.io.serializer.SerializationTestUtil.java
License:Apache License
/** * A utility that tests serialization/deserialization. * @param conf configuration to use, "io.serializations" is read to * determine the serialization/*from w w w. j a v a 2 s . co m*/ * @param metadata the metadata to pass to the serializer/deserializer * @param <K> the class of the item * @param before item to (de)serialize * @return deserialized item */ public static <K> K testSerialization(Configuration conf, K before) throws Exception { SerializationFactory factory = new SerializationFactory(conf); SerializerBase<K> serializer = (SerializerBase<K>) factory.getSerializer(before.getClass()); DeserializerBase<K> deserializer = (DeserializerBase<K>) factory.getDeserializer(before.getClass()); DataOutputBuffer out = new DataOutputBuffer(); serializer.open(out); serializer.serialize(before); serializer.close(); DataInputBuffer in = new DataInputBuffer(); in.reset(out.getData(), out.getLength()); deserializer.open(in); K after = deserializer.deserialize(null); deserializer.close(); return after; }